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