1 /*
   2  * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/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/method.hpp"
  52 #include "oops/oop.inline.hpp"
  53 #include "oops/recordComponent.hpp"
  54 #include "prims/jvmtiImpl.hpp"
  55 #include "prims/jvmtiRedefineClasses.hpp"
  56 #include "prims/jvmtiThreadState.inline.hpp"
  57 #include "prims/resolvedMethodTable.hpp"
  58 #include "prims/methodComparator.hpp"
  59 #include "runtime/atomic.hpp"
  60 #include "runtime/deoptimization.hpp"
  61 #include "runtime/handles.inline.hpp"
  62 #include "runtime/jniHandles.inline.hpp"
  63 #include "runtime/relocator.hpp"
  64 #include "runtime/safepointVerifiers.hpp"
  65 #include "utilities/bitMap.inline.hpp"
  66 #include "utilities/checkedCast.hpp"
  67 #include "utilities/events.hpp"
  68 #include "utilities/macros.hpp"
  69 
  70 Array<Method*>* VM_RedefineClasses::_old_methods = nullptr;
  71 Array<Method*>* VM_RedefineClasses::_new_methods = nullptr;
  72 Method**  VM_RedefineClasses::_matching_old_methods = nullptr;
  73 Method**  VM_RedefineClasses::_matching_new_methods = nullptr;
  74 Method**  VM_RedefineClasses::_deleted_methods      = nullptr;
  75 Method**  VM_RedefineClasses::_added_methods        = nullptr;
  76 int       VM_RedefineClasses::_matching_methods_length = 0;
  77 int       VM_RedefineClasses::_deleted_methods_length  = 0;
  78 int       VM_RedefineClasses::_added_methods_length    = 0;
  79 
  80 // This flag is global as the constructor does not reset it:
  81 bool      VM_RedefineClasses::_has_redefined_Object = false;
  82 u8        VM_RedefineClasses::_id_counter = 0;
  83 
  84 VM_RedefineClasses::VM_RedefineClasses(jint class_count,
  85                                        const jvmtiClassDefinition *class_defs,
  86                                        JvmtiClassLoadKind class_load_kind) {
  87   _class_count = class_count;
  88   _class_defs = class_defs;
  89   _class_load_kind = class_load_kind;
  90   _any_class_has_resolved_methods = false;
  91   _res = JVMTI_ERROR_NONE;
  92   _the_class = nullptr;
  93   _id = next_id();
  94 }
  95 
  96 static inline InstanceKlass* get_ik(jclass def) {
  97   oop mirror = JNIHandles::resolve_non_null(def);
  98   return InstanceKlass::cast(java_lang_Class::as_Klass(mirror));
  99 }
 100 
 101 // If any of the classes are being redefined, wait
 102 // Parallel constant pool merging leads to indeterminate constant pools.
 103 void VM_RedefineClasses::lock_classes() {
 104   JvmtiThreadState *state = JvmtiThreadState::state_for(JavaThread::current());
 105   GrowableArray<Klass*>* redef_classes = state->get_classes_being_redefined();
 106 
 107   MonitorLocker ml(RedefineClasses_lock);
 108 
 109   if (redef_classes == nullptr) {
 110     redef_classes = new (mtClass) GrowableArray<Klass*>(1, mtClass);
 111     state->set_classes_being_redefined(redef_classes);
 112   }
 113 
 114   bool has_redefined;
 115   do {
 116     has_redefined = false;
 117     // Go through classes each time until none are being redefined. Skip
 118     // the ones that are being redefined by this thread currently. Class file
 119     // load hook event may trigger new class redefine when we are redefining
 120     // a class (after lock_classes()).
 121     for (int i = 0; i < _class_count; i++) {
 122       InstanceKlass* ik = get_ik(_class_defs[i].klass);
 123       // Check if we are currently redefining the class in this thread already.
 124       if (redef_classes->contains(ik)) {
 125         assert(ik->is_being_redefined(), "sanity");
 126       } else {
 127         if (ik->is_being_redefined()) {
 128           ml.wait();
 129           has_redefined = true;
 130           break;  // for loop
 131         }
 132       }
 133     }
 134   } while (has_redefined);
 135 
 136   for (int i = 0; i < _class_count; i++) {
 137     InstanceKlass* ik = get_ik(_class_defs[i].klass);
 138     redef_classes->push(ik); // Add to the _classes_being_redefined list
 139     ik->set_is_being_redefined(true);
 140   }
 141   ml.notify_all();
 142 }
 143 
 144 void VM_RedefineClasses::unlock_classes() {
 145   JvmtiThreadState *state = JvmtiThreadState::state_for(JavaThread::current());
 146   GrowableArray<Klass*>* redef_classes = state->get_classes_being_redefined();
 147   assert(redef_classes != nullptr, "_classes_being_redefined is not allocated");
 148 
 149   MonitorLocker ml(RedefineClasses_lock);
 150 
 151   for (int i = _class_count - 1; i >= 0; i--) {
 152     InstanceKlass* def_ik = get_ik(_class_defs[i].klass);
 153     if (redef_classes->length() > 0) {
 154       // Remove the class from _classes_being_redefined list
 155       Klass* k = redef_classes->pop();
 156       assert(def_ik == k, "unlocking wrong class");
 157     }
 158     assert(def_ik->is_being_redefined(),
 159            "should be being redefined to get here");
 160 
 161     // Unlock after we finish all redefines for this class within
 162     // the thread. Same class can be pushed to the list multiple
 163     // times (not more than once by each recursive redefinition).
 164     if (!redef_classes->contains(def_ik)) {
 165       def_ik->set_is_being_redefined(false);
 166     }
 167   }
 168   ml.notify_all();
 169 }
 170 
 171 bool VM_RedefineClasses::doit_prologue() {
 172   if (_class_count == 0) {
 173     _res = JVMTI_ERROR_NONE;
 174     return false;
 175   }
 176   if (_class_defs == nullptr) {
 177     _res = JVMTI_ERROR_NULL_POINTER;
 178     return false;
 179   }
 180 
 181   for (int i = 0; i < _class_count; i++) {
 182     if (_class_defs[i].klass == nullptr) {
 183       _res = JVMTI_ERROR_INVALID_CLASS;
 184       return false;
 185     }
 186     if (_class_defs[i].class_byte_count == 0) {
 187       _res = JVMTI_ERROR_INVALID_CLASS_FORMAT;
 188       return false;
 189     }
 190     if (_class_defs[i].class_bytes == nullptr) {
 191       _res = JVMTI_ERROR_NULL_POINTER;
 192       return false;
 193     }
 194 
 195     oop mirror = JNIHandles::resolve_non_null(_class_defs[i].klass);
 196     // classes for primitives, arrays, and hidden classes
 197     // cannot be redefined.
 198     if (!is_modifiable_class(mirror)) {
 199       _res = JVMTI_ERROR_UNMODIFIABLE_CLASS;
 200       return false;
 201     }
 202   }
 203 
 204   // Start timer after all the sanity checks; not quite accurate, but
 205   // better than adding a bunch of stop() calls.
 206   if (log_is_enabled(Info, redefine, class, timer)) {
 207     _timer_vm_op_prologue.start();
 208   }
 209 
 210   lock_classes();
 211   // We first load new class versions in the prologue, because somewhere down the
 212   // call chain it is required that the current thread is a Java thread.
 213   _res = load_new_class_versions();
 214   if (_res != JVMTI_ERROR_NONE) {
 215     // free any successfully created classes, since none are redefined
 216     for (int i = 0; i < _class_count; i++) {
 217       if (_scratch_classes[i] != nullptr) {
 218         ClassLoaderData* cld = _scratch_classes[i]->class_loader_data();
 219         // Free the memory for this class at class unloading time.  Not before
 220         // because CMS might think this is still live.
 221         InstanceKlass* ik = get_ik(_class_defs[i].klass);
 222         if (ik->get_cached_class_file() == _scratch_classes[i]->get_cached_class_file()) {
 223           // Don't double-free cached_class_file copied from the original class if error.
 224           _scratch_classes[i]->set_cached_class_file(nullptr);
 225         }
 226         cld->add_to_deallocate_list(InstanceKlass::cast(_scratch_classes[i]));
 227       }
 228     }
 229     // Free os::malloc allocated memory in load_new_class_version.
 230     os::free(_scratch_classes);
 231     _timer_vm_op_prologue.stop();
 232     unlock_classes();
 233     return false;
 234   }
 235 
 236   _timer_vm_op_prologue.stop();
 237   return true;
 238 }
 239 
 240 void VM_RedefineClasses::doit() {
 241   Thread* current = Thread::current();
 242 
 243   if (log_is_enabled(Info, redefine, class, timer)) {
 244     _timer_vm_op_doit.start();
 245   }
 246 
 247 #if INCLUDE_CDS
 248   if (UseSharedSpaces) {
 249     // Sharing is enabled so we remap the shared readonly space to
 250     // shared readwrite, private just in case we need to redefine
 251     // a shared class. We do the remap during the doit() phase of
 252     // the safepoint to be safer.
 253     if (!MetaspaceShared::remap_shared_readonly_as_readwrite()) {
 254       log_info(redefine, class, load)("failed to remap shared readonly space to readwrite, private");
 255       _res = JVMTI_ERROR_INTERNAL;
 256       _timer_vm_op_doit.stop();
 257       return;
 258     }
 259   }
 260 #endif
 261 
 262   // Mark methods seen on stack and everywhere else so old methods are not
 263   // cleaned up if they're on the stack.
 264   MetadataOnStackMark md_on_stack(/*walk_all_metadata*/true, /*redefinition_walk*/true);
 265   HandleMark hm(current);   // make sure any handles created are deleted
 266                             // before the stack walk again.
 267 
 268   for (int i = 0; i < _class_count; i++) {
 269     redefine_single_class(current, _class_defs[i].klass, _scratch_classes[i]);
 270   }
 271 
 272   // Flush all compiled code that depends on the classes redefined.
 273   flush_dependent_code();
 274 
 275   // Adjust constantpool caches and vtables for all classes
 276   // that reference methods of the evolved classes.
 277   // Have to do this after all classes are redefined and all methods that
 278   // are redefined are marked as old.
 279   AdjustAndCleanMetadata adjust_and_clean_metadata(current);
 280   ClassLoaderDataGraph::classes_do(&adjust_and_clean_metadata);
 281 
 282   // JSR-292 support
 283   if (_any_class_has_resolved_methods) {
 284     bool trace_name_printed = false;
 285     ResolvedMethodTable::adjust_method_entries(&trace_name_printed);
 286   }
 287 
 288   // Increment flag indicating that some invariants are no longer true.
 289   // See jvmtiExport.hpp for detailed explanation.
 290   JvmtiExport::increment_redefinition_count();
 291 
 292   // check_class() is optionally called for product bits, but is
 293   // always called for non-product bits.
 294 #ifdef PRODUCT
 295   if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
 296 #endif
 297     log_trace(redefine, class, obsolete, metadata)("calling check_class");
 298     CheckClass check_class(current);
 299     ClassLoaderDataGraph::classes_do(&check_class);
 300 #ifdef PRODUCT
 301   }
 302 #endif
 303 
 304   // Clean up any metadata now unreferenced while MetadataOnStackMark is set.
 305   ClassLoaderDataGraph::clean_deallocate_lists(false);
 306 
 307   _timer_vm_op_doit.stop();
 308 }
 309 
 310 void VM_RedefineClasses::doit_epilogue() {
 311   unlock_classes();
 312 
 313   // Free os::malloc allocated memory.
 314   os::free(_scratch_classes);
 315 
 316   // Reset the_class to null for error printing.
 317   _the_class = nullptr;
 318 
 319   if (log_is_enabled(Info, redefine, class, timer)) {
 320     // Used to have separate timers for "doit" and "all", but the timer
 321     // overhead skewed the measurements.
 322     julong doit_time = _timer_vm_op_doit.milliseconds();
 323     julong all_time = _timer_vm_op_prologue.milliseconds() + doit_time;
 324 
 325     log_info(redefine, class, timer)
 326       ("vm_op: all=" JULONG_FORMAT "  prologue=" JULONG_FORMAT "  doit=" JULONG_FORMAT,
 327        all_time, (julong)_timer_vm_op_prologue.milliseconds(), doit_time);
 328     log_info(redefine, class, timer)
 329       ("redefine_single_class: phase1=" JULONG_FORMAT "  phase2=" JULONG_FORMAT,
 330        (julong)_timer_rsc_phase1.milliseconds(), (julong)_timer_rsc_phase2.milliseconds());
 331   }
 332 }
 333 
 334 bool VM_RedefineClasses::is_modifiable_class(oop klass_mirror) {
 335   // classes for primitives cannot be redefined
 336   if (java_lang_Class::is_primitive(klass_mirror)) {
 337     return false;
 338   }
 339   Klass* k = java_lang_Class::as_Klass(klass_mirror);
 340   // classes for arrays cannot be redefined
 341   if (k == nullptr || !k->is_instance_klass()) {
 342     return false;
 343   }
 344 
 345   // Cannot redefine or retransform a hidden class.
 346   if (InstanceKlass::cast(k)->is_hidden()) {
 347     return false;
 348   }
 349   if (InstanceKlass::cast(k) == vmClasses::Continuation_klass()) {
 350     // Don't redefine Continuation class. See 8302779.
 351     return false;
 352   }
 353   return true;
 354 }
 355 
 356 // Append the current entry at scratch_i in scratch_cp to *merge_cp_p
 357 // where the end of *merge_cp_p is specified by *merge_cp_length_p. For
 358 // direct CP entries, there is just the current entry to append. For
 359 // indirect and double-indirect CP entries, there are zero or more
 360 // referenced CP entries along with the current entry to append.
 361 // Indirect and double-indirect CP entries are handled by recursive
 362 // calls to append_entry() as needed. The referenced CP entries are
 363 // always appended to *merge_cp_p before the referee CP entry. These
 364 // referenced CP entries may already exist in *merge_cp_p in which case
 365 // there is nothing extra to append and only the current entry is
 366 // appended.
 367 void VM_RedefineClasses::append_entry(const constantPoolHandle& scratch_cp,
 368        int scratch_i, constantPoolHandle *merge_cp_p, int *merge_cp_length_p) {
 369 
 370   // append is different depending on entry tag type
 371   switch (scratch_cp->tag_at(scratch_i).value()) {
 372 
 373     // The old verifier is implemented outside the VM. It loads classes,
 374     // but does not resolve constant pool entries directly so we never
 375     // see Class entries here with the old verifier. Similarly the old
 376     // verifier does not like Class entries in the input constant pool.
 377     // The split-verifier is implemented in the VM so it can optionally
 378     // and directly resolve constant pool entries to load classes. The
 379     // split-verifier can accept either Class entries or UnresolvedClass
 380     // entries in the input constant pool. We revert the appended copy
 381     // back to UnresolvedClass so that either verifier will be happy
 382     // with the constant pool entry.
 383     //
 384     // this is an indirect CP entry so it needs special handling
 385     case JVM_CONSTANT_Class:
 386     case JVM_CONSTANT_UnresolvedClass:
 387     {
 388       int name_i = scratch_cp->klass_name_index_at(scratch_i);
 389       int new_name_i = find_or_append_indirect_entry(scratch_cp, name_i, merge_cp_p,
 390                                                      merge_cp_length_p);
 391 
 392       if (new_name_i != name_i) {
 393         log_trace(redefine, class, constantpool)
 394           ("Class entry@%d name_index change: %d to %d",
 395            *merge_cp_length_p, name_i, new_name_i);
 396       }
 397 
 398       (*merge_cp_p)->temp_unresolved_klass_at_put(*merge_cp_length_p, new_name_i);
 399       if (scratch_i != *merge_cp_length_p) {
 400         // The new entry in *merge_cp_p is at a different index than
 401         // the new entry in scratch_cp so we need to map the index values.
 402         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 403       }
 404       (*merge_cp_length_p)++;
 405     } break;
 406 
 407     // these are direct CP entries so they can be directly appended,
 408     // but double and long take two constant pool entries
 409     case JVM_CONSTANT_Double:  // fall through
 410     case JVM_CONSTANT_Long:
 411     {
 412       ConstantPool::copy_entry_to(scratch_cp, scratch_i, *merge_cp_p, *merge_cp_length_p);
 413 
 414       if (scratch_i != *merge_cp_length_p) {
 415         // The new entry in *merge_cp_p is at a different index than
 416         // the new entry in scratch_cp so we need to map the index values.
 417         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 418       }
 419       (*merge_cp_length_p) += 2;
 420     } break;
 421 
 422     // these are direct CP entries so they can be directly appended
 423     case JVM_CONSTANT_Float:   // fall through
 424     case JVM_CONSTANT_Integer: // fall through
 425     case JVM_CONSTANT_Utf8:    // fall through
 426 
 427     // This was an indirect CP entry, but it has been changed into
 428     // Symbol*s so this entry can be directly appended.
 429     case JVM_CONSTANT_String:      // fall through
 430     {
 431       ConstantPool::copy_entry_to(scratch_cp, scratch_i, *merge_cp_p, *merge_cp_length_p);
 432 
 433       if (scratch_i != *merge_cp_length_p) {
 434         // The new entry in *merge_cp_p is at a different index than
 435         // the new entry in scratch_cp so we need to map the index values.
 436         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 437       }
 438       (*merge_cp_length_p)++;
 439     } break;
 440 
 441     // this is an indirect CP entry so it needs special handling
 442     case JVM_CONSTANT_NameAndType:
 443     {
 444       int name_ref_i = scratch_cp->name_ref_index_at(scratch_i);
 445       int new_name_ref_i = find_or_append_indirect_entry(scratch_cp, name_ref_i, merge_cp_p,
 446                                                          merge_cp_length_p);
 447 
 448       int signature_ref_i = scratch_cp->signature_ref_index_at(scratch_i);
 449       int new_signature_ref_i = find_or_append_indirect_entry(scratch_cp, signature_ref_i,
 450                                                               merge_cp_p, merge_cp_length_p);
 451 
 452       // If the referenced entries already exist in *merge_cp_p, then
 453       // both new_name_ref_i and new_signature_ref_i will both be 0.
 454       // In that case, all we are appending is the current entry.
 455       if (new_name_ref_i != name_ref_i) {
 456         log_trace(redefine, class, constantpool)
 457           ("NameAndType entry@%d name_ref_index change: %d to %d",
 458            *merge_cp_length_p, name_ref_i, new_name_ref_i);
 459       }
 460       if (new_signature_ref_i != signature_ref_i) {
 461         log_trace(redefine, class, constantpool)
 462           ("NameAndType entry@%d signature_ref_index change: %d to %d",
 463            *merge_cp_length_p, signature_ref_i, new_signature_ref_i);
 464       }
 465 
 466       (*merge_cp_p)->name_and_type_at_put(*merge_cp_length_p,
 467         new_name_ref_i, new_signature_ref_i);
 468       if (scratch_i != *merge_cp_length_p) {
 469         // The new entry in *merge_cp_p is at a different index than
 470         // the new entry in scratch_cp so we need to map the index values.
 471         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 472       }
 473       (*merge_cp_length_p)++;
 474     } break;
 475 
 476     // this is a double-indirect CP entry so it needs special handling
 477     case JVM_CONSTANT_Fieldref:           // fall through
 478     case JVM_CONSTANT_InterfaceMethodref: // fall through
 479     case JVM_CONSTANT_Methodref:
 480     {
 481       int klass_ref_i = scratch_cp->uncached_klass_ref_index_at(scratch_i);
 482       int new_klass_ref_i = find_or_append_indirect_entry(scratch_cp, klass_ref_i,
 483                                                           merge_cp_p, merge_cp_length_p);
 484 
 485       int name_and_type_ref_i = scratch_cp->uncached_name_and_type_ref_index_at(scratch_i);
 486       int new_name_and_type_ref_i = find_or_append_indirect_entry(scratch_cp, name_and_type_ref_i,
 487                                                           merge_cp_p, merge_cp_length_p);
 488 
 489       const char *entry_name = nullptr;
 490       switch (scratch_cp->tag_at(scratch_i).value()) {
 491       case JVM_CONSTANT_Fieldref:
 492         entry_name = "Fieldref";
 493         (*merge_cp_p)->field_at_put(*merge_cp_length_p, new_klass_ref_i,
 494           new_name_and_type_ref_i);
 495         break;
 496       case JVM_CONSTANT_InterfaceMethodref:
 497         entry_name = "IFMethodref";
 498         (*merge_cp_p)->interface_method_at_put(*merge_cp_length_p,
 499           new_klass_ref_i, new_name_and_type_ref_i);
 500         break;
 501       case JVM_CONSTANT_Methodref:
 502         entry_name = "Methodref";
 503         (*merge_cp_p)->method_at_put(*merge_cp_length_p, new_klass_ref_i,
 504           new_name_and_type_ref_i);
 505         break;
 506       default:
 507         guarantee(false, "bad switch");
 508         break;
 509       }
 510 
 511       if (klass_ref_i != new_klass_ref_i) {
 512         log_trace(redefine, class, constantpool)
 513           ("%s entry@%d class_index changed: %d to %d", entry_name, *merge_cp_length_p, klass_ref_i, new_klass_ref_i);
 514       }
 515       if (name_and_type_ref_i != new_name_and_type_ref_i) {
 516         log_trace(redefine, class, constantpool)
 517           ("%s entry@%d name_and_type_index changed: %d to %d",
 518            entry_name, *merge_cp_length_p, name_and_type_ref_i, new_name_and_type_ref_i);
 519       }
 520 
 521       if (scratch_i != *merge_cp_length_p) {
 522         // The new entry in *merge_cp_p is at a different index than
 523         // the new entry in scratch_cp so we need to map the index values.
 524         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 525       }
 526       (*merge_cp_length_p)++;
 527     } break;
 528 
 529     // this is an indirect CP entry so it needs special handling
 530     case JVM_CONSTANT_MethodType:
 531     {
 532       int ref_i = scratch_cp->method_type_index_at(scratch_i);
 533       int new_ref_i = find_or_append_indirect_entry(scratch_cp, ref_i, merge_cp_p,
 534                                                     merge_cp_length_p);
 535       if (new_ref_i != ref_i) {
 536         log_trace(redefine, class, constantpool)
 537           ("MethodType entry@%d ref_index change: %d to %d", *merge_cp_length_p, ref_i, new_ref_i);
 538       }
 539       (*merge_cp_p)->method_type_index_at_put(*merge_cp_length_p, new_ref_i);
 540       if (scratch_i != *merge_cp_length_p) {
 541         // The new entry in *merge_cp_p is at a different index than
 542         // the new entry in scratch_cp so we need to map the index values.
 543         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 544       }
 545       (*merge_cp_length_p)++;
 546     } break;
 547 
 548     // this is an indirect CP entry so it needs special handling
 549     case JVM_CONSTANT_MethodHandle:
 550     {
 551       int ref_kind = scratch_cp->method_handle_ref_kind_at(scratch_i);
 552       int ref_i = scratch_cp->method_handle_index_at(scratch_i);
 553       int new_ref_i = find_or_append_indirect_entry(scratch_cp, ref_i, merge_cp_p,
 554                                                     merge_cp_length_p);
 555       if (new_ref_i != ref_i) {
 556         log_trace(redefine, class, constantpool)
 557           ("MethodHandle entry@%d ref_index change: %d to %d", *merge_cp_length_p, ref_i, new_ref_i);
 558       }
 559       (*merge_cp_p)->method_handle_index_at_put(*merge_cp_length_p, ref_kind, new_ref_i);
 560       if (scratch_i != *merge_cp_length_p) {
 561         // The new entry in *merge_cp_p is at a different index than
 562         // the new entry in scratch_cp so we need to map the index values.
 563         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 564       }
 565       (*merge_cp_length_p)++;
 566     } break;
 567 
 568     // this is an indirect CP entry so it needs special handling
 569     case JVM_CONSTANT_Dynamic:  // fall through
 570     case JVM_CONSTANT_InvokeDynamic:
 571     {
 572       // Index of the bootstrap specifier in the operands array
 573       int old_bs_i = scratch_cp->bootstrap_methods_attribute_index(scratch_i);
 574       int new_bs_i = find_or_append_operand(scratch_cp, old_bs_i, merge_cp_p,
 575                                             merge_cp_length_p);
 576       // The bootstrap method NameAndType_info index
 577       int old_ref_i = scratch_cp->bootstrap_name_and_type_ref_index_at(scratch_i);
 578       int new_ref_i = find_or_append_indirect_entry(scratch_cp, old_ref_i, merge_cp_p,
 579                                                     merge_cp_length_p);
 580       if (new_bs_i != old_bs_i) {
 581         log_trace(redefine, class, constantpool)
 582           ("Dynamic entry@%d bootstrap_method_attr_index change: %d to %d",
 583            *merge_cp_length_p, old_bs_i, new_bs_i);
 584       }
 585       if (new_ref_i != old_ref_i) {
 586         log_trace(redefine, class, constantpool)
 587           ("Dynamic entry@%d name_and_type_index change: %d to %d", *merge_cp_length_p, old_ref_i, new_ref_i);
 588       }
 589 
 590       if (scratch_cp->tag_at(scratch_i).is_dynamic_constant())
 591         (*merge_cp_p)->dynamic_constant_at_put(*merge_cp_length_p, new_bs_i, new_ref_i);
 592       else
 593         (*merge_cp_p)->invoke_dynamic_at_put(*merge_cp_length_p, new_bs_i, new_ref_i);
 594       if (scratch_i != *merge_cp_length_p) {
 595         // The new entry in *merge_cp_p is at a different index than
 596         // the new entry in scratch_cp so we need to map the index values.
 597         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 598       }
 599       (*merge_cp_length_p)++;
 600     } break;
 601 
 602     // At this stage, Class or UnresolvedClass could be in scratch_cp, but not
 603     // ClassIndex
 604     case JVM_CONSTANT_ClassIndex: // fall through
 605 
 606     // Invalid is used as the tag for the second constant pool entry
 607     // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
 608     // not be seen by itself.
 609     case JVM_CONSTANT_Invalid: // fall through
 610 
 611     // At this stage, String could be here, but not StringIndex
 612     case JVM_CONSTANT_StringIndex: // fall through
 613 
 614     // At this stage JVM_CONSTANT_UnresolvedClassInError should not be here

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