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