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