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