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