1 /*
   2  * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "aot/aotLoader.hpp"
  27 #include "classfile/classFileStream.hpp"
  28 #include "classfile/metadataOnStackMark.hpp"
  29 #include "classfile/systemDictionary.hpp"
  30 #include "classfile/verifier.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "gc/shared/gcLocker.hpp"
  34 #include "interpreter/oopMapCache.hpp"
  35 #include "interpreter/rewriter.hpp"
  36 #include "logging/logStream.hpp"
  37 #include "memory/metadataFactory.hpp"
  38 #include "memory/metaspaceShared.hpp"
  39 #include "memory/resourceArea.hpp"
  40 #include "memory/universe.inline.hpp"
  41 #include "oops/fieldStreams.hpp"
  42 #include "oops/klassVtable.hpp"
  43 #include "oops/oop.inline.hpp"
  44 #include "prims/jvmtiImpl.hpp"
  45 #include "prims/jvmtiRedefineClasses.hpp"
  46 #include "prims/methodComparator.hpp"
  47 #include "runtime/deoptimization.hpp"
  48 #include "runtime/relocator.hpp"
  49 #include "utilities/bitMap.inline.hpp"
  50 #include "utilities/events.hpp"
  51 
  52 Array<Method*>* VM_RedefineClasses::_old_methods = NULL;
  53 Array<Method*>* VM_RedefineClasses::_new_methods = NULL;
  54 Method**  VM_RedefineClasses::_matching_old_methods = NULL;
  55 Method**  VM_RedefineClasses::_matching_new_methods = NULL;
  56 Method**  VM_RedefineClasses::_deleted_methods      = NULL;
  57 Method**  VM_RedefineClasses::_added_methods        = NULL;
  58 int         VM_RedefineClasses::_matching_methods_length = 0;
  59 int         VM_RedefineClasses::_deleted_methods_length  = 0;
  60 int         VM_RedefineClasses::_added_methods_length    = 0;
  61 Klass*      VM_RedefineClasses::_the_class = NULL;
  62 
  63 
  64 VM_RedefineClasses::VM_RedefineClasses(jint class_count,
  65                                        const jvmtiClassDefinition *class_defs,
  66                                        JvmtiClassLoadKind class_load_kind) {
  67   _class_count = class_count;
  68   _class_defs = class_defs;
  69   _class_load_kind = class_load_kind;
  70   _res = JVMTI_ERROR_NONE;
  71 }
  72 
  73 static inline InstanceKlass* get_ik(jclass def) {
  74   oop mirror = JNIHandles::resolve_non_null(def);
  75   return InstanceKlass::cast(java_lang_Class::as_Klass(mirror));
  76 }
  77 
  78 // If any of the classes are being redefined, wait
  79 // Parallel constant pool merging leads to indeterminate constant pools.
  80 void VM_RedefineClasses::lock_classes() {
  81   MutexLocker ml(RedefineClasses_lock);
  82   bool has_redefined;
  83   do {
  84     has_redefined = false;
  85     // Go through classes each time until none are being redefined.
  86     for (int i = 0; i < _class_count; i++) {
  87       if (get_ik(_class_defs[i].klass)->is_being_redefined()) {
  88         RedefineClasses_lock->wait();
  89         has_redefined = true;
  90         break;  // for loop
  91       }
  92     }
  93   } while (has_redefined);
  94   for (int i = 0; i < _class_count; i++) {
  95     get_ik(_class_defs[i].klass)->set_is_being_redefined(true);
  96   }
  97   RedefineClasses_lock->notify_all();
  98 }
  99 
 100 void VM_RedefineClasses::unlock_classes() {
 101   MutexLocker ml(RedefineClasses_lock);
 102   for (int i = 0; i < _class_count; i++) {
 103     assert(get_ik(_class_defs[i].klass)->is_being_redefined(),
 104            "should be being redefined to get here");
 105     get_ik(_class_defs[i].klass)->set_is_being_redefined(false);
 106   }
 107   RedefineClasses_lock->notify_all();
 108 }
 109 
 110 bool VM_RedefineClasses::doit_prologue() {
 111   if (_class_count == 0) {
 112     _res = JVMTI_ERROR_NONE;
 113     return false;
 114   }
 115   if (_class_defs == NULL) {
 116     _res = JVMTI_ERROR_NULL_POINTER;
 117     return false;
 118   }
 119   for (int i = 0; i < _class_count; i++) {
 120     if (_class_defs[i].klass == NULL) {
 121       _res = JVMTI_ERROR_INVALID_CLASS;
 122       return false;
 123     }
 124     if (_class_defs[i].class_byte_count == 0) {
 125       _res = JVMTI_ERROR_INVALID_CLASS_FORMAT;
 126       return false;
 127     }
 128     if (_class_defs[i].class_bytes == NULL) {
 129       _res = JVMTI_ERROR_NULL_POINTER;
 130       return false;
 131     }
 132 
 133     oop mirror = JNIHandles::resolve_non_null(_class_defs[i].klass);
 134     // classes for primitives and arrays and vm anonymous classes cannot be redefined
 135     // check here so following code can assume these classes are InstanceKlass
 136     if (!is_modifiable_class(mirror)) {
 137       _res = JVMTI_ERROR_UNMODIFIABLE_CLASS;
 138       return false;
 139     }
 140   }
 141 
 142   // Start timer after all the sanity checks; not quite accurate, but
 143   // better than adding a bunch of stop() calls.
 144   if (log_is_enabled(Info, redefine, class, timer)) {
 145     _timer_vm_op_prologue.start();
 146   }
 147 
 148   lock_classes();
 149   // We first load new class versions in the prologue, because somewhere down the
 150   // call chain it is required that the current thread is a Java thread.
 151   _res = load_new_class_versions(Thread::current());
 152   if (_res != JVMTI_ERROR_NONE) {
 153     // free any successfully created classes, since none are redefined
 154     for (int i = 0; i < _class_count; i++) {
 155       if (_scratch_classes[i] != NULL) {
 156         ClassLoaderData* cld = _scratch_classes[i]->class_loader_data();
 157         // Free the memory for this class at class unloading time.  Not before
 158         // because CMS might think this is still live.
 159         cld->add_to_deallocate_list(InstanceKlass::cast(_scratch_classes[i]));
 160       }
 161     }
 162     // Free os::malloc allocated memory in load_new_class_version.
 163     os::free(_scratch_classes);
 164     _timer_vm_op_prologue.stop();
 165     unlock_classes();
 166     return false;
 167   }
 168 
 169   _timer_vm_op_prologue.stop();
 170   return true;
 171 }
 172 
 173 void VM_RedefineClasses::doit() {
 174   Thread *thread = Thread::current();
 175 
 176   if (UseSharedSpaces) {
 177     // Sharing is enabled so we remap the shared readonly space to
 178     // shared readwrite, private just in case we need to redefine
 179     // a shared class. We do the remap during the doit() phase of
 180     // the safepoint to be safer.
 181     if (!MetaspaceShared::remap_shared_readonly_as_readwrite()) {
 182       log_info(redefine, class, load)("failed to remap shared readonly space to readwrite, private");
 183       _res = JVMTI_ERROR_INTERNAL;
 184       return;
 185     }
 186   }
 187 
 188   // Mark methods seen on stack and everywhere else so old methods are not
 189   // cleaned up if they're on the stack.
 190   MetadataOnStackMark md_on_stack(true);
 191   HandleMark hm(thread);   // make sure any handles created are deleted
 192                            // before the stack walk again.
 193 
 194   for (int i = 0; i < _class_count; i++) {
 195     redefine_single_class(_class_defs[i].klass, _scratch_classes[i], thread);
 196   }
 197 
 198   // Clean out MethodData pointing to old Method*
 199   // Have to do this after all classes are redefined and all methods that
 200   // are redefined are marked as old.
 201   MethodDataCleaner clean_weak_method_links;
 202   ClassLoaderDataGraph::classes_do(&clean_weak_method_links);
 203 
 204   // Disable any dependent concurrent compilations
 205   SystemDictionary::notice_modification();
 206 
 207   // Set flag indicating that some invariants are no longer true.
 208   // See jvmtiExport.hpp for detailed explanation.
 209   JvmtiExport::set_has_redefined_a_class();
 210 
 211   // check_class() is optionally called for product bits, but is
 212   // always called for non-product bits.
 213 #ifdef PRODUCT
 214   if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
 215 #endif
 216     log_trace(redefine, class, obsolete, metadata)("calling check_class");
 217     CheckClass check_class(thread);
 218     ClassLoaderDataGraph::classes_do(&check_class);
 219 #ifdef PRODUCT
 220   }
 221 #endif
 222 }
 223 
 224 void VM_RedefineClasses::doit_epilogue() {
 225   unlock_classes();
 226 
 227   // Free os::malloc allocated memory.
 228   os::free(_scratch_classes);
 229 
 230   // Reset the_class to null for error printing.
 231   _the_class = NULL;
 232 
 233   if (log_is_enabled(Info, redefine, class, timer)) {
 234     // Used to have separate timers for "doit" and "all", but the timer
 235     // overhead skewed the measurements.
 236     jlong doit_time = _timer_rsc_phase1.milliseconds() +
 237                       _timer_rsc_phase2.milliseconds();
 238     jlong all_time = _timer_vm_op_prologue.milliseconds() + doit_time;
 239 
 240     log_info(redefine, class, timer)
 241       ("vm_op: all=" UINT64_FORMAT "  prologue=" UINT64_FORMAT "  doit=" UINT64_FORMAT,
 242        all_time, _timer_vm_op_prologue.milliseconds(), doit_time);
 243     log_info(redefine, class, timer)
 244       ("redefine_single_class: phase1=" UINT64_FORMAT "  phase2=" UINT64_FORMAT,
 245        _timer_rsc_phase1.milliseconds(), _timer_rsc_phase2.milliseconds());
 246   }
 247 }
 248 
 249 bool VM_RedefineClasses::is_modifiable_class(oop klass_mirror) {
 250   // classes for primitives cannot be redefined
 251   if (java_lang_Class::is_primitive(klass_mirror)) {
 252     return false;
 253   }
 254   Klass* k = java_lang_Class::as_Klass(klass_mirror);
 255   // classes for arrays cannot be redefined
 256   if (k == NULL || !k->is_instance_klass()) {
 257     return false;
 258   }
 259 
 260   // Cannot redefine or retransform an anonymous class.
 261   if (InstanceKlass::cast(k)->is_anonymous()) {
 262     return false;
 263   }
 264   return true;
 265 }
 266 
 267 // Append the current entry at scratch_i in scratch_cp to *merge_cp_p
 268 // where the end of *merge_cp_p is specified by *merge_cp_length_p. For
 269 // direct CP entries, there is just the current entry to append. For
 270 // indirect and double-indirect CP entries, there are zero or more
 271 // referenced CP entries along with the current entry to append.
 272 // Indirect and double-indirect CP entries are handled by recursive
 273 // calls to append_entry() as needed. The referenced CP entries are
 274 // always appended to *merge_cp_p before the referee CP entry. These
 275 // referenced CP entries may already exist in *merge_cp_p in which case
 276 // there is nothing extra to append and only the current entry is
 277 // appended.
 278 void VM_RedefineClasses::append_entry(const constantPoolHandle& scratch_cp,
 279        int scratch_i, constantPoolHandle *merge_cp_p, int *merge_cp_length_p,
 280        TRAPS) {
 281 
 282   // append is different depending on entry tag type
 283   switch (scratch_cp->tag_at(scratch_i).value()) {
 284 
 285     // The old verifier is implemented outside the VM. It loads classes,
 286     // but does not resolve constant pool entries directly so we never
 287     // see Class entries here with the old verifier. Similarly the old
 288     // verifier does not like Class entries in the input constant pool.
 289     // The split-verifier is implemented in the VM so it can optionally
 290     // and directly resolve constant pool entries to load classes. The
 291     // split-verifier can accept either Class entries or UnresolvedClass
 292     // entries in the input constant pool. We revert the appended copy
 293     // back to UnresolvedClass so that either verifier will be happy
 294     // with the constant pool entry.
 295     case JVM_CONSTANT_Class:
 296     {
 297       // revert the copy to JVM_CONSTANT_UnresolvedClass
 298       (*merge_cp_p)->unresolved_klass_at_put(*merge_cp_length_p,
 299         scratch_cp->klass_name_at(scratch_i));
 300 
 301       if (scratch_i != *merge_cp_length_p) {
 302         // The new entry in *merge_cp_p is at a different index than
 303         // the new entry in scratch_cp so we need to map the index values.
 304         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 305       }
 306       (*merge_cp_length_p)++;
 307     } break;
 308 
 309     // these are direct CP entries so they can be directly appended,
 310     // but double and long take two constant pool entries
 311     case JVM_CONSTANT_Double:  // fall through
 312     case JVM_CONSTANT_Long:
 313     {
 314       ConstantPool::copy_entry_to(scratch_cp, scratch_i, *merge_cp_p, *merge_cp_length_p,
 315         THREAD);
 316 
 317       if (scratch_i != *merge_cp_length_p) {
 318         // The new entry in *merge_cp_p is at a different index than
 319         // the new entry in scratch_cp so we need to map the index values.
 320         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 321       }
 322       (*merge_cp_length_p) += 2;
 323     } break;
 324 
 325     // these are direct CP entries so they can be directly appended
 326     case JVM_CONSTANT_Float:   // fall through
 327     case JVM_CONSTANT_Integer: // fall through
 328     case JVM_CONSTANT_Utf8:    // fall through
 329 
 330     // This was an indirect CP entry, but it has been changed into
 331     // Symbol*s so this entry can be directly appended.
 332     case JVM_CONSTANT_String:      // fall through
 333 
 334     // These were indirect CP entries, but they have been changed into
 335     // Symbol*s so these entries can be directly appended.
 336     case JVM_CONSTANT_UnresolvedClass:  // fall through
 337     {
 338       ConstantPool::copy_entry_to(scratch_cp, scratch_i, *merge_cp_p, *merge_cp_length_p,
 339         THREAD);
 340 
 341       if (scratch_i != *merge_cp_length_p) {
 342         // The new entry in *merge_cp_p is at a different index than
 343         // the new entry in scratch_cp so we need to map the index values.
 344         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 345       }
 346       (*merge_cp_length_p)++;
 347     } break;
 348 
 349     // this is an indirect CP entry so it needs special handling
 350     case JVM_CONSTANT_NameAndType:
 351     {
 352       int name_ref_i = scratch_cp->name_ref_index_at(scratch_i);
 353       int new_name_ref_i = find_or_append_indirect_entry(scratch_cp, name_ref_i, merge_cp_p,
 354                                                          merge_cp_length_p, THREAD);
 355 
 356       int signature_ref_i = scratch_cp->signature_ref_index_at(scratch_i);
 357       int new_signature_ref_i = find_or_append_indirect_entry(scratch_cp, signature_ref_i,
 358                                                               merge_cp_p, merge_cp_length_p,
 359                                                               THREAD);
 360 
 361       // If the referenced entries already exist in *merge_cp_p, then
 362       // both new_name_ref_i and new_signature_ref_i will both be 0.
 363       // In that case, all we are appending is the current entry.
 364       if (new_name_ref_i != name_ref_i) {
 365         log_trace(redefine, class, constantpool)
 366           ("NameAndType entry@%d name_ref_index change: %d to %d",
 367            *merge_cp_length_p, name_ref_i, new_name_ref_i);
 368       }
 369       if (new_signature_ref_i != signature_ref_i) {
 370         log_trace(redefine, class, constantpool)
 371           ("NameAndType entry@%d signature_ref_index change: %d to %d",
 372            *merge_cp_length_p, signature_ref_i, new_signature_ref_i);
 373       }
 374 
 375       (*merge_cp_p)->name_and_type_at_put(*merge_cp_length_p,
 376         new_name_ref_i, new_signature_ref_i);
 377       if (scratch_i != *merge_cp_length_p) {
 378         // The new entry in *merge_cp_p is at a different index than
 379         // the new entry in scratch_cp so we need to map the index values.
 380         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 381       }
 382       (*merge_cp_length_p)++;
 383     } break;
 384 
 385     // this is a double-indirect CP entry so it needs special handling
 386     case JVM_CONSTANT_Fieldref:           // fall through
 387     case JVM_CONSTANT_InterfaceMethodref: // fall through
 388     case JVM_CONSTANT_Methodref:
 389     {
 390       int klass_ref_i = scratch_cp->uncached_klass_ref_index_at(scratch_i);
 391       int new_klass_ref_i = find_or_append_indirect_entry(scratch_cp, klass_ref_i,
 392                                                           merge_cp_p, merge_cp_length_p, THREAD);
 393 
 394       int name_and_type_ref_i = scratch_cp->uncached_name_and_type_ref_index_at(scratch_i);
 395       int new_name_and_type_ref_i = find_or_append_indirect_entry(scratch_cp, name_and_type_ref_i,
 396                                                           merge_cp_p, merge_cp_length_p, THREAD);
 397 
 398       const char *entry_name = NULL;
 399       switch (scratch_cp->tag_at(scratch_i).value()) {
 400       case JVM_CONSTANT_Fieldref:
 401         entry_name = "Fieldref";
 402         (*merge_cp_p)->field_at_put(*merge_cp_length_p, new_klass_ref_i,
 403           new_name_and_type_ref_i);
 404         break;
 405       case JVM_CONSTANT_InterfaceMethodref:
 406         entry_name = "IFMethodref";
 407         (*merge_cp_p)->interface_method_at_put(*merge_cp_length_p,
 408           new_klass_ref_i, new_name_and_type_ref_i);
 409         break;
 410       case JVM_CONSTANT_Methodref:
 411         entry_name = "Methodref";
 412         (*merge_cp_p)->method_at_put(*merge_cp_length_p, new_klass_ref_i,
 413           new_name_and_type_ref_i);
 414         break;
 415       default:
 416         guarantee(false, "bad switch");
 417         break;
 418       }
 419 
 420       if (klass_ref_i != new_klass_ref_i) {
 421         log_trace(redefine, class, constantpool)
 422           ("%s entry@%d class_index changed: %d to %d", entry_name, *merge_cp_length_p, klass_ref_i, new_klass_ref_i);
 423       }
 424       if (name_and_type_ref_i != new_name_and_type_ref_i) {
 425         log_trace(redefine, class, constantpool)
 426           ("%s entry@%d name_and_type_index changed: %d to %d",
 427            entry_name, *merge_cp_length_p, name_and_type_ref_i, new_name_and_type_ref_i);
 428       }
 429 
 430       if (scratch_i != *merge_cp_length_p) {
 431         // The new entry in *merge_cp_p is at a different index than
 432         // the new entry in scratch_cp so we need to map the index values.
 433         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 434       }
 435       (*merge_cp_length_p)++;
 436     } break;
 437 
 438     // this is an indirect CP entry so it needs special handling
 439     case JVM_CONSTANT_MethodType:
 440     {
 441       int ref_i = scratch_cp->method_type_index_at(scratch_i);
 442       int new_ref_i = find_or_append_indirect_entry(scratch_cp, ref_i, merge_cp_p,
 443                                                     merge_cp_length_p, THREAD);
 444       if (new_ref_i != ref_i) {
 445         log_trace(redefine, class, constantpool)
 446           ("MethodType entry@%d ref_index change: %d to %d", *merge_cp_length_p, ref_i, new_ref_i);
 447       }
 448       (*merge_cp_p)->method_type_index_at_put(*merge_cp_length_p, new_ref_i);
 449       if (scratch_i != *merge_cp_length_p) {
 450         // The new entry in *merge_cp_p is at a different index than
 451         // the new entry in scratch_cp so we need to map the index values.
 452         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 453       }
 454       (*merge_cp_length_p)++;
 455     } break;
 456 
 457     // this is an indirect CP entry so it needs special handling
 458     case JVM_CONSTANT_MethodHandle:
 459     {
 460       int ref_kind = scratch_cp->method_handle_ref_kind_at(scratch_i);
 461       int ref_i = scratch_cp->method_handle_index_at(scratch_i);
 462       int new_ref_i = find_or_append_indirect_entry(scratch_cp, ref_i, merge_cp_p,
 463                                                     merge_cp_length_p, THREAD);
 464       if (new_ref_i != ref_i) {
 465         log_trace(redefine, class, constantpool)
 466           ("MethodHandle entry@%d ref_index change: %d to %d", *merge_cp_length_p, ref_i, new_ref_i);
 467       }
 468       (*merge_cp_p)->method_handle_index_at_put(*merge_cp_length_p, ref_kind, new_ref_i);
 469       if (scratch_i != *merge_cp_length_p) {
 470         // The new entry in *merge_cp_p is at a different index than
 471         // the new entry in scratch_cp so we need to map the index values.
 472         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 473       }
 474       (*merge_cp_length_p)++;
 475     } break;
 476 
 477     // this is an indirect CP entry so it needs special handling
 478     case JVM_CONSTANT_InvokeDynamic:
 479     {
 480       // Index of the bootstrap specifier in the operands array
 481       int old_bs_i = scratch_cp->invoke_dynamic_bootstrap_specifier_index(scratch_i);
 482       int new_bs_i = find_or_append_operand(scratch_cp, old_bs_i, merge_cp_p,
 483                                             merge_cp_length_p, THREAD);
 484       // The bootstrap method NameAndType_info index
 485       int old_ref_i = scratch_cp->invoke_dynamic_name_and_type_ref_index_at(scratch_i);
 486       int new_ref_i = find_or_append_indirect_entry(scratch_cp, old_ref_i, merge_cp_p,
 487                                                     merge_cp_length_p, THREAD);
 488       if (new_bs_i != old_bs_i) {
 489         log_trace(redefine, class, constantpool)
 490           ("InvokeDynamic entry@%d bootstrap_method_attr_index change: %d to %d",
 491            *merge_cp_length_p, old_bs_i, new_bs_i);
 492       }
 493       if (new_ref_i != old_ref_i) {
 494         log_trace(redefine, class, constantpool)
 495           ("InvokeDynamic entry@%d name_and_type_index change: %d to %d", *merge_cp_length_p, old_ref_i, new_ref_i);
 496       }
 497 
 498       (*merge_cp_p)->invoke_dynamic_at_put(*merge_cp_length_p, new_bs_i, new_ref_i);
 499       if (scratch_i != *merge_cp_length_p) {
 500         // The new entry in *merge_cp_p is at a different index than
 501         // the new entry in scratch_cp so we need to map the index values.
 502         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 503       }
 504       (*merge_cp_length_p)++;
 505     } break;
 506 
 507     // At this stage, Class or UnresolvedClass could be here, but not
 508     // ClassIndex
 509     case JVM_CONSTANT_ClassIndex: // fall through
 510 
 511     // Invalid is used as the tag for the second constant pool entry
 512     // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
 513     // not be seen by itself.
 514     case JVM_CONSTANT_Invalid: // fall through
 515 
 516     // At this stage, String could be here, but not StringIndex
 517     case JVM_CONSTANT_StringIndex: // fall through
 518 
 519     // At this stage JVM_CONSTANT_UnresolvedClassInError should not be
 520     // here
 521     case JVM_CONSTANT_UnresolvedClassInError: // fall through
 522 
 523     default:
 524     {
 525       // leave a breadcrumb
 526       jbyte bad_value = scratch_cp->tag_at(scratch_i).value();
 527       ShouldNotReachHere();
 528     } break;
 529   } // end switch tag value
 530 } // end append_entry()
 531 
 532 
 533 int VM_RedefineClasses::find_or_append_indirect_entry(const constantPoolHandle& scratch_cp,
 534       int ref_i, constantPoolHandle *merge_cp_p, int *merge_cp_length_p, TRAPS) {
 535 
 536   int new_ref_i = ref_i;
 537   bool match = (ref_i < *merge_cp_length_p) &&
 538                scratch_cp->compare_entry_to(ref_i, *merge_cp_p, ref_i, THREAD);
 539 
 540   if (!match) {
 541     // forward reference in *merge_cp_p or not a direct match
 542     int found_i = scratch_cp->find_matching_entry(ref_i, *merge_cp_p, THREAD);
 543     if (found_i != 0) {
 544       guarantee(found_i != ref_i, "compare_entry_to() and find_matching_entry() do not agree");
 545       // Found a matching entry somewhere else in *merge_cp_p so just need a mapping entry.
 546       new_ref_i = found_i;
 547       map_index(scratch_cp, ref_i, found_i);
 548     } else {
 549       // no match found so we have to append this entry to *merge_cp_p
 550       append_entry(scratch_cp, ref_i, merge_cp_p, merge_cp_length_p, THREAD);
 551       // The above call to append_entry() can only append one entry
 552       // so the post call query of *merge_cp_length_p is only for
 553       // the sake of consistency.
 554       new_ref_i = *merge_cp_length_p - 1;
 555     }
 556   }
 557 
 558   return new_ref_i;
 559 } // end find_or_append_indirect_entry()
 560 
 561 
 562 // Append a bootstrap specifier into the merge_cp operands that is semantically equal
 563 // to the scratch_cp operands bootstrap specifier passed by the old_bs_i index.
 564 // Recursively append new merge_cp entries referenced by the new bootstrap specifier.
 565 void VM_RedefineClasses::append_operand(const constantPoolHandle& scratch_cp, int old_bs_i,
 566        constantPoolHandle *merge_cp_p, int *merge_cp_length_p, TRAPS) {
 567 
 568   int old_ref_i = scratch_cp->operand_bootstrap_method_ref_index_at(old_bs_i);
 569   int new_ref_i = find_or_append_indirect_entry(scratch_cp, old_ref_i, merge_cp_p,
 570                                                 merge_cp_length_p, THREAD);
 571   if (new_ref_i != old_ref_i) {
 572     log_trace(redefine, class, constantpool)
 573       ("operands entry@%d bootstrap method ref_index change: %d to %d", _operands_cur_length, old_ref_i, new_ref_i);
 574   }
 575 
 576   Array<u2>* merge_ops = (*merge_cp_p)->operands();
 577   int new_bs_i = _operands_cur_length;
 578   // We have _operands_cur_length == 0 when the merge_cp operands is empty yet.
 579   // However, the operand_offset_at(0) was set in the extend_operands() call.
 580   int new_base = (new_bs_i == 0) ? (*merge_cp_p)->operand_offset_at(0)
 581                                  : (*merge_cp_p)->operand_next_offset_at(new_bs_i - 1);
 582   int argc     = scratch_cp->operand_argument_count_at(old_bs_i);
 583 
 584   ConstantPool::operand_offset_at_put(merge_ops, _operands_cur_length, new_base);
 585   merge_ops->at_put(new_base++, new_ref_i);
 586   merge_ops->at_put(new_base++, argc);
 587 
 588   for (int i = 0; i < argc; i++) {
 589     int old_arg_ref_i = scratch_cp->operand_argument_index_at(old_bs_i, i);
 590     int new_arg_ref_i = find_or_append_indirect_entry(scratch_cp, old_arg_ref_i, merge_cp_p,
 591                                                       merge_cp_length_p, THREAD);
 592     merge_ops->at_put(new_base++, new_arg_ref_i);
 593     if (new_arg_ref_i != old_arg_ref_i) {
 594       log_trace(redefine, class, constantpool)
 595         ("operands entry@%d bootstrap method argument ref_index change: %d to %d",
 596          _operands_cur_length, old_arg_ref_i, new_arg_ref_i);
 597     }
 598   }
 599   if (old_bs_i != _operands_cur_length) {
 600     // The bootstrap specifier in *merge_cp_p is at a different index than
 601     // that in scratch_cp so we need to map the index values.
 602     map_operand_index(old_bs_i, new_bs_i);
 603   }
 604   _operands_cur_length++;
 605 } // end append_operand()
 606 
 607 
 608 int VM_RedefineClasses::find_or_append_operand(const constantPoolHandle& scratch_cp,
 609       int old_bs_i, constantPoolHandle *merge_cp_p, int *merge_cp_length_p, TRAPS) {
 610 
 611   int new_bs_i = old_bs_i; // bootstrap specifier index
 612   bool match = (old_bs_i < _operands_cur_length) &&
 613                scratch_cp->compare_operand_to(old_bs_i, *merge_cp_p, old_bs_i, THREAD);
 614 
 615   if (!match) {
 616     // forward reference in *merge_cp_p or not a direct match
 617     int found_i = scratch_cp->find_matching_operand(old_bs_i, *merge_cp_p,
 618                                                     _operands_cur_length, THREAD);
 619     if (found_i != -1) {
 620       guarantee(found_i != old_bs_i, "compare_operand_to() and find_matching_operand() disagree");
 621       // found a matching operand somewhere else in *merge_cp_p so just need a mapping
 622       new_bs_i = found_i;
 623       map_operand_index(old_bs_i, found_i);
 624     } else {
 625       // no match found so we have to append this bootstrap specifier to *merge_cp_p
 626       append_operand(scratch_cp, old_bs_i, merge_cp_p, merge_cp_length_p, THREAD);
 627       new_bs_i = _operands_cur_length - 1;
 628     }
 629   }
 630   return new_bs_i;
 631 } // end find_or_append_operand()
 632 
 633 
 634 void VM_RedefineClasses::finalize_operands_merge(const constantPoolHandle& merge_cp, TRAPS) {
 635   if (merge_cp->operands() == NULL) {
 636     return;
 637   }
 638   // Shrink the merge_cp operands
 639   merge_cp->shrink_operands(_operands_cur_length, CHECK);
 640 
 641   if (log_is_enabled(Trace, redefine, class, constantpool)) {
 642     // don't want to loop unless we are tracing
 643     int count = 0;
 644     for (int i = 1; i < _operands_index_map_p->length(); i++) {
 645       int value = _operands_index_map_p->at(i);
 646       if (value != -1) {
 647         log_trace(redefine, class, constantpool)("operands_index_map[%d]: old=%d new=%d", count, i, value);
 648         count++;
 649       }
 650     }
 651   }
 652   // Clean-up
 653   _operands_index_map_p = NULL;
 654   _operands_cur_length = 0;
 655   _operands_index_map_count = 0;
 656 } // end finalize_operands_merge()
 657 
 658 
 659 jvmtiError VM_RedefineClasses::compare_and_normalize_class_versions(
 660              InstanceKlass* the_class,
 661              InstanceKlass* scratch_class) {
 662   int i;
 663 
 664   // Check superclasses, or rather their names, since superclasses themselves can be
 665   // requested to replace.
 666   // Check for NULL superclass first since this might be java.lang.Object
 667   if (the_class->super() != scratch_class->super() &&
 668       (the_class->super() == NULL || scratch_class->super() == NULL ||
 669        the_class->super()->name() !=
 670        scratch_class->super()->name())) {
 671     return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED;
 672   }
 673 
 674   // Check if the number, names and order of directly implemented interfaces are the same.
 675   // I think in principle we should just check if the sets of names of directly implemented
 676   // interfaces are the same, i.e. the order of declaration (which, however, if changed in the
 677   // .java file, also changes in .class file) should not matter. However, comparing sets is
 678   // technically a bit more difficult, and, more importantly, I am not sure at present that the
 679   // order of interfaces does not matter on the implementation level, i.e. that the VM does not
 680   // rely on it somewhere.
 681   Array<Klass*>* k_interfaces = the_class->local_interfaces();
 682   Array<Klass*>* k_new_interfaces = scratch_class->local_interfaces();
 683   int n_intfs = k_interfaces->length();
 684   if (n_intfs != k_new_interfaces->length()) {
 685     return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED;
 686   }
 687   for (i = 0; i < n_intfs; i++) {
 688     if (k_interfaces->at(i)->name() !=
 689         k_new_interfaces->at(i)->name()) {
 690       return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED;
 691     }
 692   }
 693 
 694   // Check whether class is in the error init state.
 695   if (the_class->is_in_error_state()) {
 696     // TBD #5057930: special error code is needed in 1.6
 697     return JVMTI_ERROR_INVALID_CLASS;
 698   }
 699 
 700   // Check whether class modifiers are the same.
 701   jushort old_flags = (jushort) the_class->access_flags().get_flags();
 702   jushort new_flags = (jushort) scratch_class->access_flags().get_flags();
 703   if (old_flags != new_flags) {
 704     return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED;
 705   }
 706 
 707   // Check if the number, names, types and order of fields declared in these classes
 708   // are the same.
 709   JavaFieldStream old_fs(the_class);
 710   JavaFieldStream new_fs(scratch_class);
 711   for (; !old_fs.done() && !new_fs.done(); old_fs.next(), new_fs.next()) {
 712     // access
 713     old_flags = old_fs.access_flags().as_short();
 714     new_flags = new_fs.access_flags().as_short();
 715     if ((old_flags ^ new_flags) & JVM_RECOGNIZED_FIELD_MODIFIERS) {
 716       return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED;
 717     }
 718     // offset
 719     if (old_fs.offset() != new_fs.offset()) {
 720       return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED;
 721     }
 722     // name and signature
 723     Symbol* name_sym1 = the_class->constants()->symbol_at(old_fs.name_index());
 724     Symbol* sig_sym1 = the_class->constants()->symbol_at(old_fs.signature_index());
 725     Symbol* name_sym2 = scratch_class->constants()->symbol_at(new_fs.name_index());
 726     Symbol* sig_sym2 = scratch_class->constants()->symbol_at(new_fs.signature_index());
 727     if (name_sym1 != name_sym2 || sig_sym1 != sig_sym2) {
 728       return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED;
 729     }
 730   }
 731 
 732   // If both streams aren't done then we have a differing number of
 733   // fields.
 734   if (!old_fs.done() || !new_fs.done()) {
 735     return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED;
 736   }
 737 
 738   // Do a parallel walk through the old and new methods. Detect
 739   // cases where they match (exist in both), have been added in
 740   // the new methods, or have been deleted (exist only in the
 741   // old methods).  The class file parser places methods in order
 742   // by method name, but does not order overloaded methods by
 743   // signature.  In order to determine what fate befell the methods,
 744   // this code places the overloaded new methods that have matching
 745   // old methods in the same order as the old methods and places
 746   // new overloaded methods at the end of overloaded methods of
 747   // that name. The code for this order normalization is adapted
 748   // from the algorithm used in InstanceKlass::find_method().
 749   // Since we are swapping out of order entries as we find them,
 750   // we only have to search forward through the overloaded methods.
 751   // Methods which are added and have the same name as an existing
 752   // method (but different signature) will be put at the end of
 753   // the methods with that name, and the name mismatch code will
 754   // handle them.
 755   Array<Method*>* k_old_methods(the_class->methods());
 756   Array<Method*>* k_new_methods(scratch_class->methods());
 757   int n_old_methods = k_old_methods->length();
 758   int n_new_methods = k_new_methods->length();
 759   Thread* thread = Thread::current();
 760 
 761   int ni = 0;
 762   int oi = 0;
 763   while (true) {
 764     Method* k_old_method;
 765     Method* k_new_method;
 766     enum { matched, added, deleted, undetermined } method_was = undetermined;
 767 
 768     if (oi >= n_old_methods) {
 769       if (ni >= n_new_methods) {
 770         break; // we've looked at everything, done
 771       }
 772       // New method at the end
 773       k_new_method = k_new_methods->at(ni);
 774       method_was = added;
 775     } else if (ni >= n_new_methods) {
 776       // Old method, at the end, is deleted
 777       k_old_method = k_old_methods->at(oi);
 778       method_was = deleted;
 779     } else {
 780       // There are more methods in both the old and new lists
 781       k_old_method = k_old_methods->at(oi);
 782       k_new_method = k_new_methods->at(ni);
 783       if (k_old_method->name() != k_new_method->name()) {
 784         // Methods are sorted by method name, so a mismatch means added
 785         // or deleted
 786         if (k_old_method->name()->fast_compare(k_new_method->name()) > 0) {
 787           method_was = added;
 788         } else {
 789           method_was = deleted;
 790         }
 791       } else if (k_old_method->signature() == k_new_method->signature()) {
 792         // Both the name and signature match
 793         method_was = matched;
 794       } else {
 795         // The name matches, but the signature doesn't, which means we have to
 796         // search forward through the new overloaded methods.
 797         int nj;  // outside the loop for post-loop check
 798         for (nj = ni + 1; nj < n_new_methods; nj++) {
 799           Method* m = k_new_methods->at(nj);
 800           if (k_old_method->name() != m->name()) {
 801             // reached another method name so no more overloaded methods
 802             method_was = deleted;
 803             break;
 804           }
 805           if (k_old_method->signature() == m->signature()) {
 806             // found a match so swap the methods
 807             k_new_methods->at_put(ni, m);
 808             k_new_methods->at_put(nj, k_new_method);
 809             k_new_method = m;
 810             method_was = matched;
 811             break;
 812           }
 813         }
 814 
 815         if (nj >= n_new_methods) {
 816           // reached the end without a match; so method was deleted
 817           method_was = deleted;
 818         }
 819       }
 820     }
 821 
 822     switch (method_was) {
 823     case matched:
 824       // methods match, be sure modifiers do too
 825       old_flags = (jushort) k_old_method->access_flags().get_flags();
 826       new_flags = (jushort) k_new_method->access_flags().get_flags();
 827       if ((old_flags ^ new_flags) & ~(JVM_ACC_NATIVE)) {
 828         return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED;
 829       }
 830       {
 831         u2 new_num = k_new_method->method_idnum();
 832         u2 old_num = k_old_method->method_idnum();
 833         if (new_num != old_num) {
 834           Method* idnum_owner = scratch_class->method_with_idnum(old_num);
 835           if (idnum_owner != NULL) {
 836             // There is already a method assigned this idnum -- switch them
 837             // Take current and original idnum from the new_method
 838             idnum_owner->set_method_idnum(new_num);
 839             idnum_owner->set_orig_method_idnum(k_new_method->orig_method_idnum());
 840           }
 841           // Take current and original idnum from the old_method
 842           k_new_method->set_method_idnum(old_num);
 843           k_new_method->set_orig_method_idnum(k_old_method->orig_method_idnum());
 844           if (thread->has_pending_exception()) {
 845             return JVMTI_ERROR_OUT_OF_MEMORY;
 846           }
 847         }
 848       }
 849       log_trace(redefine, class, normalize)
 850         ("Method matched: new: %s [%d] == old: %s [%d]",
 851          k_new_method->name_and_sig_as_C_string(), ni, k_old_method->name_and_sig_as_C_string(), oi);
 852       // advance to next pair of methods
 853       ++oi;
 854       ++ni;
 855       break;
 856     case added:
 857       // method added, see if it is OK
 858       new_flags = (jushort) k_new_method->access_flags().get_flags();
 859       if ((new_flags & JVM_ACC_PRIVATE) == 0
 860            // hack: private should be treated as final, but alas
 861           || (new_flags & (JVM_ACC_FINAL|JVM_ACC_STATIC)) == 0
 862          ) {
 863         // new methods must be private
 864         return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_ADDED;
 865       }
 866       {
 867         u2 num = the_class->next_method_idnum();
 868         if (num == ConstMethod::UNSET_IDNUM) {
 869           // cannot add any more methods
 870           return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_ADDED;
 871         }
 872         u2 new_num = k_new_method->method_idnum();
 873         Method* idnum_owner = scratch_class->method_with_idnum(num);
 874         if (idnum_owner != NULL) {
 875           // There is already a method assigned this idnum -- switch them
 876           // Take current and original idnum from the new_method
 877           idnum_owner->set_method_idnum(new_num);
 878           idnum_owner->set_orig_method_idnum(k_new_method->orig_method_idnum());
 879         }
 880         k_new_method->set_method_idnum(num);
 881         k_new_method->set_orig_method_idnum(num);
 882         if (thread->has_pending_exception()) {
 883           return JVMTI_ERROR_OUT_OF_MEMORY;
 884         }
 885       }
 886       log_trace(redefine, class, normalize)
 887         ("Method added: new: %s [%d]", k_new_method->name_and_sig_as_C_string(), ni);
 888       ++ni; // advance to next new method
 889       break;
 890     case deleted:
 891       // method deleted, see if it is OK
 892       old_flags = (jushort) k_old_method->access_flags().get_flags();
 893       if ((old_flags & JVM_ACC_PRIVATE) == 0
 894            // hack: private should be treated as final, but alas
 895           || (old_flags & (JVM_ACC_FINAL|JVM_ACC_STATIC)) == 0
 896          ) {
 897         // deleted methods must be private
 898         return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_DELETED;
 899       }
 900       log_trace(redefine, class, normalize)
 901         ("Method deleted: old: %s [%d]", k_old_method->name_and_sig_as_C_string(), oi);
 902       ++oi; // advance to next old method
 903       break;
 904     default:
 905       ShouldNotReachHere();
 906     }
 907   }
 908 
 909   return JVMTI_ERROR_NONE;
 910 }
 911 
 912 
 913 // Find new constant pool index value for old constant pool index value
 914 // by seaching the index map. Returns zero (0) if there is no mapped
 915 // value for the old constant pool index.
 916 int VM_RedefineClasses::find_new_index(int old_index) {
 917   if (_index_map_count == 0) {
 918     // map is empty so nothing can be found
 919     return 0;
 920   }
 921 
 922   if (old_index < 1 || old_index >= _index_map_p->length()) {
 923     // The old_index is out of range so it is not mapped. This should
 924     // not happen in regular constant pool merging use, but it can
 925     // happen if a corrupt annotation is processed.
 926     return 0;
 927   }
 928 
 929   int value = _index_map_p->at(old_index);
 930   if (value == -1) {
 931     // the old_index is not mapped
 932     return 0;
 933   }
 934 
 935   return value;
 936 } // end find_new_index()
 937 
 938 
 939 // Find new bootstrap specifier index value for old bootstrap specifier index
 940 // value by seaching the index map. Returns unused index (-1) if there is
 941 // no mapped value for the old bootstrap specifier index.
 942 int VM_RedefineClasses::find_new_operand_index(int old_index) {
 943   if (_operands_index_map_count == 0) {
 944     // map is empty so nothing can be found
 945     return -1;
 946   }
 947 
 948   if (old_index == -1 || old_index >= _operands_index_map_p->length()) {
 949     // The old_index is out of range so it is not mapped.
 950     // This should not happen in regular constant pool merging use.
 951     return -1;
 952   }
 953 
 954   int value = _operands_index_map_p->at(old_index);
 955   if (value == -1) {
 956     // the old_index is not mapped
 957     return -1;
 958   }
 959 
 960   return value;
 961 } // end find_new_operand_index()
 962 
 963 
 964 // Returns true if the current mismatch is due to a resolved/unresolved
 965 // class pair. Otherwise, returns false.
 966 bool VM_RedefineClasses::is_unresolved_class_mismatch(const constantPoolHandle& cp1,
 967        int index1, const constantPoolHandle& cp2, int index2) {
 968 
 969   jbyte t1 = cp1->tag_at(index1).value();
 970   if (t1 != JVM_CONSTANT_Class && t1 != JVM_CONSTANT_UnresolvedClass) {
 971     return false;  // wrong entry type; not our special case
 972   }
 973 
 974   jbyte t2 = cp2->tag_at(index2).value();
 975   if (t2 != JVM_CONSTANT_Class && t2 != JVM_CONSTANT_UnresolvedClass) {
 976     return false;  // wrong entry type; not our special case
 977   }
 978 
 979   if (t1 == t2) {
 980     return false;  // not a mismatch; not our special case
 981   }
 982 
 983   char *s1 = cp1->klass_name_at(index1)->as_C_string();
 984   char *s2 = cp2->klass_name_at(index2)->as_C_string();
 985   if (strcmp(s1, s2) != 0) {
 986     return false;  // strings don't match; not our special case
 987   }
 988 
 989   return true;  // made it through the gauntlet; this is our special case
 990 } // end is_unresolved_class_mismatch()
 991 
 992 
 993 jvmtiError VM_RedefineClasses::load_new_class_versions(TRAPS) {
 994 
 995   // For consistency allocate memory using os::malloc wrapper.
 996   _scratch_classes = (InstanceKlass**)
 997     os::malloc(sizeof(InstanceKlass*) * _class_count, mtClass);
 998   if (_scratch_classes == NULL) {
 999     return JVMTI_ERROR_OUT_OF_MEMORY;
1000   }
1001   // Zero initialize the _scratch_classes array.
1002   for (int i = 0; i < _class_count; i++) {
1003     _scratch_classes[i] = NULL;
1004   }
1005 
1006   ResourceMark rm(THREAD);
1007 
1008   JvmtiThreadState *state = JvmtiThreadState::state_for(JavaThread::current());
1009   // state can only be NULL if the current thread is exiting which
1010   // should not happen since we're trying to do a RedefineClasses
1011   guarantee(state != NULL, "exiting thread calling load_new_class_versions");
1012   for (int i = 0; i < _class_count; i++) {
1013     // Create HandleMark so that any handles created while loading new class
1014     // versions are deleted. Constant pools are deallocated while merging
1015     // constant pools
1016     HandleMark hm(THREAD);
1017     InstanceKlass* the_class = get_ik(_class_defs[i].klass);
1018     Symbol*  the_class_sym = the_class->name();
1019 
1020     log_debug(redefine, class, load)
1021       ("loading name=%s kind=%d (avail_mem=" UINT64_FORMAT "K)",
1022        the_class->external_name(), _class_load_kind, os::available_memory() >> 10);
1023 
1024     ClassFileStream st((u1*)_class_defs[i].class_bytes,
1025                        _class_defs[i].class_byte_count,
1026                        "__VM_RedefineClasses__",
1027                        ClassFileStream::verify);
1028 
1029     // Parse the stream.
1030     Handle the_class_loader(THREAD, the_class->class_loader());
1031     Handle protection_domain(THREAD, the_class->protection_domain());
1032     // Set redefined class handle in JvmtiThreadState class.
1033     // This redefined class is sent to agent event handler for class file
1034     // load hook event.
1035     state->set_class_being_redefined(the_class, _class_load_kind);
1036 
1037     InstanceKlass* scratch_class = SystemDictionary::parse_stream(
1038                                                       the_class_sym,
1039                                                       the_class_loader,
1040                                                       protection_domain,
1041                                                       &st,
1042                                                       THREAD);
1043     // Clear class_being_redefined just to be sure.
1044     state->clear_class_being_redefined();
1045 
1046     // TODO: if this is retransform, and nothing changed we can skip it
1047 
1048     // Need to clean up allocated InstanceKlass if there's an error so assign
1049     // the result here. Caller deallocates all the scratch classes in case of
1050     // an error.
1051     _scratch_classes[i] = scratch_class;
1052 
1053     if (HAS_PENDING_EXCEPTION) {
1054       Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1055       log_info(redefine, class, load, exceptions)("parse_stream exception: '%s'", ex_name->as_C_string());
1056       CLEAR_PENDING_EXCEPTION;
1057 
1058       if (ex_name == vmSymbols::java_lang_UnsupportedClassVersionError()) {
1059         return JVMTI_ERROR_UNSUPPORTED_VERSION;
1060       } else if (ex_name == vmSymbols::java_lang_ClassFormatError()) {
1061         return JVMTI_ERROR_INVALID_CLASS_FORMAT;
1062       } else if (ex_name == vmSymbols::java_lang_ClassCircularityError()) {
1063         return JVMTI_ERROR_CIRCULAR_CLASS_DEFINITION;
1064       } else if (ex_name == vmSymbols::java_lang_NoClassDefFoundError()) {
1065         // The message will be "XXX (wrong name: YYY)"
1066         return JVMTI_ERROR_NAMES_DONT_MATCH;
1067       } else if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1068         return JVMTI_ERROR_OUT_OF_MEMORY;
1069       } else {  // Just in case more exceptions can be thrown..
1070         return JVMTI_ERROR_FAILS_VERIFICATION;
1071       }
1072     }
1073 
1074     // Ensure class is linked before redefine
1075     if (!the_class->is_linked()) {
1076       the_class->link_class(THREAD);
1077       if (HAS_PENDING_EXCEPTION) {
1078         Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1079         log_info(redefine, class, load, exceptions)("link_class exception: '%s'", ex_name->as_C_string());
1080         CLEAR_PENDING_EXCEPTION;
1081         if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1082           return JVMTI_ERROR_OUT_OF_MEMORY;
1083         } else {
1084           return JVMTI_ERROR_INTERNAL;
1085         }
1086       }
1087     }
1088 
1089     // Do the validity checks in compare_and_normalize_class_versions()
1090     // before verifying the byte codes. By doing these checks first, we
1091     // limit the number of functions that require redirection from
1092     // the_class to scratch_class. In particular, we don't have to
1093     // modify JNI GetSuperclass() and thus won't change its performance.
1094     jvmtiError res = compare_and_normalize_class_versions(the_class,
1095                        scratch_class);
1096     if (res != JVMTI_ERROR_NONE) {
1097       return res;
1098     }
1099 
1100     // verify what the caller passed us
1101     {
1102       // The bug 6214132 caused the verification to fail.
1103       // Information about the_class and scratch_class is temporarily
1104       // recorded into jvmtiThreadState. This data is used to redirect
1105       // the_class to scratch_class in the JVM_* functions called by the
1106       // verifier. Please, refer to jvmtiThreadState.hpp for the detailed
1107       // description.
1108       RedefineVerifyMark rvm(the_class, scratch_class, state);
1109       Verifier::verify(
1110         scratch_class, Verifier::ThrowException, true, THREAD);
1111     }
1112 
1113     if (HAS_PENDING_EXCEPTION) {
1114       Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1115       log_info(redefine, class, load, exceptions)("verify_byte_codes exception: '%s'", ex_name->as_C_string());
1116       CLEAR_PENDING_EXCEPTION;
1117       if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1118         return JVMTI_ERROR_OUT_OF_MEMORY;
1119       } else {
1120         // tell the caller the bytecodes are bad
1121         return JVMTI_ERROR_FAILS_VERIFICATION;
1122       }
1123     }
1124 
1125     res = merge_cp_and_rewrite(the_class, scratch_class, THREAD);
1126     if (HAS_PENDING_EXCEPTION) {
1127       Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1128       log_info(redefine, class, load, exceptions)("merge_cp_and_rewrite exception: '%s'", ex_name->as_C_string());
1129       CLEAR_PENDING_EXCEPTION;
1130       if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1131         return JVMTI_ERROR_OUT_OF_MEMORY;
1132       } else {
1133         return JVMTI_ERROR_INTERNAL;
1134       }
1135     }
1136 
1137     if (VerifyMergedCPBytecodes) {
1138       // verify what we have done during constant pool merging
1139       {
1140         RedefineVerifyMark rvm(the_class, scratch_class, state);
1141         Verifier::verify(scratch_class, Verifier::ThrowException, true, THREAD);
1142       }
1143 
1144       if (HAS_PENDING_EXCEPTION) {
1145         Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1146         log_info(redefine, class, load, exceptions)
1147           ("verify_byte_codes post merge-CP exception: '%s'", ex_name->as_C_string());
1148         CLEAR_PENDING_EXCEPTION;
1149         if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1150           return JVMTI_ERROR_OUT_OF_MEMORY;
1151         } else {
1152           // tell the caller that constant pool merging screwed up
1153           return JVMTI_ERROR_INTERNAL;
1154         }
1155       }
1156     }
1157 
1158     Rewriter::rewrite(scratch_class, THREAD);
1159     if (!HAS_PENDING_EXCEPTION) {
1160       scratch_class->link_methods(THREAD);
1161     }
1162     if (HAS_PENDING_EXCEPTION) {
1163       Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1164       log_info(redefine, class, load, exceptions)
1165         ("Rewriter::rewrite or link_methods exception: '%s'", ex_name->as_C_string());
1166       CLEAR_PENDING_EXCEPTION;
1167       if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1168         return JVMTI_ERROR_OUT_OF_MEMORY;
1169       } else {
1170         return JVMTI_ERROR_INTERNAL;
1171       }
1172     }
1173 
1174     log_debug(redefine, class, load)
1175       ("loaded name=%s (avail_mem=" UINT64_FORMAT "K)", the_class->external_name(), os::available_memory() >> 10);
1176   }
1177 
1178   return JVMTI_ERROR_NONE;
1179 }
1180 
1181 
1182 // Map old_index to new_index as needed. scratch_cp is only needed
1183 // for log calls.
1184 void VM_RedefineClasses::map_index(const constantPoolHandle& scratch_cp,
1185        int old_index, int new_index) {
1186   if (find_new_index(old_index) != 0) {
1187     // old_index is already mapped
1188     return;
1189   }
1190 
1191   if (old_index == new_index) {
1192     // no mapping is needed
1193     return;
1194   }
1195 
1196   _index_map_p->at_put(old_index, new_index);
1197   _index_map_count++;
1198 
1199   log_trace(redefine, class, constantpool)
1200     ("mapped tag %d at index %d to %d", scratch_cp->tag_at(old_index).value(), old_index, new_index);
1201 } // end map_index()
1202 
1203 
1204 // Map old_index to new_index as needed.
1205 void VM_RedefineClasses::map_operand_index(int old_index, int new_index) {
1206   if (find_new_operand_index(old_index) != -1) {
1207     // old_index is already mapped
1208     return;
1209   }
1210 
1211   if (old_index == new_index) {
1212     // no mapping is needed
1213     return;
1214   }
1215 
1216   _operands_index_map_p->at_put(old_index, new_index);
1217   _operands_index_map_count++;
1218 
1219   log_trace(redefine, class, constantpool)("mapped bootstrap specifier at index %d to %d", old_index, new_index);
1220 } // end map_index()
1221 
1222 
1223 // Merge old_cp and scratch_cp and return the results of the merge via
1224 // merge_cp_p. The number of entries in *merge_cp_p is returned via
1225 // merge_cp_length_p. The entries in old_cp occupy the same locations
1226 // in *merge_cp_p. Also creates a map of indices from entries in
1227 // scratch_cp to the corresponding entry in *merge_cp_p. Index map
1228 // entries are only created for entries in scratch_cp that occupy a
1229 // different location in *merged_cp_p.
1230 bool VM_RedefineClasses::merge_constant_pools(const constantPoolHandle& old_cp,
1231        const constantPoolHandle& scratch_cp, constantPoolHandle *merge_cp_p,
1232        int *merge_cp_length_p, TRAPS) {
1233 
1234   if (merge_cp_p == NULL) {
1235     assert(false, "caller must provide scratch constantPool");
1236     return false; // robustness
1237   }
1238   if (merge_cp_length_p == NULL) {
1239     assert(false, "caller must provide scratch CP length");
1240     return false; // robustness
1241   }
1242   // Worst case we need old_cp->length() + scratch_cp()->length(),
1243   // but the caller might be smart so make sure we have at least
1244   // the minimum.
1245   if ((*merge_cp_p)->length() < old_cp->length()) {
1246     assert(false, "merge area too small");
1247     return false; // robustness
1248   }
1249 
1250   log_info(redefine, class, constantpool)("old_cp_len=%d, scratch_cp_len=%d", old_cp->length(), scratch_cp->length());
1251 
1252   {
1253     // Pass 0:
1254     // The old_cp is copied to *merge_cp_p; this means that any code
1255     // using old_cp does not have to change. This work looks like a
1256     // perfect fit for ConstantPool*::copy_cp_to(), but we need to
1257     // handle one special case:
1258     // - revert JVM_CONSTANT_Class to JVM_CONSTANT_UnresolvedClass
1259     // This will make verification happy.
1260 
1261     int old_i;  // index into old_cp
1262 
1263     // index zero (0) is not used in constantPools
1264     for (old_i = 1; old_i < old_cp->length(); old_i++) {
1265       // leave debugging crumb
1266       jbyte old_tag = old_cp->tag_at(old_i).value();
1267       switch (old_tag) {
1268       case JVM_CONSTANT_Class:
1269       case JVM_CONSTANT_UnresolvedClass:
1270         // revert the copy to JVM_CONSTANT_UnresolvedClass
1271         // May be resolving while calling this so do the same for
1272         // JVM_CONSTANT_UnresolvedClass (klass_name_at() deals with transition)
1273         (*merge_cp_p)->unresolved_klass_at_put(old_i,
1274           old_cp->klass_name_at(old_i));
1275         break;
1276 
1277       case JVM_CONSTANT_Double:
1278       case JVM_CONSTANT_Long:
1279         // just copy the entry to *merge_cp_p, but double and long take
1280         // two constant pool entries
1281         ConstantPool::copy_entry_to(old_cp, old_i, *merge_cp_p, old_i, CHECK_0);
1282         old_i++;
1283         break;
1284 
1285       default:
1286         // just copy the entry to *merge_cp_p
1287         ConstantPool::copy_entry_to(old_cp, old_i, *merge_cp_p, old_i, CHECK_0);
1288         break;
1289       }
1290     } // end for each old_cp entry
1291 
1292     ConstantPool::copy_operands(old_cp, *merge_cp_p, CHECK_0);
1293     (*merge_cp_p)->extend_operands(scratch_cp, CHECK_0);
1294 
1295     // We don't need to sanity check that *merge_cp_length_p is within
1296     // *merge_cp_p bounds since we have the minimum on-entry check above.
1297     (*merge_cp_length_p) = old_i;
1298   }
1299 
1300   // merge_cp_len should be the same as old_cp->length() at this point
1301   // so this trace message is really a "warm-and-breathing" message.
1302   log_debug(redefine, class, constantpool)("after pass 0: merge_cp_len=%d", *merge_cp_length_p);
1303 
1304   int scratch_i;  // index into scratch_cp
1305   {
1306     // Pass 1a:
1307     // Compare scratch_cp entries to the old_cp entries that we have
1308     // already copied to *merge_cp_p. In this pass, we are eliminating
1309     // exact duplicates (matching entry at same index) so we only
1310     // compare entries in the common indice range.
1311     int increment = 1;
1312     int pass1a_length = MIN2(old_cp->length(), scratch_cp->length());
1313     for (scratch_i = 1; scratch_i < pass1a_length; scratch_i += increment) {
1314       switch (scratch_cp->tag_at(scratch_i).value()) {
1315       case JVM_CONSTANT_Double:
1316       case JVM_CONSTANT_Long:
1317         // double and long take two constant pool entries
1318         increment = 2;
1319         break;
1320 
1321       default:
1322         increment = 1;
1323         break;
1324       }
1325 
1326       bool match = scratch_cp->compare_entry_to(scratch_i, *merge_cp_p,
1327         scratch_i, CHECK_0);
1328       if (match) {
1329         // found a match at the same index so nothing more to do
1330         continue;
1331       } else if (is_unresolved_class_mismatch(scratch_cp, scratch_i,
1332                                               *merge_cp_p, scratch_i)) {
1333         // The mismatch in compare_entry_to() above is because of a
1334         // resolved versus unresolved class entry at the same index
1335         // with the same string value. Since Pass 0 reverted any
1336         // class entries to unresolved class entries in *merge_cp_p,
1337         // we go with the unresolved class entry.
1338         continue;
1339       }
1340 
1341       int found_i = scratch_cp->find_matching_entry(scratch_i, *merge_cp_p,
1342         CHECK_0);
1343       if (found_i != 0) {
1344         guarantee(found_i != scratch_i,
1345           "compare_entry_to() and find_matching_entry() do not agree");
1346 
1347         // Found a matching entry somewhere else in *merge_cp_p so
1348         // just need a mapping entry.
1349         map_index(scratch_cp, scratch_i, found_i);
1350         continue;
1351       }
1352 
1353       // The find_matching_entry() call above could fail to find a match
1354       // due to a resolved versus unresolved class or string entry situation
1355       // like we solved above with the is_unresolved_*_mismatch() calls.
1356       // However, we would have to call is_unresolved_*_mismatch() over
1357       // all of *merge_cp_p (potentially) and that doesn't seem to be
1358       // worth the time.
1359 
1360       // No match found so we have to append this entry and any unique
1361       // referenced entries to *merge_cp_p.
1362       append_entry(scratch_cp, scratch_i, merge_cp_p, merge_cp_length_p,
1363         CHECK_0);
1364     }
1365   }
1366 
1367   log_debug(redefine, class, constantpool)
1368     ("after pass 1a: merge_cp_len=%d, scratch_i=%d, index_map_len=%d",
1369      *merge_cp_length_p, scratch_i, _index_map_count);
1370 
1371   if (scratch_i < scratch_cp->length()) {
1372     // Pass 1b:
1373     // old_cp is smaller than scratch_cp so there are entries in
1374     // scratch_cp that we have not yet processed. We take care of
1375     // those now.
1376     int increment = 1;
1377     for (; scratch_i < scratch_cp->length(); scratch_i += increment) {
1378       switch (scratch_cp->tag_at(scratch_i).value()) {
1379       case JVM_CONSTANT_Double:
1380       case JVM_CONSTANT_Long:
1381         // double and long take two constant pool entries
1382         increment = 2;
1383         break;
1384 
1385       default:
1386         increment = 1;
1387         break;
1388       }
1389 
1390       int found_i =
1391         scratch_cp->find_matching_entry(scratch_i, *merge_cp_p, CHECK_0);
1392       if (found_i != 0) {
1393         // Found a matching entry somewhere else in *merge_cp_p so
1394         // just need a mapping entry.
1395         map_index(scratch_cp, scratch_i, found_i);
1396         continue;
1397       }
1398 
1399       // No match found so we have to append this entry and any unique
1400       // referenced entries to *merge_cp_p.
1401       append_entry(scratch_cp, scratch_i, merge_cp_p, merge_cp_length_p,
1402         CHECK_0);
1403     }
1404 
1405     log_debug(redefine, class, constantpool)
1406       ("after pass 1b: merge_cp_len=%d, scratch_i=%d, index_map_len=%d",
1407        *merge_cp_length_p, scratch_i, _index_map_count);
1408   }
1409   finalize_operands_merge(*merge_cp_p, THREAD);
1410 
1411   return true;
1412 } // end merge_constant_pools()
1413 
1414 
1415 // Scoped object to clean up the constant pool(s) created for merging
1416 class MergeCPCleaner {
1417   ClassLoaderData*   _loader_data;
1418   ConstantPool*      _cp;
1419   ConstantPool*      _scratch_cp;
1420  public:
1421   MergeCPCleaner(ClassLoaderData* loader_data, ConstantPool* merge_cp) :
1422                  _loader_data(loader_data), _cp(merge_cp), _scratch_cp(NULL) {}
1423   ~MergeCPCleaner() {
1424     _loader_data->add_to_deallocate_list(_cp);
1425     if (_scratch_cp != NULL) {
1426       _loader_data->add_to_deallocate_list(_scratch_cp);
1427     }
1428   }
1429   void add_scratch_cp(ConstantPool* scratch_cp) { _scratch_cp = scratch_cp; }
1430 };
1431 
1432 // Merge constant pools between the_class and scratch_class and
1433 // potentially rewrite bytecodes in scratch_class to use the merged
1434 // constant pool.
1435 jvmtiError VM_RedefineClasses::merge_cp_and_rewrite(
1436              InstanceKlass* the_class, InstanceKlass* scratch_class,
1437              TRAPS) {
1438   // worst case merged constant pool length is old and new combined
1439   int merge_cp_length = the_class->constants()->length()
1440         + scratch_class->constants()->length();
1441 
1442   // Constant pools are not easily reused so we allocate a new one
1443   // each time.
1444   // merge_cp is created unsafe for concurrent GC processing.  It
1445   // should be marked safe before discarding it. Even though
1446   // garbage,  if it crosses a card boundary, it may be scanned
1447   // in order to find the start of the first complete object on the card.
1448   ClassLoaderData* loader_data = the_class->class_loader_data();
1449   ConstantPool* merge_cp_oop =
1450     ConstantPool::allocate(loader_data,
1451                            merge_cp_length,
1452                            CHECK_(JVMTI_ERROR_OUT_OF_MEMORY));
1453   MergeCPCleaner cp_cleaner(loader_data, merge_cp_oop);
1454 
1455   HandleMark hm(THREAD);  // make sure handles are cleared before
1456                           // MergeCPCleaner clears out merge_cp_oop
1457   constantPoolHandle merge_cp(THREAD, merge_cp_oop);
1458 
1459   // Get constants() from the old class because it could have been rewritten
1460   // while we were at a safepoint allocating a new constant pool.
1461   constantPoolHandle old_cp(THREAD, the_class->constants());
1462   constantPoolHandle scratch_cp(THREAD, scratch_class->constants());
1463 
1464   // If the length changed, the class was redefined out from under us. Return
1465   // an error.
1466   if (merge_cp_length != the_class->constants()->length()
1467          + scratch_class->constants()->length()) {
1468     return JVMTI_ERROR_INTERNAL;
1469   }
1470 
1471   // Update the version number of the constant pools (may keep scratch_cp)
1472   merge_cp->increment_and_save_version(old_cp->version());
1473   scratch_cp->increment_and_save_version(old_cp->version());
1474 
1475   ResourceMark rm(THREAD);
1476   _index_map_count = 0;
1477   _index_map_p = new intArray(scratch_cp->length(), scratch_cp->length(), -1);
1478 
1479   _operands_cur_length = ConstantPool::operand_array_length(old_cp->operands());
1480   _operands_index_map_count = 0;
1481   int operands_index_map_len = ConstantPool::operand_array_length(scratch_cp->operands());
1482   _operands_index_map_p = new intArray(operands_index_map_len, operands_index_map_len, -1);
1483 
1484   // reference to the cp holder is needed for copy_operands()
1485   merge_cp->set_pool_holder(scratch_class);
1486   bool result = merge_constant_pools(old_cp, scratch_cp, &merge_cp,
1487                   &merge_cp_length, THREAD);
1488   merge_cp->set_pool_holder(NULL);
1489 
1490   if (!result) {
1491     // The merge can fail due to memory allocation failure or due
1492     // to robustness checks.
1493     return JVMTI_ERROR_INTERNAL;
1494   }
1495 
1496   log_info(redefine, class, constantpool)("merge_cp_len=%d, index_map_len=%d", merge_cp_length, _index_map_count);
1497 
1498   if (_index_map_count == 0) {
1499     // there is nothing to map between the new and merged constant pools
1500 
1501     if (old_cp->length() == scratch_cp->length()) {
1502       // The old and new constant pools are the same length and the
1503       // index map is empty. This means that the three constant pools
1504       // are equivalent (but not the same). Unfortunately, the new
1505       // constant pool has not gone through link resolution nor have
1506       // the new class bytecodes gone through constant pool cache
1507       // rewriting so we can't use the old constant pool with the new
1508       // class.
1509 
1510       // toss the merged constant pool at return
1511     } else if (old_cp->length() < scratch_cp->length()) {
1512       // The old constant pool has fewer entries than the new constant
1513       // pool and the index map is empty. This means the new constant
1514       // pool is a superset of the old constant pool. However, the old
1515       // class bytecodes have already gone through constant pool cache
1516       // rewriting so we can't use the new constant pool with the old
1517       // class.
1518 
1519       // toss the merged constant pool at return
1520     } else {
1521       // The old constant pool has more entries than the new constant
1522       // pool and the index map is empty. This means that both the old
1523       // and merged constant pools are supersets of the new constant
1524       // pool.
1525 
1526       // Replace the new constant pool with a shrunken copy of the
1527       // merged constant pool
1528       set_new_constant_pool(loader_data, scratch_class, merge_cp, merge_cp_length,
1529                             CHECK_(JVMTI_ERROR_OUT_OF_MEMORY));
1530       // The new constant pool replaces scratch_cp so have cleaner clean it up.
1531       // It can't be cleaned up while there are handles to it.
1532       cp_cleaner.add_scratch_cp(scratch_cp());
1533     }
1534   } else {
1535     if (log_is_enabled(Trace, redefine, class, constantpool)) {
1536       // don't want to loop unless we are tracing
1537       int count = 0;
1538       for (int i = 1; i < _index_map_p->length(); i++) {
1539         int value = _index_map_p->at(i);
1540 
1541         if (value != -1) {
1542           log_trace(redefine, class, constantpool)("index_map[%d]: old=%d new=%d", count, i, value);
1543           count++;
1544         }
1545       }
1546     }
1547 
1548     // We have entries mapped between the new and merged constant pools
1549     // so we have to rewrite some constant pool references.
1550     if (!rewrite_cp_refs(scratch_class, THREAD)) {
1551       return JVMTI_ERROR_INTERNAL;
1552     }
1553 
1554     // Replace the new constant pool with a shrunken copy of the
1555     // merged constant pool so now the rewritten bytecodes have
1556     // valid references; the previous new constant pool will get
1557     // GCed.
1558     set_new_constant_pool(loader_data, scratch_class, merge_cp, merge_cp_length,
1559                           CHECK_(JVMTI_ERROR_OUT_OF_MEMORY));
1560     // The new constant pool replaces scratch_cp so have cleaner clean it up.
1561     // It can't be cleaned up while there are handles to it.
1562     cp_cleaner.add_scratch_cp(scratch_cp());
1563   }
1564 
1565   return JVMTI_ERROR_NONE;
1566 } // end merge_cp_and_rewrite()
1567 
1568 
1569 // Rewrite constant pool references in klass scratch_class.
1570 bool VM_RedefineClasses::rewrite_cp_refs(InstanceKlass* scratch_class,
1571        TRAPS) {
1572 
1573   // rewrite constant pool references in the methods:
1574   if (!rewrite_cp_refs_in_methods(scratch_class, THREAD)) {
1575     // propagate failure back to caller
1576     return false;
1577   }
1578 
1579   // rewrite constant pool references in the class_annotations:
1580   if (!rewrite_cp_refs_in_class_annotations(scratch_class, THREAD)) {
1581     // propagate failure back to caller
1582     return false;
1583   }
1584 
1585   // rewrite constant pool references in the fields_annotations:
1586   if (!rewrite_cp_refs_in_fields_annotations(scratch_class, THREAD)) {
1587     // propagate failure back to caller
1588     return false;
1589   }
1590 
1591   // rewrite constant pool references in the methods_annotations:
1592   if (!rewrite_cp_refs_in_methods_annotations(scratch_class, THREAD)) {
1593     // propagate failure back to caller
1594     return false;
1595   }
1596 
1597   // rewrite constant pool references in the methods_parameter_annotations:
1598   if (!rewrite_cp_refs_in_methods_parameter_annotations(scratch_class,
1599          THREAD)) {
1600     // propagate failure back to caller
1601     return false;
1602   }
1603 
1604   // rewrite constant pool references in the methods_default_annotations:
1605   if (!rewrite_cp_refs_in_methods_default_annotations(scratch_class,
1606          THREAD)) {
1607     // propagate failure back to caller
1608     return false;
1609   }
1610 
1611   // rewrite constant pool references in the class_type_annotations:
1612   if (!rewrite_cp_refs_in_class_type_annotations(scratch_class, THREAD)) {
1613     // propagate failure back to caller
1614     return false;
1615   }
1616 
1617   // rewrite constant pool references in the fields_type_annotations:
1618   if (!rewrite_cp_refs_in_fields_type_annotations(scratch_class, THREAD)) {
1619     // propagate failure back to caller
1620     return false;
1621   }
1622 
1623   // rewrite constant pool references in the methods_type_annotations:
1624   if (!rewrite_cp_refs_in_methods_type_annotations(scratch_class, THREAD)) {
1625     // propagate failure back to caller
1626     return false;
1627   }
1628 
1629   // There can be type annotations in the Code part of a method_info attribute.
1630   // These annotations are not accessible, even by reflection.
1631   // Currently they are not even parsed by the ClassFileParser.
1632   // If runtime access is added they will also need to be rewritten.
1633 
1634   // rewrite source file name index:
1635   u2 source_file_name_idx = scratch_class->source_file_name_index();
1636   if (source_file_name_idx != 0) {
1637     u2 new_source_file_name_idx = find_new_index(source_file_name_idx);
1638     if (new_source_file_name_idx != 0) {
1639       scratch_class->set_source_file_name_index(new_source_file_name_idx);
1640     }
1641   }
1642 
1643   // rewrite class generic signature index:
1644   u2 generic_signature_index = scratch_class->generic_signature_index();
1645   if (generic_signature_index != 0) {
1646     u2 new_generic_signature_index = find_new_index(generic_signature_index);
1647     if (new_generic_signature_index != 0) {
1648       scratch_class->set_generic_signature_index(new_generic_signature_index);
1649     }
1650   }
1651 
1652   return true;
1653 } // end rewrite_cp_refs()
1654 
1655 // Rewrite constant pool references in the methods.
1656 bool VM_RedefineClasses::rewrite_cp_refs_in_methods(
1657        InstanceKlass* scratch_class, TRAPS) {
1658 
1659   Array<Method*>* methods = scratch_class->methods();
1660 
1661   if (methods == NULL || methods->length() == 0) {
1662     // no methods so nothing to do
1663     return true;
1664   }
1665 
1666   // rewrite constant pool references in the methods:
1667   for (int i = methods->length() - 1; i >= 0; i--) {
1668     methodHandle method(THREAD, methods->at(i));
1669     methodHandle new_method;
1670     rewrite_cp_refs_in_method(method, &new_method, THREAD);
1671     if (!new_method.is_null()) {
1672       // the method has been replaced so save the new method version
1673       // even in the case of an exception.  original method is on the
1674       // deallocation list.
1675       methods->at_put(i, new_method());
1676     }
1677     if (HAS_PENDING_EXCEPTION) {
1678       Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1679       log_info(redefine, class, load, exceptions)("rewrite_cp_refs_in_method exception: '%s'", ex_name->as_C_string());
1680       // Need to clear pending exception here as the super caller sets
1681       // the JVMTI_ERROR_INTERNAL if the returned value is false.
1682       CLEAR_PENDING_EXCEPTION;
1683       return false;
1684     }
1685   }
1686 
1687   return true;
1688 }
1689 
1690 
1691 // Rewrite constant pool references in the specific method. This code
1692 // was adapted from Rewriter::rewrite_method().
1693 void VM_RedefineClasses::rewrite_cp_refs_in_method(methodHandle method,
1694        methodHandle *new_method_p, TRAPS) {
1695 
1696   *new_method_p = methodHandle();  // default is no new method
1697 
1698   // We cache a pointer to the bytecodes here in code_base. If GC
1699   // moves the Method*, then the bytecodes will also move which
1700   // will likely cause a crash. We create a NoSafepointVerifier
1701   // object to detect whether we pass a possible safepoint in this
1702   // code block.
1703   NoSafepointVerifier nsv;
1704 
1705   // Bytecodes and their length
1706   address code_base = method->code_base();
1707   int code_length = method->code_size();
1708 
1709   int bc_length;
1710   for (int bci = 0; bci < code_length; bci += bc_length) {
1711     address bcp = code_base + bci;
1712     Bytecodes::Code c = (Bytecodes::Code)(*bcp);
1713 
1714     bc_length = Bytecodes::length_for(c);
1715     if (bc_length == 0) {
1716       // More complicated bytecodes report a length of zero so
1717       // we have to try again a slightly different way.
1718       bc_length = Bytecodes::length_at(method(), bcp);
1719     }
1720 
1721     assert(bc_length != 0, "impossible bytecode length");
1722 
1723     switch (c) {
1724       case Bytecodes::_ldc:
1725       {
1726         int cp_index = *(bcp + 1);
1727         int new_index = find_new_index(cp_index);
1728 
1729         if (StressLdcRewrite && new_index == 0) {
1730           // If we are stressing ldc -> ldc_w rewriting, then we
1731           // always need a new_index value.
1732           new_index = cp_index;
1733         }
1734         if (new_index != 0) {
1735           // the original index is mapped so we have more work to do
1736           if (!StressLdcRewrite && new_index <= max_jubyte) {
1737             // The new value can still use ldc instead of ldc_w
1738             // unless we are trying to stress ldc -> ldc_w rewriting
1739             log_trace(redefine, class, constantpool)
1740               ("%s@" INTPTR_FORMAT " old=%d, new=%d", Bytecodes::name(c), p2i(bcp), cp_index, new_index);
1741             *(bcp + 1) = new_index;
1742           } else {
1743             log_trace(redefine, class, constantpool)
1744               ("%s->ldc_w@" INTPTR_FORMAT " old=%d, new=%d", Bytecodes::name(c), p2i(bcp), cp_index, new_index);
1745             // the new value needs ldc_w instead of ldc
1746             u_char inst_buffer[4]; // max instruction size is 4 bytes
1747             bcp = (address)inst_buffer;
1748             // construct new instruction sequence
1749             *bcp = Bytecodes::_ldc_w;
1750             bcp++;
1751             // Rewriter::rewrite_method() does not rewrite ldc -> ldc_w.
1752             // See comment below for difference between put_Java_u2()
1753             // and put_native_u2().
1754             Bytes::put_Java_u2(bcp, new_index);
1755 
1756             Relocator rc(method, NULL /* no RelocatorListener needed */);
1757             methodHandle m;
1758             {
1759               PauseNoSafepointVerifier pnsv(&nsv);
1760 
1761               // ldc is 2 bytes and ldc_w is 3 bytes
1762               m = rc.insert_space_at(bci, 3, inst_buffer, CHECK);
1763             }
1764 
1765             // return the new method so that the caller can update
1766             // the containing class
1767             *new_method_p = method = m;
1768             // switch our bytecode processing loop from the old method
1769             // to the new method
1770             code_base = method->code_base();
1771             code_length = method->code_size();
1772             bcp = code_base + bci;
1773             c = (Bytecodes::Code)(*bcp);
1774             bc_length = Bytecodes::length_for(c);
1775             assert(bc_length != 0, "sanity check");
1776           } // end we need ldc_w instead of ldc
1777         } // end if there is a mapped index
1778       } break;
1779 
1780       // these bytecodes have a two-byte constant pool index
1781       case Bytecodes::_anewarray      : // fall through
1782       case Bytecodes::_checkcast      : // fall through
1783       case Bytecodes::_getfield       : // fall through
1784       case Bytecodes::_getstatic      : // fall through
1785       case Bytecodes::_instanceof     : // fall through
1786       case Bytecodes::_invokedynamic  : // fall through
1787       case Bytecodes::_invokeinterface: // fall through
1788       case Bytecodes::_invokespecial  : // fall through
1789       case Bytecodes::_invokestatic   : // fall through
1790       case Bytecodes::_invokevirtual  : // fall through
1791       case Bytecodes::_ldc_w          : // fall through
1792       case Bytecodes::_ldc2_w         : // fall through
1793       case Bytecodes::_multianewarray : // fall through
1794       case Bytecodes::_new            : // fall through
1795       case Bytecodes::_putfield       : // fall through
1796       case Bytecodes::_putstatic      :
1797       {
1798         address p = bcp + 1;
1799         int cp_index = Bytes::get_Java_u2(p);
1800         int new_index = find_new_index(cp_index);
1801         if (new_index != 0) {
1802           // the original index is mapped so update w/ new value
1803           log_trace(redefine, class, constantpool)
1804             ("%s@" INTPTR_FORMAT " old=%d, new=%d", Bytecodes::name(c),p2i(bcp), cp_index, new_index);
1805           // Rewriter::rewrite_method() uses put_native_u2() in this
1806           // situation because it is reusing the constant pool index
1807           // location for a native index into the ConstantPoolCache.
1808           // Since we are updating the constant pool index prior to
1809           // verification and ConstantPoolCache initialization, we
1810           // need to keep the new index in Java byte order.
1811           Bytes::put_Java_u2(p, new_index);
1812         }
1813       } break;
1814     }
1815   } // end for each bytecode
1816 
1817   // We also need to rewrite the parameter name indexes, if there is
1818   // method parameter data present
1819   if(method->has_method_parameters()) {
1820     const int len = method->method_parameters_length();
1821     MethodParametersElement* elem = method->method_parameters_start();
1822 
1823     for (int i = 0; i < len; i++) {
1824       const u2 cp_index = elem[i].name_cp_index;
1825       const u2 new_cp_index = find_new_index(cp_index);
1826       if (new_cp_index != 0) {
1827         elem[i].name_cp_index = new_cp_index;
1828       }
1829     }
1830   }
1831 } // end rewrite_cp_refs_in_method()
1832 
1833 
1834 // Rewrite constant pool references in the class_annotations field.
1835 bool VM_RedefineClasses::rewrite_cp_refs_in_class_annotations(
1836        InstanceKlass* scratch_class, TRAPS) {
1837 
1838   AnnotationArray* class_annotations = scratch_class->class_annotations();
1839   if (class_annotations == NULL || class_annotations->length() == 0) {
1840     // no class_annotations so nothing to do
1841     return true;
1842   }
1843 
1844   log_debug(redefine, class, annotation)("class_annotations length=%d", class_annotations->length());
1845 
1846   int byte_i = 0;  // byte index into class_annotations
1847   return rewrite_cp_refs_in_annotations_typeArray(class_annotations, byte_i,
1848            THREAD);
1849 }
1850 
1851 
1852 // Rewrite constant pool references in an annotations typeArray. This
1853 // "structure" is adapted from the RuntimeVisibleAnnotations_attribute
1854 // that is described in section 4.8.15 of the 2nd-edition of the VM spec:
1855 //
1856 // annotations_typeArray {
1857 //   u2 num_annotations;
1858 //   annotation annotations[num_annotations];
1859 // }
1860 //
1861 bool VM_RedefineClasses::rewrite_cp_refs_in_annotations_typeArray(
1862        AnnotationArray* annotations_typeArray, int &byte_i_ref, TRAPS) {
1863 
1864   if ((byte_i_ref + 2) > annotations_typeArray->length()) {
1865     // not enough room for num_annotations field
1866     log_debug(redefine, class, annotation)("length() is too small for num_annotations field");
1867     return false;
1868   }
1869 
1870   u2 num_annotations = Bytes::get_Java_u2((address)
1871                          annotations_typeArray->adr_at(byte_i_ref));
1872   byte_i_ref += 2;
1873 
1874   log_debug(redefine, class, annotation)("num_annotations=%d", num_annotations);
1875 
1876   int calc_num_annotations = 0;
1877   for (; calc_num_annotations < num_annotations; calc_num_annotations++) {
1878     if (!rewrite_cp_refs_in_annotation_struct(annotations_typeArray,
1879            byte_i_ref, THREAD)) {
1880       log_debug(redefine, class, annotation)("bad annotation_struct at %d", calc_num_annotations);
1881       // propagate failure back to caller
1882       return false;
1883     }
1884   }
1885   assert(num_annotations == calc_num_annotations, "sanity check");
1886 
1887   return true;
1888 } // end rewrite_cp_refs_in_annotations_typeArray()
1889 
1890 
1891 // Rewrite constant pool references in the annotation struct portion of
1892 // an annotations_typeArray. This "structure" is from section 4.8.15 of
1893 // the 2nd-edition of the VM spec:
1894 //
1895 // struct annotation {
1896 //   u2 type_index;
1897 //   u2 num_element_value_pairs;
1898 //   {
1899 //     u2 element_name_index;
1900 //     element_value value;
1901 //   } element_value_pairs[num_element_value_pairs];
1902 // }
1903 //
1904 bool VM_RedefineClasses::rewrite_cp_refs_in_annotation_struct(
1905        AnnotationArray* annotations_typeArray, int &byte_i_ref, TRAPS) {
1906   if ((byte_i_ref + 2 + 2) > annotations_typeArray->length()) {
1907     // not enough room for smallest annotation_struct
1908     log_debug(redefine, class, annotation)("length() is too small for annotation_struct");
1909     return false;
1910   }
1911 
1912   u2 type_index = rewrite_cp_ref_in_annotation_data(annotations_typeArray,
1913                     byte_i_ref, "type_index", THREAD);
1914 
1915   u2 num_element_value_pairs = Bytes::get_Java_u2((address)
1916                                  annotations_typeArray->adr_at(byte_i_ref));
1917   byte_i_ref += 2;
1918 
1919   log_debug(redefine, class, annotation)
1920     ("type_index=%d  num_element_value_pairs=%d", type_index, num_element_value_pairs);
1921 
1922   int calc_num_element_value_pairs = 0;
1923   for (; calc_num_element_value_pairs < num_element_value_pairs;
1924        calc_num_element_value_pairs++) {
1925     if ((byte_i_ref + 2) > annotations_typeArray->length()) {
1926       // not enough room for another element_name_index, let alone
1927       // the rest of another component
1928       log_debug(redefine, class, annotation)("length() is too small for element_name_index");
1929       return false;
1930     }
1931 
1932     u2 element_name_index = rewrite_cp_ref_in_annotation_data(
1933                               annotations_typeArray, byte_i_ref,
1934                               "element_name_index", THREAD);
1935 
1936     log_debug(redefine, class, annotation)("element_name_index=%d", element_name_index);
1937 
1938     if (!rewrite_cp_refs_in_element_value(annotations_typeArray,
1939            byte_i_ref, THREAD)) {
1940       log_debug(redefine, class, annotation)("bad element_value at %d", calc_num_element_value_pairs);
1941       // propagate failure back to caller
1942       return false;
1943     }
1944   } // end for each component
1945   assert(num_element_value_pairs == calc_num_element_value_pairs,
1946     "sanity check");
1947 
1948   return true;
1949 } // end rewrite_cp_refs_in_annotation_struct()
1950 
1951 
1952 // Rewrite a constant pool reference at the current position in
1953 // annotations_typeArray if needed. Returns the original constant
1954 // pool reference if a rewrite was not needed or the new constant
1955 // pool reference if a rewrite was needed.
1956 u2 VM_RedefineClasses::rewrite_cp_ref_in_annotation_data(
1957      AnnotationArray* annotations_typeArray, int &byte_i_ref,
1958      const char * trace_mesg, TRAPS) {
1959 
1960   address cp_index_addr = (address)
1961     annotations_typeArray->adr_at(byte_i_ref);
1962   u2 old_cp_index = Bytes::get_Java_u2(cp_index_addr);
1963   u2 new_cp_index = find_new_index(old_cp_index);
1964   if (new_cp_index != 0) {
1965     log_debug(redefine, class, annotation)("mapped old %s=%d", trace_mesg, old_cp_index);
1966     Bytes::put_Java_u2(cp_index_addr, new_cp_index);
1967     old_cp_index = new_cp_index;
1968   }
1969   byte_i_ref += 2;
1970   return old_cp_index;
1971 }
1972 
1973 
1974 // Rewrite constant pool references in the element_value portion of an
1975 // annotations_typeArray. This "structure" is from section 4.8.15.1 of
1976 // the 2nd-edition of the VM spec:
1977 //
1978 // struct element_value {
1979 //   u1 tag;
1980 //   union {
1981 //     u2 const_value_index;
1982 //     {
1983 //       u2 type_name_index;
1984 //       u2 const_name_index;
1985 //     } enum_const_value;
1986 //     u2 class_info_index;
1987 //     annotation annotation_value;
1988 //     struct {
1989 //       u2 num_values;
1990 //       element_value values[num_values];
1991 //     } array_value;
1992 //   } value;
1993 // }
1994 //
1995 bool VM_RedefineClasses::rewrite_cp_refs_in_element_value(
1996        AnnotationArray* annotations_typeArray, int &byte_i_ref, TRAPS) {
1997 
1998   if ((byte_i_ref + 1) > annotations_typeArray->length()) {
1999     // not enough room for a tag let alone the rest of an element_value
2000     log_debug(redefine, class, annotation)("length() is too small for a tag");
2001     return false;
2002   }
2003 
2004   u1 tag = annotations_typeArray->at(byte_i_ref);
2005   byte_i_ref++;
2006   log_debug(redefine, class, annotation)("tag='%c'", tag);
2007 
2008   switch (tag) {
2009     // These BaseType tag values are from Table 4.2 in VM spec:
2010     case 'B':  // byte
2011     case 'C':  // char
2012     case 'D':  // double
2013     case 'F':  // float
2014     case 'I':  // int
2015     case 'J':  // long
2016     case 'S':  // short
2017     case 'Z':  // boolean
2018 
2019     // The remaining tag values are from Table 4.8 in the 2nd-edition of
2020     // the VM spec:
2021     case 's':
2022     {
2023       // For the above tag values (including the BaseType values),
2024       // value.const_value_index is right union field.
2025 
2026       if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2027         // not enough room for a const_value_index
2028         log_debug(redefine, class, annotation)("length() is too small for a const_value_index");
2029         return false;
2030       }
2031 
2032       u2 const_value_index = rewrite_cp_ref_in_annotation_data(
2033                                annotations_typeArray, byte_i_ref,
2034                                "const_value_index", THREAD);
2035 
2036       log_debug(redefine, class, annotation)("const_value_index=%d", const_value_index);
2037     } break;
2038 
2039     case 'e':
2040     {
2041       // for the above tag value, value.enum_const_value is right union field
2042 
2043       if ((byte_i_ref + 4) > annotations_typeArray->length()) {
2044         // not enough room for a enum_const_value
2045         log_debug(redefine, class, annotation)("length() is too small for a enum_const_value");
2046         return false;
2047       }
2048 
2049       u2 type_name_index = rewrite_cp_ref_in_annotation_data(
2050                              annotations_typeArray, byte_i_ref,
2051                              "type_name_index", THREAD);
2052 
2053       u2 const_name_index = rewrite_cp_ref_in_annotation_data(
2054                               annotations_typeArray, byte_i_ref,
2055                               "const_name_index", THREAD);
2056 
2057       log_debug(redefine, class, annotation)
2058         ("type_name_index=%d  const_name_index=%d", type_name_index, const_name_index);
2059     } break;
2060 
2061     case 'c':
2062     {
2063       // for the above tag value, value.class_info_index is right union field
2064 
2065       if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2066         // not enough room for a class_info_index
2067         log_debug(redefine, class, annotation)("length() is too small for a class_info_index");
2068         return false;
2069       }
2070 
2071       u2 class_info_index = rewrite_cp_ref_in_annotation_data(
2072                               annotations_typeArray, byte_i_ref,
2073                               "class_info_index", THREAD);
2074 
2075       log_debug(redefine, class, annotation)("class_info_index=%d", class_info_index);
2076     } break;
2077 
2078     case '@':
2079       // For the above tag value, value.attr_value is the right union
2080       // field. This is a nested annotation.
2081       if (!rewrite_cp_refs_in_annotation_struct(annotations_typeArray,
2082              byte_i_ref, THREAD)) {
2083         // propagate failure back to caller
2084         return false;
2085       }
2086       break;
2087 
2088     case '[':
2089     {
2090       if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2091         // not enough room for a num_values field
2092         log_debug(redefine, class, annotation)("length() is too small for a num_values field");
2093         return false;
2094       }
2095 
2096       // For the above tag value, value.array_value is the right union
2097       // field. This is an array of nested element_value.
2098       u2 num_values = Bytes::get_Java_u2((address)
2099                         annotations_typeArray->adr_at(byte_i_ref));
2100       byte_i_ref += 2;
2101       log_debug(redefine, class, annotation)("num_values=%d", num_values);
2102 
2103       int calc_num_values = 0;
2104       for (; calc_num_values < num_values; calc_num_values++) {
2105         if (!rewrite_cp_refs_in_element_value(
2106                annotations_typeArray, byte_i_ref, THREAD)) {
2107           log_debug(redefine, class, annotation)("bad nested element_value at %d", calc_num_values);
2108           // propagate failure back to caller
2109           return false;
2110         }
2111       }
2112       assert(num_values == calc_num_values, "sanity check");
2113     } break;
2114 
2115     default:
2116       log_debug(redefine, class, annotation)("bad tag=0x%x", tag);
2117       return false;
2118   } // end decode tag field
2119 
2120   return true;
2121 } // end rewrite_cp_refs_in_element_value()
2122 
2123 
2124 // Rewrite constant pool references in a fields_annotations field.
2125 bool VM_RedefineClasses::rewrite_cp_refs_in_fields_annotations(
2126        InstanceKlass* scratch_class, TRAPS) {
2127 
2128   Array<AnnotationArray*>* fields_annotations = scratch_class->fields_annotations();
2129 
2130   if (fields_annotations == NULL || fields_annotations->length() == 0) {
2131     // no fields_annotations so nothing to do
2132     return true;
2133   }
2134 
2135   log_debug(redefine, class, annotation)("fields_annotations length=%d", fields_annotations->length());
2136 
2137   for (int i = 0; i < fields_annotations->length(); i++) {
2138     AnnotationArray* field_annotations = fields_annotations->at(i);
2139     if (field_annotations == NULL || field_annotations->length() == 0) {
2140       // this field does not have any annotations so skip it
2141       continue;
2142     }
2143 
2144     int byte_i = 0;  // byte index into field_annotations
2145     if (!rewrite_cp_refs_in_annotations_typeArray(field_annotations, byte_i,
2146            THREAD)) {
2147       log_debug(redefine, class, annotation)("bad field_annotations at %d", i);
2148       // propagate failure back to caller
2149       return false;
2150     }
2151   }
2152 
2153   return true;
2154 } // end rewrite_cp_refs_in_fields_annotations()
2155 
2156 
2157 // Rewrite constant pool references in a methods_annotations field.
2158 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_annotations(
2159        InstanceKlass* scratch_class, TRAPS) {
2160 
2161   for (int i = 0; i < scratch_class->methods()->length(); i++) {
2162     Method* m = scratch_class->methods()->at(i);
2163     AnnotationArray* method_annotations = m->constMethod()->method_annotations();
2164 
2165     if (method_annotations == NULL || method_annotations->length() == 0) {
2166       // this method does not have any annotations so skip it
2167       continue;
2168     }
2169 
2170     int byte_i = 0;  // byte index into method_annotations
2171     if (!rewrite_cp_refs_in_annotations_typeArray(method_annotations, byte_i,
2172            THREAD)) {
2173       log_debug(redefine, class, annotation)("bad method_annotations at %d", i);
2174       // propagate failure back to caller
2175       return false;
2176     }
2177   }
2178 
2179   return true;
2180 } // end rewrite_cp_refs_in_methods_annotations()
2181 
2182 
2183 // Rewrite constant pool references in a methods_parameter_annotations
2184 // field. This "structure" is adapted from the
2185 // RuntimeVisibleParameterAnnotations_attribute described in section
2186 // 4.8.17 of the 2nd-edition of the VM spec:
2187 //
2188 // methods_parameter_annotations_typeArray {
2189 //   u1 num_parameters;
2190 //   {
2191 //     u2 num_annotations;
2192 //     annotation annotations[num_annotations];
2193 //   } parameter_annotations[num_parameters];
2194 // }
2195 //
2196 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_parameter_annotations(
2197        InstanceKlass* scratch_class, TRAPS) {
2198 
2199   for (int i = 0; i < scratch_class->methods()->length(); i++) {
2200     Method* m = scratch_class->methods()->at(i);
2201     AnnotationArray* method_parameter_annotations = m->constMethod()->parameter_annotations();
2202     if (method_parameter_annotations == NULL
2203         || method_parameter_annotations->length() == 0) {
2204       // this method does not have any parameter annotations so skip it
2205       continue;
2206     }
2207 
2208     if (method_parameter_annotations->length() < 1) {
2209       // not enough room for a num_parameters field
2210       log_debug(redefine, class, annotation)("length() is too small for a num_parameters field at %d", i);
2211       return false;
2212     }
2213 
2214     int byte_i = 0;  // byte index into method_parameter_annotations
2215 
2216     u1 num_parameters = method_parameter_annotations->at(byte_i);
2217     byte_i++;
2218 
2219     log_debug(redefine, class, annotation)("num_parameters=%d", num_parameters);
2220 
2221     int calc_num_parameters = 0;
2222     for (; calc_num_parameters < num_parameters; calc_num_parameters++) {
2223       if (!rewrite_cp_refs_in_annotations_typeArray(
2224              method_parameter_annotations, byte_i, THREAD)) {
2225         log_debug(redefine, class, annotation)("bad method_parameter_annotations at %d", calc_num_parameters);
2226         // propagate failure back to caller
2227         return false;
2228       }
2229     }
2230     assert(num_parameters == calc_num_parameters, "sanity check");
2231   }
2232 
2233   return true;
2234 } // end rewrite_cp_refs_in_methods_parameter_annotations()
2235 
2236 
2237 // Rewrite constant pool references in a methods_default_annotations
2238 // field. This "structure" is adapted from the AnnotationDefault_attribute
2239 // that is described in section 4.8.19 of the 2nd-edition of the VM spec:
2240 //
2241 // methods_default_annotations_typeArray {
2242 //   element_value default_value;
2243 // }
2244 //
2245 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_default_annotations(
2246        InstanceKlass* scratch_class, TRAPS) {
2247 
2248   for (int i = 0; i < scratch_class->methods()->length(); i++) {
2249     Method* m = scratch_class->methods()->at(i);
2250     AnnotationArray* method_default_annotations = m->constMethod()->default_annotations();
2251     if (method_default_annotations == NULL
2252         || method_default_annotations->length() == 0) {
2253       // this method does not have any default annotations so skip it
2254       continue;
2255     }
2256 
2257     int byte_i = 0;  // byte index into method_default_annotations
2258 
2259     if (!rewrite_cp_refs_in_element_value(
2260            method_default_annotations, byte_i, THREAD)) {
2261       log_debug(redefine, class, annotation)("bad default element_value at %d", i);
2262       // propagate failure back to caller
2263       return false;
2264     }
2265   }
2266 
2267   return true;
2268 } // end rewrite_cp_refs_in_methods_default_annotations()
2269 
2270 
2271 // Rewrite constant pool references in a class_type_annotations field.
2272 bool VM_RedefineClasses::rewrite_cp_refs_in_class_type_annotations(
2273        InstanceKlass* scratch_class, TRAPS) {
2274 
2275   AnnotationArray* class_type_annotations = scratch_class->class_type_annotations();
2276   if (class_type_annotations == NULL || class_type_annotations->length() == 0) {
2277     // no class_type_annotations so nothing to do
2278     return true;
2279   }
2280 
2281   log_debug(redefine, class, annotation)("class_type_annotations length=%d", class_type_annotations->length());
2282 
2283   int byte_i = 0;  // byte index into class_type_annotations
2284   return rewrite_cp_refs_in_type_annotations_typeArray(class_type_annotations,
2285       byte_i, "ClassFile", THREAD);
2286 } // end rewrite_cp_refs_in_class_type_annotations()
2287 
2288 
2289 // Rewrite constant pool references in a fields_type_annotations field.
2290 bool VM_RedefineClasses::rewrite_cp_refs_in_fields_type_annotations(
2291        InstanceKlass* scratch_class, TRAPS) {
2292 
2293   Array<AnnotationArray*>* fields_type_annotations = scratch_class->fields_type_annotations();
2294   if (fields_type_annotations == NULL || fields_type_annotations->length() == 0) {
2295     // no fields_type_annotations so nothing to do
2296     return true;
2297   }
2298 
2299   log_debug(redefine, class, annotation)("fields_type_annotations length=%d", fields_type_annotations->length());
2300 
2301   for (int i = 0; i < fields_type_annotations->length(); i++) {
2302     AnnotationArray* field_type_annotations = fields_type_annotations->at(i);
2303     if (field_type_annotations == NULL || field_type_annotations->length() == 0) {
2304       // this field does not have any annotations so skip it
2305       continue;
2306     }
2307 
2308     int byte_i = 0;  // byte index into field_type_annotations
2309     if (!rewrite_cp_refs_in_type_annotations_typeArray(field_type_annotations,
2310            byte_i, "field_info", THREAD)) {
2311       log_debug(redefine, class, annotation)("bad field_type_annotations at %d", i);
2312       // propagate failure back to caller
2313       return false;
2314     }
2315   }
2316 
2317   return true;
2318 } // end rewrite_cp_refs_in_fields_type_annotations()
2319 
2320 
2321 // Rewrite constant pool references in a methods_type_annotations field.
2322 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_type_annotations(
2323        InstanceKlass* scratch_class, TRAPS) {
2324 
2325   for (int i = 0; i < scratch_class->methods()->length(); i++) {
2326     Method* m = scratch_class->methods()->at(i);
2327     AnnotationArray* method_type_annotations = m->constMethod()->type_annotations();
2328 
2329     if (method_type_annotations == NULL || method_type_annotations->length() == 0) {
2330       // this method does not have any annotations so skip it
2331       continue;
2332     }
2333 
2334     log_debug(redefine, class, annotation)("methods type_annotations length=%d", method_type_annotations->length());
2335 
2336     int byte_i = 0;  // byte index into method_type_annotations
2337     if (!rewrite_cp_refs_in_type_annotations_typeArray(method_type_annotations,
2338            byte_i, "method_info", THREAD)) {
2339       log_debug(redefine, class, annotation)("bad method_type_annotations at %d", i);
2340       // propagate failure back to caller
2341       return false;
2342     }
2343   }
2344 
2345   return true;
2346 } // end rewrite_cp_refs_in_methods_type_annotations()
2347 
2348 
2349 // Rewrite constant pool references in a type_annotations
2350 // field. This "structure" is adapted from the
2351 // RuntimeVisibleTypeAnnotations_attribute described in
2352 // section 4.7.20 of the Java SE 8 Edition of the VM spec:
2353 //
2354 // type_annotations_typeArray {
2355 //   u2              num_annotations;
2356 //   type_annotation annotations[num_annotations];
2357 // }
2358 //
2359 bool VM_RedefineClasses::rewrite_cp_refs_in_type_annotations_typeArray(
2360        AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
2361        const char * location_mesg, TRAPS) {
2362 
2363   if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2364     // not enough room for num_annotations field
2365     log_debug(redefine, class, annotation)("length() is too small for num_annotations field");
2366     return false;
2367   }
2368 
2369   u2 num_annotations = Bytes::get_Java_u2((address)
2370                          type_annotations_typeArray->adr_at(byte_i_ref));
2371   byte_i_ref += 2;
2372 
2373   log_debug(redefine, class, annotation)("num_type_annotations=%d", num_annotations);
2374 
2375   int calc_num_annotations = 0;
2376   for (; calc_num_annotations < num_annotations; calc_num_annotations++) {
2377     if (!rewrite_cp_refs_in_type_annotation_struct(type_annotations_typeArray,
2378            byte_i_ref, location_mesg, THREAD)) {
2379       log_debug(redefine, class, annotation)("bad type_annotation_struct at %d", calc_num_annotations);
2380       // propagate failure back to caller
2381       return false;
2382     }
2383   }
2384   assert(num_annotations == calc_num_annotations, "sanity check");
2385 
2386   if (byte_i_ref != type_annotations_typeArray->length()) {
2387     log_debug(redefine, class, annotation)
2388       ("read wrong amount of bytes at end of processing type_annotations_typeArray (%d of %d bytes were read)",
2389        byte_i_ref, type_annotations_typeArray->length());
2390     return false;
2391   }
2392 
2393   return true;
2394 } // end rewrite_cp_refs_in_type_annotations_typeArray()
2395 
2396 
2397 // Rewrite constant pool references in a type_annotation
2398 // field. This "structure" is adapted from the
2399 // RuntimeVisibleTypeAnnotations_attribute described in
2400 // section 4.7.20 of the Java SE 8 Edition of the VM spec:
2401 //
2402 // type_annotation {
2403 //   u1 target_type;
2404 //   union {
2405 //     type_parameter_target;
2406 //     supertype_target;
2407 //     type_parameter_bound_target;
2408 //     empty_target;
2409 //     method_formal_parameter_target;
2410 //     throws_target;
2411 //     localvar_target;
2412 //     catch_target;
2413 //     offset_target;
2414 //     type_argument_target;
2415 //   } target_info;
2416 //   type_path target_path;
2417 //   annotation anno;
2418 // }
2419 //
2420 bool VM_RedefineClasses::rewrite_cp_refs_in_type_annotation_struct(
2421        AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
2422        const char * location_mesg, TRAPS) {
2423 
2424   if (!skip_type_annotation_target(type_annotations_typeArray,
2425          byte_i_ref, location_mesg, THREAD)) {
2426     return false;
2427   }
2428 
2429   if (!skip_type_annotation_type_path(type_annotations_typeArray,
2430          byte_i_ref, THREAD)) {
2431     return false;
2432   }
2433 
2434   if (!rewrite_cp_refs_in_annotation_struct(type_annotations_typeArray,
2435          byte_i_ref, THREAD)) {
2436     return false;
2437   }
2438 
2439   return true;
2440 } // end rewrite_cp_refs_in_type_annotation_struct()
2441 
2442 
2443 // Read, verify and skip over the target_type and target_info part
2444 // so that rewriting can continue in the later parts of the struct.
2445 //
2446 // u1 target_type;
2447 // union {
2448 //   type_parameter_target;
2449 //   supertype_target;
2450 //   type_parameter_bound_target;
2451 //   empty_target;
2452 //   method_formal_parameter_target;
2453 //   throws_target;
2454 //   localvar_target;
2455 //   catch_target;
2456 //   offset_target;
2457 //   type_argument_target;
2458 // } target_info;
2459 //
2460 bool VM_RedefineClasses::skip_type_annotation_target(
2461        AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
2462        const char * location_mesg, TRAPS) {
2463 
2464   if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
2465     // not enough room for a target_type let alone the rest of a type_annotation
2466     log_debug(redefine, class, annotation)("length() is too small for a target_type");
2467     return false;
2468   }
2469 
2470   u1 target_type = type_annotations_typeArray->at(byte_i_ref);
2471   byte_i_ref += 1;
2472   log_debug(redefine, class, annotation)("target_type=0x%.2x", target_type);
2473   log_debug(redefine, class, annotation)("location=%s", location_mesg);
2474 
2475   // Skip over target_info
2476   switch (target_type) {
2477     case 0x00:
2478     // kind: type parameter declaration of generic class or interface
2479     // location: ClassFile
2480     case 0x01:
2481     // kind: type parameter declaration of generic method or constructor
2482     // location: method_info
2483 
2484     {
2485       // struct:
2486       // type_parameter_target {
2487       //   u1 type_parameter_index;
2488       // }
2489       //
2490       if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
2491         log_debug(redefine, class, annotation)("length() is too small for a type_parameter_target");
2492         return false;
2493       }
2494 
2495       u1 type_parameter_index = type_annotations_typeArray->at(byte_i_ref);
2496       byte_i_ref += 1;
2497 
2498       log_debug(redefine, class, annotation)("type_parameter_target: type_parameter_index=%d", type_parameter_index);
2499     } break;
2500 
2501     case 0x10:
2502     // kind: type in extends clause of class or interface declaration
2503     //       (including the direct superclass of an anonymous class declaration),
2504     //       or in implements clause of interface declaration
2505     // location: ClassFile
2506 
2507     {
2508       // struct:
2509       // supertype_target {
2510       //   u2 supertype_index;
2511       // }
2512       //
2513       if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2514         log_debug(redefine, class, annotation)("length() is too small for a supertype_target");
2515         return false;
2516       }
2517 
2518       u2 supertype_index = Bytes::get_Java_u2((address)
2519                              type_annotations_typeArray->adr_at(byte_i_ref));
2520       byte_i_ref += 2;
2521 
2522       log_debug(redefine, class, annotation)("supertype_target: supertype_index=%d", supertype_index);
2523     } break;
2524 
2525     case 0x11:
2526     // kind: type in bound of type parameter declaration of generic class or interface
2527     // location: ClassFile
2528     case 0x12:
2529     // kind: type in bound of type parameter declaration of generic method or constructor
2530     // location: method_info
2531 
2532     {
2533       // struct:
2534       // type_parameter_bound_target {
2535       //   u1 type_parameter_index;
2536       //   u1 bound_index;
2537       // }
2538       //
2539       if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2540         log_debug(redefine, class, annotation)("length() is too small for a type_parameter_bound_target");
2541         return false;
2542       }
2543 
2544       u1 type_parameter_index = type_annotations_typeArray->at(byte_i_ref);
2545       byte_i_ref += 1;
2546       u1 bound_index = type_annotations_typeArray->at(byte_i_ref);
2547       byte_i_ref += 1;
2548 
2549       log_debug(redefine, class, annotation)
2550         ("type_parameter_bound_target: type_parameter_index=%d, bound_index=%d", type_parameter_index, bound_index);
2551     } break;
2552 
2553     case 0x13:
2554     // kind: type in field declaration
2555     // location: field_info
2556     case 0x14:
2557     // kind: return type of method, or type of newly constructed object
2558     // location: method_info
2559     case 0x15:
2560     // kind: receiver type of method or constructor
2561     // location: method_info
2562 
2563     {
2564       // struct:
2565       // empty_target {
2566       // }
2567       //
2568       log_debug(redefine, class, annotation)("empty_target");
2569     } break;
2570 
2571     case 0x16:
2572     // kind: type in formal parameter declaration of method, constructor, or lambda expression
2573     // location: method_info
2574 
2575     {
2576       // struct:
2577       // formal_parameter_target {
2578       //   u1 formal_parameter_index;
2579       // }
2580       //
2581       if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
2582         log_debug(redefine, class, annotation)("length() is too small for a formal_parameter_target");
2583         return false;
2584       }
2585 
2586       u1 formal_parameter_index = type_annotations_typeArray->at(byte_i_ref);
2587       byte_i_ref += 1;
2588 
2589       log_debug(redefine, class, annotation)
2590         ("formal_parameter_target: formal_parameter_index=%d", formal_parameter_index);
2591     } break;
2592 
2593     case 0x17:
2594     // kind: type in throws clause of method or constructor
2595     // location: method_info
2596 
2597     {
2598       // struct:
2599       // throws_target {
2600       //   u2 throws_type_index
2601       // }
2602       //
2603       if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2604         log_debug(redefine, class, annotation)("length() is too small for a throws_target");
2605         return false;
2606       }
2607 
2608       u2 throws_type_index = Bytes::get_Java_u2((address)
2609                                type_annotations_typeArray->adr_at(byte_i_ref));
2610       byte_i_ref += 2;
2611 
2612       log_debug(redefine, class, annotation)("throws_target: throws_type_index=%d", throws_type_index);
2613     } break;
2614 
2615     case 0x40:
2616     // kind: type in local variable declaration
2617     // location: Code
2618     case 0x41:
2619     // kind: type in resource variable declaration
2620     // location: Code
2621 
2622     {
2623       // struct:
2624       // localvar_target {
2625       //   u2 table_length;
2626       //   struct {
2627       //     u2 start_pc;
2628       //     u2 length;
2629       //     u2 index;
2630       //   } table[table_length];
2631       // }
2632       //
2633       if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2634         // not enough room for a table_length let alone the rest of a localvar_target
2635         log_debug(redefine, class, annotation)("length() is too small for a localvar_target table_length");
2636         return false;
2637       }
2638 
2639       u2 table_length = Bytes::get_Java_u2((address)
2640                           type_annotations_typeArray->adr_at(byte_i_ref));
2641       byte_i_ref += 2;
2642 
2643       log_debug(redefine, class, annotation)("localvar_target: table_length=%d", table_length);
2644 
2645       int table_struct_size = 2 + 2 + 2; // 3 u2 variables per table entry
2646       int table_size = table_length * table_struct_size;
2647 
2648       if ((byte_i_ref + table_size) > type_annotations_typeArray->length()) {
2649         // not enough room for a table
2650         log_debug(redefine, class, annotation)("length() is too small for a table array of length %d", table_length);
2651         return false;
2652       }
2653 
2654       // Skip over table
2655       byte_i_ref += table_size;
2656     } break;
2657 
2658     case 0x42:
2659     // kind: type in exception parameter declaration
2660     // location: Code
2661 
2662     {
2663       // struct:
2664       // catch_target {
2665       //   u2 exception_table_index;
2666       // }
2667       //
2668       if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2669         log_debug(redefine, class, annotation)("length() is too small for a catch_target");
2670         return false;
2671       }
2672 
2673       u2 exception_table_index = Bytes::get_Java_u2((address)
2674                                    type_annotations_typeArray->adr_at(byte_i_ref));
2675       byte_i_ref += 2;
2676 
2677       log_debug(redefine, class, annotation)("catch_target: exception_table_index=%d", exception_table_index);
2678     } break;
2679 
2680     case 0x43:
2681     // kind: type in instanceof expression
2682     // location: Code
2683     case 0x44:
2684     // kind: type in new expression
2685     // location: Code
2686     case 0x45:
2687     // kind: type in method reference expression using ::new
2688     // location: Code
2689     case 0x46:
2690     // kind: type in method reference expression using ::Identifier
2691     // location: Code
2692 
2693     {
2694       // struct:
2695       // offset_target {
2696       //   u2 offset;
2697       // }
2698       //
2699       if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2700         log_debug(redefine, class, annotation)("length() is too small for a offset_target");
2701         return false;
2702       }
2703 
2704       u2 offset = Bytes::get_Java_u2((address)
2705                     type_annotations_typeArray->adr_at(byte_i_ref));
2706       byte_i_ref += 2;
2707 
2708       log_debug(redefine, class, annotation)("offset_target: offset=%d", offset);
2709     } break;
2710 
2711     case 0x47:
2712     // kind: type in cast expression
2713     // location: Code
2714     case 0x48:
2715     // kind: type argument for generic constructor in new expression or
2716     //       explicit constructor invocation statement
2717     // location: Code
2718     case 0x49:
2719     // kind: type argument for generic method in method invocation expression
2720     // location: Code
2721     case 0x4A:
2722     // kind: type argument for generic constructor in method reference expression using ::new
2723     // location: Code
2724     case 0x4B:
2725     // kind: type argument for generic method in method reference expression using ::Identifier
2726     // location: Code
2727 
2728     {
2729       // struct:
2730       // type_argument_target {
2731       //   u2 offset;
2732       //   u1 type_argument_index;
2733       // }
2734       //
2735       if ((byte_i_ref + 3) > type_annotations_typeArray->length()) {
2736         log_debug(redefine, class, annotation)("length() is too small for a type_argument_target");
2737         return false;
2738       }
2739 
2740       u2 offset = Bytes::get_Java_u2((address)
2741                     type_annotations_typeArray->adr_at(byte_i_ref));
2742       byte_i_ref += 2;
2743       u1 type_argument_index = type_annotations_typeArray->at(byte_i_ref);
2744       byte_i_ref += 1;
2745 
2746       log_debug(redefine, class, annotation)
2747         ("type_argument_target: offset=%d, type_argument_index=%d", offset, type_argument_index);
2748     } break;
2749 
2750     default:
2751       log_debug(redefine, class, annotation)("unknown target_type");
2752 #ifdef ASSERT
2753       ShouldNotReachHere();
2754 #endif
2755       return false;
2756   }
2757 
2758   return true;
2759 } // end skip_type_annotation_target()
2760 
2761 
2762 // Read, verify and skip over the type_path part so that rewriting
2763 // can continue in the later parts of the struct.
2764 //
2765 // type_path {
2766 //   u1 path_length;
2767 //   {
2768 //     u1 type_path_kind;
2769 //     u1 type_argument_index;
2770 //   } path[path_length];
2771 // }
2772 //
2773 bool VM_RedefineClasses::skip_type_annotation_type_path(
2774        AnnotationArray* type_annotations_typeArray, int &byte_i_ref, TRAPS) {
2775 
2776   if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
2777     // not enough room for a path_length let alone the rest of the type_path
2778     log_debug(redefine, class, annotation)("length() is too small for a type_path");
2779     return false;
2780   }
2781 
2782   u1 path_length = type_annotations_typeArray->at(byte_i_ref);
2783   byte_i_ref += 1;
2784 
2785   log_debug(redefine, class, annotation)("type_path: path_length=%d", path_length);
2786 
2787   int calc_path_length = 0;
2788   for (; calc_path_length < path_length; calc_path_length++) {
2789     if ((byte_i_ref + 1 + 1) > type_annotations_typeArray->length()) {
2790       // not enough room for a path
2791       log_debug(redefine, class, annotation)
2792         ("length() is too small for path entry %d of %d", calc_path_length, path_length);
2793       return false;
2794     }
2795 
2796     u1 type_path_kind = type_annotations_typeArray->at(byte_i_ref);
2797     byte_i_ref += 1;
2798     u1 type_argument_index = type_annotations_typeArray->at(byte_i_ref);
2799     byte_i_ref += 1;
2800 
2801     log_debug(redefine, class, annotation)
2802       ("type_path: path[%d]: type_path_kind=%d, type_argument_index=%d",
2803        calc_path_length, type_path_kind, type_argument_index);
2804 
2805     if (type_path_kind > 3 || (type_path_kind != 3 && type_argument_index != 0)) {
2806       // not enough room for a path
2807       log_debug(redefine, class, annotation)("inconsistent type_path values");
2808       return false;
2809     }
2810   }
2811   assert(path_length == calc_path_length, "sanity check");
2812 
2813   return true;
2814 } // end skip_type_annotation_type_path()
2815 
2816 
2817 // Rewrite constant pool references in the method's stackmap table.
2818 // These "structures" are adapted from the StackMapTable_attribute that
2819 // is described in section 4.8.4 of the 6.0 version of the VM spec
2820 // (dated 2005.10.26):
2821 // file:///net/quincunx.sfbay/export/gbracha/ClassFile-Java6.pdf
2822 //
2823 // stack_map {
2824 //   u2 number_of_entries;
2825 //   stack_map_frame entries[number_of_entries];
2826 // }
2827 //
2828 void VM_RedefineClasses::rewrite_cp_refs_in_stack_map_table(
2829        const methodHandle& method, TRAPS) {
2830 
2831   if (!method->has_stackmap_table()) {
2832     return;
2833   }
2834 
2835   AnnotationArray* stackmap_data = method->stackmap_data();
2836   address stackmap_p = (address)stackmap_data->adr_at(0);
2837   address stackmap_end = stackmap_p + stackmap_data->length();
2838 
2839   assert(stackmap_p + 2 <= stackmap_end, "no room for number_of_entries");
2840   u2 number_of_entries = Bytes::get_Java_u2(stackmap_p);
2841   stackmap_p += 2;
2842 
2843   log_debug(redefine, class, stackmap)("number_of_entries=%u", number_of_entries);
2844 
2845   // walk through each stack_map_frame
2846   u2 calc_number_of_entries = 0;
2847   for (; calc_number_of_entries < number_of_entries; calc_number_of_entries++) {
2848     // The stack_map_frame structure is a u1 frame_type followed by
2849     // 0 or more bytes of data:
2850     //
2851     // union stack_map_frame {
2852     //   same_frame;
2853     //   same_locals_1_stack_item_frame;
2854     //   same_locals_1_stack_item_frame_extended;
2855     //   chop_frame;
2856     //   same_frame_extended;
2857     //   append_frame;
2858     //   full_frame;
2859     // }
2860 
2861     assert(stackmap_p + 1 <= stackmap_end, "no room for frame_type");
2862     u1 frame_type = *stackmap_p;
2863     stackmap_p++;
2864 
2865     // same_frame {
2866     //   u1 frame_type = SAME; /* 0-63 */
2867     // }
2868     if (frame_type <= 63) {
2869       // nothing more to do for same_frame
2870     }
2871 
2872     // same_locals_1_stack_item_frame {
2873     //   u1 frame_type = SAME_LOCALS_1_STACK_ITEM; /* 64-127 */
2874     //   verification_type_info stack[1];
2875     // }
2876     else if (frame_type >= 64 && frame_type <= 127) {
2877       rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
2878         calc_number_of_entries, frame_type, THREAD);
2879     }
2880 
2881     // reserved for future use
2882     else if (frame_type >= 128 && frame_type <= 246) {
2883       // nothing more to do for reserved frame_types
2884     }
2885 
2886     // same_locals_1_stack_item_frame_extended {
2887     //   u1 frame_type = SAME_LOCALS_1_STACK_ITEM_EXTENDED; /* 247 */
2888     //   u2 offset_delta;
2889     //   verification_type_info stack[1];
2890     // }
2891     else if (frame_type == 247) {
2892       stackmap_p += 2;
2893       rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
2894         calc_number_of_entries, frame_type, THREAD);
2895     }
2896 
2897     // chop_frame {
2898     //   u1 frame_type = CHOP; /* 248-250 */
2899     //   u2 offset_delta;
2900     // }
2901     else if (frame_type >= 248 && frame_type <= 250) {
2902       stackmap_p += 2;
2903     }
2904 
2905     // same_frame_extended {
2906     //   u1 frame_type = SAME_FRAME_EXTENDED; /* 251*/
2907     //   u2 offset_delta;
2908     // }
2909     else if (frame_type == 251) {
2910       stackmap_p += 2;
2911     }
2912 
2913     // append_frame {
2914     //   u1 frame_type = APPEND; /* 252-254 */
2915     //   u2 offset_delta;
2916     //   verification_type_info locals[frame_type - 251];
2917     // }
2918     else if (frame_type >= 252 && frame_type <= 254) {
2919       assert(stackmap_p + 2 <= stackmap_end,
2920         "no room for offset_delta");
2921       stackmap_p += 2;
2922       u1 len = frame_type - 251;
2923       for (u1 i = 0; i < len; i++) {
2924         rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
2925           calc_number_of_entries, frame_type, THREAD);
2926       }
2927     }
2928 
2929     // full_frame {
2930     //   u1 frame_type = FULL_FRAME; /* 255 */
2931     //   u2 offset_delta;
2932     //   u2 number_of_locals;
2933     //   verification_type_info locals[number_of_locals];
2934     //   u2 number_of_stack_items;
2935     //   verification_type_info stack[number_of_stack_items];
2936     // }
2937     else if (frame_type == 255) {
2938       assert(stackmap_p + 2 + 2 <= stackmap_end,
2939         "no room for smallest full_frame");
2940       stackmap_p += 2;
2941 
2942       u2 number_of_locals = Bytes::get_Java_u2(stackmap_p);
2943       stackmap_p += 2;
2944 
2945       for (u2 locals_i = 0; locals_i < number_of_locals; locals_i++) {
2946         rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
2947           calc_number_of_entries, frame_type, THREAD);
2948       }
2949 
2950       // Use the largest size for the number_of_stack_items, but only get
2951       // the right number of bytes.
2952       u2 number_of_stack_items = Bytes::get_Java_u2(stackmap_p);
2953       stackmap_p += 2;
2954 
2955       for (u2 stack_i = 0; stack_i < number_of_stack_items; stack_i++) {
2956         rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
2957           calc_number_of_entries, frame_type, THREAD);
2958       }
2959     }
2960   } // end while there is a stack_map_frame
2961   assert(number_of_entries == calc_number_of_entries, "sanity check");
2962 } // end rewrite_cp_refs_in_stack_map_table()
2963 
2964 
2965 // Rewrite constant pool references in the verification type info
2966 // portion of the method's stackmap table. These "structures" are
2967 // adapted from the StackMapTable_attribute that is described in
2968 // section 4.8.4 of the 6.0 version of the VM spec (dated 2005.10.26):
2969 // file:///net/quincunx.sfbay/export/gbracha/ClassFile-Java6.pdf
2970 //
2971 // The verification_type_info structure is a u1 tag followed by 0 or
2972 // more bytes of data:
2973 //
2974 // union verification_type_info {
2975 //   Top_variable_info;
2976 //   Integer_variable_info;
2977 //   Float_variable_info;
2978 //   Long_variable_info;
2979 //   Double_variable_info;
2980 //   Null_variable_info;
2981 //   UninitializedThis_variable_info;
2982 //   Object_variable_info;
2983 //   Uninitialized_variable_info;
2984 // }
2985 //
2986 void VM_RedefineClasses::rewrite_cp_refs_in_verification_type_info(
2987        address& stackmap_p_ref, address stackmap_end, u2 frame_i,
2988        u1 frame_type, TRAPS) {
2989 
2990   assert(stackmap_p_ref + 1 <= stackmap_end, "no room for tag");
2991   u1 tag = *stackmap_p_ref;
2992   stackmap_p_ref++;
2993 
2994   switch (tag) {
2995   // Top_variable_info {
2996   //   u1 tag = ITEM_Top; /* 0 */
2997   // }
2998   // verificationType.hpp has zero as ITEM_Bogus instead of ITEM_Top
2999   case 0:  // fall through
3000 
3001   // Integer_variable_info {
3002   //   u1 tag = ITEM_Integer; /* 1 */
3003   // }
3004   case ITEM_Integer:  // fall through
3005 
3006   // Float_variable_info {
3007   //   u1 tag = ITEM_Float; /* 2 */
3008   // }
3009   case ITEM_Float:  // fall through
3010 
3011   // Double_variable_info {
3012   //   u1 tag = ITEM_Double; /* 3 */
3013   // }
3014   case ITEM_Double:  // fall through
3015 
3016   // Long_variable_info {
3017   //   u1 tag = ITEM_Long; /* 4 */
3018   // }
3019   case ITEM_Long:  // fall through
3020 
3021   // Null_variable_info {
3022   //   u1 tag = ITEM_Null; /* 5 */
3023   // }
3024   case ITEM_Null:  // fall through
3025 
3026   // UninitializedThis_variable_info {
3027   //   u1 tag = ITEM_UninitializedThis; /* 6 */
3028   // }
3029   case ITEM_UninitializedThis:
3030     // nothing more to do for the above tag types
3031     break;
3032 
3033   // Object_variable_info {
3034   //   u1 tag = ITEM_Object; /* 7 */
3035   //   u2 cpool_index;
3036   // }
3037   case ITEM_Object:
3038   {
3039     assert(stackmap_p_ref + 2 <= stackmap_end, "no room for cpool_index");
3040     u2 cpool_index = Bytes::get_Java_u2(stackmap_p_ref);
3041     u2 new_cp_index = find_new_index(cpool_index);
3042     if (new_cp_index != 0) {
3043       log_debug(redefine, class, stackmap)("mapped old cpool_index=%d", cpool_index);
3044       Bytes::put_Java_u2(stackmap_p_ref, new_cp_index);
3045       cpool_index = new_cp_index;
3046     }
3047     stackmap_p_ref += 2;
3048 
3049     log_debug(redefine, class, stackmap)
3050       ("frame_i=%u, frame_type=%u, cpool_index=%d", frame_i, frame_type, cpool_index);
3051   } break;
3052 
3053   // Uninitialized_variable_info {
3054   //   u1 tag = ITEM_Uninitialized; /* 8 */
3055   //   u2 offset;
3056   // }
3057   case ITEM_Uninitialized:
3058     assert(stackmap_p_ref + 2 <= stackmap_end, "no room for offset");
3059     stackmap_p_ref += 2;
3060     break;
3061 
3062   default:
3063     log_debug(redefine, class, stackmap)("frame_i=%u, frame_type=%u, bad tag=0x%x", frame_i, frame_type, tag);
3064     ShouldNotReachHere();
3065     break;
3066   } // end switch (tag)
3067 } // end rewrite_cp_refs_in_verification_type_info()
3068 
3069 
3070 // Change the constant pool associated with klass scratch_class to
3071 // scratch_cp. If shrink is true, then scratch_cp_length elements
3072 // are copied from scratch_cp to a smaller constant pool and the
3073 // smaller constant pool is associated with scratch_class.
3074 void VM_RedefineClasses::set_new_constant_pool(
3075        ClassLoaderData* loader_data,
3076        InstanceKlass* scratch_class, constantPoolHandle scratch_cp,
3077        int scratch_cp_length, TRAPS) {
3078   assert(scratch_cp->length() >= scratch_cp_length, "sanity check");
3079 
3080   // scratch_cp is a merged constant pool and has enough space for a
3081   // worst case merge situation. We want to associate the minimum
3082   // sized constant pool with the klass to save space.
3083   ConstantPool* cp = ConstantPool::allocate(loader_data, scratch_cp_length, CHECK);
3084   constantPoolHandle smaller_cp(THREAD, cp);
3085 
3086   // preserve version() value in the smaller copy
3087   int version = scratch_cp->version();
3088   assert(version != 0, "sanity check");
3089   smaller_cp->set_version(version);
3090 
3091   // attach klass to new constant pool
3092   // reference to the cp holder is needed for copy_operands()
3093   smaller_cp->set_pool_holder(scratch_class);
3094 
3095   scratch_cp->copy_cp_to(1, scratch_cp_length - 1, smaller_cp, 1, THREAD);
3096   if (HAS_PENDING_EXCEPTION) {
3097     // Exception is handled in the caller
3098     loader_data->add_to_deallocate_list(smaller_cp());
3099     return;
3100   }
3101   scratch_cp = smaller_cp;
3102 
3103   // attach new constant pool to klass
3104   scratch_class->set_constants(scratch_cp());
3105 
3106   int i;  // for portability
3107 
3108   // update each field in klass to use new constant pool indices as needed
3109   for (JavaFieldStream fs(scratch_class); !fs.done(); fs.next()) {
3110     jshort cur_index = fs.name_index();
3111     jshort new_index = find_new_index(cur_index);
3112     if (new_index != 0) {
3113       log_trace(redefine, class, constantpool)("field-name_index change: %d to %d", cur_index, new_index);
3114       fs.set_name_index(new_index);
3115     }
3116     cur_index = fs.signature_index();
3117     new_index = find_new_index(cur_index);
3118     if (new_index != 0) {
3119       log_trace(redefine, class, constantpool)("field-signature_index change: %d to %d", cur_index, new_index);
3120       fs.set_signature_index(new_index);
3121     }
3122     cur_index = fs.initval_index();
3123     new_index = find_new_index(cur_index);
3124     if (new_index != 0) {
3125       log_trace(redefine, class, constantpool)("field-initval_index change: %d to %d", cur_index, new_index);
3126       fs.set_initval_index(new_index);
3127     }
3128     cur_index = fs.generic_signature_index();
3129     new_index = find_new_index(cur_index);
3130     if (new_index != 0) {
3131       log_trace(redefine, class, constantpool)("field-generic_signature change: %d to %d", cur_index, new_index);
3132       fs.set_generic_signature_index(new_index);
3133     }
3134   } // end for each field
3135 
3136   // Update constant pool indices in the inner classes info to use
3137   // new constant indices as needed. The inner classes info is a
3138   // quadruple:
3139   // (inner_class_info, outer_class_info, inner_name, inner_access_flags)
3140   InnerClassesIterator iter(scratch_class);
3141   for (; !iter.done(); iter.next()) {
3142     int cur_index = iter.inner_class_info_index();
3143     if (cur_index == 0) {
3144       continue;  // JVM spec. allows null inner class refs so skip it
3145     }
3146     int new_index = find_new_index(cur_index);
3147     if (new_index != 0) {
3148       log_trace(redefine, class, constantpool)("inner_class_info change: %d to %d", cur_index, new_index);
3149       iter.set_inner_class_info_index(new_index);
3150     }
3151     cur_index = iter.outer_class_info_index();
3152     new_index = find_new_index(cur_index);
3153     if (new_index != 0) {
3154       log_trace(redefine, class, constantpool)("outer_class_info change: %d to %d", cur_index, new_index);
3155       iter.set_outer_class_info_index(new_index);
3156     }
3157     cur_index = iter.inner_name_index();
3158     new_index = find_new_index(cur_index);
3159     if (new_index != 0) {
3160       log_trace(redefine, class, constantpool)("inner_name change: %d to %d", cur_index, new_index);
3161       iter.set_inner_name_index(new_index);
3162     }
3163   } // end for each inner class
3164 
3165   // Attach each method in klass to the new constant pool and update
3166   // to use new constant pool indices as needed:
3167   Array<Method*>* methods = scratch_class->methods();
3168   for (i = methods->length() - 1; i >= 0; i--) {
3169     methodHandle method(THREAD, methods->at(i));
3170     method->set_constants(scratch_cp());
3171 
3172     int new_index = find_new_index(method->name_index());
3173     if (new_index != 0) {
3174       log_trace(redefine, class, constantpool)
3175         ("method-name_index change: %d to %d", method->name_index(), new_index);
3176       method->set_name_index(new_index);
3177     }
3178     new_index = find_new_index(method->signature_index());
3179     if (new_index != 0) {
3180       log_trace(redefine, class, constantpool)
3181         ("method-signature_index change: %d to %d", method->signature_index(), new_index);
3182       method->set_signature_index(new_index);
3183     }
3184     new_index = find_new_index(method->generic_signature_index());
3185     if (new_index != 0) {
3186       log_trace(redefine, class, constantpool)
3187         ("method-generic_signature_index change: %d to %d", method->generic_signature_index(), new_index);
3188       method->set_generic_signature_index(new_index);
3189     }
3190 
3191     // Update constant pool indices in the method's checked exception
3192     // table to use new constant indices as needed.
3193     int cext_length = method->checked_exceptions_length();
3194     if (cext_length > 0) {
3195       CheckedExceptionElement * cext_table =
3196         method->checked_exceptions_start();
3197       for (int j = 0; j < cext_length; j++) {
3198         int cur_index = cext_table[j].class_cp_index;
3199         int new_index = find_new_index(cur_index);
3200         if (new_index != 0) {
3201           log_trace(redefine, class, constantpool)("cext-class_cp_index change: %d to %d", cur_index, new_index);
3202           cext_table[j].class_cp_index = (u2)new_index;
3203         }
3204       } // end for each checked exception table entry
3205     } // end if there are checked exception table entries
3206 
3207     // Update each catch type index in the method's exception table
3208     // to use new constant pool indices as needed. The exception table
3209     // holds quadruple entries of the form:
3210     //   (beg_bci, end_bci, handler_bci, klass_index)
3211 
3212     ExceptionTable ex_table(method());
3213     int ext_length = ex_table.length();
3214 
3215     for (int j = 0; j < ext_length; j ++) {
3216       int cur_index = ex_table.catch_type_index(j);
3217       int new_index = find_new_index(cur_index);
3218       if (new_index != 0) {
3219         log_trace(redefine, class, constantpool)("ext-klass_index change: %d to %d", cur_index, new_index);
3220         ex_table.set_catch_type_index(j, new_index);
3221       }
3222     } // end for each exception table entry
3223 
3224     // Update constant pool indices in the method's local variable
3225     // table to use new constant indices as needed. The local variable
3226     // table hold sextuple entries of the form:
3227     // (start_pc, length, name_index, descriptor_index, signature_index, slot)
3228     int lvt_length = method->localvariable_table_length();
3229     if (lvt_length > 0) {
3230       LocalVariableTableElement * lv_table =
3231         method->localvariable_table_start();
3232       for (int j = 0; j < lvt_length; j++) {
3233         int cur_index = lv_table[j].name_cp_index;
3234         int new_index = find_new_index(cur_index);
3235         if (new_index != 0) {
3236           log_trace(redefine, class, constantpool)("lvt-name_cp_index change: %d to %d", cur_index, new_index);
3237           lv_table[j].name_cp_index = (u2)new_index;
3238         }
3239         cur_index = lv_table[j].descriptor_cp_index;
3240         new_index = find_new_index(cur_index);
3241         if (new_index != 0) {
3242           log_trace(redefine, class, constantpool)("lvt-descriptor_cp_index change: %d to %d", cur_index, new_index);
3243           lv_table[j].descriptor_cp_index = (u2)new_index;
3244         }
3245         cur_index = lv_table[j].signature_cp_index;
3246         new_index = find_new_index(cur_index);
3247         if (new_index != 0) {
3248           log_trace(redefine, class, constantpool)("lvt-signature_cp_index change: %d to %d", cur_index, new_index);
3249           lv_table[j].signature_cp_index = (u2)new_index;
3250         }
3251       } // end for each local variable table entry
3252     } // end if there are local variable table entries
3253 
3254     rewrite_cp_refs_in_stack_map_table(method, THREAD);
3255   } // end for each method
3256 } // end set_new_constant_pool()
3257 
3258 
3259 // Unevolving classes may point to methods of the_class directly
3260 // from their constant pool caches, itables, and/or vtables. We
3261 // use the ClassLoaderDataGraph::classes_do() facility and this helper
3262 // to fix up these pointers.
3263 
3264 // Adjust cpools and vtables closure
3265 void VM_RedefineClasses::AdjustCpoolCacheAndVtable::do_klass(Klass* k) {
3266 
3267   // This is a very busy routine. We don't want too much tracing
3268   // printed out.
3269   bool trace_name_printed = false;
3270   InstanceKlass *the_class = InstanceKlass::cast(_the_class);
3271 
3272   // If the class being redefined is java.lang.Object, we need to fix all
3273   // array class vtables also
3274   if (k->is_array_klass() && _the_class == SystemDictionary::Object_klass()) {
3275     k->vtable()->adjust_method_entries(the_class, &trace_name_printed);
3276 
3277   } else if (k->is_instance_klass()) {
3278     HandleMark hm(_thread);
3279     InstanceKlass *ik = InstanceKlass::cast(k);
3280 
3281     // HotSpot specific optimization! HotSpot does not currently
3282     // support delegation from the bootstrap class loader to a
3283     // user-defined class loader. This means that if the bootstrap
3284     // class loader is the initiating class loader, then it will also
3285     // be the defining class loader. This also means that classes
3286     // loaded by the bootstrap class loader cannot refer to classes
3287     // loaded by a user-defined class loader. Note: a user-defined
3288     // class loader can delegate to the bootstrap class loader.
3289     //
3290     // If the current class being redefined has a user-defined class
3291     // loader as its defining class loader, then we can skip all
3292     // classes loaded by the bootstrap class loader.
3293     bool is_user_defined = (_the_class->class_loader() != NULL);
3294     if (is_user_defined && ik->class_loader() == NULL) {
3295       return;
3296     }
3297 
3298     // Fix the vtable embedded in the_class and subclasses of the_class,
3299     // if one exists. We discard scratch_class and we don't keep an
3300     // InstanceKlass around to hold obsolete methods so we don't have
3301     // any other InstanceKlass embedded vtables to update. The vtable
3302     // holds the Method*s for virtual (but not final) methods.
3303     // Default methods, or concrete methods in interfaces are stored
3304     // in the vtable, so if an interface changes we need to check
3305     // adjust_method_entries() for every InstanceKlass, which will also
3306     // adjust the default method vtable indices.
3307     // We also need to adjust any default method entries that are
3308     // not yet in the vtable, because the vtable setup is in progress.
3309     // This must be done after we adjust the default_methods and
3310     // default_vtable_indices for methods already in the vtable.
3311     // If redefining Unsafe, walk all the vtables looking for entries.
3312     if (ik->vtable_length() > 0 && (_the_class->is_interface()
3313         || _the_class == SystemDictionary::internal_Unsafe_klass()
3314         || ik->is_subtype_of(_the_class))) {
3315       // ik->vtable() creates a wrapper object; rm cleans it up
3316       ResourceMark rm(_thread);
3317 
3318       ik->vtable()->adjust_method_entries(the_class, &trace_name_printed);
3319       ik->adjust_default_methods(the_class, &trace_name_printed);
3320     }
3321 
3322     // If the current class has an itable and we are either redefining an
3323     // interface or if the current class is a subclass of the_class, then
3324     // we potentially have to fix the itable. If we are redefining an
3325     // interface, then we have to call adjust_method_entries() for
3326     // every InstanceKlass that has an itable since there isn't a
3327     // subclass relationship between an interface and an InstanceKlass.
3328     // If redefining Unsafe, walk all the itables looking for entries.
3329     if (ik->itable_length() > 0 && (_the_class->is_interface()
3330         || _the_class == SystemDictionary::internal_Unsafe_klass()
3331         || ik->is_subclass_of(_the_class))) {
3332       // ik->itable() creates a wrapper object; rm cleans it up
3333       ResourceMark rm(_thread);
3334 
3335       ik->itable()->adjust_method_entries(the_class, &trace_name_printed);
3336     }
3337 
3338     // The constant pools in other classes (other_cp) can refer to
3339     // methods in the_class. We have to update method information in
3340     // other_cp's cache. If other_cp has a previous version, then we
3341     // have to repeat the process for each previous version. The
3342     // constant pool cache holds the Method*s for non-virtual
3343     // methods and for virtual, final methods.
3344     //
3345     // Special case: if the current class is the_class, then new_cp
3346     // has already been attached to the_class and old_cp has already
3347     // been added as a previous version. The new_cp doesn't have any
3348     // cached references to old methods so it doesn't need to be
3349     // updated. We can simply start with the previous version(s) in
3350     // that case.
3351     constantPoolHandle other_cp;
3352     ConstantPoolCache* cp_cache;
3353 
3354     if (ik != _the_class) {
3355       // this klass' constant pool cache may need adjustment
3356       other_cp = constantPoolHandle(ik->constants());
3357       cp_cache = other_cp->cache();
3358       if (cp_cache != NULL) {
3359         cp_cache->adjust_method_entries(the_class, &trace_name_printed);
3360       }
3361     }
3362 
3363     // the previous versions' constant pool caches may need adjustment
3364     for (InstanceKlass* pv_node = ik->previous_versions();
3365          pv_node != NULL;
3366          pv_node = pv_node->previous_versions()) {
3367       cp_cache = pv_node->constants()->cache();
3368       if (cp_cache != NULL) {
3369         cp_cache->adjust_method_entries(pv_node, &trace_name_printed);
3370       }
3371     }
3372   }
3373 }
3374 
3375 // Clean method data for this class
3376 void VM_RedefineClasses::MethodDataCleaner::do_klass(Klass* k) {
3377   if (k->is_instance_klass()) {
3378     InstanceKlass *ik = InstanceKlass::cast(k);
3379     // Clean MethodData of this class's methods so they don't refer to
3380     // old methods that are no longer running.
3381     Array<Method*>* methods = ik->methods();
3382     int num_methods = methods->length();
3383     for (int index = 0; index < num_methods; ++index) {
3384       if (methods->at(index)->method_data() != NULL) {
3385         methods->at(index)->method_data()->clean_weak_method_links();
3386       }
3387     }
3388   }
3389 }
3390 
3391 void VM_RedefineClasses::update_jmethod_ids() {
3392   for (int j = 0; j < _matching_methods_length; ++j) {
3393     Method* old_method = _matching_old_methods[j];
3394     jmethodID jmid = old_method->find_jmethod_id_or_null();
3395     if (jmid != NULL) {
3396       // There is a jmethodID, change it to point to the new method
3397       methodHandle new_method_h(_matching_new_methods[j]);
3398       Method::change_method_associated_with_jmethod_id(jmid, new_method_h());
3399       assert(Method::resolve_jmethod_id(jmid) == _matching_new_methods[j],
3400              "should be replaced");
3401     }
3402   }
3403 }
3404 
3405 int VM_RedefineClasses::check_methods_and_mark_as_obsolete() {
3406   int emcp_method_count = 0;
3407   int obsolete_count = 0;
3408   int old_index = 0;
3409   for (int j = 0; j < _matching_methods_length; ++j, ++old_index) {
3410     Method* old_method = _matching_old_methods[j];
3411     Method* new_method = _matching_new_methods[j];
3412     Method* old_array_method;
3413 
3414     // Maintain an old_index into the _old_methods array by skipping
3415     // deleted methods
3416     while ((old_array_method = _old_methods->at(old_index)) != old_method) {
3417       ++old_index;
3418     }
3419 
3420     if (MethodComparator::methods_EMCP(old_method, new_method)) {
3421       // The EMCP definition from JSR-163 requires the bytecodes to be
3422       // the same with the exception of constant pool indices which may
3423       // differ. However, the constants referred to by those indices
3424       // must be the same.
3425       //
3426       // We use methods_EMCP() for comparison since constant pool
3427       // merging can remove duplicate constant pool entries that were
3428       // present in the old method and removed from the rewritten new
3429       // method. A faster binary comparison function would consider the
3430       // old and new methods to be different when they are actually
3431       // EMCP.
3432       //
3433       // The old and new methods are EMCP and you would think that we
3434       // could get rid of one of them here and now and save some space.
3435       // However, the concept of EMCP only considers the bytecodes and
3436       // the constant pool entries in the comparison. Other things,
3437       // e.g., the line number table (LNT) or the local variable table
3438       // (LVT) don't count in the comparison. So the new (and EMCP)
3439       // method can have a new LNT that we need so we can't just
3440       // overwrite the new method with the old method.
3441       //
3442       // When this routine is called, we have already attached the new
3443       // methods to the_class so the old methods are effectively
3444       // overwritten. However, if an old method is still executing,
3445       // then the old method cannot be collected until sometime after
3446       // the old method call has returned. So the overwriting of old
3447       // methods by new methods will save us space except for those
3448       // (hopefully few) old methods that are still executing.
3449       //
3450       // A method refers to a ConstMethod* and this presents another
3451       // possible avenue to space savings. The ConstMethod* in the
3452       // new method contains possibly new attributes (LNT, LVT, etc).
3453       // At first glance, it seems possible to save space by replacing
3454       // the ConstMethod* in the old method with the ConstMethod*
3455       // from the new method. The old and new methods would share the
3456       // same ConstMethod* and we would save the space occupied by
3457       // the old ConstMethod*. However, the ConstMethod* contains
3458       // a back reference to the containing method. Sharing the
3459       // ConstMethod* between two methods could lead to confusion in
3460       // the code that uses the back reference. This would lead to
3461       // brittle code that could be broken in non-obvious ways now or
3462       // in the future.
3463       //
3464       // Another possibility is to copy the ConstMethod* from the new
3465       // method to the old method and then overwrite the new method with
3466       // the old method. Since the ConstMethod* contains the bytecodes
3467       // for the method embedded in the oop, this option would change
3468       // the bytecodes out from under any threads executing the old
3469       // method and make the thread's bcp invalid. Since EMCP requires
3470       // that the bytecodes be the same modulo constant pool indices, it
3471       // is straight forward to compute the correct new bcp in the new
3472       // ConstMethod* from the old bcp in the old ConstMethod*. The
3473       // time consuming part would be searching all the frames in all
3474       // of the threads to find all of the calls to the old method.
3475       //
3476       // It looks like we will have to live with the limited savings
3477       // that we get from effectively overwriting the old methods
3478       // when the new methods are attached to the_class.
3479 
3480       // Count number of methods that are EMCP.  The method will be marked
3481       // old but not obsolete if it is EMCP.
3482       emcp_method_count++;
3483 
3484       // An EMCP method is _not_ obsolete. An obsolete method has a
3485       // different jmethodID than the current method. An EMCP method
3486       // has the same jmethodID as the current method. Having the
3487       // same jmethodID for all EMCP versions of a method allows for
3488       // a consistent view of the EMCP methods regardless of which
3489       // EMCP method you happen to have in hand. For example, a
3490       // breakpoint set in one EMCP method will work for all EMCP
3491       // versions of the method including the current one.
3492     } else {
3493       // mark obsolete methods as such
3494       old_method->set_is_obsolete();
3495       obsolete_count++;
3496 
3497       // obsolete methods need a unique idnum so they become new entries in
3498       // the jmethodID cache in InstanceKlass
3499       assert(old_method->method_idnum() == new_method->method_idnum(), "must match");
3500       u2 num = InstanceKlass::cast(_the_class)->next_method_idnum();
3501       if (num != ConstMethod::UNSET_IDNUM) {
3502         old_method->set_method_idnum(num);
3503       }
3504 
3505       // With tracing we try not to "yack" too much. The position of
3506       // this trace assumes there are fewer obsolete methods than
3507       // EMCP methods.
3508       if (log_is_enabled(Trace, redefine, class, obsolete, mark)) {
3509         ResourceMark rm;
3510         log_trace(redefine, class, obsolete, mark)
3511           ("mark %s(%s) as obsolete", old_method->name()->as_C_string(), old_method->signature()->as_C_string());
3512       }
3513     }
3514     old_method->set_is_old();
3515   }
3516   for (int i = 0; i < _deleted_methods_length; ++i) {
3517     Method* old_method = _deleted_methods[i];
3518 
3519     assert(!old_method->has_vtable_index(),
3520            "cannot delete methods with vtable entries");;
3521 
3522     // Mark all deleted methods as old, obsolete and deleted
3523     old_method->set_is_deleted();
3524     old_method->set_is_old();
3525     old_method->set_is_obsolete();
3526     ++obsolete_count;
3527     // With tracing we try not to "yack" too much. The position of
3528     // this trace assumes there are fewer obsolete methods than
3529     // EMCP methods.
3530     if (log_is_enabled(Trace, redefine, class, obsolete, mark)) {
3531       ResourceMark rm;
3532       log_trace(redefine, class, obsolete, mark)
3533         ("mark deleted %s(%s) as obsolete", old_method->name()->as_C_string(), old_method->signature()->as_C_string());
3534     }
3535   }
3536   assert((emcp_method_count + obsolete_count) == _old_methods->length(),
3537     "sanity check");
3538   log_trace(redefine, class, obsolete, mark)("EMCP_cnt=%d, obsolete_cnt=%d", emcp_method_count, obsolete_count);
3539   return emcp_method_count;
3540 }
3541 
3542 // This internal class transfers the native function registration from old methods
3543 // to new methods.  It is designed to handle both the simple case of unchanged
3544 // native methods and the complex cases of native method prefixes being added and/or
3545 // removed.
3546 // It expects only to be used during the VM_RedefineClasses op (a safepoint).
3547 //
3548 // This class is used after the new methods have been installed in "the_class".
3549 //
3550 // So, for example, the following must be handled.  Where 'm' is a method and
3551 // a number followed by an underscore is a prefix.
3552 //
3553 //                                      Old Name    New Name
3554 // Simple transfer to new method        m       ->  m
3555 // Add prefix                           m       ->  1_m
3556 // Remove prefix                        1_m     ->  m
3557 // Simultaneous add of prefixes         m       ->  3_2_1_m
3558 // Simultaneous removal of prefixes     3_2_1_m ->  m
3559 // Simultaneous add and remove          1_m     ->  2_m
3560 // Same, caused by prefix removal only  3_2_1_m ->  3_2_m
3561 //
3562 class TransferNativeFunctionRegistration {
3563  private:
3564   InstanceKlass* the_class;
3565   int prefix_count;
3566   char** prefixes;
3567 
3568   // Recursively search the binary tree of possibly prefixed method names.
3569   // Iteration could be used if all agents were well behaved. Full tree walk is
3570   // more resilent to agents not cleaning up intermediate methods.
3571   // Branch at each depth in the binary tree is:
3572   //    (1) without the prefix.
3573   //    (2) with the prefix.
3574   // where 'prefix' is the prefix at that 'depth' (first prefix, second prefix,...)
3575   Method* search_prefix_name_space(int depth, char* name_str, size_t name_len,
3576                                      Symbol* signature) {
3577     TempNewSymbol name_symbol = SymbolTable::probe(name_str, (int)name_len);
3578     if (name_symbol != NULL) {
3579       Method* method = the_class->lookup_method(name_symbol, signature);
3580       if (method != NULL) {
3581         // Even if prefixed, intermediate methods must exist.
3582         if (method->is_native()) {
3583           // Wahoo, we found a (possibly prefixed) version of the method, return it.
3584           return method;
3585         }
3586         if (depth < prefix_count) {
3587           // Try applying further prefixes (other than this one).
3588           method = search_prefix_name_space(depth+1, name_str, name_len, signature);
3589           if (method != NULL) {
3590             return method; // found
3591           }
3592 
3593           // Try adding this prefix to the method name and see if it matches
3594           // another method name.
3595           char* prefix = prefixes[depth];
3596           size_t prefix_len = strlen(prefix);
3597           size_t trial_len = name_len + prefix_len;
3598           char* trial_name_str = NEW_RESOURCE_ARRAY(char, trial_len + 1);
3599           strcpy(trial_name_str, prefix);
3600           strcat(trial_name_str, name_str);
3601           method = search_prefix_name_space(depth+1, trial_name_str, trial_len,
3602                                             signature);
3603           if (method != NULL) {
3604             // If found along this branch, it was prefixed, mark as such
3605             method->set_is_prefixed_native();
3606             return method; // found
3607           }
3608         }
3609       }
3610     }
3611     return NULL;  // This whole branch bore nothing
3612   }
3613 
3614   // Return the method name with old prefixes stripped away.
3615   char* method_name_without_prefixes(Method* method) {
3616     Symbol* name = method->name();
3617     char* name_str = name->as_utf8();
3618 
3619     // Old prefixing may be defunct, strip prefixes, if any.
3620     for (int i = prefix_count-1; i >= 0; i--) {
3621       char* prefix = prefixes[i];
3622       size_t prefix_len = strlen(prefix);
3623       if (strncmp(prefix, name_str, prefix_len) == 0) {
3624         name_str += prefix_len;
3625       }
3626     }
3627     return name_str;
3628   }
3629 
3630   // Strip any prefixes off the old native method, then try to find a
3631   // (possibly prefixed) new native that matches it.
3632   Method* strip_and_search_for_new_native(Method* method) {
3633     ResourceMark rm;
3634     char* name_str = method_name_without_prefixes(method);
3635     return search_prefix_name_space(0, name_str, strlen(name_str),
3636                                     method->signature());
3637   }
3638 
3639  public:
3640 
3641   // Construct a native method transfer processor for this class.
3642   TransferNativeFunctionRegistration(InstanceKlass* _the_class) {
3643     assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
3644 
3645     the_class = _the_class;
3646     prefixes = JvmtiExport::get_all_native_method_prefixes(&prefix_count);
3647   }
3648 
3649   // Attempt to transfer any of the old or deleted methods that are native
3650   void transfer_registrations(Method** old_methods, int methods_length) {
3651     for (int j = 0; j < methods_length; j++) {
3652       Method* old_method = old_methods[j];
3653 
3654       if (old_method->is_native() && old_method->has_native_function()) {
3655         Method* new_method = strip_and_search_for_new_native(old_method);
3656         if (new_method != NULL) {
3657           // Actually set the native function in the new method.
3658           // Redefine does not send events (except CFLH), certainly not this
3659           // behind the scenes re-registration.
3660           new_method->set_native_function(old_method->native_function(),
3661                               !Method::native_bind_event_is_interesting);
3662         }
3663       }
3664     }
3665   }
3666 };
3667 
3668 // Don't lose the association between a native method and its JNI function.
3669 void VM_RedefineClasses::transfer_old_native_function_registrations(InstanceKlass* the_class) {
3670   TransferNativeFunctionRegistration transfer(the_class);
3671   transfer.transfer_registrations(_deleted_methods, _deleted_methods_length);
3672   transfer.transfer_registrations(_matching_old_methods, _matching_methods_length);
3673 }
3674 
3675 // Deoptimize all compiled code that depends on this class.
3676 //
3677 // If the can_redefine_classes capability is obtained in the onload
3678 // phase then the compiler has recorded all dependencies from startup.
3679 // In that case we need only deoptimize and throw away all compiled code
3680 // that depends on the class.
3681 //
3682 // If can_redefine_classes is obtained sometime after the onload
3683 // phase then the dependency information may be incomplete. In that case
3684 // the first call to RedefineClasses causes all compiled code to be
3685 // thrown away. As can_redefine_classes has been obtained then
3686 // all future compilations will record dependencies so second and
3687 // subsequent calls to RedefineClasses need only throw away code
3688 // that depends on the class.
3689 //
3690 void VM_RedefineClasses::flush_dependent_code(InstanceKlass* ik, TRAPS) {
3691   assert_locked_or_safepoint(Compile_lock);
3692 
3693   // All dependencies have been recorded from startup or this is a second or
3694   // subsequent use of RedefineClasses
3695   if (JvmtiExport::all_dependencies_are_recorded()) {
3696     CodeCache::flush_evol_dependents_on(ik);
3697   } else {
3698     CodeCache::mark_all_nmethods_for_deoptimization();
3699 
3700     ResourceMark rm(THREAD);
3701     DeoptimizationMarker dm;
3702 
3703     // Deoptimize all activations depending on marked nmethods
3704     Deoptimization::deoptimize_dependents();
3705 
3706     // Make the dependent methods not entrant
3707     CodeCache::make_marked_nmethods_not_entrant();
3708 
3709     // From now on we know that the dependency information is complete
3710     JvmtiExport::set_all_dependencies_are_recorded(true);
3711   }
3712 }
3713 
3714 void VM_RedefineClasses::compute_added_deleted_matching_methods() {
3715   Method* old_method;
3716   Method* new_method;
3717 
3718   _matching_old_methods = NEW_RESOURCE_ARRAY(Method*, _old_methods->length());
3719   _matching_new_methods = NEW_RESOURCE_ARRAY(Method*, _old_methods->length());
3720   _added_methods        = NEW_RESOURCE_ARRAY(Method*, _new_methods->length());
3721   _deleted_methods      = NEW_RESOURCE_ARRAY(Method*, _old_methods->length());
3722 
3723   _matching_methods_length = 0;
3724   _deleted_methods_length  = 0;
3725   _added_methods_length    = 0;
3726 
3727   int nj = 0;
3728   int oj = 0;
3729   while (true) {
3730     if (oj >= _old_methods->length()) {
3731       if (nj >= _new_methods->length()) {
3732         break; // we've looked at everything, done
3733       }
3734       // New method at the end
3735       new_method = _new_methods->at(nj);
3736       _added_methods[_added_methods_length++] = new_method;
3737       ++nj;
3738     } else if (nj >= _new_methods->length()) {
3739       // Old method, at the end, is deleted
3740       old_method = _old_methods->at(oj);
3741       _deleted_methods[_deleted_methods_length++] = old_method;
3742       ++oj;
3743     } else {
3744       old_method = _old_methods->at(oj);
3745       new_method = _new_methods->at(nj);
3746       if (old_method->name() == new_method->name()) {
3747         if (old_method->signature() == new_method->signature()) {
3748           _matching_old_methods[_matching_methods_length  ] = old_method;
3749           _matching_new_methods[_matching_methods_length++] = new_method;
3750           ++nj;
3751           ++oj;
3752         } else {
3753           // added overloaded have already been moved to the end,
3754           // so this is a deleted overloaded method
3755           _deleted_methods[_deleted_methods_length++] = old_method;
3756           ++oj;
3757         }
3758       } else { // names don't match
3759         if (old_method->name()->fast_compare(new_method->name()) > 0) {
3760           // new method
3761           _added_methods[_added_methods_length++] = new_method;
3762           ++nj;
3763         } else {
3764           // deleted method
3765           _deleted_methods[_deleted_methods_length++] = old_method;
3766           ++oj;
3767         }
3768       }
3769     }
3770   }
3771   assert(_matching_methods_length + _deleted_methods_length == _old_methods->length(), "sanity");
3772   assert(_matching_methods_length + _added_methods_length == _new_methods->length(), "sanity");
3773 }
3774 
3775 
3776 void VM_RedefineClasses::swap_annotations(InstanceKlass* the_class,
3777                                           InstanceKlass* scratch_class) {
3778   // Swap annotation fields values
3779   Annotations* old_annotations = the_class->annotations();
3780   the_class->set_annotations(scratch_class->annotations());
3781   scratch_class->set_annotations(old_annotations);
3782 }
3783 
3784 
3785 // Install the redefinition of a class:
3786 //    - house keeping (flushing breakpoints and caches, deoptimizing
3787 //      dependent compiled code)
3788 //    - replacing parts in the_class with parts from scratch_class
3789 //    - adding a weak reference to track the obsolete but interesting
3790 //      parts of the_class
3791 //    - adjusting constant pool caches and vtables in other classes
3792 //      that refer to methods in the_class. These adjustments use the
3793 //      ClassLoaderDataGraph::classes_do() facility which only allows
3794 //      a helper method to be specified. The interesting parameters
3795 //      that we would like to pass to the helper method are saved in
3796 //      static global fields in the VM operation.
3797 void VM_RedefineClasses::redefine_single_class(jclass the_jclass,
3798        InstanceKlass* scratch_class, TRAPS) {
3799 
3800   HandleMark hm(THREAD);   // make sure handles from this call are freed
3801 
3802   if (log_is_enabled(Info, redefine, class, timer)) {
3803     _timer_rsc_phase1.start();
3804   }
3805 
3806   InstanceKlass* the_class = get_ik(the_jclass);
3807 
3808   // Remove all breakpoints in methods of this class
3809   JvmtiBreakpoints& jvmti_breakpoints = JvmtiCurrentBreakpoints::get_jvmti_breakpoints();
3810   jvmti_breakpoints.clearall_in_class_at_safepoint(the_class);
3811 
3812   // Deoptimize all compiled code that depends on this class
3813   flush_dependent_code(the_class, THREAD);
3814 
3815   _old_methods = the_class->methods();
3816   _new_methods = scratch_class->methods();
3817   _the_class = the_class;
3818   compute_added_deleted_matching_methods();
3819   update_jmethod_ids();
3820 
3821   // Attach new constant pool to the original klass. The original
3822   // klass still refers to the old constant pool (for now).
3823   scratch_class->constants()->set_pool_holder(the_class);
3824 
3825 #if 0
3826   // In theory, with constant pool merging in place we should be able
3827   // to save space by using the new, merged constant pool in place of
3828   // the old constant pool(s). By "pool(s)" I mean the constant pool in
3829   // the klass version we are replacing now and any constant pool(s) in
3830   // previous versions of klass. Nice theory, doesn't work in practice.
3831   // When this code is enabled, even simple programs throw NullPointer
3832   // exceptions. I'm guessing that this is caused by some constant pool
3833   // cache difference between the new, merged constant pool and the
3834   // constant pool that was just being used by the klass. I'm keeping
3835   // this code around to archive the idea, but the code has to remain
3836   // disabled for now.
3837 
3838   // Attach each old method to the new constant pool. This can be
3839   // done here since we are past the bytecode verification and
3840   // constant pool optimization phases.
3841   for (int i = _old_methods->length() - 1; i >= 0; i--) {
3842     Method* method = _old_methods->at(i);
3843     method->set_constants(scratch_class->constants());
3844   }
3845 
3846   // NOTE: this doesn't work because you can redefine the same class in two
3847   // threads, each getting their own constant pool data appended to the
3848   // original constant pool.  In order for the new methods to work when they
3849   // become old methods, they need to keep their updated copy of the constant pool.
3850 
3851   {
3852     // walk all previous versions of the klass
3853     InstanceKlass *ik = the_class;
3854     PreviousVersionWalker pvw(ik);
3855     do {
3856       ik = pvw.next_previous_version();
3857       if (ik != NULL) {
3858 
3859         // attach previous version of klass to the new constant pool
3860         ik->set_constants(scratch_class->constants());
3861 
3862         // Attach each method in the previous version of klass to the
3863         // new constant pool
3864         Array<Method*>* prev_methods = ik->methods();
3865         for (int i = prev_methods->length() - 1; i >= 0; i--) {
3866           Method* method = prev_methods->at(i);
3867           method->set_constants(scratch_class->constants());
3868         }
3869       }
3870     } while (ik != NULL);
3871   }
3872 #endif
3873 
3874   // Replace methods and constantpool
3875   the_class->set_methods(_new_methods);
3876   scratch_class->set_methods(_old_methods);     // To prevent potential GCing of the old methods,
3877                                           // and to be able to undo operation easily.
3878 
3879   Array<int>* old_ordering = the_class->method_ordering();
3880   the_class->set_method_ordering(scratch_class->method_ordering());
3881   scratch_class->set_method_ordering(old_ordering);
3882 
3883   ConstantPool* old_constants = the_class->constants();
3884   the_class->set_constants(scratch_class->constants());
3885   scratch_class->set_constants(old_constants);  // See the previous comment.
3886 #if 0
3887   // We are swapping the guts of "the new class" with the guts of "the
3888   // class". Since the old constant pool has just been attached to "the
3889   // new class", it seems logical to set the pool holder in the old
3890   // constant pool also. However, doing this will change the observable
3891   // class hierarchy for any old methods that are still executing. A
3892   // method can query the identity of its "holder" and this query uses
3893   // the method's constant pool link to find the holder. The change in
3894   // holding class from "the class" to "the new class" can confuse
3895   // things.
3896   //
3897   // Setting the old constant pool's holder will also cause
3898   // verification done during vtable initialization below to fail.
3899   // During vtable initialization, the vtable's class is verified to be
3900   // a subtype of the method's holder. The vtable's class is "the
3901   // class" and the method's holder is gotten from the constant pool
3902   // link in the method itself. For "the class"'s directly implemented
3903   // methods, the method holder is "the class" itself (as gotten from
3904   // the new constant pool). The check works fine in this case. The
3905   // check also works fine for methods inherited from super classes.
3906   //
3907   // Miranda methods are a little more complicated. A miranda method is
3908   // provided by an interface when the class implementing the interface
3909   // does not provide its own method.  These interfaces are implemented
3910   // internally as an InstanceKlass. These special instanceKlasses
3911   // share the constant pool of the class that "implements" the
3912   // interface. By sharing the constant pool, the method holder of a
3913   // miranda method is the class that "implements" the interface. In a
3914   // non-redefine situation, the subtype check works fine. However, if
3915   // the old constant pool's pool holder is modified, then the check
3916   // fails because there is no class hierarchy relationship between the
3917   // vtable's class and "the new class".
3918 
3919   old_constants->set_pool_holder(scratch_class());
3920 #endif
3921 
3922   // track number of methods that are EMCP for add_previous_version() call below
3923   int emcp_method_count = check_methods_and_mark_as_obsolete();
3924   transfer_old_native_function_registrations(the_class);
3925 
3926   // The class file bytes from before any retransformable agents mucked
3927   // with them was cached on the scratch class, move to the_class.
3928   // Note: we still want to do this if nothing needed caching since it
3929   // should get cleared in the_class too.
3930   if (the_class->get_cached_class_file_bytes() == 0) {
3931     // the_class doesn't have a cache yet so copy it
3932     the_class->set_cached_class_file(scratch_class->get_cached_class_file());
3933   }
3934   else if (scratch_class->get_cached_class_file_bytes() !=
3935            the_class->get_cached_class_file_bytes()) {
3936     // The same class can be present twice in the scratch classes list or there
3937     // are multiple concurrent RetransformClasses calls on different threads.
3938     // In such cases we have to deallocate scratch_class cached_class_file.
3939     os::free(scratch_class->get_cached_class_file());
3940   }
3941 
3942   // NULL out in scratch class to not delete twice.  The class to be redefined
3943   // always owns these bytes.
3944   scratch_class->set_cached_class_file(NULL);
3945 
3946   // Replace inner_classes
3947   Array<u2>* old_inner_classes = the_class->inner_classes();
3948   the_class->set_inner_classes(scratch_class->inner_classes());
3949   scratch_class->set_inner_classes(old_inner_classes);
3950 
3951   // Initialize the vtable and interface table after
3952   // methods have been rewritten
3953   {
3954     ResourceMark rm(THREAD);
3955     // no exception should happen here since we explicitly
3956     // do not check loader constraints.
3957     // compare_and_normalize_class_versions has already checked:
3958     //  - classloaders unchanged, signatures unchanged
3959     //  - all instanceKlasses for redefined classes reused & contents updated
3960     the_class->vtable()->initialize_vtable(false, THREAD);
3961     the_class->itable()->initialize_itable(false, THREAD);
3962     assert(!HAS_PENDING_EXCEPTION || (THREAD->pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())), "redefine exception");
3963   }
3964 
3965   // Leave arrays of jmethodIDs and itable index cache unchanged
3966 
3967   // Copy the "source file name" attribute from new class version
3968   the_class->set_source_file_name_index(
3969     scratch_class->source_file_name_index());
3970 
3971   // Copy the "source debug extension" attribute from new class version
3972   the_class->set_source_debug_extension(
3973     scratch_class->source_debug_extension(),
3974     scratch_class->source_debug_extension() == NULL ? 0 :
3975     (int)strlen(scratch_class->source_debug_extension()));
3976 
3977   // Use of javac -g could be different in the old and the new
3978   if (scratch_class->access_flags().has_localvariable_table() !=
3979       the_class->access_flags().has_localvariable_table()) {
3980 
3981     AccessFlags flags = the_class->access_flags();
3982     if (scratch_class->access_flags().has_localvariable_table()) {
3983       flags.set_has_localvariable_table();
3984     } else {
3985       flags.clear_has_localvariable_table();
3986     }
3987     the_class->set_access_flags(flags);
3988   }
3989 
3990   swap_annotations(the_class, scratch_class);
3991 
3992   // Replace minor version number of class file
3993   u2 old_minor_version = the_class->minor_version();
3994   the_class->set_minor_version(scratch_class->minor_version());
3995   scratch_class->set_minor_version(old_minor_version);
3996 
3997   // Replace major version number of class file
3998   u2 old_major_version = the_class->major_version();
3999   the_class->set_major_version(scratch_class->major_version());
4000   scratch_class->set_major_version(old_major_version);
4001 
4002   // Replace CP indexes for class and name+type of enclosing method
4003   u2 old_class_idx  = the_class->enclosing_method_class_index();
4004   u2 old_method_idx = the_class->enclosing_method_method_index();
4005   the_class->set_enclosing_method_indices(
4006     scratch_class->enclosing_method_class_index(),
4007     scratch_class->enclosing_method_method_index());
4008   scratch_class->set_enclosing_method_indices(old_class_idx, old_method_idx);
4009 
4010   // Replace fingerprint data
4011   the_class->set_has_passed_fingerprint_check(scratch_class->has_passed_fingerprint_check());
4012   the_class->store_fingerprint(scratch_class->get_stored_fingerprint());
4013 
4014   the_class->set_has_been_redefined();
4015 
4016   if (!the_class->should_be_initialized()) {
4017     // Class was already initialized, so AOT has only seen the original version.
4018     // We need to let AOT look at it again.
4019     AOTLoader::load_for_klass(the_class, THREAD);
4020   }
4021 
4022   // keep track of previous versions of this class
4023   the_class->add_previous_version(scratch_class, emcp_method_count);
4024 
4025   _timer_rsc_phase1.stop();
4026   if (log_is_enabled(Info, redefine, class, timer)) {
4027     _timer_rsc_phase2.start();
4028   }
4029 
4030   // Adjust constantpool caches and vtables for all classes
4031   // that reference methods of the evolved class.
4032   AdjustCpoolCacheAndVtable adjust_cpool_cache_and_vtable(THREAD);
4033   ClassLoaderDataGraph::classes_do(&adjust_cpool_cache_and_vtable);
4034 
4035   // JSR-292 support
4036   MemberNameTable* mnt = the_class->member_names();
4037   if (mnt != NULL) {
4038     bool trace_name_printed = false;
4039     mnt->adjust_method_entries(the_class, &trace_name_printed);
4040   }
4041 
4042   if (the_class->oop_map_cache() != NULL) {
4043     // Flush references to any obsolete methods from the oop map cache
4044     // so that obsolete methods are not pinned.
4045     the_class->oop_map_cache()->flush_obsolete_entries();
4046   }
4047 
4048   increment_class_counter((InstanceKlass *)the_class, THREAD);
4049   {
4050     ResourceMark rm(THREAD);
4051     // increment the classRedefinedCount field in the_class and in any
4052     // direct and indirect subclasses of the_class
4053     log_info(redefine, class, load)
4054       ("redefined name=%s, count=%d (avail_mem=" UINT64_FORMAT "K)",
4055        the_class->external_name(), java_lang_Class::classRedefinedCount(the_class->java_mirror()), os::available_memory() >> 10);
4056     Events::log_redefinition(THREAD, "redefined class name=%s, count=%d",
4057                              the_class->external_name(),
4058                              java_lang_Class::classRedefinedCount(the_class->java_mirror()));
4059 
4060   }
4061   _timer_rsc_phase2.stop();
4062 } // end redefine_single_class()
4063 
4064 
4065 // Increment the classRedefinedCount field in the specific InstanceKlass
4066 // and in all direct and indirect subclasses.
4067 void VM_RedefineClasses::increment_class_counter(InstanceKlass *ik, TRAPS) {
4068   oop class_mirror = ik->java_mirror();
4069   Klass* class_oop = java_lang_Class::as_Klass(class_mirror);
4070   int new_count = java_lang_Class::classRedefinedCount(class_mirror) + 1;
4071   java_lang_Class::set_classRedefinedCount(class_mirror, new_count);
4072 
4073   if (class_oop != _the_class) {
4074     // _the_class count is printed at end of redefine_single_class()
4075     log_debug(redefine, class, subclass)("updated count in subclass=%s to %d", ik->external_name(), new_count);
4076   }
4077 
4078   for (Klass *subk = ik->subklass(); subk != NULL;
4079        subk = subk->next_sibling()) {
4080     if (subk->is_instance_klass()) {
4081       // Only update instanceKlasses
4082       InstanceKlass *subik = InstanceKlass::cast(subk);
4083       // recursively do subclasses of the current subclass
4084       increment_class_counter(subik, THREAD);
4085     }
4086   }
4087 }
4088 
4089 void VM_RedefineClasses::CheckClass::do_klass(Klass* k) {
4090   bool no_old_methods = true;  // be optimistic
4091 
4092   // Both array and instance classes have vtables.
4093   // a vtable should never contain old or obsolete methods
4094   ResourceMark rm(_thread);
4095   if (k->vtable_length() > 0 &&
4096       !k->vtable()->check_no_old_or_obsolete_entries()) {
4097     if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
4098       log_trace(redefine, class, obsolete, metadata)
4099         ("klassVtable::check_no_old_or_obsolete_entries failure -- OLD or OBSOLETE method found -- class: %s",
4100          k->signature_name());
4101       k->vtable()->dump_vtable();
4102     }
4103     no_old_methods = false;
4104   }
4105 
4106   if (k->is_instance_klass()) {
4107     HandleMark hm(_thread);
4108     InstanceKlass *ik = InstanceKlass::cast(k);
4109 
4110     // an itable should never contain old or obsolete methods
4111     if (ik->itable_length() > 0 &&
4112         !ik->itable()->check_no_old_or_obsolete_entries()) {
4113       if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
4114         log_trace(redefine, class, obsolete, metadata)
4115           ("klassItable::check_no_old_or_obsolete_entries failure -- OLD or OBSOLETE method found -- class: %s",
4116            ik->signature_name());
4117         ik->itable()->dump_itable();
4118       }
4119       no_old_methods = false;
4120     }
4121 
4122     // the constant pool cache should never contain non-deleted old or obsolete methods
4123     if (ik->constants() != NULL &&
4124         ik->constants()->cache() != NULL &&
4125         !ik->constants()->cache()->check_no_old_or_obsolete_entries()) {
4126       if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
4127         log_trace(redefine, class, obsolete, metadata)
4128           ("cp-cache::check_no_old_or_obsolete_entries failure -- OLD or OBSOLETE method found -- class: %s",
4129            ik->signature_name());
4130         ik->constants()->cache()->dump_cache();
4131       }
4132       no_old_methods = false;
4133     }
4134   }
4135 
4136   // print and fail guarantee if old methods are found.
4137   if (!no_old_methods) {
4138     if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
4139       dump_methods();
4140     } else {
4141       log_trace(redefine, class)("Use the '-Xlog:redefine+class*:' option "
4142         "to see more info about the following guarantee() failure.");
4143     }
4144     guarantee(false, "OLD and/or OBSOLETE method(s) found");
4145   }
4146 }
4147 
4148 
4149 void VM_RedefineClasses::dump_methods() {
4150   int j;
4151   log_trace(redefine, class, dump)("_old_methods --");
4152   for (j = 0; j < _old_methods->length(); ++j) {
4153     LogStreamHandle(Trace, redefine, class, dump) log_stream;
4154     Method* m = _old_methods->at(j);
4155     log_stream.print("%4d  (%5d)  ", j, m->vtable_index());
4156     m->access_flags().print_on(&log_stream);
4157     log_stream.print(" --  ");
4158     m->print_name(&log_stream);
4159     log_stream.cr();
4160   }
4161   log_trace(redefine, class, dump)("_new_methods --");
4162   for (j = 0; j < _new_methods->length(); ++j) {
4163     LogStreamHandle(Trace, redefine, class, dump) log_stream;
4164     Method* m = _new_methods->at(j);
4165     log_stream.print("%4d  (%5d)  ", j, m->vtable_index());
4166     m->access_flags().print_on(&log_stream);
4167     log_stream.print(" --  ");
4168     m->print_name(&log_stream);
4169     log_stream.cr();
4170   }
4171   log_trace(redefine, class, dump)("_matching_methods --");
4172   for (j = 0; j < _matching_methods_length; ++j) {
4173     LogStreamHandle(Trace, redefine, class, dump) log_stream;
4174     Method* m = _matching_old_methods[j];
4175     log_stream.print("%4d  (%5d)  ", j, m->vtable_index());
4176     m->access_flags().print_on(&log_stream);
4177     log_stream.print(" --  ");
4178     m->print_name();
4179     log_stream.cr();
4180 
4181     m = _matching_new_methods[j];
4182     log_stream.print("      (%5d)  ", m->vtable_index());
4183     m->access_flags().print_on(&log_stream);
4184     log_stream.cr();
4185   }
4186   log_trace(redefine, class, dump)("_deleted_methods --");
4187   for (j = 0; j < _deleted_methods_length; ++j) {
4188     LogStreamHandle(Trace, redefine, class, dump) log_stream;
4189     Method* m = _deleted_methods[j];
4190     log_stream.print("%4d  (%5d)  ", j, m->vtable_index());
4191     m->access_flags().print_on(&log_stream);
4192     log_stream.print(" --  ");
4193     m->print_name(&log_stream);
4194     log_stream.cr();
4195   }
4196   log_trace(redefine, class, dump)("_added_methods --");
4197   for (j = 0; j < _added_methods_length; ++j) {
4198     LogStreamHandle(Trace, redefine, class, dump) log_stream;
4199     Method* m = _added_methods[j];
4200     log_stream.print("%4d  (%5d)  ", j, m->vtable_index());
4201     m->access_flags().print_on(&log_stream);
4202     log_stream.print(" --  ");
4203     m->print_name(&log_stream);
4204     log_stream.cr();
4205   }
4206 }
4207 
4208 void VM_RedefineClasses::print_on_error(outputStream* st) const {
4209   VM_Operation::print_on_error(st);
4210   if (_the_class != NULL) {
4211     ResourceMark rm;
4212     st->print_cr(", redefining class %s", _the_class->external_name());
4213   }
4214 }