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