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