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