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