1 /*
   2  * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/metaspaceShared.hpp"
  27 #include "classfile/classFileStream.hpp"
  28 #include "classfile/classLoaderDataGraph.hpp"
  29 #include "classfile/classLoadInfo.hpp"
  30 #include "classfile/javaClasses.inline.hpp"
  31 #include "classfile/metadataOnStackMark.hpp"
  32 #include "classfile/symbolTable.hpp"
  33 #include "classfile/klassFactory.hpp"
  34 #include "classfile/verifier.hpp"
  35 #include "classfile/vmClasses.hpp"
  36 #include "classfile/vmSymbols.hpp"
  37 #include "code/codeCache.hpp"
  38 #include "compiler/compileBroker.hpp"
  39 #include "interpreter/oopMapCache.hpp"
  40 #include "interpreter/rewriter.hpp"
  41 #include "jfr/jfrEvents.hpp"
  42 #include "logging/logStream.hpp"
  43 #include "memory/metadataFactory.hpp"
  44 #include "memory/resourceArea.hpp"
  45 #include "memory/universe.hpp"
  46 #include "oops/annotations.hpp"
  47 #include "oops/constantPool.hpp"
  48 #include "oops/fieldStreams.inline.hpp"
  49 #include "oops/klass.inline.hpp"
  50 #include "oops/klassVtable.hpp"
  51 #include "oops/oop.inline.hpp"
  52 #include "oops/recordComponent.hpp"
  53 #include "prims/jvmtiImpl.hpp"
  54 #include "prims/jvmtiRedefineClasses.hpp"
  55 #include "prims/jvmtiThreadState.inline.hpp"
  56 #include "prims/resolvedMethodTable.hpp"
  57 #include "prims/methodComparator.hpp"
  58 #include "runtime/atomic.hpp"
  59 #include "runtime/deoptimization.hpp"
  60 #include "runtime/handles.inline.hpp"
  61 #include "runtime/jniHandles.inline.hpp"
  62 #include "runtime/relocator.hpp"
  63 #include "runtime/safepointVerifiers.hpp"
  64 #include "utilities/bitMap.inline.hpp"
  65 #include "utilities/events.hpp"
  66 
  67 Array<Method*>* VM_RedefineClasses::_old_methods = NULL;
  68 Array<Method*>* VM_RedefineClasses::_new_methods = NULL;
  69 Method**  VM_RedefineClasses::_matching_old_methods = NULL;
  70 Method**  VM_RedefineClasses::_matching_new_methods = NULL;
  71 Method**  VM_RedefineClasses::_deleted_methods      = NULL;
  72 Method**  VM_RedefineClasses::_added_methods        = NULL;
  73 int       VM_RedefineClasses::_matching_methods_length = 0;
  74 int       VM_RedefineClasses::_deleted_methods_length  = 0;
  75 int       VM_RedefineClasses::_added_methods_length    = 0;
  76 
  77 // This flag is global as the constructor does not reset it:
  78 bool      VM_RedefineClasses::_has_redefined_Object = false;
  79 u8        VM_RedefineClasses::_id_counter = 0;
  80 
  81 VM_RedefineClasses::VM_RedefineClasses(jint class_count,
  82                                        const jvmtiClassDefinition *class_defs,
  83                                        JvmtiClassLoadKind class_load_kind) {
  84   _class_count = class_count;
  85   _class_defs = class_defs;
  86   _class_load_kind = class_load_kind;
  87   _any_class_has_resolved_methods = false;
  88   _res = JVMTI_ERROR_NONE;
  89   _the_class = NULL;
  90   _id = next_id();
  91 }
  92 
  93 static inline InstanceKlass* get_ik(jclass def) {
  94   oop mirror = JNIHandles::resolve_non_null(def);
  95   return InstanceKlass::cast(java_lang_Class::as_Klass(mirror));
  96 }
  97 
  98 // If any of the classes are being redefined, wait
  99 // Parallel constant pool merging leads to indeterminate constant pools.
 100 void VM_RedefineClasses::lock_classes() {
 101   JvmtiThreadState *state = JvmtiThreadState::state_for(JavaThread::current());
 102   GrowableArray<Klass*>* redef_classes = state->get_classes_being_redefined();
 103 
 104   MonitorLocker ml(RedefineClasses_lock);
 105 
 106   if (redef_classes == NULL) {
 107     redef_classes = new(ResourceObj::C_HEAP, mtClass) GrowableArray<Klass*>(1, mtClass);
 108     state->set_classes_being_redefined(redef_classes);
 109   }
 110 
 111   bool has_redefined;
 112   do {
 113     has_redefined = false;
 114     // Go through classes each time until none are being redefined. Skip
 115     // the ones that are being redefined by this thread currently. Class file
 116     // load hook event may trigger new class redefine when we are redefining
 117     // a class (after lock_classes()).
 118     for (int i = 0; i < _class_count; i++) {
 119       InstanceKlass* ik = get_ik(_class_defs[i].klass);
 120       // Check if we are currently redefining the class in this thread already.
 121       if (redef_classes->contains(ik)) {
 122         assert(ik->is_being_redefined(), "sanity");
 123       } else {
 124         if (ik->is_being_redefined()) {
 125           ml.wait();
 126           has_redefined = true;
 127           break;  // for loop
 128         }
 129       }
 130     }
 131   } while (has_redefined);
 132 
 133   for (int i = 0; i < _class_count; i++) {
 134     InstanceKlass* ik = get_ik(_class_defs[i].klass);
 135     redef_classes->push(ik); // Add to the _classes_being_redefined list
 136     ik->set_is_being_redefined(true);
 137   }
 138   ml.notify_all();
 139 }
 140 
 141 void VM_RedefineClasses::unlock_classes() {
 142   JvmtiThreadState *state = JvmtiThreadState::state_for(JavaThread::current());
 143   GrowableArray<Klass*>* redef_classes = state->get_classes_being_redefined();
 144   assert(redef_classes != NULL, "_classes_being_redefined is not allocated");
 145 
 146   MonitorLocker ml(RedefineClasses_lock);
 147 
 148   for (int i = _class_count - 1; i >= 0; i--) {
 149     InstanceKlass* def_ik = get_ik(_class_defs[i].klass);
 150     if (redef_classes->length() > 0) {
 151       // Remove the class from _classes_being_redefined list
 152       Klass* k = redef_classes->pop();
 153       assert(def_ik == k, "unlocking wrong class");
 154     }
 155     assert(def_ik->is_being_redefined(),
 156            "should be being redefined to get here");
 157 
 158     // Unlock after we finish all redefines for this class within
 159     // the thread. Same class can be pushed to the list multiple
 160     // times (not more than once by each recursive redefinition).
 161     if (!redef_classes->contains(def_ik)) {
 162       def_ik->set_is_being_redefined(false);
 163     }
 164   }
 165   ml.notify_all();
 166 }
 167 
 168 bool VM_RedefineClasses::doit_prologue() {
 169   if (_class_count == 0) {
 170     _res = JVMTI_ERROR_NONE;
 171     return false;
 172   }
 173   if (_class_defs == NULL) {
 174     _res = JVMTI_ERROR_NULL_POINTER;
 175     return false;
 176   }
 177 
 178   for (int i = 0; i < _class_count; i++) {
 179     if (_class_defs[i].klass == NULL) {
 180       _res = JVMTI_ERROR_INVALID_CLASS;
 181       return false;
 182     }
 183     if (_class_defs[i].class_byte_count == 0) {
 184       _res = JVMTI_ERROR_INVALID_CLASS_FORMAT;
 185       return false;
 186     }
 187     if (_class_defs[i].class_bytes == NULL) {
 188       _res = JVMTI_ERROR_NULL_POINTER;
 189       return false;
 190     }
 191 
 192     oop mirror = JNIHandles::resolve_non_null(_class_defs[i].klass);
 193     // classes for primitives, arrays, and hidden classes
 194     // cannot be redefined.
 195     if (!is_modifiable_class(mirror)) {
 196       _res = JVMTI_ERROR_UNMODIFIABLE_CLASS;
 197       return false;
 198     }
 199   }
 200 
 201   // Start timer after all the sanity checks; not quite accurate, but
 202   // better than adding a bunch of stop() calls.
 203   if (log_is_enabled(Info, redefine, class, timer)) {
 204     _timer_vm_op_prologue.start();
 205   }
 206 
 207   lock_classes();
 208   // We first load new class versions in the prologue, because somewhere down the
 209   // call chain it is required that the current thread is a Java thread.
 210   _res = load_new_class_versions();
 211   if (_res != JVMTI_ERROR_NONE) {
 212     // free any successfully created classes, since none are redefined
 213     for (int i = 0; i < _class_count; i++) {
 214       if (_scratch_classes[i] != NULL) {
 215         ClassLoaderData* cld = _scratch_classes[i]->class_loader_data();
 216         // Free the memory for this class at class unloading time.  Not before
 217         // because CMS might think this is still live.
 218         InstanceKlass* ik = get_ik(_class_defs[i].klass);
 219         if (ik->get_cached_class_file() == _scratch_classes[i]->get_cached_class_file()) {
 220           // Don't double-free cached_class_file copied from the original class if error.
 221           _scratch_classes[i]->set_cached_class_file(NULL);
 222         }
 223         cld->add_to_deallocate_list(InstanceKlass::cast(_scratch_classes[i]));
 224       }
 225     }
 226     // Free os::malloc allocated memory in load_new_class_version.
 227     os::free(_scratch_classes);
 228     _timer_vm_op_prologue.stop();
 229     unlock_classes();
 230     return false;
 231   }
 232 
 233   _timer_vm_op_prologue.stop();
 234   return true;
 235 }
 236 
 237 void VM_RedefineClasses::doit() {
 238   Thread* current = Thread::current();
 239 
 240 #if INCLUDE_CDS
 241   if (UseSharedSpaces) {
 242     // Sharing is enabled so we remap the shared readonly space to
 243     // shared readwrite, private just in case we need to redefine
 244     // a shared class. We do the remap during the doit() phase of
 245     // the safepoint to be safer.
 246     if (!MetaspaceShared::remap_shared_readonly_as_readwrite()) {
 247       log_info(redefine, class, load)("failed to remap shared readonly space to readwrite, private");
 248       _res = JVMTI_ERROR_INTERNAL;
 249       return;
 250     }
 251   }
 252 #endif
 253 
 254   // Mark methods seen on stack and everywhere else so old methods are not
 255   // cleaned up if they're on the stack.
 256   MetadataOnStackMark md_on_stack(/*walk_all_metadata*/true, /*redefinition_walk*/true);
 257   HandleMark hm(current);   // make sure any handles created are deleted
 258                             // before the stack walk again.
 259 
 260   for (int i = 0; i < _class_count; i++) {
 261     redefine_single_class(current, _class_defs[i].klass, _scratch_classes[i]);
 262   }
 263 
 264   // Flush all compiled code that depends on the classes redefined.
 265   flush_dependent_code();
 266 
 267   // Adjust constantpool caches and vtables for all classes
 268   // that reference methods of the evolved classes.
 269   // Have to do this after all classes are redefined and all methods that
 270   // are redefined are marked as old.
 271   AdjustAndCleanMetadata adjust_and_clean_metadata(current);
 272   ClassLoaderDataGraph::classes_do(&adjust_and_clean_metadata);
 273 
 274   // JSR-292 support
 275   if (_any_class_has_resolved_methods) {
 276     bool trace_name_printed = false;
 277     ResolvedMethodTable::adjust_method_entries(&trace_name_printed);
 278   }
 279 
 280   // Increment flag indicating that some invariants are no longer true.
 281   // See jvmtiExport.hpp for detailed explanation.
 282   JvmtiExport::increment_redefinition_count();
 283 
 284   // check_class() is optionally called for product bits, but is
 285   // always called for non-product bits.
 286 #ifdef PRODUCT
 287   if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
 288 #endif
 289     log_trace(redefine, class, obsolete, metadata)("calling check_class");
 290     CheckClass check_class(current);
 291     ClassLoaderDataGraph::classes_do(&check_class);
 292 #ifdef PRODUCT
 293   }
 294 #endif
 295 
 296   // Clean up any metadata now unreferenced while MetadataOnStackMark is set.
 297   ClassLoaderDataGraph::clean_deallocate_lists(false);
 298 }
 299 
 300 void VM_RedefineClasses::doit_epilogue() {
 301   unlock_classes();
 302 
 303   // Free os::malloc allocated memory.
 304   os::free(_scratch_classes);
 305 
 306   // Reset the_class to null for error printing.
 307   _the_class = NULL;
 308 
 309   if (log_is_enabled(Info, redefine, class, timer)) {
 310     // Used to have separate timers for "doit" and "all", but the timer
 311     // overhead skewed the measurements.
 312     julong doit_time = _timer_rsc_phase1.milliseconds() +
 313                        _timer_rsc_phase2.milliseconds();
 314     julong all_time = _timer_vm_op_prologue.milliseconds() + doit_time;
 315 
 316     log_info(redefine, class, timer)
 317       ("vm_op: all=" JULONG_FORMAT "  prologue=" JULONG_FORMAT "  doit=" JULONG_FORMAT,
 318        all_time, (julong)_timer_vm_op_prologue.milliseconds(), doit_time);
 319     log_info(redefine, class, timer)
 320       ("redefine_single_class: phase1=" JULONG_FORMAT "  phase2=" JULONG_FORMAT,
 321        (julong)_timer_rsc_phase1.milliseconds(), (julong)_timer_rsc_phase2.milliseconds());
 322   }
 323 }
 324 
 325 bool VM_RedefineClasses::is_modifiable_class(oop klass_mirror) {
 326   // classes for primitives cannot be redefined
 327   if (java_lang_Class::is_primitive(klass_mirror)) {
 328     return false;
 329   }
 330   Klass* k = java_lang_Class::as_Klass(klass_mirror);
 331   // classes for arrays cannot be redefined
 332   if (k == NULL || !k->is_instance_klass()) {
 333     return false;
 334   }
 335 
 336   // Cannot redefine or retransform a hidden class.
 337   if (InstanceKlass::cast(k)->is_hidden()) {
 338     return false;
 339   }
 340   return true;
 341 }
 342 
 343 // Append the current entry at scratch_i in scratch_cp to *merge_cp_p
 344 // where the end of *merge_cp_p is specified by *merge_cp_length_p. For
 345 // direct CP entries, there is just the current entry to append. For
 346 // indirect and double-indirect CP entries, there are zero or more
 347 // referenced CP entries along with the current entry to append.
 348 // Indirect and double-indirect CP entries are handled by recursive
 349 // calls to append_entry() as needed. The referenced CP entries are
 350 // always appended to *merge_cp_p before the referee CP entry. These
 351 // referenced CP entries may already exist in *merge_cp_p in which case
 352 // there is nothing extra to append and only the current entry is
 353 // appended.
 354 void VM_RedefineClasses::append_entry(const constantPoolHandle& scratch_cp,
 355        int scratch_i, constantPoolHandle *merge_cp_p, int *merge_cp_length_p) {
 356 
 357   // append is different depending on entry tag type
 358   switch (scratch_cp->tag_at(scratch_i).value()) {
 359 
 360     // The old verifier is implemented outside the VM. It loads classes,
 361     // but does not resolve constant pool entries directly so we never
 362     // see Class entries here with the old verifier. Similarly the old
 363     // verifier does not like Class entries in the input constant pool.
 364     // The split-verifier is implemented in the VM so it can optionally
 365     // and directly resolve constant pool entries to load classes. The
 366     // split-verifier can accept either Class entries or UnresolvedClass
 367     // entries in the input constant pool. We revert the appended copy
 368     // back to UnresolvedClass so that either verifier will be happy
 369     // with the constant pool entry.
 370     //
 371     // this is an indirect CP entry so it needs special handling
 372     case JVM_CONSTANT_Class:
 373     case JVM_CONSTANT_UnresolvedClass:
 374     {
 375       int name_i = scratch_cp->klass_name_index_at(scratch_i);
 376       int new_name_i = find_or_append_indirect_entry(scratch_cp, name_i, merge_cp_p,
 377                                                      merge_cp_length_p);
 378 
 379       if (new_name_i != name_i) {
 380         log_trace(redefine, class, constantpool)
 381           ("Class entry@%d name_index change: %d to %d",
 382            *merge_cp_length_p, name_i, new_name_i);
 383       }
 384 
 385       (*merge_cp_p)->temp_unresolved_klass_at_put(*merge_cp_length_p, new_name_i);
 386       if (scratch_i != *merge_cp_length_p) {
 387         // The new entry in *merge_cp_p is at a different index than
 388         // the new entry in scratch_cp so we need to map the index values.
 389         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 390       }
 391       (*merge_cp_length_p)++;
 392     } break;
 393 
 394     // these are direct CP entries so they can be directly appended,
 395     // but double and long take two constant pool entries
 396     case JVM_CONSTANT_Double:  // fall through
 397     case JVM_CONSTANT_Long:
 398     {
 399       ConstantPool::copy_entry_to(scratch_cp, scratch_i, *merge_cp_p, *merge_cp_length_p);
 400 
 401       if (scratch_i != *merge_cp_length_p) {
 402         // The new entry in *merge_cp_p is at a different index than
 403         // the new entry in scratch_cp so we need to map the index values.
 404         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 405       }
 406       (*merge_cp_length_p) += 2;
 407     } break;
 408 
 409     // these are direct CP entries so they can be directly appended
 410     case JVM_CONSTANT_Float:   // fall through
 411     case JVM_CONSTANT_Integer: // fall through
 412     case JVM_CONSTANT_Utf8:    // fall through
 413 
 414     // This was an indirect CP entry, but it has been changed into
 415     // Symbol*s so this entry can be directly appended.
 416     case JVM_CONSTANT_String:      // fall through
 417     {
 418       ConstantPool::copy_entry_to(scratch_cp, scratch_i, *merge_cp_p, *merge_cp_length_p);
 419 
 420       if (scratch_i != *merge_cp_length_p) {
 421         // The new entry in *merge_cp_p is at a different index than
 422         // the new entry in scratch_cp so we need to map the index values.
 423         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 424       }
 425       (*merge_cp_length_p)++;
 426     } break;
 427 
 428     // this is an indirect CP entry so it needs special handling
 429     case JVM_CONSTANT_NameAndType:
 430     {
 431       int name_ref_i = scratch_cp->name_ref_index_at(scratch_i);
 432       int new_name_ref_i = find_or_append_indirect_entry(scratch_cp, name_ref_i, merge_cp_p,
 433                                                          merge_cp_length_p);
 434 
 435       int signature_ref_i = scratch_cp->signature_ref_index_at(scratch_i);
 436       int new_signature_ref_i = find_or_append_indirect_entry(scratch_cp, signature_ref_i,
 437                                                               merge_cp_p, merge_cp_length_p);
 438 
 439       // If the referenced entries already exist in *merge_cp_p, then
 440       // both new_name_ref_i and new_signature_ref_i will both be 0.
 441       // In that case, all we are appending is the current entry.
 442       if (new_name_ref_i != name_ref_i) {
 443         log_trace(redefine, class, constantpool)
 444           ("NameAndType entry@%d name_ref_index change: %d to %d",
 445            *merge_cp_length_p, name_ref_i, new_name_ref_i);
 446       }
 447       if (new_signature_ref_i != signature_ref_i) {
 448         log_trace(redefine, class, constantpool)
 449           ("NameAndType entry@%d signature_ref_index change: %d to %d",
 450            *merge_cp_length_p, signature_ref_i, new_signature_ref_i);
 451       }
 452 
 453       (*merge_cp_p)->name_and_type_at_put(*merge_cp_length_p,
 454         new_name_ref_i, new_signature_ref_i);
 455       if (scratch_i != *merge_cp_length_p) {
 456         // The new entry in *merge_cp_p is at a different index than
 457         // the new entry in scratch_cp so we need to map the index values.
 458         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 459       }
 460       (*merge_cp_length_p)++;
 461     } break;
 462 
 463     // this is a double-indirect CP entry so it needs special handling
 464     case JVM_CONSTANT_Fieldref:           // fall through
 465     case JVM_CONSTANT_InterfaceMethodref: // fall through
 466     case JVM_CONSTANT_Methodref:
 467     {
 468       int klass_ref_i = scratch_cp->uncached_klass_ref_index_at(scratch_i);
 469       int new_klass_ref_i = find_or_append_indirect_entry(scratch_cp, klass_ref_i,
 470                                                           merge_cp_p, merge_cp_length_p);
 471 
 472       int name_and_type_ref_i = scratch_cp->uncached_name_and_type_ref_index_at(scratch_i);
 473       int new_name_and_type_ref_i = find_or_append_indirect_entry(scratch_cp, name_and_type_ref_i,
 474                                                           merge_cp_p, merge_cp_length_p);
 475 
 476       const char *entry_name = NULL;
 477       switch (scratch_cp->tag_at(scratch_i).value()) {
 478       case JVM_CONSTANT_Fieldref:
 479         entry_name = "Fieldref";
 480         (*merge_cp_p)->field_at_put(*merge_cp_length_p, new_klass_ref_i,
 481           new_name_and_type_ref_i);
 482         break;
 483       case JVM_CONSTANT_InterfaceMethodref:
 484         entry_name = "IFMethodref";
 485         (*merge_cp_p)->interface_method_at_put(*merge_cp_length_p,
 486           new_klass_ref_i, new_name_and_type_ref_i);
 487         break;
 488       case JVM_CONSTANT_Methodref:
 489         entry_name = "Methodref";
 490         (*merge_cp_p)->method_at_put(*merge_cp_length_p, new_klass_ref_i,
 491           new_name_and_type_ref_i);
 492         break;
 493       default:
 494         guarantee(false, "bad switch");
 495         break;
 496       }
 497 
 498       if (klass_ref_i != new_klass_ref_i) {
 499         log_trace(redefine, class, constantpool)
 500           ("%s entry@%d class_index changed: %d to %d", entry_name, *merge_cp_length_p, klass_ref_i, new_klass_ref_i);
 501       }
 502       if (name_and_type_ref_i != new_name_and_type_ref_i) {
 503         log_trace(redefine, class, constantpool)
 504           ("%s entry@%d name_and_type_index changed: %d to %d",
 505            entry_name, *merge_cp_length_p, name_and_type_ref_i, new_name_and_type_ref_i);
 506       }
 507 
 508       if (scratch_i != *merge_cp_length_p) {
 509         // The new entry in *merge_cp_p is at a different index than
 510         // the new entry in scratch_cp so we need to map the index values.
 511         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 512       }
 513       (*merge_cp_length_p)++;
 514     } break;
 515 
 516     // this is an indirect CP entry so it needs special handling
 517     case JVM_CONSTANT_MethodType:
 518     {
 519       int ref_i = scratch_cp->method_type_index_at(scratch_i);
 520       int new_ref_i = find_or_append_indirect_entry(scratch_cp, ref_i, merge_cp_p,
 521                                                     merge_cp_length_p);
 522       if (new_ref_i != ref_i) {
 523         log_trace(redefine, class, constantpool)
 524           ("MethodType entry@%d ref_index change: %d to %d", *merge_cp_length_p, ref_i, new_ref_i);
 525       }
 526       (*merge_cp_p)->method_type_index_at_put(*merge_cp_length_p, new_ref_i);
 527       if (scratch_i != *merge_cp_length_p) {
 528         // The new entry in *merge_cp_p is at a different index than
 529         // the new entry in scratch_cp so we need to map the index values.
 530         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 531       }
 532       (*merge_cp_length_p)++;
 533     } break;
 534 
 535     // this is an indirect CP entry so it needs special handling
 536     case JVM_CONSTANT_MethodHandle:
 537     {
 538       int ref_kind = scratch_cp->method_handle_ref_kind_at(scratch_i);
 539       int ref_i = scratch_cp->method_handle_index_at(scratch_i);
 540       int new_ref_i = find_or_append_indirect_entry(scratch_cp, ref_i, merge_cp_p,
 541                                                     merge_cp_length_p);
 542       if (new_ref_i != ref_i) {
 543         log_trace(redefine, class, constantpool)
 544           ("MethodHandle entry@%d ref_index change: %d to %d", *merge_cp_length_p, ref_i, new_ref_i);
 545       }
 546       (*merge_cp_p)->method_handle_index_at_put(*merge_cp_length_p, ref_kind, new_ref_i);
 547       if (scratch_i != *merge_cp_length_p) {
 548         // The new entry in *merge_cp_p is at a different index than
 549         // the new entry in scratch_cp so we need to map the index values.
 550         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 551       }
 552       (*merge_cp_length_p)++;
 553     } break;
 554 
 555     // this is an indirect CP entry so it needs special handling
 556     case JVM_CONSTANT_Dynamic:  // fall through
 557     case JVM_CONSTANT_InvokeDynamic:
 558     {
 559       // Index of the bootstrap specifier in the operands array
 560       int old_bs_i = scratch_cp->bootstrap_methods_attribute_index(scratch_i);
 561       int new_bs_i = find_or_append_operand(scratch_cp, old_bs_i, merge_cp_p,
 562                                             merge_cp_length_p);
 563       // The bootstrap method NameAndType_info index
 564       int old_ref_i = scratch_cp->bootstrap_name_and_type_ref_index_at(scratch_i);
 565       int new_ref_i = find_or_append_indirect_entry(scratch_cp, old_ref_i, merge_cp_p,
 566                                                     merge_cp_length_p);
 567       if (new_bs_i != old_bs_i) {
 568         log_trace(redefine, class, constantpool)
 569           ("Dynamic entry@%d bootstrap_method_attr_index change: %d to %d",
 570            *merge_cp_length_p, old_bs_i, new_bs_i);
 571       }
 572       if (new_ref_i != old_ref_i) {
 573         log_trace(redefine, class, constantpool)
 574           ("Dynamic entry@%d name_and_type_index change: %d to %d", *merge_cp_length_p, old_ref_i, new_ref_i);
 575       }
 576 
 577       if (scratch_cp->tag_at(scratch_i).is_dynamic_constant())
 578         (*merge_cp_p)->dynamic_constant_at_put(*merge_cp_length_p, new_bs_i, new_ref_i);
 579       else
 580         (*merge_cp_p)->invoke_dynamic_at_put(*merge_cp_length_p, new_bs_i, new_ref_i);
 581       if (scratch_i != *merge_cp_length_p) {
 582         // The new entry in *merge_cp_p is at a different index than
 583         // the new entry in scratch_cp so we need to map the index values.
 584         map_index(scratch_cp, scratch_i, *merge_cp_length_p);
 585       }
 586       (*merge_cp_length_p)++;
 587     } break;
 588 
 589     // At this stage, Class or UnresolvedClass could be in scratch_cp, but not
 590     // ClassIndex
 591     case JVM_CONSTANT_ClassIndex: // fall through
 592 
 593     // Invalid is used as the tag for the second constant pool entry
 594     // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
 595     // not be seen by itself.
 596     case JVM_CONSTANT_Invalid: // fall through
 597 
 598     // At this stage, String could be here, but not StringIndex
 599     case JVM_CONSTANT_StringIndex: // fall through
 600 
 601     // At this stage JVM_CONSTANT_UnresolvedClassInError should not be
 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 } // end rewrite_cp_refs_in_method()
2270 
2271 
2272 // Rewrite constant pool references in the class_annotations field.
2273 bool VM_RedefineClasses::rewrite_cp_refs_in_class_annotations(InstanceKlass* scratch_class) {
2274 
2275   AnnotationArray* class_annotations = scratch_class->class_annotations();
2276   if (class_annotations == NULL || class_annotations->length() == 0) {
2277     // no class_annotations so nothing to do
2278     return true;
2279   }
2280 
2281   log_debug(redefine, class, annotation)("class_annotations length=%d", class_annotations->length());
2282 
2283   int byte_i = 0;  // byte index into class_annotations
2284   return rewrite_cp_refs_in_annotations_typeArray(class_annotations, byte_i);
2285 }
2286 
2287 
2288 // Rewrite constant pool references in an annotations typeArray. This
2289 // "structure" is adapted from the RuntimeVisibleAnnotations_attribute
2290 // that is described in section 4.8.15 of the 2nd-edition of the VM spec:
2291 //
2292 // annotations_typeArray {
2293 //   u2 num_annotations;
2294 //   annotation annotations[num_annotations];
2295 // }
2296 //
2297 bool VM_RedefineClasses::rewrite_cp_refs_in_annotations_typeArray(
2298        AnnotationArray* annotations_typeArray, int &byte_i_ref) {
2299 
2300   if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2301     // not enough room for num_annotations field
2302     log_debug(redefine, class, annotation)("length() is too small for num_annotations field");
2303     return false;
2304   }
2305 
2306   u2 num_annotations = Bytes::get_Java_u2((address)
2307                          annotations_typeArray->adr_at(byte_i_ref));
2308   byte_i_ref += 2;
2309 
2310   log_debug(redefine, class, annotation)("num_annotations=%d", num_annotations);
2311 
2312   int calc_num_annotations = 0;
2313   for (; calc_num_annotations < num_annotations; calc_num_annotations++) {
2314     if (!rewrite_cp_refs_in_annotation_struct(annotations_typeArray, byte_i_ref)) {
2315       log_debug(redefine, class, annotation)("bad annotation_struct at %d", calc_num_annotations);
2316       // propagate failure back to caller
2317       return false;
2318     }
2319   }
2320   assert(num_annotations == calc_num_annotations, "sanity check");
2321 
2322   return true;
2323 } // end rewrite_cp_refs_in_annotations_typeArray()
2324 
2325 
2326 // Rewrite constant pool references in the annotation struct portion of
2327 // an annotations_typeArray. This "structure" is from section 4.8.15 of
2328 // the 2nd-edition of the VM spec:
2329 //
2330 // struct annotation {
2331 //   u2 type_index;
2332 //   u2 num_element_value_pairs;
2333 //   {
2334 //     u2 element_name_index;
2335 //     element_value value;
2336 //   } element_value_pairs[num_element_value_pairs];
2337 // }
2338 //
2339 bool VM_RedefineClasses::rewrite_cp_refs_in_annotation_struct(
2340        AnnotationArray* annotations_typeArray, int &byte_i_ref) {
2341   if ((byte_i_ref + 2 + 2) > annotations_typeArray->length()) {
2342     // not enough room for smallest annotation_struct
2343     log_debug(redefine, class, annotation)("length() is too small for annotation_struct");
2344     return false;
2345   }
2346 
2347   u2 type_index = rewrite_cp_ref_in_annotation_data(annotations_typeArray,
2348                     byte_i_ref, "type_index");
2349 
2350   u2 num_element_value_pairs = Bytes::get_Java_u2((address)
2351                                  annotations_typeArray->adr_at(byte_i_ref));
2352   byte_i_ref += 2;
2353 
2354   log_debug(redefine, class, annotation)
2355     ("type_index=%d  num_element_value_pairs=%d", type_index, num_element_value_pairs);
2356 
2357   int calc_num_element_value_pairs = 0;
2358   for (; calc_num_element_value_pairs < num_element_value_pairs;
2359        calc_num_element_value_pairs++) {
2360     if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2361       // not enough room for another element_name_index, let alone
2362       // the rest of another component
2363       log_debug(redefine, class, annotation)("length() is too small for element_name_index");
2364       return false;
2365     }
2366 
2367     u2 element_name_index = rewrite_cp_ref_in_annotation_data(
2368                               annotations_typeArray, byte_i_ref,
2369                               "element_name_index");
2370 
2371     log_debug(redefine, class, annotation)("element_name_index=%d", element_name_index);
2372 
2373     if (!rewrite_cp_refs_in_element_value(annotations_typeArray, byte_i_ref)) {
2374       log_debug(redefine, class, annotation)("bad element_value at %d", calc_num_element_value_pairs);
2375       // propagate failure back to caller
2376       return false;
2377     }
2378   } // end for each component
2379   assert(num_element_value_pairs == calc_num_element_value_pairs,
2380     "sanity check");
2381 
2382   return true;
2383 } // end rewrite_cp_refs_in_annotation_struct()
2384 
2385 
2386 // Rewrite a constant pool reference at the current position in
2387 // annotations_typeArray if needed. Returns the original constant
2388 // pool reference if a rewrite was not needed or the new constant
2389 // pool reference if a rewrite was needed.
2390 u2 VM_RedefineClasses::rewrite_cp_ref_in_annotation_data(
2391      AnnotationArray* annotations_typeArray, int &byte_i_ref,
2392      const char * trace_mesg) {
2393 
2394   address cp_index_addr = (address)
2395     annotations_typeArray->adr_at(byte_i_ref);
2396   u2 old_cp_index = Bytes::get_Java_u2(cp_index_addr);
2397   u2 new_cp_index = find_new_index(old_cp_index);
2398   if (new_cp_index != 0) {
2399     log_debug(redefine, class, annotation)("mapped old %s=%d", trace_mesg, old_cp_index);
2400     Bytes::put_Java_u2(cp_index_addr, new_cp_index);
2401     old_cp_index = new_cp_index;
2402   }
2403   byte_i_ref += 2;
2404   return old_cp_index;
2405 }
2406 
2407 
2408 // Rewrite constant pool references in the element_value portion of an
2409 // annotations_typeArray. This "structure" is from section 4.8.15.1 of
2410 // the 2nd-edition of the VM spec:
2411 //
2412 // struct element_value {
2413 //   u1 tag;
2414 //   union {
2415 //     u2 const_value_index;
2416 //     {
2417 //       u2 type_name_index;
2418 //       u2 const_name_index;
2419 //     } enum_const_value;
2420 //     u2 class_info_index;
2421 //     annotation annotation_value;
2422 //     struct {
2423 //       u2 num_values;
2424 //       element_value values[num_values];
2425 //     } array_value;
2426 //   } value;
2427 // }
2428 //
2429 bool VM_RedefineClasses::rewrite_cp_refs_in_element_value(
2430        AnnotationArray* annotations_typeArray, int &byte_i_ref) {
2431 
2432   if ((byte_i_ref + 1) > annotations_typeArray->length()) {
2433     // not enough room for a tag let alone the rest of an element_value
2434     log_debug(redefine, class, annotation)("length() is too small for a tag");
2435     return false;
2436   }
2437 
2438   u1 tag = annotations_typeArray->at(byte_i_ref);
2439   byte_i_ref++;
2440   log_debug(redefine, class, annotation)("tag='%c'", tag);
2441 
2442   switch (tag) {
2443     // These BaseType tag values are from Table 4.2 in VM spec:
2444     case JVM_SIGNATURE_BYTE:
2445     case JVM_SIGNATURE_CHAR:
2446     case JVM_SIGNATURE_DOUBLE:
2447     case JVM_SIGNATURE_FLOAT:
2448     case JVM_SIGNATURE_INT:
2449     case JVM_SIGNATURE_LONG:
2450     case JVM_SIGNATURE_SHORT:
2451     case JVM_SIGNATURE_BOOLEAN:
2452 
2453     // The remaining tag values are from Table 4.8 in the 2nd-edition of
2454     // the VM spec:
2455     case 's':
2456     {
2457       // For the above tag values (including the BaseType values),
2458       // value.const_value_index is right union field.
2459 
2460       if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2461         // not enough room for a const_value_index
2462         log_debug(redefine, class, annotation)("length() is too small for a const_value_index");
2463         return false;
2464       }
2465 
2466       u2 const_value_index = rewrite_cp_ref_in_annotation_data(
2467                                annotations_typeArray, byte_i_ref,
2468                                "const_value_index");
2469 
2470       log_debug(redefine, class, annotation)("const_value_index=%d", const_value_index);
2471     } break;
2472 
2473     case 'e':
2474     {
2475       // for the above tag value, value.enum_const_value is right union field
2476 
2477       if ((byte_i_ref + 4) > annotations_typeArray->length()) {
2478         // not enough room for a enum_const_value
2479         log_debug(redefine, class, annotation)("length() is too small for a enum_const_value");
2480         return false;
2481       }
2482 
2483       u2 type_name_index = rewrite_cp_ref_in_annotation_data(
2484                              annotations_typeArray, byte_i_ref,
2485                              "type_name_index");
2486 
2487       u2 const_name_index = rewrite_cp_ref_in_annotation_data(
2488                               annotations_typeArray, byte_i_ref,
2489                               "const_name_index");
2490 
2491       log_debug(redefine, class, annotation)
2492         ("type_name_index=%d  const_name_index=%d", type_name_index, const_name_index);
2493     } break;
2494 
2495     case 'c':
2496     {
2497       // for the above tag value, value.class_info_index is right union field
2498 
2499       if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2500         // not enough room for a class_info_index
2501         log_debug(redefine, class, annotation)("length() is too small for a class_info_index");
2502         return false;
2503       }
2504 
2505       u2 class_info_index = rewrite_cp_ref_in_annotation_data(
2506                               annotations_typeArray, byte_i_ref,
2507                               "class_info_index");
2508 
2509       log_debug(redefine, class, annotation)("class_info_index=%d", class_info_index);
2510     } break;
2511 
2512     case '@':
2513       // For the above tag value, value.attr_value is the right union
2514       // field. This is a nested annotation.
2515       if (!rewrite_cp_refs_in_annotation_struct(annotations_typeArray, byte_i_ref)) {
2516         // propagate failure back to caller
2517         return false;
2518       }
2519       break;
2520 
2521     case JVM_SIGNATURE_ARRAY:
2522     {
2523       if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2524         // not enough room for a num_values field
2525         log_debug(redefine, class, annotation)("length() is too small for a num_values field");
2526         return false;
2527       }
2528 
2529       // For the above tag value, value.array_value is the right union
2530       // field. This is an array of nested element_value.
2531       u2 num_values = Bytes::get_Java_u2((address)
2532                         annotations_typeArray->adr_at(byte_i_ref));
2533       byte_i_ref += 2;
2534       log_debug(redefine, class, annotation)("num_values=%d", num_values);
2535 
2536       int calc_num_values = 0;
2537       for (; calc_num_values < num_values; calc_num_values++) {
2538         if (!rewrite_cp_refs_in_element_value(annotations_typeArray, byte_i_ref)) {
2539           log_debug(redefine, class, annotation)("bad nested element_value at %d", calc_num_values);
2540           // propagate failure back to caller
2541           return false;
2542         }
2543       }
2544       assert(num_values == calc_num_values, "sanity check");
2545     } break;
2546 
2547     default:
2548       log_debug(redefine, class, annotation)("bad tag=0x%x", tag);
2549       return false;
2550   } // end decode tag field
2551 
2552   return true;
2553 } // end rewrite_cp_refs_in_element_value()
2554 
2555 
2556 // Rewrite constant pool references in a fields_annotations field.
2557 bool VM_RedefineClasses::rewrite_cp_refs_in_fields_annotations(
2558        InstanceKlass* scratch_class) {
2559 
2560   Array<AnnotationArray*>* fields_annotations = scratch_class->fields_annotations();
2561 
2562   if (fields_annotations == NULL || fields_annotations->length() == 0) {
2563     // no fields_annotations so nothing to do
2564     return true;
2565   }
2566 
2567   log_debug(redefine, class, annotation)("fields_annotations length=%d", fields_annotations->length());
2568 
2569   for (int i = 0; i < fields_annotations->length(); i++) {
2570     AnnotationArray* field_annotations = fields_annotations->at(i);
2571     if (field_annotations == NULL || field_annotations->length() == 0) {
2572       // this field does not have any annotations so skip it
2573       continue;
2574     }
2575 
2576     int byte_i = 0;  // byte index into field_annotations
2577     if (!rewrite_cp_refs_in_annotations_typeArray(field_annotations, byte_i)) {
2578       log_debug(redefine, class, annotation)("bad field_annotations at %d", i);
2579       // propagate failure back to caller
2580       return false;
2581     }
2582   }
2583 
2584   return true;
2585 } // end rewrite_cp_refs_in_fields_annotations()
2586 
2587 
2588 // Rewrite constant pool references in a methods_annotations field.
2589 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_annotations(
2590        InstanceKlass* scratch_class) {
2591 
2592   for (int i = 0; i < scratch_class->methods()->length(); i++) {
2593     Method* m = scratch_class->methods()->at(i);
2594     AnnotationArray* method_annotations = m->constMethod()->method_annotations();
2595 
2596     if (method_annotations == NULL || method_annotations->length() == 0) {
2597       // this method does not have any annotations so skip it
2598       continue;
2599     }
2600 
2601     int byte_i = 0;  // byte index into method_annotations
2602     if (!rewrite_cp_refs_in_annotations_typeArray(method_annotations, byte_i)) {
2603       log_debug(redefine, class, annotation)("bad method_annotations at %d", i);
2604       // propagate failure back to caller
2605       return false;
2606     }
2607   }
2608 
2609   return true;
2610 } // end rewrite_cp_refs_in_methods_annotations()
2611 
2612 
2613 // Rewrite constant pool references in a methods_parameter_annotations
2614 // field. This "structure" is adapted from the
2615 // RuntimeVisibleParameterAnnotations_attribute described in section
2616 // 4.8.17 of the 2nd-edition of the VM spec:
2617 //
2618 // methods_parameter_annotations_typeArray {
2619 //   u1 num_parameters;
2620 //   {
2621 //     u2 num_annotations;
2622 //     annotation annotations[num_annotations];
2623 //   } parameter_annotations[num_parameters];
2624 // }
2625 //
2626 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_parameter_annotations(
2627        InstanceKlass* scratch_class) {
2628 
2629   for (int i = 0; i < scratch_class->methods()->length(); i++) {
2630     Method* m = scratch_class->methods()->at(i);
2631     AnnotationArray* method_parameter_annotations = m->constMethod()->parameter_annotations();
2632     if (method_parameter_annotations == NULL
2633         || method_parameter_annotations->length() == 0) {
2634       // this method does not have any parameter annotations so skip it
2635       continue;
2636     }
2637 
2638     if (method_parameter_annotations->length() < 1) {
2639       // not enough room for a num_parameters field
2640       log_debug(redefine, class, annotation)("length() is too small for a num_parameters field at %d", i);
2641       return false;
2642     }
2643 
2644     int byte_i = 0;  // byte index into method_parameter_annotations
2645 
2646     u1 num_parameters = method_parameter_annotations->at(byte_i);
2647     byte_i++;
2648 
2649     log_debug(redefine, class, annotation)("num_parameters=%d", num_parameters);
2650 
2651     int calc_num_parameters = 0;
2652     for (; calc_num_parameters < num_parameters; calc_num_parameters++) {
2653       if (!rewrite_cp_refs_in_annotations_typeArray(method_parameter_annotations, byte_i)) {
2654         log_debug(redefine, class, annotation)("bad method_parameter_annotations at %d", calc_num_parameters);
2655         // propagate failure back to caller
2656         return false;
2657       }
2658     }
2659     assert(num_parameters == calc_num_parameters, "sanity check");
2660   }
2661 
2662   return true;
2663 } // end rewrite_cp_refs_in_methods_parameter_annotations()
2664 
2665 
2666 // Rewrite constant pool references in a methods_default_annotations
2667 // field. This "structure" is adapted from the AnnotationDefault_attribute
2668 // that is described in section 4.8.19 of the 2nd-edition of the VM spec:
2669 //
2670 // methods_default_annotations_typeArray {
2671 //   element_value default_value;
2672 // }
2673 //
2674 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_default_annotations(
2675        InstanceKlass* scratch_class) {
2676 
2677   for (int i = 0; i < scratch_class->methods()->length(); i++) {
2678     Method* m = scratch_class->methods()->at(i);
2679     AnnotationArray* method_default_annotations = m->constMethod()->default_annotations();
2680     if (method_default_annotations == NULL
2681         || method_default_annotations->length() == 0) {
2682       // this method does not have any default annotations so skip it
2683       continue;
2684     }
2685 
2686     int byte_i = 0;  // byte index into method_default_annotations
2687 
2688     if (!rewrite_cp_refs_in_element_value(
2689            method_default_annotations, byte_i)) {
2690       log_debug(redefine, class, annotation)("bad default element_value at %d", i);
2691       // propagate failure back to caller
2692       return false;
2693     }
2694   }
2695 
2696   return true;
2697 } // end rewrite_cp_refs_in_methods_default_annotations()
2698 
2699 
2700 // Rewrite constant pool references in a class_type_annotations field.
2701 bool VM_RedefineClasses::rewrite_cp_refs_in_class_type_annotations(
2702        InstanceKlass* scratch_class) {
2703 
2704   AnnotationArray* class_type_annotations = scratch_class->class_type_annotations();
2705   if (class_type_annotations == NULL || class_type_annotations->length() == 0) {
2706     // no class_type_annotations so nothing to do
2707     return true;
2708   }
2709 
2710   log_debug(redefine, class, annotation)("class_type_annotations length=%d", class_type_annotations->length());
2711 
2712   int byte_i = 0;  // byte index into class_type_annotations
2713   return rewrite_cp_refs_in_type_annotations_typeArray(class_type_annotations,
2714       byte_i, "ClassFile");
2715 } // end rewrite_cp_refs_in_class_type_annotations()
2716 
2717 
2718 // Rewrite constant pool references in a fields_type_annotations field.
2719 bool VM_RedefineClasses::rewrite_cp_refs_in_fields_type_annotations(InstanceKlass* scratch_class) {
2720 
2721   Array<AnnotationArray*>* fields_type_annotations = scratch_class->fields_type_annotations();
2722   if (fields_type_annotations == NULL || fields_type_annotations->length() == 0) {
2723     // no fields_type_annotations so nothing to do
2724     return true;
2725   }
2726 
2727   log_debug(redefine, class, annotation)("fields_type_annotations length=%d", fields_type_annotations->length());
2728 
2729   for (int i = 0; i < fields_type_annotations->length(); i++) {
2730     AnnotationArray* field_type_annotations = fields_type_annotations->at(i);
2731     if (field_type_annotations == NULL || field_type_annotations->length() == 0) {
2732       // this field does not have any annotations so skip it
2733       continue;
2734     }
2735 
2736     int byte_i = 0;  // byte index into field_type_annotations
2737     if (!rewrite_cp_refs_in_type_annotations_typeArray(field_type_annotations,
2738            byte_i, "field_info")) {
2739       log_debug(redefine, class, annotation)("bad field_type_annotations at %d", i);
2740       // propagate failure back to caller
2741       return false;
2742     }
2743   }
2744 
2745   return true;
2746 } // end rewrite_cp_refs_in_fields_type_annotations()
2747 
2748 
2749 // Rewrite constant pool references in a methods_type_annotations field.
2750 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_type_annotations(
2751        InstanceKlass* scratch_class) {
2752 
2753   for (int i = 0; i < scratch_class->methods()->length(); i++) {
2754     Method* m = scratch_class->methods()->at(i);
2755     AnnotationArray* method_type_annotations = m->constMethod()->type_annotations();
2756 
2757     if (method_type_annotations == NULL || method_type_annotations->length() == 0) {
2758       // this method does not have any annotations so skip it
2759       continue;
2760     }
2761 
2762     log_debug(redefine, class, annotation)("methods type_annotations length=%d", method_type_annotations->length());
2763 
2764     int byte_i = 0;  // byte index into method_type_annotations
2765     if (!rewrite_cp_refs_in_type_annotations_typeArray(method_type_annotations,
2766            byte_i, "method_info")) {
2767       log_debug(redefine, class, annotation)("bad method_type_annotations at %d", i);
2768       // propagate failure back to caller
2769       return false;
2770     }
2771   }
2772 
2773   return true;
2774 } // end rewrite_cp_refs_in_methods_type_annotations()
2775 
2776 
2777 // Rewrite constant pool references in a type_annotations
2778 // field. This "structure" is adapted from the
2779 // RuntimeVisibleTypeAnnotations_attribute described in
2780 // section 4.7.20 of the Java SE 8 Edition of the VM spec:
2781 //
2782 // type_annotations_typeArray {
2783 //   u2              num_annotations;
2784 //   type_annotation annotations[num_annotations];
2785 // }
2786 //
2787 bool VM_RedefineClasses::rewrite_cp_refs_in_type_annotations_typeArray(
2788        AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
2789        const char * location_mesg) {
2790 
2791   if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2792     // not enough room for num_annotations field
2793     log_debug(redefine, class, annotation)("length() is too small for num_annotations field");
2794     return false;
2795   }
2796 
2797   u2 num_annotations = Bytes::get_Java_u2((address)
2798                          type_annotations_typeArray->adr_at(byte_i_ref));
2799   byte_i_ref += 2;
2800 
2801   log_debug(redefine, class, annotation)("num_type_annotations=%d", num_annotations);
2802 
2803   int calc_num_annotations = 0;
2804   for (; calc_num_annotations < num_annotations; calc_num_annotations++) {
2805     if (!rewrite_cp_refs_in_type_annotation_struct(type_annotations_typeArray,
2806            byte_i_ref, location_mesg)) {
2807       log_debug(redefine, class, annotation)("bad type_annotation_struct at %d", calc_num_annotations);
2808       // propagate failure back to caller
2809       return false;
2810     }
2811   }
2812   assert(num_annotations == calc_num_annotations, "sanity check");
2813 
2814   if (byte_i_ref != type_annotations_typeArray->length()) {
2815     log_debug(redefine, class, annotation)
2816       ("read wrong amount of bytes at end of processing type_annotations_typeArray (%d of %d bytes were read)",
2817        byte_i_ref, type_annotations_typeArray->length());
2818     return false;
2819   }
2820 
2821   return true;
2822 } // end rewrite_cp_refs_in_type_annotations_typeArray()
2823 
2824 
2825 // Rewrite constant pool references in a type_annotation
2826 // field. This "structure" is adapted from the
2827 // RuntimeVisibleTypeAnnotations_attribute described in
2828 // section 4.7.20 of the Java SE 8 Edition of the VM spec:
2829 //
2830 // type_annotation {
2831 //   u1 target_type;
2832 //   union {
2833 //     type_parameter_target;
2834 //     supertype_target;
2835 //     type_parameter_bound_target;
2836 //     empty_target;
2837 //     method_formal_parameter_target;
2838 //     throws_target;
2839 //     localvar_target;
2840 //     catch_target;
2841 //     offset_target;
2842 //     type_argument_target;
2843 //   } target_info;
2844 //   type_path target_path;
2845 //   annotation anno;
2846 // }
2847 //
2848 bool VM_RedefineClasses::rewrite_cp_refs_in_type_annotation_struct(
2849        AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
2850        const char * location_mesg) {
2851 
2852   if (!skip_type_annotation_target(type_annotations_typeArray,
2853          byte_i_ref, location_mesg)) {
2854     return false;
2855   }
2856 
2857   if (!skip_type_annotation_type_path(type_annotations_typeArray, byte_i_ref)) {
2858     return false;
2859   }
2860 
2861   if (!rewrite_cp_refs_in_annotation_struct(type_annotations_typeArray, byte_i_ref)) {
2862     return false;
2863   }
2864 
2865   return true;
2866 } // end rewrite_cp_refs_in_type_annotation_struct()
2867 
2868 
2869 // Read, verify and skip over the target_type and target_info part
2870 // so that rewriting can continue in the later parts of the struct.
2871 //
2872 // u1 target_type;
2873 // union {
2874 //   type_parameter_target;
2875 //   supertype_target;
2876 //   type_parameter_bound_target;
2877 //   empty_target;
2878 //   method_formal_parameter_target;
2879 //   throws_target;
2880 //   localvar_target;
2881 //   catch_target;
2882 //   offset_target;
2883 //   type_argument_target;
2884 // } target_info;
2885 //
2886 bool VM_RedefineClasses::skip_type_annotation_target(
2887        AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
2888        const char * location_mesg) {
2889 
2890   if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
2891     // not enough room for a target_type let alone the rest of a type_annotation
2892     log_debug(redefine, class, annotation)("length() is too small for a target_type");
2893     return false;
2894   }
2895 
2896   u1 target_type = type_annotations_typeArray->at(byte_i_ref);
2897   byte_i_ref += 1;
2898   log_debug(redefine, class, annotation)("target_type=0x%.2x", target_type);
2899   log_debug(redefine, class, annotation)("location=%s", location_mesg);
2900 
2901   // Skip over target_info
2902   switch (target_type) {
2903     case 0x00:
2904     // kind: type parameter declaration of generic class or interface
2905     // location: ClassFile
2906     case 0x01:
2907     // kind: type parameter declaration of generic method or constructor
2908     // location: method_info
2909 
2910     {
2911       // struct:
2912       // type_parameter_target {
2913       //   u1 type_parameter_index;
2914       // }
2915       //
2916       if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
2917         log_debug(redefine, class, annotation)("length() is too small for a type_parameter_target");
2918         return false;
2919       }
2920 
2921       u1 type_parameter_index = type_annotations_typeArray->at(byte_i_ref);
2922       byte_i_ref += 1;
2923 
2924       log_debug(redefine, class, annotation)("type_parameter_target: type_parameter_index=%d", type_parameter_index);
2925     } break;
2926 
2927     case 0x10:
2928     // kind: type in extends clause of class or interface declaration
2929     //       or in implements clause of interface declaration
2930     // location: ClassFile
2931 
2932     {
2933       // struct:
2934       // supertype_target {
2935       //   u2 supertype_index;
2936       // }
2937       //
2938       if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2939         log_debug(redefine, class, annotation)("length() is too small for a supertype_target");
2940         return false;
2941       }
2942 
2943       u2 supertype_index = Bytes::get_Java_u2((address)
2944                              type_annotations_typeArray->adr_at(byte_i_ref));
2945       byte_i_ref += 2;
2946 
2947       log_debug(redefine, class, annotation)("supertype_target: supertype_index=%d", supertype_index);
2948     } break;
2949 
2950     case 0x11:
2951     // kind: type in bound of type parameter declaration of generic class or interface
2952     // location: ClassFile
2953     case 0x12:
2954     // kind: type in bound of type parameter declaration of generic method or constructor
2955     // location: method_info
2956 
2957     {
2958       // struct:
2959       // type_parameter_bound_target {
2960       //   u1 type_parameter_index;
2961       //   u1 bound_index;
2962       // }
2963       //
2964       if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2965         log_debug(redefine, class, annotation)("length() is too small for a type_parameter_bound_target");
2966         return false;
2967       }
2968 
2969       u1 type_parameter_index = type_annotations_typeArray->at(byte_i_ref);
2970       byte_i_ref += 1;
2971       u1 bound_index = type_annotations_typeArray->at(byte_i_ref);
2972       byte_i_ref += 1;
2973 
2974       log_debug(redefine, class, annotation)
2975         ("type_parameter_bound_target: type_parameter_index=%d, bound_index=%d", type_parameter_index, bound_index);
2976     } break;
2977 
2978     case 0x13:
2979     // kind: type in field declaration
2980     // location: field_info
2981     case 0x14:
2982     // kind: return type of method, or type of newly constructed object
2983     // location: method_info
2984     case 0x15:
2985     // kind: receiver type of method or constructor
2986     // location: method_info
2987 
2988     {
2989       // struct:
2990       // empty_target {
2991       // }
2992       //
2993       log_debug(redefine, class, annotation)("empty_target");
2994     } break;
2995 
2996     case 0x16:
2997     // kind: type in formal parameter declaration of method, constructor, or lambda expression
2998     // location: method_info
2999 
3000     {
3001       // struct:
3002       // formal_parameter_target {
3003       //   u1 formal_parameter_index;
3004       // }
3005       //
3006       if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
3007         log_debug(redefine, class, annotation)("length() is too small for a formal_parameter_target");
3008         return false;
3009       }
3010 
3011       u1 formal_parameter_index = type_annotations_typeArray->at(byte_i_ref);
3012       byte_i_ref += 1;
3013 
3014       log_debug(redefine, class, annotation)
3015         ("formal_parameter_target: formal_parameter_index=%d", formal_parameter_index);
3016     } break;
3017 
3018     case 0x17:
3019     // kind: type in throws clause of method or constructor
3020     // location: method_info
3021 
3022     {
3023       // struct:
3024       // throws_target {
3025       //   u2 throws_type_index
3026       // }
3027       //
3028       if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
3029         log_debug(redefine, class, annotation)("length() is too small for a throws_target");
3030         return false;
3031       }
3032 
3033       u2 throws_type_index = Bytes::get_Java_u2((address)
3034                                type_annotations_typeArray->adr_at(byte_i_ref));
3035       byte_i_ref += 2;
3036 
3037       log_debug(redefine, class, annotation)("throws_target: throws_type_index=%d", throws_type_index);
3038     } break;
3039 
3040     case 0x40:
3041     // kind: type in local variable declaration
3042     // location: Code
3043     case 0x41:
3044     // kind: type in resource variable declaration
3045     // location: Code
3046 
3047     {
3048       // struct:
3049       // localvar_target {
3050       //   u2 table_length;
3051       //   struct {
3052       //     u2 start_pc;
3053       //     u2 length;
3054       //     u2 index;
3055       //   } table[table_length];
3056       // }
3057       //
3058       if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
3059         // not enough room for a table_length let alone the rest of a localvar_target
3060         log_debug(redefine, class, annotation)("length() is too small for a localvar_target table_length");
3061         return false;
3062       }
3063 
3064       u2 table_length = Bytes::get_Java_u2((address)
3065                           type_annotations_typeArray->adr_at(byte_i_ref));
3066       byte_i_ref += 2;
3067 
3068       log_debug(redefine, class, annotation)("localvar_target: table_length=%d", table_length);
3069 
3070       int table_struct_size = 2 + 2 + 2; // 3 u2 variables per table entry
3071       int table_size = table_length * table_struct_size;
3072 
3073       if ((byte_i_ref + table_size) > type_annotations_typeArray->length()) {
3074         // not enough room for a table
3075         log_debug(redefine, class, annotation)("length() is too small for a table array of length %d", table_length);
3076         return false;
3077       }
3078 
3079       // Skip over table
3080       byte_i_ref += table_size;
3081     } break;
3082 
3083     case 0x42:
3084     // kind: type in exception parameter declaration
3085     // location: Code
3086 
3087     {
3088       // struct:
3089       // catch_target {
3090       //   u2 exception_table_index;
3091       // }
3092       //
3093       if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
3094         log_debug(redefine, class, annotation)("length() is too small for a catch_target");
3095         return false;
3096       }
3097 
3098       u2 exception_table_index = Bytes::get_Java_u2((address)
3099                                    type_annotations_typeArray->adr_at(byte_i_ref));
3100       byte_i_ref += 2;
3101 
3102       log_debug(redefine, class, annotation)("catch_target: exception_table_index=%d", exception_table_index);
3103     } break;
3104 
3105     case 0x43:
3106     // kind: type in instanceof expression
3107     // location: Code
3108     case 0x44:
3109     // kind: type in new expression
3110     // location: Code
3111     case 0x45:
3112     // kind: type in method reference expression using ::new
3113     // location: Code
3114     case 0x46:
3115     // kind: type in method reference expression using ::Identifier
3116     // location: Code
3117 
3118     {
3119       // struct:
3120       // offset_target {
3121       //   u2 offset;
3122       // }
3123       //
3124       if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
3125         log_debug(redefine, class, annotation)("length() is too small for a offset_target");
3126         return false;
3127       }
3128 
3129       u2 offset = Bytes::get_Java_u2((address)
3130                     type_annotations_typeArray->adr_at(byte_i_ref));
3131       byte_i_ref += 2;
3132 
3133       log_debug(redefine, class, annotation)("offset_target: offset=%d", offset);
3134     } break;
3135 
3136     case 0x47:
3137     // kind: type in cast expression
3138     // location: Code
3139     case 0x48:
3140     // kind: type argument for generic constructor in new expression or
3141     //       explicit constructor invocation statement
3142     // location: Code
3143     case 0x49:
3144     // kind: type argument for generic method in method invocation expression
3145     // location: Code
3146     case 0x4A:
3147     // kind: type argument for generic constructor in method reference expression using ::new
3148     // location: Code
3149     case 0x4B:
3150     // kind: type argument for generic method in method reference expression using ::Identifier
3151     // location: Code
3152 
3153     {
3154       // struct:
3155       // type_argument_target {
3156       //   u2 offset;
3157       //   u1 type_argument_index;
3158       // }
3159       //
3160       if ((byte_i_ref + 3) > type_annotations_typeArray->length()) {
3161         log_debug(redefine, class, annotation)("length() is too small for a type_argument_target");
3162         return false;
3163       }
3164 
3165       u2 offset = Bytes::get_Java_u2((address)
3166                     type_annotations_typeArray->adr_at(byte_i_ref));
3167       byte_i_ref += 2;
3168       u1 type_argument_index = type_annotations_typeArray->at(byte_i_ref);
3169       byte_i_ref += 1;
3170 
3171       log_debug(redefine, class, annotation)
3172         ("type_argument_target: offset=%d, type_argument_index=%d", offset, type_argument_index);
3173     } break;
3174 
3175     default:
3176       log_debug(redefine, class, annotation)("unknown target_type");
3177 #ifdef ASSERT
3178       ShouldNotReachHere();
3179 #endif
3180       return false;
3181   }
3182 
3183   return true;
3184 } // end skip_type_annotation_target()
3185 
3186 
3187 // Read, verify and skip over the type_path part so that rewriting
3188 // can continue in the later parts of the struct.
3189 //
3190 // type_path {
3191 //   u1 path_length;
3192 //   {
3193 //     u1 type_path_kind;
3194 //     u1 type_argument_index;
3195 //   } path[path_length];
3196 // }
3197 //
3198 bool VM_RedefineClasses::skip_type_annotation_type_path(
3199        AnnotationArray* type_annotations_typeArray, int &byte_i_ref) {
3200 
3201   if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
3202     // not enough room for a path_length let alone the rest of the type_path
3203     log_debug(redefine, class, annotation)("length() is too small for a type_path");
3204     return false;
3205   }
3206 
3207   u1 path_length = type_annotations_typeArray->at(byte_i_ref);
3208   byte_i_ref += 1;
3209 
3210   log_debug(redefine, class, annotation)("type_path: path_length=%d", path_length);
3211 
3212   int calc_path_length = 0;
3213   for (; calc_path_length < path_length; calc_path_length++) {
3214     if ((byte_i_ref + 1 + 1) > type_annotations_typeArray->length()) {
3215       // not enough room for a path
3216       log_debug(redefine, class, annotation)
3217         ("length() is too small for path entry %d of %d", calc_path_length, path_length);
3218       return false;
3219     }
3220 
3221     u1 type_path_kind = type_annotations_typeArray->at(byte_i_ref);
3222     byte_i_ref += 1;
3223     u1 type_argument_index = type_annotations_typeArray->at(byte_i_ref);
3224     byte_i_ref += 1;
3225 
3226     log_debug(redefine, class, annotation)
3227       ("type_path: path[%d]: type_path_kind=%d, type_argument_index=%d",
3228        calc_path_length, type_path_kind, type_argument_index);
3229 
3230     if (type_path_kind > 3 || (type_path_kind != 3 && type_argument_index != 0)) {
3231       // not enough room for a path
3232       log_debug(redefine, class, annotation)("inconsistent type_path values");
3233       return false;
3234     }
3235   }
3236   assert(path_length == calc_path_length, "sanity check");
3237 
3238   return true;
3239 } // end skip_type_annotation_type_path()
3240 
3241 
3242 // Rewrite constant pool references in the method's stackmap table.
3243 // These "structures" are adapted from the StackMapTable_attribute that
3244 // is described in section 4.8.4 of the 6.0 version of the VM spec
3245 // (dated 2005.10.26):
3246 // file:///net/quincunx.sfbay/export/gbracha/ClassFile-Java6.pdf
3247 //
3248 // stack_map {
3249 //   u2 number_of_entries;
3250 //   stack_map_frame entries[number_of_entries];
3251 // }
3252 //
3253 void VM_RedefineClasses::rewrite_cp_refs_in_stack_map_table(
3254        const methodHandle& method) {
3255 
3256   if (!method->has_stackmap_table()) {
3257     return;
3258   }
3259 
3260   AnnotationArray* stackmap_data = method->stackmap_data();
3261   address stackmap_p = (address)stackmap_data->adr_at(0);
3262   address stackmap_end = stackmap_p + stackmap_data->length();
3263 
3264   assert(stackmap_p + 2 <= stackmap_end, "no room for number_of_entries");
3265   u2 number_of_entries = Bytes::get_Java_u2(stackmap_p);
3266   stackmap_p += 2;
3267 
3268   log_debug(redefine, class, stackmap)("number_of_entries=%u", number_of_entries);
3269 
3270   // walk through each stack_map_frame
3271   u2 calc_number_of_entries = 0;
3272   for (; calc_number_of_entries < number_of_entries; calc_number_of_entries++) {
3273     // The stack_map_frame structure is a u1 frame_type followed by
3274     // 0 or more bytes of data:
3275     //
3276     // union stack_map_frame {
3277     //   same_frame;
3278     //   same_locals_1_stack_item_frame;
3279     //   same_locals_1_stack_item_frame_extended;
3280     //   chop_frame;
3281     //   same_frame_extended;
3282     //   append_frame;
3283     //   full_frame;
3284     // }
3285 
3286     assert(stackmap_p + 1 <= stackmap_end, "no room for frame_type");
3287     u1 frame_type = *stackmap_p;
3288     stackmap_p++;
3289 
3290     // same_frame {
3291     //   u1 frame_type = SAME; /* 0-63 */
3292     // }
3293     if (frame_type <= 63) {
3294       // nothing more to do for same_frame
3295     }
3296 
3297     // same_locals_1_stack_item_frame {
3298     //   u1 frame_type = SAME_LOCALS_1_STACK_ITEM; /* 64-127 */
3299     //   verification_type_info stack[1];
3300     // }
3301     else if (frame_type >= 64 && frame_type <= 127) {
3302       rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
3303         calc_number_of_entries, frame_type);
3304     }
3305 
3306     // reserved for future use
3307     else if (frame_type >= 128 && frame_type <= 246) {
3308       // nothing more to do for reserved frame_types
3309     }
3310 
3311     // same_locals_1_stack_item_frame_extended {
3312     //   u1 frame_type = SAME_LOCALS_1_STACK_ITEM_EXTENDED; /* 247 */
3313     //   u2 offset_delta;
3314     //   verification_type_info stack[1];
3315     // }
3316     else if (frame_type == 247) {
3317       stackmap_p += 2;
3318       rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
3319         calc_number_of_entries, frame_type);
3320     }
3321 
3322     // chop_frame {
3323     //   u1 frame_type = CHOP; /* 248-250 */
3324     //   u2 offset_delta;
3325     // }
3326     else if (frame_type >= 248 && frame_type <= 250) {
3327       stackmap_p += 2;
3328     }
3329 
3330     // same_frame_extended {
3331     //   u1 frame_type = SAME_FRAME_EXTENDED; /* 251*/
3332     //   u2 offset_delta;
3333     // }
3334     else if (frame_type == 251) {
3335       stackmap_p += 2;
3336     }
3337 
3338     // append_frame {
3339     //   u1 frame_type = APPEND; /* 252-254 */
3340     //   u2 offset_delta;
3341     //   verification_type_info locals[frame_type - 251];
3342     // }
3343     else if (frame_type >= 252 && frame_type <= 254) {
3344       assert(stackmap_p + 2 <= stackmap_end,
3345         "no room for offset_delta");
3346       stackmap_p += 2;
3347       u1 len = frame_type - 251;
3348       for (u1 i = 0; i < len; i++) {
3349         rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
3350           calc_number_of_entries, frame_type);
3351       }
3352     }
3353 
3354     // full_frame {
3355     //   u1 frame_type = FULL_FRAME; /* 255 */
3356     //   u2 offset_delta;
3357     //   u2 number_of_locals;
3358     //   verification_type_info locals[number_of_locals];
3359     //   u2 number_of_stack_items;
3360     //   verification_type_info stack[number_of_stack_items];
3361     // }
3362     else if (frame_type == 255) {
3363       assert(stackmap_p + 2 + 2 <= stackmap_end,
3364         "no room for smallest full_frame");
3365       stackmap_p += 2;
3366 
3367       u2 number_of_locals = Bytes::get_Java_u2(stackmap_p);
3368       stackmap_p += 2;
3369 
3370       for (u2 locals_i = 0; locals_i < number_of_locals; locals_i++) {
3371         rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
3372           calc_number_of_entries, frame_type);
3373       }
3374 
3375       // Use the largest size for the number_of_stack_items, but only get
3376       // the right number of bytes.
3377       u2 number_of_stack_items = Bytes::get_Java_u2(stackmap_p);
3378       stackmap_p += 2;
3379 
3380       for (u2 stack_i = 0; stack_i < number_of_stack_items; stack_i++) {
3381         rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
3382           calc_number_of_entries, frame_type);
3383       }
3384     }
3385   } // end while there is a stack_map_frame
3386   assert(number_of_entries == calc_number_of_entries, "sanity check");
3387 } // end rewrite_cp_refs_in_stack_map_table()
3388 
3389 
3390 // Rewrite constant pool references in the verification type info
3391 // portion of the method's stackmap table. These "structures" are
3392 // adapted from the StackMapTable_attribute that is described in
3393 // section 4.8.4 of the 6.0 version of the VM spec (dated 2005.10.26):
3394 // file:///net/quincunx.sfbay/export/gbracha/ClassFile-Java6.pdf
3395 //
3396 // The verification_type_info structure is a u1 tag followed by 0 or
3397 // more bytes of data:
3398 //
3399 // union verification_type_info {
3400 //   Top_variable_info;
3401 //   Integer_variable_info;
3402 //   Float_variable_info;
3403 //   Long_variable_info;
3404 //   Double_variable_info;
3405 //   Null_variable_info;
3406 //   UninitializedThis_variable_info;
3407 //   Object_variable_info;
3408 //   Uninitialized_variable_info;
3409 // }
3410 //
3411 void VM_RedefineClasses::rewrite_cp_refs_in_verification_type_info(
3412        address& stackmap_p_ref, address stackmap_end, u2 frame_i,
3413        u1 frame_type) {
3414 
3415   assert(stackmap_p_ref + 1 <= stackmap_end, "no room for tag");
3416   u1 tag = *stackmap_p_ref;
3417   stackmap_p_ref++;
3418 
3419   switch (tag) {
3420   // Top_variable_info {
3421   //   u1 tag = ITEM_Top; /* 0 */
3422   // }
3423   // verificationType.hpp has zero as ITEM_Bogus instead of ITEM_Top
3424   case 0:  // fall through
3425 
3426   // Integer_variable_info {
3427   //   u1 tag = ITEM_Integer; /* 1 */
3428   // }
3429   case ITEM_Integer:  // fall through
3430 
3431   // Float_variable_info {
3432   //   u1 tag = ITEM_Float; /* 2 */
3433   // }
3434   case ITEM_Float:  // fall through
3435 
3436   // Double_variable_info {
3437   //   u1 tag = ITEM_Double; /* 3 */
3438   // }
3439   case ITEM_Double:  // fall through
3440 
3441   // Long_variable_info {
3442   //   u1 tag = ITEM_Long; /* 4 */
3443   // }
3444   case ITEM_Long:  // fall through
3445 
3446   // Null_variable_info {
3447   //   u1 tag = ITEM_Null; /* 5 */
3448   // }
3449   case ITEM_Null:  // fall through
3450 
3451   // UninitializedThis_variable_info {
3452   //   u1 tag = ITEM_UninitializedThis; /* 6 */
3453   // }
3454   case ITEM_UninitializedThis:
3455     // nothing more to do for the above tag types
3456     break;
3457 
3458   // Object_variable_info {
3459   //   u1 tag = ITEM_Object; /* 7 */
3460   //   u2 cpool_index;
3461   // }
3462   case ITEM_Object:
3463   {
3464     assert(stackmap_p_ref + 2 <= stackmap_end, "no room for cpool_index");
3465     u2 cpool_index = Bytes::get_Java_u2(stackmap_p_ref);
3466     u2 new_cp_index = find_new_index(cpool_index);
3467     if (new_cp_index != 0) {
3468       log_debug(redefine, class, stackmap)("mapped old cpool_index=%d", cpool_index);
3469       Bytes::put_Java_u2(stackmap_p_ref, new_cp_index);
3470       cpool_index = new_cp_index;
3471     }
3472     stackmap_p_ref += 2;
3473 
3474     log_debug(redefine, class, stackmap)
3475       ("frame_i=%u, frame_type=%u, cpool_index=%d", frame_i, frame_type, cpool_index);
3476   } break;
3477 
3478   // Uninitialized_variable_info {
3479   //   u1 tag = ITEM_Uninitialized; /* 8 */
3480   //   u2 offset;
3481   // }
3482   case ITEM_Uninitialized:
3483     assert(stackmap_p_ref + 2 <= stackmap_end, "no room for offset");
3484     stackmap_p_ref += 2;
3485     break;
3486 
3487   default:
3488     log_debug(redefine, class, stackmap)("frame_i=%u, frame_type=%u, bad tag=0x%x", frame_i, frame_type, tag);
3489     ShouldNotReachHere();
3490     break;
3491   } // end switch (tag)
3492 } // end rewrite_cp_refs_in_verification_type_info()
3493 
3494 
3495 // Change the constant pool associated with klass scratch_class to
3496 // scratch_cp. If shrink is true, then scratch_cp_length elements
3497 // are copied from scratch_cp to a smaller constant pool and the
3498 // smaller constant pool is associated with scratch_class.
3499 void VM_RedefineClasses::set_new_constant_pool(
3500        ClassLoaderData* loader_data,
3501        InstanceKlass* scratch_class, constantPoolHandle scratch_cp,
3502        int scratch_cp_length, TRAPS) {
3503   assert(scratch_cp->length() >= scratch_cp_length, "sanity check");
3504 
3505   // scratch_cp is a merged constant pool and has enough space for a
3506   // worst case merge situation. We want to associate the minimum
3507   // sized constant pool with the klass to save space.
3508   ConstantPool* cp = ConstantPool::allocate(loader_data, scratch_cp_length, CHECK);
3509   constantPoolHandle smaller_cp(THREAD, cp);
3510 
3511   // preserve version() value in the smaller copy
3512   int version = scratch_cp->version();
3513   assert(version != 0, "sanity check");
3514   smaller_cp->set_version(version);
3515 
3516   // attach klass to new constant pool
3517   // reference to the cp holder is needed for copy_operands()
3518   smaller_cp->set_pool_holder(scratch_class);
3519 
3520   smaller_cp->copy_fields(scratch_cp());
3521 
3522   scratch_cp->copy_cp_to(1, scratch_cp_length - 1, smaller_cp, 1, THREAD);
3523   if (HAS_PENDING_EXCEPTION) {
3524     // Exception is handled in the caller
3525     loader_data->add_to_deallocate_list(smaller_cp());
3526     return;
3527   }
3528   scratch_cp = smaller_cp;
3529 
3530   // attach new constant pool to klass
3531   scratch_class->set_constants(scratch_cp());
3532   scratch_cp->initialize_unresolved_klasses(loader_data, CHECK);
3533 
3534   int i;  // for portability
3535 
3536   // update each field in klass to use new constant pool indices as needed
3537   for (JavaFieldStream fs(scratch_class); !fs.done(); fs.next()) {
3538     jshort cur_index = fs.name_index();
3539     jshort new_index = find_new_index(cur_index);
3540     if (new_index != 0) {
3541       log_trace(redefine, class, constantpool)("field-name_index change: %d to %d", cur_index, new_index);
3542       fs.set_name_index(new_index);
3543     }
3544     cur_index = fs.signature_index();
3545     new_index = find_new_index(cur_index);
3546     if (new_index != 0) {
3547       log_trace(redefine, class, constantpool)("field-signature_index change: %d to %d", cur_index, new_index);
3548       fs.set_signature_index(new_index);
3549     }
3550     cur_index = fs.initval_index();
3551     new_index = find_new_index(cur_index);
3552     if (new_index != 0) {
3553       log_trace(redefine, class, constantpool)("field-initval_index change: %d to %d", cur_index, new_index);
3554       fs.set_initval_index(new_index);
3555     }
3556     cur_index = fs.generic_signature_index();
3557     new_index = find_new_index(cur_index);
3558     if (new_index != 0) {
3559       log_trace(redefine, class, constantpool)("field-generic_signature change: %d to %d", cur_index, new_index);
3560       fs.set_generic_signature_index(new_index);
3561     }
3562   } // end for each field
3563 
3564   // Update constant pool indices in the inner classes info to use
3565   // new constant indices as needed. The inner classes info is a
3566   // quadruple:
3567   // (inner_class_info, outer_class_info, inner_name, inner_access_flags)
3568   InnerClassesIterator iter(scratch_class);
3569   for (; !iter.done(); iter.next()) {
3570     int cur_index = iter.inner_class_info_index();
3571     if (cur_index == 0) {
3572       continue;  // JVM spec. allows null inner class refs so skip it
3573     }
3574     int new_index = find_new_index(cur_index);
3575     if (new_index != 0) {
3576       log_trace(redefine, class, constantpool)("inner_class_info change: %d to %d", cur_index, new_index);
3577       iter.set_inner_class_info_index(new_index);
3578     }
3579     cur_index = iter.outer_class_info_index();
3580     new_index = find_new_index(cur_index);
3581     if (new_index != 0) {
3582       log_trace(redefine, class, constantpool)("outer_class_info change: %d to %d", cur_index, new_index);
3583       iter.set_outer_class_info_index(new_index);
3584     }
3585     cur_index = iter.inner_name_index();
3586     new_index = find_new_index(cur_index);
3587     if (new_index != 0) {
3588       log_trace(redefine, class, constantpool)("inner_name change: %d to %d", cur_index, new_index);
3589       iter.set_inner_name_index(new_index);
3590     }
3591   } // end for each inner class
3592 
3593   // Attach each method in klass to the new constant pool and update
3594   // to use new constant pool indices as needed:
3595   Array<Method*>* methods = scratch_class->methods();
3596   for (i = methods->length() - 1; i >= 0; i--) {
3597     methodHandle method(THREAD, methods->at(i));
3598     method->set_constants(scratch_cp());
3599 
3600     int new_index = find_new_index(method->name_index());
3601     if (new_index != 0) {
3602       log_trace(redefine, class, constantpool)
3603         ("method-name_index change: %d to %d", method->name_index(), new_index);
3604       method->set_name_index(new_index);
3605     }
3606     new_index = find_new_index(method->signature_index());
3607     if (new_index != 0) {
3608       log_trace(redefine, class, constantpool)
3609         ("method-signature_index change: %d to %d", method->signature_index(), new_index);
3610       method->set_signature_index(new_index);
3611     }
3612     new_index = find_new_index(method->generic_signature_index());
3613     if (new_index != 0) {
3614       log_trace(redefine, class, constantpool)
3615         ("method-generic_signature_index change: %d to %d", method->generic_signature_index(), new_index);
3616       method->set_generic_signature_index(new_index);
3617     }
3618 
3619     // Update constant pool indices in the method's checked exception
3620     // table to use new constant indices as needed.
3621     int cext_length = method->checked_exceptions_length();
3622     if (cext_length > 0) {
3623       CheckedExceptionElement * cext_table =
3624         method->checked_exceptions_start();
3625       for (int j = 0; j < cext_length; j++) {
3626         int cur_index = cext_table[j].class_cp_index;
3627         int new_index = find_new_index(cur_index);
3628         if (new_index != 0) {
3629           log_trace(redefine, class, constantpool)("cext-class_cp_index change: %d to %d", cur_index, new_index);
3630           cext_table[j].class_cp_index = (u2)new_index;
3631         }
3632       } // end for each checked exception table entry
3633     } // end if there are checked exception table entries
3634 
3635     // Update each catch type index in the method's exception table
3636     // to use new constant pool indices as needed. The exception table
3637     // holds quadruple entries of the form:
3638     //   (beg_bci, end_bci, handler_bci, klass_index)
3639 
3640     ExceptionTable ex_table(method());
3641     int ext_length = ex_table.length();
3642 
3643     for (int j = 0; j < ext_length; j ++) {
3644       int cur_index = ex_table.catch_type_index(j);
3645       int new_index = find_new_index(cur_index);
3646       if (new_index != 0) {
3647         log_trace(redefine, class, constantpool)("ext-klass_index change: %d to %d", cur_index, new_index);
3648         ex_table.set_catch_type_index(j, new_index);
3649       }
3650     } // end for each exception table entry
3651 
3652     // Update constant pool indices in the method's local variable
3653     // table to use new constant indices as needed. The local variable
3654     // table hold sextuple entries of the form:
3655     // (start_pc, length, name_index, descriptor_index, signature_index, slot)
3656     int lvt_length = method->localvariable_table_length();
3657     if (lvt_length > 0) {
3658       LocalVariableTableElement * lv_table =
3659         method->localvariable_table_start();
3660       for (int j = 0; j < lvt_length; j++) {
3661         int cur_index = lv_table[j].name_cp_index;
3662         int new_index = find_new_index(cur_index);
3663         if (new_index != 0) {
3664           log_trace(redefine, class, constantpool)("lvt-name_cp_index change: %d to %d", cur_index, new_index);
3665           lv_table[j].name_cp_index = (u2)new_index;
3666         }
3667         cur_index = lv_table[j].descriptor_cp_index;
3668         new_index = find_new_index(cur_index);
3669         if (new_index != 0) {
3670           log_trace(redefine, class, constantpool)("lvt-descriptor_cp_index change: %d to %d", cur_index, new_index);
3671           lv_table[j].descriptor_cp_index = (u2)new_index;
3672         }
3673         cur_index = lv_table[j].signature_cp_index;
3674         new_index = find_new_index(cur_index);
3675         if (new_index != 0) {
3676           log_trace(redefine, class, constantpool)("lvt-signature_cp_index change: %d to %d", cur_index, new_index);
3677           lv_table[j].signature_cp_index = (u2)new_index;
3678         }
3679       } // end for each local variable table entry
3680     } // end if there are local variable table entries
3681 
3682     // Update constant pool indices in the method's method_parameters.
3683     int mp_length = method->method_parameters_length();
3684     if (mp_length > 0) {
3685       MethodParametersElement* elem = method->method_parameters_start();
3686       for (int j = 0; j < mp_length; j++) {
3687         const int cp_index = elem[j].name_cp_index;
3688         const int new_cp_index = find_new_index(cp_index);
3689         if (new_cp_index != 0) {
3690           elem[j].name_cp_index = (u2)new_cp_index;
3691         }
3692       }
3693     }
3694 
3695     rewrite_cp_refs_in_stack_map_table(method);
3696   } // end for each method
3697 } // end set_new_constant_pool()
3698 
3699 
3700 // Unevolving classes may point to methods of the_class directly
3701 // from their constant pool caches, itables, and/or vtables. We
3702 // use the ClassLoaderDataGraph::classes_do() facility and this helper
3703 // to fix up these pointers.  MethodData also points to old methods and
3704 // must be cleaned.
3705 
3706 // Adjust cpools and vtables closure
3707 void VM_RedefineClasses::AdjustAndCleanMetadata::do_klass(Klass* k) {
3708 
3709   // This is a very busy routine. We don't want too much tracing
3710   // printed out.
3711   bool trace_name_printed = false;
3712 
3713   // If the class being redefined is java.lang.Object, we need to fix all
3714   // array class vtables also. The _has_redefined_Object flag is global.
3715   // Once the java.lang.Object has been redefined (by the current or one
3716   // of the previous VM_RedefineClasses operations) we have to always
3717   // adjust method entries for array classes.
3718   if (k->is_array_klass() && _has_redefined_Object) {
3719     k->vtable().adjust_method_entries(&trace_name_printed);
3720 
3721   } else if (k->is_instance_klass()) {
3722     HandleMark hm(_thread);
3723     InstanceKlass *ik = InstanceKlass::cast(k);
3724 
3725     // Clean MethodData of this class's methods so they don't refer to
3726     // old methods that are no longer running.
3727     Array<Method*>* methods = ik->methods();
3728     int num_methods = methods->length();
3729     for (int index = 0; index < num_methods; ++index) {
3730       if (methods->at(index)->method_data() != NULL) {
3731         methods->at(index)->method_data()->clean_weak_method_links();
3732       }
3733     }
3734 
3735     // Adjust all vtables, default methods and itables, to clean out old methods.
3736     ResourceMark rm(_thread);
3737     if (ik->vtable_length() > 0) {
3738       ik->vtable().adjust_method_entries(&trace_name_printed);
3739       ik->adjust_default_methods(&trace_name_printed);
3740     }
3741 
3742     if (ik->itable_length() > 0) {
3743       ik->itable().adjust_method_entries(&trace_name_printed);
3744     }
3745 
3746     // The constant pools in other classes (other_cp) can refer to
3747     // old methods.  We have to update method information in
3748     // other_cp's cache. If other_cp has a previous version, then we
3749     // have to repeat the process for each previous version. The
3750     // constant pool cache holds the Method*s for non-virtual
3751     // methods and for virtual, final methods.
3752     //
3753     // Special case: if the current class is being redefined by the current
3754     // VM_RedefineClasses operation, then new_cp has already been attached
3755     // to the_class and old_cp has already been added as a previous version.
3756     // The new_cp doesn't have any cached references to old methods so it
3757     // doesn't need to be updated and we could optimize by skipping it.
3758     // However, the current class can be marked as being redefined by another
3759     // VM_RedefineClasses operation which has already executed its doit_prologue
3760     // and needs cpcache method entries adjusted. For simplicity, the cpcache
3761     // update is done unconditionally. It should result in doing nothing for
3762     // classes being redefined by the current VM_RedefineClasses operation.
3763     // Method entries in the previous version(s) are adjusted as well.
3764     ConstantPoolCache* cp_cache;
3765 
3766     // this klass' constant pool cache may need adjustment
3767     ConstantPool* other_cp = ik->constants();
3768     cp_cache = other_cp->cache();
3769     if (cp_cache != NULL) {
3770       cp_cache->adjust_method_entries(&trace_name_printed);
3771     }
3772 
3773     // the previous versions' constant pool caches may need adjustment
3774     for (InstanceKlass* pv_node = ik->previous_versions();
3775          pv_node != NULL;
3776          pv_node = pv_node->previous_versions()) {
3777       cp_cache = pv_node->constants()->cache();
3778       if (cp_cache != NULL) {
3779         cp_cache->adjust_method_entries(&trace_name_printed);
3780       }
3781     }
3782   }
3783 }
3784 
3785 void VM_RedefineClasses::update_jmethod_ids() {
3786   for (int j = 0; j < _matching_methods_length; ++j) {
3787     Method* old_method = _matching_old_methods[j];
3788     jmethodID jmid = old_method->find_jmethod_id_or_null();
3789     if (jmid != NULL) {
3790       // There is a jmethodID, change it to point to the new method
3791       Method* new_method = _matching_new_methods[j];
3792       Method::change_method_associated_with_jmethod_id(jmid, new_method);
3793       assert(Method::resolve_jmethod_id(jmid) == _matching_new_methods[j],
3794              "should be replaced");
3795     }
3796   }
3797 }
3798 
3799 int VM_RedefineClasses::check_methods_and_mark_as_obsolete() {
3800   int emcp_method_count = 0;
3801   int obsolete_count = 0;
3802   int old_index = 0;
3803   for (int j = 0; j < _matching_methods_length; ++j, ++old_index) {
3804     Method* old_method = _matching_old_methods[j];
3805     Method* new_method = _matching_new_methods[j];
3806     Method* old_array_method;
3807 
3808     // Maintain an old_index into the _old_methods array by skipping
3809     // deleted methods
3810     while ((old_array_method = _old_methods->at(old_index)) != old_method) {
3811       ++old_index;
3812     }
3813 
3814     if (MethodComparator::methods_EMCP(old_method, new_method)) {
3815       // The EMCP definition from JSR-163 requires the bytecodes to be
3816       // the same with the exception of constant pool indices which may
3817       // differ. However, the constants referred to by those indices
3818       // must be the same.
3819       //
3820       // We use methods_EMCP() for comparison since constant pool
3821       // merging can remove duplicate constant pool entries that were
3822       // present in the old method and removed from the rewritten new
3823       // method. A faster binary comparison function would consider the
3824       // old and new methods to be different when they are actually
3825       // EMCP.
3826       //
3827       // The old and new methods are EMCP and you would think that we
3828       // could get rid of one of them here and now and save some space.
3829       // However, the concept of EMCP only considers the bytecodes and
3830       // the constant pool entries in the comparison. Other things,
3831       // e.g., the line number table (LNT) or the local variable table
3832       // (LVT) don't count in the comparison. So the new (and EMCP)
3833       // method can have a new LNT that we need so we can't just
3834       // overwrite the new method with the old method.
3835       //
3836       // When this routine is called, we have already attached the new
3837       // methods to the_class so the old methods are effectively
3838       // overwritten. However, if an old method is still executing,
3839       // then the old method cannot be collected until sometime after
3840       // the old method call has returned. So the overwriting of old
3841       // methods by new methods will save us space except for those
3842       // (hopefully few) old methods that are still executing.
3843       //
3844       // A method refers to a ConstMethod* and this presents another
3845       // possible avenue to space savings. The ConstMethod* in the
3846       // new method contains possibly new attributes (LNT, LVT, etc).
3847       // At first glance, it seems possible to save space by replacing
3848       // the ConstMethod* in the old method with the ConstMethod*
3849       // from the new method. The old and new methods would share the
3850       // same ConstMethod* and we would save the space occupied by
3851       // the old ConstMethod*. However, the ConstMethod* contains
3852       // a back reference to the containing method. Sharing the
3853       // ConstMethod* between two methods could lead to confusion in
3854       // the code that uses the back reference. This would lead to
3855       // brittle code that could be broken in non-obvious ways now or
3856       // in the future.
3857       //
3858       // Another possibility is to copy the ConstMethod* from the new
3859       // method to the old method and then overwrite the new method with
3860       // the old method. Since the ConstMethod* contains the bytecodes
3861       // for the method embedded in the oop, this option would change
3862       // the bytecodes out from under any threads executing the old
3863       // method and make the thread's bcp invalid. Since EMCP requires
3864       // that the bytecodes be the same modulo constant pool indices, it
3865       // is straight forward to compute the correct new bcp in the new
3866       // ConstMethod* from the old bcp in the old ConstMethod*. The
3867       // time consuming part would be searching all the frames in all
3868       // of the threads to find all of the calls to the old method.
3869       //
3870       // It looks like we will have to live with the limited savings
3871       // that we get from effectively overwriting the old methods
3872       // when the new methods are attached to the_class.
3873 
3874       // Count number of methods that are EMCP.  The method will be marked
3875       // old but not obsolete if it is EMCP.
3876       emcp_method_count++;
3877 
3878       // An EMCP method is _not_ obsolete. An obsolete method has a
3879       // different jmethodID than the current method. An EMCP method
3880       // has the same jmethodID as the current method. Having the
3881       // same jmethodID for all EMCP versions of a method allows for
3882       // a consistent view of the EMCP methods regardless of which
3883       // EMCP method you happen to have in hand. For example, a
3884       // breakpoint set in one EMCP method will work for all EMCP
3885       // versions of the method including the current one.
3886     } else {
3887       // mark obsolete methods as such
3888       old_method->set_is_obsolete();
3889       obsolete_count++;
3890 
3891       // obsolete methods need a unique idnum so they become new entries in
3892       // the jmethodID cache in InstanceKlass
3893       assert(old_method->method_idnum() == new_method->method_idnum(), "must match");
3894       u2 num = InstanceKlass::cast(_the_class)->next_method_idnum();
3895       if (num != ConstMethod::UNSET_IDNUM) {
3896         old_method->set_method_idnum(num);
3897       }
3898 
3899       // With tracing we try not to "yack" too much. The position of
3900       // this trace assumes there are fewer obsolete methods than
3901       // EMCP methods.
3902       if (log_is_enabled(Trace, redefine, class, obsolete, mark)) {
3903         ResourceMark rm;
3904         log_trace(redefine, class, obsolete, mark)
3905           ("mark %s(%s) as obsolete", old_method->name()->as_C_string(), old_method->signature()->as_C_string());
3906       }
3907     }
3908     old_method->set_is_old();
3909   }
3910   for (int i = 0; i < _deleted_methods_length; ++i) {
3911     Method* old_method = _deleted_methods[i];
3912 
3913     assert(!old_method->has_vtable_index(),
3914            "cannot delete methods with vtable entries");;
3915 
3916     // Mark all deleted methods as old, obsolete and deleted
3917     old_method->set_is_deleted();
3918     old_method->set_is_old();
3919     old_method->set_is_obsolete();
3920     ++obsolete_count;
3921     // With tracing we try not to "yack" too much. The position of
3922     // this trace assumes there are fewer obsolete methods than
3923     // EMCP methods.
3924     if (log_is_enabled(Trace, redefine, class, obsolete, mark)) {
3925       ResourceMark rm;
3926       log_trace(redefine, class, obsolete, mark)
3927         ("mark deleted %s(%s) as obsolete", old_method->name()->as_C_string(), old_method->signature()->as_C_string());
3928     }
3929   }
3930   assert((emcp_method_count + obsolete_count) == _old_methods->length(),
3931     "sanity check");
3932   log_trace(redefine, class, obsolete, mark)("EMCP_cnt=%d, obsolete_cnt=%d", emcp_method_count, obsolete_count);
3933   return emcp_method_count;
3934 }
3935 
3936 // This internal class transfers the native function registration from old methods
3937 // to new methods.  It is designed to handle both the simple case of unchanged
3938 // native methods and the complex cases of native method prefixes being added and/or
3939 // removed.
3940 // It expects only to be used during the VM_RedefineClasses op (a safepoint).
3941 //
3942 // This class is used after the new methods have been installed in "the_class".
3943 //
3944 // So, for example, the following must be handled.  Where 'm' is a method and
3945 // a number followed by an underscore is a prefix.
3946 //
3947 //                                      Old Name    New Name
3948 // Simple transfer to new method        m       ->  m
3949 // Add prefix                           m       ->  1_m
3950 // Remove prefix                        1_m     ->  m
3951 // Simultaneous add of prefixes         m       ->  3_2_1_m
3952 // Simultaneous removal of prefixes     3_2_1_m ->  m
3953 // Simultaneous add and remove          1_m     ->  2_m
3954 // Same, caused by prefix removal only  3_2_1_m ->  3_2_m
3955 //
3956 class TransferNativeFunctionRegistration {
3957  private:
3958   InstanceKlass* the_class;
3959   int prefix_count;
3960   char** prefixes;
3961 
3962   // Recursively search the binary tree of possibly prefixed method names.
3963   // Iteration could be used if all agents were well behaved. Full tree walk is
3964   // more resilent to agents not cleaning up intermediate methods.
3965   // Branch at each depth in the binary tree is:
3966   //    (1) without the prefix.
3967   //    (2) with the prefix.
3968   // where 'prefix' is the prefix at that 'depth' (first prefix, second prefix,...)
3969   Method* search_prefix_name_space(int depth, char* name_str, size_t name_len,
3970                                      Symbol* signature) {
3971     TempNewSymbol name_symbol = SymbolTable::probe(name_str, (int)name_len);
3972     if (name_symbol != NULL) {
3973       Method* method = the_class->lookup_method(name_symbol, signature);
3974       if (method != NULL) {
3975         // Even if prefixed, intermediate methods must exist.
3976         if (method->is_native()) {
3977           // Wahoo, we found a (possibly prefixed) version of the method, return it.
3978           return method;
3979         }
3980         if (depth < prefix_count) {
3981           // Try applying further prefixes (other than this one).
3982           method = search_prefix_name_space(depth+1, name_str, name_len, signature);
3983           if (method != NULL) {
3984             return method; // found
3985           }
3986 
3987           // Try adding this prefix to the method name and see if it matches
3988           // another method name.
3989           char* prefix = prefixes[depth];
3990           size_t prefix_len = strlen(prefix);
3991           size_t trial_len = name_len + prefix_len;
3992           char* trial_name_str = NEW_RESOURCE_ARRAY(char, trial_len + 1);
3993           strcpy(trial_name_str, prefix);
3994           strcat(trial_name_str, name_str);
3995           method = search_prefix_name_space(depth+1, trial_name_str, trial_len,
3996                                             signature);
3997           if (method != NULL) {
3998             // If found along this branch, it was prefixed, mark as such
3999             method->set_is_prefixed_native();
4000             return method; // found
4001           }
4002         }
4003       }
4004     }
4005     return NULL;  // This whole branch bore nothing
4006   }
4007 
4008   // Return the method name with old prefixes stripped away.
4009   char* method_name_without_prefixes(Method* method) {
4010     Symbol* name = method->name();
4011     char* name_str = name->as_utf8();
4012 
4013     // Old prefixing may be defunct, strip prefixes, if any.
4014     for (int i = prefix_count-1; i >= 0; i--) {
4015       char* prefix = prefixes[i];
4016       size_t prefix_len = strlen(prefix);
4017       if (strncmp(prefix, name_str, prefix_len) == 0) {
4018         name_str += prefix_len;
4019       }
4020     }
4021     return name_str;
4022   }
4023 
4024   // Strip any prefixes off the old native method, then try to find a
4025   // (possibly prefixed) new native that matches it.
4026   Method* strip_and_search_for_new_native(Method* method) {
4027     ResourceMark rm;
4028     char* name_str = method_name_without_prefixes(method);
4029     return search_prefix_name_space(0, name_str, strlen(name_str),
4030                                     method->signature());
4031   }
4032 
4033  public:
4034 
4035   // Construct a native method transfer processor for this class.
4036   TransferNativeFunctionRegistration(InstanceKlass* _the_class) {
4037     assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
4038 
4039     the_class = _the_class;
4040     prefixes = JvmtiExport::get_all_native_method_prefixes(&prefix_count);
4041   }
4042 
4043   // Attempt to transfer any of the old or deleted methods that are native
4044   void transfer_registrations(Method** old_methods, int methods_length) {
4045     for (int j = 0; j < methods_length; j++) {
4046       Method* old_method = old_methods[j];
4047 
4048       if (old_method->is_native() && old_method->has_native_function()) {
4049         Method* new_method = strip_and_search_for_new_native(old_method);
4050         if (new_method != NULL) {
4051           // Actually set the native function in the new method.
4052           // Redefine does not send events (except CFLH), certainly not this
4053           // behind the scenes re-registration.
4054           new_method->set_native_function(old_method->native_function(),
4055                               !Method::native_bind_event_is_interesting);
4056         }
4057       }
4058     }
4059   }
4060 };
4061 
4062 // Don't lose the association between a native method and its JNI function.
4063 void VM_RedefineClasses::transfer_old_native_function_registrations(InstanceKlass* the_class) {
4064   TransferNativeFunctionRegistration transfer(the_class);
4065   transfer.transfer_registrations(_deleted_methods, _deleted_methods_length);
4066   transfer.transfer_registrations(_matching_old_methods, _matching_methods_length);
4067 }
4068 
4069 // Deoptimize all compiled code that depends on the classes redefined.
4070 //
4071 // If the can_redefine_classes capability is obtained in the onload
4072 // phase then the compiler has recorded all dependencies from startup.
4073 // In that case we need only deoptimize and throw away all compiled code
4074 // that depends on the class.
4075 //
4076 // If can_redefine_classes is obtained sometime after the onload
4077 // phase then the dependency information may be incomplete. In that case
4078 // the first call to RedefineClasses causes all compiled code to be
4079 // thrown away. As can_redefine_classes has been obtained then
4080 // all future compilations will record dependencies so second and
4081 // subsequent calls to RedefineClasses need only throw away code
4082 // that depends on the class.
4083 //
4084 
4085 void VM_RedefineClasses::flush_dependent_code() {
4086   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
4087 
4088   bool deopt_needed;
4089 
4090   // This is the first redefinition, mark all the nmethods for deoptimization
4091   if (!JvmtiExport::all_dependencies_are_recorded()) {
4092     log_debug(redefine, class, nmethod)("Marked all nmethods for deopt");
4093     CodeCache::mark_all_nmethods_for_evol_deoptimization();
4094     deopt_needed = true;
4095   } else {
4096     int deopt = CodeCache::mark_dependents_for_evol_deoptimization();
4097     log_debug(redefine, class, nmethod)("Marked %d dependent nmethods for deopt", deopt);
4098     deopt_needed = (deopt != 0);
4099   }
4100 
4101   if (deopt_needed) {
4102     CodeCache::flush_evol_dependents();
4103   }
4104 
4105   // From now on we know that the dependency information is complete
4106   JvmtiExport::set_all_dependencies_are_recorded(true);
4107 }
4108 
4109 void VM_RedefineClasses::compute_added_deleted_matching_methods() {
4110   Method* old_method;
4111   Method* new_method;
4112 
4113   _matching_old_methods = NEW_RESOURCE_ARRAY(Method*, _old_methods->length());
4114   _matching_new_methods = NEW_RESOURCE_ARRAY(Method*, _old_methods->length());
4115   _added_methods        = NEW_RESOURCE_ARRAY(Method*, _new_methods->length());
4116   _deleted_methods      = NEW_RESOURCE_ARRAY(Method*, _old_methods->length());
4117 
4118   _matching_methods_length = 0;
4119   _deleted_methods_length  = 0;
4120   _added_methods_length    = 0;
4121 
4122   int nj = 0;
4123   int oj = 0;
4124   while (true) {
4125     if (oj >= _old_methods->length()) {
4126       if (nj >= _new_methods->length()) {
4127         break; // we've looked at everything, done
4128       }
4129       // New method at the end
4130       new_method = _new_methods->at(nj);
4131       _added_methods[_added_methods_length++] = new_method;
4132       ++nj;
4133     } else if (nj >= _new_methods->length()) {
4134       // Old method, at the end, is deleted
4135       old_method = _old_methods->at(oj);
4136       _deleted_methods[_deleted_methods_length++] = old_method;
4137       ++oj;
4138     } else {
4139       old_method = _old_methods->at(oj);
4140       new_method = _new_methods->at(nj);
4141       if (old_method->name() == new_method->name()) {
4142         if (old_method->signature() == new_method->signature()) {
4143           _matching_old_methods[_matching_methods_length  ] = old_method;
4144           _matching_new_methods[_matching_methods_length++] = new_method;
4145           ++nj;
4146           ++oj;
4147         } else {
4148           // added overloaded have already been moved to the end,
4149           // so this is a deleted overloaded method
4150           _deleted_methods[_deleted_methods_length++] = old_method;
4151           ++oj;
4152         }
4153       } else { // names don't match
4154         if (old_method->name()->fast_compare(new_method->name()) > 0) {
4155           // new method
4156           _added_methods[_added_methods_length++] = new_method;
4157           ++nj;
4158         } else {
4159           // deleted method
4160           _deleted_methods[_deleted_methods_length++] = old_method;
4161           ++oj;
4162         }
4163       }
4164     }
4165   }
4166   assert(_matching_methods_length + _deleted_methods_length == _old_methods->length(), "sanity");
4167   assert(_matching_methods_length + _added_methods_length == _new_methods->length(), "sanity");
4168 }
4169 
4170 
4171 void VM_RedefineClasses::swap_annotations(InstanceKlass* the_class,
4172                                           InstanceKlass* scratch_class) {
4173   // Swap annotation fields values
4174   Annotations* old_annotations = the_class->annotations();
4175   the_class->set_annotations(scratch_class->annotations());
4176   scratch_class->set_annotations(old_annotations);
4177 }
4178 
4179 
4180 // Install the redefinition of a class:
4181 //    - house keeping (flushing breakpoints and caches, deoptimizing
4182 //      dependent compiled code)
4183 //    - replacing parts in the_class with parts from scratch_class
4184 //    - adding a weak reference to track the obsolete but interesting
4185 //      parts of the_class
4186 //    - adjusting constant pool caches and vtables in other classes
4187 //      that refer to methods in the_class. These adjustments use the
4188 //      ClassLoaderDataGraph::classes_do() facility which only allows
4189 //      a helper method to be specified. The interesting parameters
4190 //      that we would like to pass to the helper method are saved in
4191 //      static global fields in the VM operation.
4192 void VM_RedefineClasses::redefine_single_class(Thread* current, jclass the_jclass,
4193                                                InstanceKlass* scratch_class) {
4194 
4195   HandleMark hm(current);   // make sure handles from this call are freed
4196 
4197   if (log_is_enabled(Info, redefine, class, timer)) {
4198     _timer_rsc_phase1.start();
4199   }
4200 
4201   InstanceKlass* the_class = get_ik(the_jclass);
4202 
4203   // Set a flag to control and optimize adjusting method entries
4204   _has_redefined_Object |= the_class == vmClasses::Object_klass();
4205 
4206   // Remove all breakpoints in methods of this class
4207   JvmtiBreakpoints& jvmti_breakpoints = JvmtiCurrentBreakpoints::get_jvmti_breakpoints();
4208   jvmti_breakpoints.clearall_in_class_at_safepoint(the_class);
4209 
4210   _old_methods = the_class->methods();
4211   _new_methods = scratch_class->methods();
4212   _the_class = the_class;
4213   compute_added_deleted_matching_methods();
4214   update_jmethod_ids();
4215 
4216   _any_class_has_resolved_methods = the_class->has_resolved_methods() || _any_class_has_resolved_methods;
4217 
4218   // Attach new constant pool to the original klass. The original
4219   // klass still refers to the old constant pool (for now).
4220   scratch_class->constants()->set_pool_holder(the_class);
4221 
4222 #if 0
4223   // In theory, with constant pool merging in place we should be able
4224   // to save space by using the new, merged constant pool in place of
4225   // the old constant pool(s). By "pool(s)" I mean the constant pool in
4226   // the klass version we are replacing now and any constant pool(s) in
4227   // previous versions of klass. Nice theory, doesn't work in practice.
4228   // When this code is enabled, even simple programs throw NullPointer
4229   // exceptions. I'm guessing that this is caused by some constant pool
4230   // cache difference between the new, merged constant pool and the
4231   // constant pool that was just being used by the klass. I'm keeping
4232   // this code around to archive the idea, but the code has to remain
4233   // disabled for now.
4234 
4235   // Attach each old method to the new constant pool. This can be
4236   // done here since we are past the bytecode verification and
4237   // constant pool optimization phases.
4238   for (int i = _old_methods->length() - 1; i >= 0; i--) {
4239     Method* method = _old_methods->at(i);
4240     method->set_constants(scratch_class->constants());
4241   }
4242 
4243   // NOTE: this doesn't work because you can redefine the same class in two
4244   // threads, each getting their own constant pool data appended to the
4245   // original constant pool.  In order for the new methods to work when they
4246   // become old methods, they need to keep their updated copy of the constant pool.
4247 
4248   {
4249     // walk all previous versions of the klass
4250     InstanceKlass *ik = the_class;
4251     PreviousVersionWalker pvw(ik);
4252     do {
4253       ik = pvw.next_previous_version();
4254       if (ik != NULL) {
4255 
4256         // attach previous version of klass to the new constant pool
4257         ik->set_constants(scratch_class->constants());
4258 
4259         // Attach each method in the previous version of klass to the
4260         // new constant pool
4261         Array<Method*>* prev_methods = ik->methods();
4262         for (int i = prev_methods->length() - 1; i >= 0; i--) {
4263           Method* method = prev_methods->at(i);
4264           method->set_constants(scratch_class->constants());
4265         }
4266       }
4267     } while (ik != NULL);
4268   }
4269 #endif
4270 
4271   // Replace methods and constantpool
4272   the_class->set_methods(_new_methods);
4273   scratch_class->set_methods(_old_methods);     // To prevent potential GCing of the old methods,
4274                                           // and to be able to undo operation easily.
4275 
4276   Array<int>* old_ordering = the_class->method_ordering();
4277   the_class->set_method_ordering(scratch_class->method_ordering());
4278   scratch_class->set_method_ordering(old_ordering);
4279 
4280   ConstantPool* old_constants = the_class->constants();
4281   the_class->set_constants(scratch_class->constants());
4282   scratch_class->set_constants(old_constants);  // See the previous comment.
4283 #if 0
4284   // We are swapping the guts of "the new class" with the guts of "the
4285   // class". Since the old constant pool has just been attached to "the
4286   // new class", it seems logical to set the pool holder in the old
4287   // constant pool also. However, doing this will change the observable
4288   // class hierarchy for any old methods that are still executing. A
4289   // method can query the identity of its "holder" and this query uses
4290   // the method's constant pool link to find the holder. The change in
4291   // holding class from "the class" to "the new class" can confuse
4292   // things.
4293   //
4294   // Setting the old constant pool's holder will also cause
4295   // verification done during vtable initialization below to fail.
4296   // During vtable initialization, the vtable's class is verified to be
4297   // a subtype of the method's holder. The vtable's class is "the
4298   // class" and the method's holder is gotten from the constant pool
4299   // link in the method itself. For "the class"'s directly implemented
4300   // methods, the method holder is "the class" itself (as gotten from
4301   // the new constant pool). The check works fine in this case. The
4302   // check also works fine for methods inherited from super classes.
4303   //
4304   // Miranda methods are a little more complicated. A miranda method is
4305   // provided by an interface when the class implementing the interface
4306   // does not provide its own method.  These interfaces are implemented
4307   // internally as an InstanceKlass. These special instanceKlasses
4308   // share the constant pool of the class that "implements" the
4309   // interface. By sharing the constant pool, the method holder of a
4310   // miranda method is the class that "implements" the interface. In a
4311   // non-redefine situation, the subtype check works fine. However, if
4312   // the old constant pool's pool holder is modified, then the check
4313   // fails because there is no class hierarchy relationship between the
4314   // vtable's class and "the new class".
4315 
4316   old_constants->set_pool_holder(scratch_class());
4317 #endif
4318 
4319   // track number of methods that are EMCP for add_previous_version() call below
4320   int emcp_method_count = check_methods_and_mark_as_obsolete();
4321   transfer_old_native_function_registrations(the_class);
4322 
4323   // The class file bytes from before any retransformable agents mucked
4324   // with them was cached on the scratch class, move to the_class.
4325   // Note: we still want to do this if nothing needed caching since it
4326   // should get cleared in the_class too.
4327   if (the_class->get_cached_class_file() == 0) {
4328     // the_class doesn't have a cache yet so copy it
4329     the_class->set_cached_class_file(scratch_class->get_cached_class_file());
4330   }
4331   else if (scratch_class->get_cached_class_file() !=
4332            the_class->get_cached_class_file()) {
4333     // The same class can be present twice in the scratch classes list or there
4334     // are multiple concurrent RetransformClasses calls on different threads.
4335     // In such cases we have to deallocate scratch_class cached_class_file.
4336     os::free(scratch_class->get_cached_class_file());
4337   }
4338 
4339   // NULL out in scratch class to not delete twice.  The class to be redefined
4340   // always owns these bytes.
4341   scratch_class->set_cached_class_file(NULL);
4342 
4343   // Replace inner_classes
4344   Array<u2>* old_inner_classes = the_class->inner_classes();
4345   the_class->set_inner_classes(scratch_class->inner_classes());
4346   scratch_class->set_inner_classes(old_inner_classes);
4347 
4348   // Initialize the vtable and interface table after
4349   // methods have been rewritten
4350   // no exception should happen here since we explicitly
4351   // do not check loader constraints.
4352   // compare_and_normalize_class_versions has already checked:
4353   //  - classloaders unchanged, signatures unchanged
4354   //  - all instanceKlasses for redefined classes reused & contents updated
4355   the_class->vtable().initialize_vtable();
4356   the_class->itable().initialize_itable();
4357 
4358   // Leave arrays of jmethodIDs and itable index cache unchanged
4359 
4360   // Copy the "source file name" attribute from new class version
4361   the_class->set_source_file_name_index(
4362     scratch_class->source_file_name_index());
4363 
4364   // Copy the "source debug extension" attribute from new class version
4365   the_class->set_source_debug_extension(
4366     scratch_class->source_debug_extension(),
4367     scratch_class->source_debug_extension() == NULL ? 0 :
4368     (int)strlen(scratch_class->source_debug_extension()));
4369 
4370   // Use of javac -g could be different in the old and the new
4371   if (scratch_class->access_flags().has_localvariable_table() !=
4372       the_class->access_flags().has_localvariable_table()) {
4373 
4374     AccessFlags flags = the_class->access_flags();
4375     if (scratch_class->access_flags().has_localvariable_table()) {
4376       flags.set_has_localvariable_table();
4377     } else {
4378       flags.clear_has_localvariable_table();
4379     }
4380     the_class->set_access_flags(flags);
4381   }
4382 
4383   swap_annotations(the_class, scratch_class);
4384 
4385   // Replace minor version number of class file
4386   u2 old_minor_version = the_class->constants()->minor_version();
4387   the_class->constants()->set_minor_version(scratch_class->constants()->minor_version());
4388   scratch_class->constants()->set_minor_version(old_minor_version);
4389 
4390   // Replace major version number of class file
4391   u2 old_major_version = the_class->constants()->major_version();
4392   the_class->constants()->set_major_version(scratch_class->constants()->major_version());
4393   scratch_class->constants()->set_major_version(old_major_version);
4394 
4395   // Replace CP indexes for class and name+type of enclosing method
4396   u2 old_class_idx  = the_class->enclosing_method_class_index();
4397   u2 old_method_idx = the_class->enclosing_method_method_index();
4398   the_class->set_enclosing_method_indices(
4399     scratch_class->enclosing_method_class_index(),
4400     scratch_class->enclosing_method_method_index());
4401   scratch_class->set_enclosing_method_indices(old_class_idx, old_method_idx);
4402 
4403   the_class->set_has_been_redefined();
4404 
4405   // Scratch class is unloaded but still needs cleaning, and skipping for CDS.
4406   scratch_class->set_is_scratch_class();
4407 
4408   // keep track of previous versions of this class
4409   the_class->add_previous_version(scratch_class, emcp_method_count);
4410 
4411   _timer_rsc_phase1.stop();
4412   if (log_is_enabled(Info, redefine, class, timer)) {
4413     _timer_rsc_phase2.start();
4414   }
4415 
4416   if (the_class->oop_map_cache() != NULL) {
4417     // Flush references to any obsolete methods from the oop map cache
4418     // so that obsolete methods are not pinned.
4419     the_class->oop_map_cache()->flush_obsolete_entries();
4420   }
4421 
4422   increment_class_counter(the_class);
4423 
4424   if (EventClassRedefinition::is_enabled()) {
4425     EventClassRedefinition event;
4426     event.set_classModificationCount(java_lang_Class::classRedefinedCount(the_class->java_mirror()));
4427     event.set_redefinedClass(the_class);
4428     event.set_redefinitionId(_id);
4429     event.commit();
4430   }
4431 
4432   {
4433     ResourceMark rm(current);
4434     // increment the classRedefinedCount field in the_class and in any
4435     // direct and indirect subclasses of the_class
4436     log_info(redefine, class, load)
4437       ("redefined name=%s, count=%d (avail_mem=" UINT64_FORMAT "K)",
4438        the_class->external_name(), java_lang_Class::classRedefinedCount(the_class->java_mirror()), os::available_memory() >> 10);
4439     Events::log_redefinition(current, "redefined class name=%s, count=%d",
4440                              the_class->external_name(),
4441                              java_lang_Class::classRedefinedCount(the_class->java_mirror()));
4442 
4443   }
4444   _timer_rsc_phase2.stop();
4445 
4446 } // end redefine_single_class()
4447 
4448 
4449 // Increment the classRedefinedCount field in the specific InstanceKlass
4450 // and in all direct and indirect subclasses.
4451 void VM_RedefineClasses::increment_class_counter(InstanceKlass* ik) {
4452   for (ClassHierarchyIterator iter(ik); !iter.done(); iter.next()) {
4453     // Only update instanceKlasses
4454     Klass* sub = iter.klass();
4455     if (sub->is_instance_klass()) {
4456       oop class_mirror = InstanceKlass::cast(sub)->java_mirror();
4457       Klass* class_oop = java_lang_Class::as_Klass(class_mirror);
4458       int new_count = java_lang_Class::classRedefinedCount(class_mirror) + 1;
4459       java_lang_Class::set_classRedefinedCount(class_mirror, new_count);
4460 
4461       if (class_oop != _the_class) {
4462         // _the_class count is printed at end of redefine_single_class()
4463         log_debug(redefine, class, subclass)("updated count in subclass=%s to %d", ik->external_name(), new_count);
4464       }
4465     }
4466   }
4467 }
4468 
4469 void VM_RedefineClasses::CheckClass::do_klass(Klass* k) {
4470   bool no_old_methods = true;  // be optimistic
4471 
4472   // Both array and instance classes have vtables.
4473   // a vtable should never contain old or obsolete methods
4474   ResourceMark rm(_thread);
4475   if (k->vtable_length() > 0 &&
4476       !k->vtable().check_no_old_or_obsolete_entries()) {
4477     if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
4478       log_trace(redefine, class, obsolete, metadata)
4479         ("klassVtable::check_no_old_or_obsolete_entries failure -- OLD or OBSOLETE method found -- class: %s",
4480          k->signature_name());
4481       k->vtable().dump_vtable();
4482     }
4483     no_old_methods = false;
4484   }
4485 
4486   if (k->is_instance_klass()) {
4487     HandleMark hm(_thread);
4488     InstanceKlass *ik = InstanceKlass::cast(k);
4489 
4490     // an itable should never contain old or obsolete methods
4491     if (ik->itable_length() > 0 &&
4492         !ik->itable().check_no_old_or_obsolete_entries()) {
4493       if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
4494         log_trace(redefine, class, obsolete, metadata)
4495           ("klassItable::check_no_old_or_obsolete_entries failure -- OLD or OBSOLETE method found -- class: %s",
4496            ik->signature_name());
4497         ik->itable().dump_itable();
4498       }
4499       no_old_methods = false;
4500     }
4501 
4502     // the constant pool cache should never contain non-deleted old or obsolete methods
4503     if (ik->constants() != NULL &&
4504         ik->constants()->cache() != NULL &&
4505         !ik->constants()->cache()->check_no_old_or_obsolete_entries()) {
4506       if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
4507         log_trace(redefine, class, obsolete, metadata)
4508           ("cp-cache::check_no_old_or_obsolete_entries failure -- OLD or OBSOLETE method found -- class: %s",
4509            ik->signature_name());
4510         ik->constants()->cache()->dump_cache();
4511       }
4512       no_old_methods = false;
4513     }
4514   }
4515 
4516   // print and fail guarantee if old methods are found.
4517   if (!no_old_methods) {
4518     if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
4519       dump_methods();
4520     } else {
4521       log_trace(redefine, class)("Use the '-Xlog:redefine+class*:' option "
4522         "to see more info about the following guarantee() failure.");
4523     }
4524     guarantee(false, "OLD and/or OBSOLETE method(s) found");
4525   }
4526 }
4527 
4528 u8 VM_RedefineClasses::next_id() {
4529   while (true) {
4530     u8 id = _id_counter;
4531     u8 next_id = id + 1;
4532     u8 result = Atomic::cmpxchg(&_id_counter, id, next_id);
4533     if (result == id) {
4534       return next_id;
4535     }
4536   }
4537 }
4538 
4539 void VM_RedefineClasses::dump_methods() {
4540   int j;
4541   log_trace(redefine, class, dump)("_old_methods --");
4542   for (j = 0; j < _old_methods->length(); ++j) {
4543     LogStreamHandle(Trace, redefine, class, dump) log_stream;
4544     Method* m = _old_methods->at(j);
4545     log_stream.print("%4d  (%5d)  ", j, m->vtable_index());
4546     m->access_flags().print_on(&log_stream);
4547     log_stream.print(" --  ");
4548     m->print_name(&log_stream);
4549     log_stream.cr();
4550   }
4551   log_trace(redefine, class, dump)("_new_methods --");
4552   for (j = 0; j < _new_methods->length(); ++j) {
4553     LogStreamHandle(Trace, redefine, class, dump) log_stream;
4554     Method* m = _new_methods->at(j);
4555     log_stream.print("%4d  (%5d)  ", j, m->vtable_index());
4556     m->access_flags().print_on(&log_stream);
4557     log_stream.print(" --  ");
4558     m->print_name(&log_stream);
4559     log_stream.cr();
4560   }
4561   log_trace(redefine, class, dump)("_matching_methods --");
4562   for (j = 0; j < _matching_methods_length; ++j) {
4563     LogStreamHandle(Trace, redefine, class, dump) log_stream;
4564     Method* m = _matching_old_methods[j];
4565     log_stream.print("%4d  (%5d)  ", j, m->vtable_index());
4566     m->access_flags().print_on(&log_stream);
4567     log_stream.print(" --  ");
4568     m->print_name();
4569     log_stream.cr();
4570 
4571     m = _matching_new_methods[j];
4572     log_stream.print("      (%5d)  ", m->vtable_index());
4573     m->access_flags().print_on(&log_stream);
4574     log_stream.cr();
4575   }
4576   log_trace(redefine, class, dump)("_deleted_methods --");
4577   for (j = 0; j < _deleted_methods_length; ++j) {
4578     LogStreamHandle(Trace, redefine, class, dump) log_stream;
4579     Method* m = _deleted_methods[j];
4580     log_stream.print("%4d  (%5d)  ", j, m->vtable_index());
4581     m->access_flags().print_on(&log_stream);
4582     log_stream.print(" --  ");
4583     m->print_name(&log_stream);
4584     log_stream.cr();
4585   }
4586   log_trace(redefine, class, dump)("_added_methods --");
4587   for (j = 0; j < _added_methods_length; ++j) {
4588     LogStreamHandle(Trace, redefine, class, dump) log_stream;
4589     Method* m = _added_methods[j];
4590     log_stream.print("%4d  (%5d)  ", j, m->vtable_index());
4591     m->access_flags().print_on(&log_stream);
4592     log_stream.print(" --  ");
4593     m->print_name(&log_stream);
4594     log_stream.cr();
4595   }
4596 }
4597 
4598 void VM_RedefineClasses::print_on_error(outputStream* st) const {
4599   VM_Operation::print_on_error(st);
4600   if (_the_class != NULL) {
4601     ResourceMark rm;
4602     st->print_cr(", redefining class %s", _the_class->external_name());
4603   }
4604 }