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