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