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