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