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