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