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