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

3402 void VM_RedefineClasses::check_class(Klass* k_oop,
3403                                      ClassLoaderData* initiating_loader,
3404                                      TRAPS) {
3405   Klass *k = k_oop;
3406   if (k->oop_is_instance()) {
3407     HandleMark hm(THREAD);
3408     InstanceKlass *ik = (InstanceKlass *) k;
3409     bool no_old_methods = true;  // be optimistic

3410     ResourceMark rm(THREAD);
3411 
3412     // a vtable should never contain old or obsolete methods
3413     if (ik->vtable_length() > 0 &&
3414         !ik->vtable()->check_no_old_or_obsolete_entries()) {
3415       if (RC_TRACE_ENABLED(0x00004000)) {
3416         RC_TRACE_WITH_THREAD(0x00004000, THREAD,
3417           ("klassVtable::check_no_old_or_obsolete_entries failure"
3418            " -- OLD or OBSOLETE method found -- class: %s",
3419            ik->signature_name()));
3420         ik->vtable()->dump_vtable();

3421       }
3422       no_old_methods = false;
3423     }
3424 
3425     // an itable should never contain old or obsolete methods
3426     if (ik->itable_length() > 0 &&
3427         !ik->itable()->check_no_old_or_obsolete_entries()) {
3428       if (RC_TRACE_ENABLED(0x00004000)) {
3429         RC_TRACE_WITH_THREAD(0x00004000, THREAD,
3430           ("klassItable::check_no_old_or_obsolete_entries failure"
3431            " -- OLD or OBSOLETE method found -- class: %s",
3432            ik->signature_name()));
3433         ik->itable()->dump_itable();
3434       }
3435       no_old_methods = false;
3436     }
3437 
3438     // the constant pool cache should never contain old or obsolete methods
3439     if (ik->constants() != NULL &&
3440         ik->constants()->cache() != NULL &&
3441         !ik->constants()->cache()->check_no_old_or_obsolete_entries()) {
3442       if (RC_TRACE_ENABLED(0x00004000)) {
3443         RC_TRACE_WITH_THREAD(0x00004000, THREAD,
3444           ("cp-cache::check_no_old_or_obsolete_entries failure"
3445            " -- OLD or OBSOLETE method found -- class: %s",
3446            ik->signature_name()));
3447         ik->constants()->cache()->dump_cache();
3448       }
3449       no_old_methods = false;
3450     }
3451 
3452     if (!no_old_methods) {
3453       if (RC_TRACE_ENABLED(0x00004000)) {
3454         dump_methods();
3455       } else {
3456         tty->print_cr("INFO: use the '-XX:TraceRedefineClasses=16384' option "
3457           "to see more info about the following guarantee() failure.");
3458       }
3459       guarantee(false, "OLD and/or OBSOLETE method(s) found");
3460     }
3461   }
3462 }
3463 
3464 void VM_RedefineClasses::dump_methods() {
3465   int j;
3466   RC_TRACE(0x00004000, ("_old_methods --"));
3467   for (j = 0; j < _old_methods->length(); ++j) {
3468     Method* m = _old_methods->at(j);
3469     RC_TRACE_NO_CR(0x00004000, ("%4d  (%5d)  ", j, m->vtable_index()));
3470     m->access_flags().print_on(tty);
3471     tty->print(" --  ");
3472     m->print_name(tty);
3473     tty->cr();
3474   }
3475   RC_TRACE(0x00004000, ("_new_methods --"));
3476   for (j = 0; j < _new_methods->length(); ++j) {
3477     Method* m = _new_methods->at(j);
3478     RC_TRACE_NO_CR(0x00004000, ("%4d  (%5d)  ", j, m->vtable_index()));
3479     m->access_flags().print_on(tty);
3480     tty->print(" --  ");
3481     m->print_name(tty);
3482     tty->cr();
3483   }
3484   RC_TRACE(0x00004000, ("_matching_(old/new)_methods --"));
3485   for (j = 0; j < _matching_methods_length; ++j) {
3486     Method* m = _matching_old_methods[j];
3487     RC_TRACE_NO_CR(0x00004000, ("%4d  (%5d)  ", j, m->vtable_index()));
3488     m->access_flags().print_on(tty);
3489     tty->print(" --  ");
3490     m->print_name(tty);
3491     tty->cr();
3492     m = _matching_new_methods[j];
3493     RC_TRACE_NO_CR(0x00004000, ("      (%5d)  ", m->vtable_index()));
3494     m->access_flags().print_on(tty);
3495     tty->cr();
3496   }
3497   RC_TRACE(0x00004000, ("_deleted_methods --"));
3498   for (j = 0; j < _deleted_methods_length; ++j) {
3499     Method* m = _deleted_methods[j];
3500     RC_TRACE_NO_CR(0x00004000, ("%4d  (%5d)  ", j, m->vtable_index()));
3501     m->access_flags().print_on(tty);
3502     tty->print(" --  ");
3503     m->print_name(tty);
3504     tty->cr();
3505   }
3506   RC_TRACE(0x00004000, ("_added_methods --"));
3507   for (j = 0; j < _added_methods_length; ++j) {
3508     Method* m = _added_methods[j];
3509     RC_TRACE_NO_CR(0x00004000, ("%4d  (%5d)  ", j, m->vtable_index()));
3510     m->access_flags().print_on(tty);
3511     tty->print(" --  ");
3512     m->print_name(tty);
3513     tty->cr();
3514   }
3515 }

--- EOF ---