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