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