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