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