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