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