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