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