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