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