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