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 // Increment flag indicating that some invariants are no longer true. 236 // See jvmtiExport.hpp for detailed explanation. 237 JvmtiExport::increment_redefinition_count(); 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 if (old_cp->has_dynamic_constant()) { 1627 merge_cp->set_has_dynamic_constant(); 1628 scratch_cp->set_has_dynamic_constant(); 1629 } 1630 1631 log_info(redefine, class, constantpool)("merge_cp_len=%d, index_map_len=%d", merge_cp_length, _index_map_count); 1632 1633 if (_index_map_count == 0) { 1634 // there is nothing to map between the new and merged constant pools 1635 1636 if (old_cp->length() == scratch_cp->length()) { 1637 // The old and new constant pools are the same length and the 1638 // index map is empty. This means that the three constant pools 1639 // are equivalent (but not the same). Unfortunately, the new 1640 // constant pool has not gone through link resolution nor have 1641 // the new class bytecodes gone through constant pool cache 1642 // rewriting so we can't use the old constant pool with the new 1643 // class. 1644 1645 // toss the merged constant pool at return 1646 } else if (old_cp->length() < scratch_cp->length()) { 1647 // The old constant pool has fewer entries than the new constant 1648 // pool and the index map is empty. This means the new constant 1649 // pool is a superset of the old constant pool. However, the old 1650 // class bytecodes have already gone through constant pool cache 1651 // rewriting so we can't use the new constant pool with the old 1652 // class. 1653 1654 // toss the merged constant pool at return 1655 } else { 1656 // The old constant pool has more entries than the new constant 1657 // pool and the index map is empty. This means that both the old 1658 // and merged constant pools are supersets of the new constant 1659 // pool. 1660 1661 // Replace the new constant pool with a shrunken copy of the 1662 // merged constant pool 1663 set_new_constant_pool(loader_data, scratch_class, merge_cp, merge_cp_length, 1664 CHECK_(JVMTI_ERROR_OUT_OF_MEMORY)); 1665 // The new constant pool replaces scratch_cp so have cleaner clean it up. 1666 // It can't be cleaned up while there are handles to it. 1667 cp_cleaner.add_scratch_cp(scratch_cp()); 1668 } 1669 } else { 1670 if (log_is_enabled(Trace, redefine, class, constantpool)) { 1671 // don't want to loop unless we are tracing 1672 int count = 0; 1673 for (int i = 1; i < _index_map_p->length(); i++) { 1674 int value = _index_map_p->at(i); 1675 1676 if (value != -1) { 1677 log_trace(redefine, class, constantpool)("index_map[%d]: old=%d new=%d", count, i, value); 1678 count++; 1679 } 1680 } 1681 } 1682 1683 // We have entries mapped between the new and merged constant pools 1684 // so we have to rewrite some constant pool references. 1685 if (!rewrite_cp_refs(scratch_class, THREAD)) { 1686 return JVMTI_ERROR_INTERNAL; 1687 } 1688 1689 // Replace the new constant pool with a shrunken copy of the 1690 // merged constant pool so now the rewritten bytecodes have 1691 // valid references; the previous new constant pool will get 1692 // GCed. 1693 set_new_constant_pool(loader_data, scratch_class, merge_cp, merge_cp_length, 1694 CHECK_(JVMTI_ERROR_OUT_OF_MEMORY)); 1695 // The new constant pool replaces scratch_cp so have cleaner clean it up. 1696 // It can't be cleaned up while there are handles to it. 1697 cp_cleaner.add_scratch_cp(scratch_cp()); 1698 } 1699 1700 return JVMTI_ERROR_NONE; 1701 } // end merge_cp_and_rewrite() 1702 1703 1704 // Rewrite constant pool references in klass scratch_class. 1705 bool VM_RedefineClasses::rewrite_cp_refs(InstanceKlass* scratch_class, 1706 TRAPS) { 1707 1708 // rewrite constant pool references in the nest attributes: 1709 if (!rewrite_cp_refs_in_nest_attributes(scratch_class)) { 1710 // propagate failure back to caller 1711 return false; 1712 } 1713 1714 // rewrite constant pool references in the methods: 1715 if (!rewrite_cp_refs_in_methods(scratch_class, THREAD)) { 1716 // propagate failure back to caller 1717 return false; 1718 } 1719 1720 // rewrite constant pool references in the class_annotations: 1721 if (!rewrite_cp_refs_in_class_annotations(scratch_class, THREAD)) { 1722 // propagate failure back to caller 1723 return false; 1724 } 1725 1726 // rewrite constant pool references in the fields_annotations: 1727 if (!rewrite_cp_refs_in_fields_annotations(scratch_class, THREAD)) { 1728 // propagate failure back to caller 1729 return false; 1730 } 1731 1732 // rewrite constant pool references in the methods_annotations: 1733 if (!rewrite_cp_refs_in_methods_annotations(scratch_class, THREAD)) { 1734 // propagate failure back to caller 1735 return false; 1736 } 1737 1738 // rewrite constant pool references in the methods_parameter_annotations: 1739 if (!rewrite_cp_refs_in_methods_parameter_annotations(scratch_class, 1740 THREAD)) { 1741 // propagate failure back to caller 1742 return false; 1743 } 1744 1745 // rewrite constant pool references in the methods_default_annotations: 1746 if (!rewrite_cp_refs_in_methods_default_annotations(scratch_class, 1747 THREAD)) { 1748 // propagate failure back to caller 1749 return false; 1750 } 1751 1752 // rewrite constant pool references in the class_type_annotations: 1753 if (!rewrite_cp_refs_in_class_type_annotations(scratch_class, THREAD)) { 1754 // propagate failure back to caller 1755 return false; 1756 } 1757 1758 // rewrite constant pool references in the fields_type_annotations: 1759 if (!rewrite_cp_refs_in_fields_type_annotations(scratch_class, THREAD)) { 1760 // propagate failure back to caller 1761 return false; 1762 } 1763 1764 // rewrite constant pool references in the methods_type_annotations: 1765 if (!rewrite_cp_refs_in_methods_type_annotations(scratch_class, THREAD)) { 1766 // propagate failure back to caller 1767 return false; 1768 } 1769 1770 // There can be type annotations in the Code part of a method_info attribute. 1771 // These annotations are not accessible, even by reflection. 1772 // Currently they are not even parsed by the ClassFileParser. 1773 // If runtime access is added they will also need to be rewritten. 1774 1775 // rewrite source file name index: 1776 u2 source_file_name_idx = scratch_class->source_file_name_index(); 1777 if (source_file_name_idx != 0) { 1778 u2 new_source_file_name_idx = find_new_index(source_file_name_idx); 1779 if (new_source_file_name_idx != 0) { 1780 scratch_class->set_source_file_name_index(new_source_file_name_idx); 1781 } 1782 } 1783 1784 // rewrite class generic signature index: 1785 u2 generic_signature_index = scratch_class->generic_signature_index(); 1786 if (generic_signature_index != 0) { 1787 u2 new_generic_signature_index = find_new_index(generic_signature_index); 1788 if (new_generic_signature_index != 0) { 1789 scratch_class->set_generic_signature_index(new_generic_signature_index); 1790 } 1791 } 1792 1793 return true; 1794 } // end rewrite_cp_refs() 1795 1796 // Rewrite constant pool references in the NestHost and NestMembers attributes. 1797 bool VM_RedefineClasses::rewrite_cp_refs_in_nest_attributes( 1798 InstanceKlass* scratch_class) { 1799 1800 u2 cp_index = scratch_class->nest_host_index(); 1801 if (cp_index != 0) { 1802 scratch_class->set_nest_host_index(find_new_index(cp_index)); 1803 } 1804 Array<u2>* nest_members = scratch_class->nest_members(); 1805 for (int i = 0; i < nest_members->length(); i++) { 1806 u2 cp_index = nest_members->at(i); 1807 nest_members->at_put(i, find_new_index(cp_index)); 1808 } 1809 return true; 1810 } 1811 1812 // Rewrite constant pool references in the methods. 1813 bool VM_RedefineClasses::rewrite_cp_refs_in_methods( 1814 InstanceKlass* scratch_class, TRAPS) { 1815 1816 Array<Method*>* methods = scratch_class->methods(); 1817 1818 if (methods == NULL || methods->length() == 0) { 1819 // no methods so nothing to do 1820 return true; 1821 } 1822 1823 // rewrite constant pool references in the methods: 1824 for (int i = methods->length() - 1; i >= 0; i--) { 1825 methodHandle method(THREAD, methods->at(i)); 1826 methodHandle new_method; 1827 rewrite_cp_refs_in_method(method, &new_method, THREAD); 1828 if (!new_method.is_null()) { 1829 // the method has been replaced so save the new method version 1830 // even in the case of an exception. original method is on the 1831 // deallocation list. 1832 methods->at_put(i, new_method()); 1833 } 1834 if (HAS_PENDING_EXCEPTION) { 1835 Symbol* ex_name = PENDING_EXCEPTION->klass()->name(); 1836 log_info(redefine, class, load, exceptions)("rewrite_cp_refs_in_method exception: '%s'", ex_name->as_C_string()); 1837 // Need to clear pending exception here as the super caller sets 1838 // the JVMTI_ERROR_INTERNAL if the returned value is false. 1839 CLEAR_PENDING_EXCEPTION; 1840 return false; 1841 } 1842 } 1843 1844 return true; 1845 } 1846 1847 1848 // Rewrite constant pool references in the specific method. This code 1849 // was adapted from Rewriter::rewrite_method(). 1850 void VM_RedefineClasses::rewrite_cp_refs_in_method(methodHandle method, 1851 methodHandle *new_method_p, TRAPS) { 1852 1853 *new_method_p = methodHandle(); // default is no new method 1854 1855 // We cache a pointer to the bytecodes here in code_base. If GC 1856 // moves the Method*, then the bytecodes will also move which 1857 // will likely cause a crash. We create a NoSafepointVerifier 1858 // object to detect whether we pass a possible safepoint in this 1859 // code block. 1860 NoSafepointVerifier nsv; 1861 1862 // Bytecodes and their length 1863 address code_base = method->code_base(); 1864 int code_length = method->code_size(); 1865 1866 int bc_length; 1867 for (int bci = 0; bci < code_length; bci += bc_length) { 1868 address bcp = code_base + bci; 1869 Bytecodes::Code c = (Bytecodes::Code)(*bcp); 1870 1871 bc_length = Bytecodes::length_for(c); 1872 if (bc_length == 0) { 1873 // More complicated bytecodes report a length of zero so 1874 // we have to try again a slightly different way. 1875 bc_length = Bytecodes::length_at(method(), bcp); 1876 } 1877 1878 assert(bc_length != 0, "impossible bytecode length"); 1879 1880 switch (c) { 1881 case Bytecodes::_ldc: 1882 { 1883 int cp_index = *(bcp + 1); 1884 int new_index = find_new_index(cp_index); 1885 1886 if (StressLdcRewrite && new_index == 0) { 1887 // If we are stressing ldc -> ldc_w rewriting, then we 1888 // always need a new_index value. 1889 new_index = cp_index; 1890 } 1891 if (new_index != 0) { 1892 // the original index is mapped so we have more work to do 1893 if (!StressLdcRewrite && new_index <= max_jubyte) { 1894 // The new value can still use ldc instead of ldc_w 1895 // unless we are trying to stress ldc -> ldc_w rewriting 1896 log_trace(redefine, class, constantpool) 1897 ("%s@" INTPTR_FORMAT " old=%d, new=%d", Bytecodes::name(c), p2i(bcp), cp_index, new_index); 1898 *(bcp + 1) = new_index; 1899 } else { 1900 log_trace(redefine, class, constantpool) 1901 ("%s->ldc_w@" INTPTR_FORMAT " old=%d, new=%d", Bytecodes::name(c), p2i(bcp), cp_index, new_index); 1902 // the new value needs ldc_w instead of ldc 1903 u_char inst_buffer[4]; // max instruction size is 4 bytes 1904 bcp = (address)inst_buffer; 1905 // construct new instruction sequence 1906 *bcp = Bytecodes::_ldc_w; 1907 bcp++; 1908 // Rewriter::rewrite_method() does not rewrite ldc -> ldc_w. 1909 // See comment below for difference between put_Java_u2() 1910 // and put_native_u2(). 1911 Bytes::put_Java_u2(bcp, new_index); 1912 1913 Relocator rc(method, NULL /* no RelocatorListener needed */); 1914 methodHandle m; 1915 { 1916 PauseNoSafepointVerifier pnsv(&nsv); 1917 1918 // ldc is 2 bytes and ldc_w is 3 bytes 1919 m = rc.insert_space_at(bci, 3, inst_buffer, CHECK); 1920 } 1921 1922 // return the new method so that the caller can update 1923 // the containing class 1924 *new_method_p = method = m; 1925 // switch our bytecode processing loop from the old method 1926 // to the new method 1927 code_base = method->code_base(); 1928 code_length = method->code_size(); 1929 bcp = code_base + bci; 1930 c = (Bytecodes::Code)(*bcp); 1931 bc_length = Bytecodes::length_for(c); 1932 assert(bc_length != 0, "sanity check"); 1933 } // end we need ldc_w instead of ldc 1934 } // end if there is a mapped index 1935 } break; 1936 1937 // these bytecodes have a two-byte constant pool index 1938 case Bytecodes::_anewarray : // fall through 1939 case Bytecodes::_checkcast : // fall through 1940 case Bytecodes::_getfield : // fall through 1941 case Bytecodes::_getstatic : // fall through 1942 case Bytecodes::_instanceof : // fall through 1943 case Bytecodes::_invokedynamic : // fall through 1944 case Bytecodes::_invokeinterface: // fall through 1945 case Bytecodes::_invokespecial : // fall through 1946 case Bytecodes::_invokestatic : // fall through 1947 case Bytecodes::_invokevirtual : // fall through 1948 case Bytecodes::_ldc_w : // fall through 1949 case Bytecodes::_ldc2_w : // fall through 1950 case Bytecodes::_multianewarray : // fall through 1951 case Bytecodes::_new : // fall through 1952 case Bytecodes::_putfield : // fall through 1953 case Bytecodes::_putstatic : 1954 { 1955 address p = bcp + 1; 1956 int cp_index = Bytes::get_Java_u2(p); 1957 int new_index = find_new_index(cp_index); 1958 if (new_index != 0) { 1959 // the original index is mapped so update w/ new value 1960 log_trace(redefine, class, constantpool) 1961 ("%s@" INTPTR_FORMAT " old=%d, new=%d", Bytecodes::name(c),p2i(bcp), cp_index, new_index); 1962 // Rewriter::rewrite_method() uses put_native_u2() in this 1963 // situation because it is reusing the constant pool index 1964 // location for a native index into the ConstantPoolCache. 1965 // Since we are updating the constant pool index prior to 1966 // verification and ConstantPoolCache initialization, we 1967 // need to keep the new index in Java byte order. 1968 Bytes::put_Java_u2(p, new_index); 1969 } 1970 } break; 1971 default: 1972 break; 1973 } 1974 } // end for each bytecode 1975 1976 // We also need to rewrite the parameter name indexes, if there is 1977 // method parameter data present 1978 if(method->has_method_parameters()) { 1979 const int len = method->method_parameters_length(); 1980 MethodParametersElement* elem = method->method_parameters_start(); 1981 1982 for (int i = 0; i < len; i++) { 1983 const u2 cp_index = elem[i].name_cp_index; 1984 const u2 new_cp_index = find_new_index(cp_index); 1985 if (new_cp_index != 0) { 1986 elem[i].name_cp_index = new_cp_index; 1987 } 1988 } 1989 } 1990 } // end rewrite_cp_refs_in_method() 1991 1992 1993 // Rewrite constant pool references in the class_annotations field. 1994 bool VM_RedefineClasses::rewrite_cp_refs_in_class_annotations( 1995 InstanceKlass* scratch_class, TRAPS) { 1996 1997 AnnotationArray* class_annotations = scratch_class->class_annotations(); 1998 if (class_annotations == NULL || class_annotations->length() == 0) { 1999 // no class_annotations so nothing to do 2000 return true; 2001 } 2002 2003 log_debug(redefine, class, annotation)("class_annotations length=%d", class_annotations->length()); 2004 2005 int byte_i = 0; // byte index into class_annotations 2006 return rewrite_cp_refs_in_annotations_typeArray(class_annotations, byte_i, 2007 THREAD); 2008 } 2009 2010 2011 // Rewrite constant pool references in an annotations typeArray. This 2012 // "structure" is adapted from the RuntimeVisibleAnnotations_attribute 2013 // that is described in section 4.8.15 of the 2nd-edition of the VM spec: 2014 // 2015 // annotations_typeArray { 2016 // u2 num_annotations; 2017 // annotation annotations[num_annotations]; 2018 // } 2019 // 2020 bool VM_RedefineClasses::rewrite_cp_refs_in_annotations_typeArray( 2021 AnnotationArray* annotations_typeArray, int &byte_i_ref, TRAPS) { 2022 2023 if ((byte_i_ref + 2) > annotations_typeArray->length()) { 2024 // not enough room for num_annotations field 2025 log_debug(redefine, class, annotation)("length() is too small for num_annotations field"); 2026 return false; 2027 } 2028 2029 u2 num_annotations = Bytes::get_Java_u2((address) 2030 annotations_typeArray->adr_at(byte_i_ref)); 2031 byte_i_ref += 2; 2032 2033 log_debug(redefine, class, annotation)("num_annotations=%d", num_annotations); 2034 2035 int calc_num_annotations = 0; 2036 for (; calc_num_annotations < num_annotations; calc_num_annotations++) { 2037 if (!rewrite_cp_refs_in_annotation_struct(annotations_typeArray, 2038 byte_i_ref, THREAD)) { 2039 log_debug(redefine, class, annotation)("bad annotation_struct at %d", calc_num_annotations); 2040 // propagate failure back to caller 2041 return false; 2042 } 2043 } 2044 assert(num_annotations == calc_num_annotations, "sanity check"); 2045 2046 return true; 2047 } // end rewrite_cp_refs_in_annotations_typeArray() 2048 2049 2050 // Rewrite constant pool references in the annotation struct portion of 2051 // an annotations_typeArray. This "structure" is from section 4.8.15 of 2052 // the 2nd-edition of the VM spec: 2053 // 2054 // struct annotation { 2055 // u2 type_index; 2056 // u2 num_element_value_pairs; 2057 // { 2058 // u2 element_name_index; 2059 // element_value value; 2060 // } element_value_pairs[num_element_value_pairs]; 2061 // } 2062 // 2063 bool VM_RedefineClasses::rewrite_cp_refs_in_annotation_struct( 2064 AnnotationArray* annotations_typeArray, int &byte_i_ref, TRAPS) { 2065 if ((byte_i_ref + 2 + 2) > annotations_typeArray->length()) { 2066 // not enough room for smallest annotation_struct 2067 log_debug(redefine, class, annotation)("length() is too small for annotation_struct"); 2068 return false; 2069 } 2070 2071 u2 type_index = rewrite_cp_ref_in_annotation_data(annotations_typeArray, 2072 byte_i_ref, "type_index", THREAD); 2073 2074 u2 num_element_value_pairs = Bytes::get_Java_u2((address) 2075 annotations_typeArray->adr_at(byte_i_ref)); 2076 byte_i_ref += 2; 2077 2078 log_debug(redefine, class, annotation) 2079 ("type_index=%d num_element_value_pairs=%d", type_index, num_element_value_pairs); 2080 2081 int calc_num_element_value_pairs = 0; 2082 for (; calc_num_element_value_pairs < num_element_value_pairs; 2083 calc_num_element_value_pairs++) { 2084 if ((byte_i_ref + 2) > annotations_typeArray->length()) { 2085 // not enough room for another element_name_index, let alone 2086 // the rest of another component 2087 log_debug(redefine, class, annotation)("length() is too small for element_name_index"); 2088 return false; 2089 } 2090 2091 u2 element_name_index = rewrite_cp_ref_in_annotation_data( 2092 annotations_typeArray, byte_i_ref, 2093 "element_name_index", THREAD); 2094 2095 log_debug(redefine, class, annotation)("element_name_index=%d", element_name_index); 2096 2097 if (!rewrite_cp_refs_in_element_value(annotations_typeArray, 2098 byte_i_ref, THREAD)) { 2099 log_debug(redefine, class, annotation)("bad element_value at %d", calc_num_element_value_pairs); 2100 // propagate failure back to caller 2101 return false; 2102 } 2103 } // end for each component 2104 assert(num_element_value_pairs == calc_num_element_value_pairs, 2105 "sanity check"); 2106 2107 return true; 2108 } // end rewrite_cp_refs_in_annotation_struct() 2109 2110 2111 // Rewrite a constant pool reference at the current position in 2112 // annotations_typeArray if needed. Returns the original constant 2113 // pool reference if a rewrite was not needed or the new constant 2114 // pool reference if a rewrite was needed. 2115 u2 VM_RedefineClasses::rewrite_cp_ref_in_annotation_data( 2116 AnnotationArray* annotations_typeArray, int &byte_i_ref, 2117 const char * trace_mesg, TRAPS) { 2118 2119 address cp_index_addr = (address) 2120 annotations_typeArray->adr_at(byte_i_ref); 2121 u2 old_cp_index = Bytes::get_Java_u2(cp_index_addr); 2122 u2 new_cp_index = find_new_index(old_cp_index); 2123 if (new_cp_index != 0) { 2124 log_debug(redefine, class, annotation)("mapped old %s=%d", trace_mesg, old_cp_index); 2125 Bytes::put_Java_u2(cp_index_addr, new_cp_index); 2126 old_cp_index = new_cp_index; 2127 } 2128 byte_i_ref += 2; 2129 return old_cp_index; 2130 } 2131 2132 2133 // Rewrite constant pool references in the element_value portion of an 2134 // annotations_typeArray. This "structure" is from section 4.8.15.1 of 2135 // the 2nd-edition of the VM spec: 2136 // 2137 // struct element_value { 2138 // u1 tag; 2139 // union { 2140 // u2 const_value_index; 2141 // { 2142 // u2 type_name_index; 2143 // u2 const_name_index; 2144 // } enum_const_value; 2145 // u2 class_info_index; 2146 // annotation annotation_value; 2147 // struct { 2148 // u2 num_values; 2149 // element_value values[num_values]; 2150 // } array_value; 2151 // } value; 2152 // } 2153 // 2154 bool VM_RedefineClasses::rewrite_cp_refs_in_element_value( 2155 AnnotationArray* annotations_typeArray, int &byte_i_ref, TRAPS) { 2156 2157 if ((byte_i_ref + 1) > annotations_typeArray->length()) { 2158 // not enough room for a tag let alone the rest of an element_value 2159 log_debug(redefine, class, annotation)("length() is too small for a tag"); 2160 return false; 2161 } 2162 2163 u1 tag = annotations_typeArray->at(byte_i_ref); 2164 byte_i_ref++; 2165 log_debug(redefine, class, annotation)("tag='%c'", tag); 2166 2167 switch (tag) { 2168 // These BaseType tag values are from Table 4.2 in VM spec: 2169 case 'B': // byte 2170 case 'C': // char 2171 case 'D': // double 2172 case 'F': // float 2173 case 'I': // int 2174 case 'J': // long 2175 case 'S': // short 2176 case 'Z': // boolean 2177 2178 // The remaining tag values are from Table 4.8 in the 2nd-edition of 2179 // the VM spec: 2180 case 's': 2181 { 2182 // For the above tag values (including the BaseType values), 2183 // value.const_value_index is right union field. 2184 2185 if ((byte_i_ref + 2) > annotations_typeArray->length()) { 2186 // not enough room for a const_value_index 2187 log_debug(redefine, class, annotation)("length() is too small for a const_value_index"); 2188 return false; 2189 } 2190 2191 u2 const_value_index = rewrite_cp_ref_in_annotation_data( 2192 annotations_typeArray, byte_i_ref, 2193 "const_value_index", THREAD); 2194 2195 log_debug(redefine, class, annotation)("const_value_index=%d", const_value_index); 2196 } break; 2197 2198 case 'e': 2199 { 2200 // for the above tag value, value.enum_const_value is right union field 2201 2202 if ((byte_i_ref + 4) > annotations_typeArray->length()) { 2203 // not enough room for a enum_const_value 2204 log_debug(redefine, class, annotation)("length() is too small for a enum_const_value"); 2205 return false; 2206 } 2207 2208 u2 type_name_index = rewrite_cp_ref_in_annotation_data( 2209 annotations_typeArray, byte_i_ref, 2210 "type_name_index", THREAD); 2211 2212 u2 const_name_index = rewrite_cp_ref_in_annotation_data( 2213 annotations_typeArray, byte_i_ref, 2214 "const_name_index", THREAD); 2215 2216 log_debug(redefine, class, annotation) 2217 ("type_name_index=%d const_name_index=%d", type_name_index, const_name_index); 2218 } break; 2219 2220 case 'c': 2221 { 2222 // for the above tag value, value.class_info_index is right union field 2223 2224 if ((byte_i_ref + 2) > annotations_typeArray->length()) { 2225 // not enough room for a class_info_index 2226 log_debug(redefine, class, annotation)("length() is too small for a class_info_index"); 2227 return false; 2228 } 2229 2230 u2 class_info_index = rewrite_cp_ref_in_annotation_data( 2231 annotations_typeArray, byte_i_ref, 2232 "class_info_index", THREAD); 2233 2234 log_debug(redefine, class, annotation)("class_info_index=%d", class_info_index); 2235 } break; 2236 2237 case '@': 2238 // For the above tag value, value.attr_value is the right union 2239 // field. This is a nested annotation. 2240 if (!rewrite_cp_refs_in_annotation_struct(annotations_typeArray, 2241 byte_i_ref, THREAD)) { 2242 // propagate failure back to caller 2243 return false; 2244 } 2245 break; 2246 2247 case '[': 2248 { 2249 if ((byte_i_ref + 2) > annotations_typeArray->length()) { 2250 // not enough room for a num_values field 2251 log_debug(redefine, class, annotation)("length() is too small for a num_values field"); 2252 return false; 2253 } 2254 2255 // For the above tag value, value.array_value is the right union 2256 // field. This is an array of nested element_value. 2257 u2 num_values = Bytes::get_Java_u2((address) 2258 annotations_typeArray->adr_at(byte_i_ref)); 2259 byte_i_ref += 2; 2260 log_debug(redefine, class, annotation)("num_values=%d", num_values); 2261 2262 int calc_num_values = 0; 2263 for (; calc_num_values < num_values; calc_num_values++) { 2264 if (!rewrite_cp_refs_in_element_value( 2265 annotations_typeArray, byte_i_ref, THREAD)) { 2266 log_debug(redefine, class, annotation)("bad nested element_value at %d", calc_num_values); 2267 // propagate failure back to caller 2268 return false; 2269 } 2270 } 2271 assert(num_values == calc_num_values, "sanity check"); 2272 } break; 2273 2274 default: 2275 log_debug(redefine, class, annotation)("bad tag=0x%x", tag); 2276 return false; 2277 } // end decode tag field 2278 2279 return true; 2280 } // end rewrite_cp_refs_in_element_value() 2281 2282 2283 // Rewrite constant pool references in a fields_annotations field. 2284 bool VM_RedefineClasses::rewrite_cp_refs_in_fields_annotations( 2285 InstanceKlass* scratch_class, TRAPS) { 2286 2287 Array<AnnotationArray*>* fields_annotations = scratch_class->fields_annotations(); 2288 2289 if (fields_annotations == NULL || fields_annotations->length() == 0) { 2290 // no fields_annotations so nothing to do 2291 return true; 2292 } 2293 2294 log_debug(redefine, class, annotation)("fields_annotations length=%d", fields_annotations->length()); 2295 2296 for (int i = 0; i < fields_annotations->length(); i++) { 2297 AnnotationArray* field_annotations = fields_annotations->at(i); 2298 if (field_annotations == NULL || field_annotations->length() == 0) { 2299 // this field does not have any annotations so skip it 2300 continue; 2301 } 2302 2303 int byte_i = 0; // byte index into field_annotations 2304 if (!rewrite_cp_refs_in_annotations_typeArray(field_annotations, byte_i, 2305 THREAD)) { 2306 log_debug(redefine, class, annotation)("bad field_annotations at %d", i); 2307 // propagate failure back to caller 2308 return false; 2309 } 2310 } 2311 2312 return true; 2313 } // end rewrite_cp_refs_in_fields_annotations() 2314 2315 2316 // Rewrite constant pool references in a methods_annotations field. 2317 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_annotations( 2318 InstanceKlass* scratch_class, TRAPS) { 2319 2320 for (int i = 0; i < scratch_class->methods()->length(); i++) { 2321 Method* m = scratch_class->methods()->at(i); 2322 AnnotationArray* method_annotations = m->constMethod()->method_annotations(); 2323 2324 if (method_annotations == NULL || method_annotations->length() == 0) { 2325 // this method does not have any annotations so skip it 2326 continue; 2327 } 2328 2329 int byte_i = 0; // byte index into method_annotations 2330 if (!rewrite_cp_refs_in_annotations_typeArray(method_annotations, byte_i, 2331 THREAD)) { 2332 log_debug(redefine, class, annotation)("bad method_annotations at %d", i); 2333 // propagate failure back to caller 2334 return false; 2335 } 2336 } 2337 2338 return true; 2339 } // end rewrite_cp_refs_in_methods_annotations() 2340 2341 2342 // Rewrite constant pool references in a methods_parameter_annotations 2343 // field. This "structure" is adapted from the 2344 // RuntimeVisibleParameterAnnotations_attribute described in section 2345 // 4.8.17 of the 2nd-edition of the VM spec: 2346 // 2347 // methods_parameter_annotations_typeArray { 2348 // u1 num_parameters; 2349 // { 2350 // u2 num_annotations; 2351 // annotation annotations[num_annotations]; 2352 // } parameter_annotations[num_parameters]; 2353 // } 2354 // 2355 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_parameter_annotations( 2356 InstanceKlass* scratch_class, TRAPS) { 2357 2358 for (int i = 0; i < scratch_class->methods()->length(); i++) { 2359 Method* m = scratch_class->methods()->at(i); 2360 AnnotationArray* method_parameter_annotations = m->constMethod()->parameter_annotations(); 2361 if (method_parameter_annotations == NULL 2362 || method_parameter_annotations->length() == 0) { 2363 // this method does not have any parameter annotations so skip it 2364 continue; 2365 } 2366 2367 if (method_parameter_annotations->length() < 1) { 2368 // not enough room for a num_parameters field 2369 log_debug(redefine, class, annotation)("length() is too small for a num_parameters field at %d", i); 2370 return false; 2371 } 2372 2373 int byte_i = 0; // byte index into method_parameter_annotations 2374 2375 u1 num_parameters = method_parameter_annotations->at(byte_i); 2376 byte_i++; 2377 2378 log_debug(redefine, class, annotation)("num_parameters=%d", num_parameters); 2379 2380 int calc_num_parameters = 0; 2381 for (; calc_num_parameters < num_parameters; calc_num_parameters++) { 2382 if (!rewrite_cp_refs_in_annotations_typeArray( 2383 method_parameter_annotations, byte_i, THREAD)) { 2384 log_debug(redefine, class, annotation)("bad method_parameter_annotations at %d", calc_num_parameters); 2385 // propagate failure back to caller 2386 return false; 2387 } 2388 } 2389 assert(num_parameters == calc_num_parameters, "sanity check"); 2390 } 2391 2392 return true; 2393 } // end rewrite_cp_refs_in_methods_parameter_annotations() 2394 2395 2396 // Rewrite constant pool references in a methods_default_annotations 2397 // field. This "structure" is adapted from the AnnotationDefault_attribute 2398 // that is described in section 4.8.19 of the 2nd-edition of the VM spec: 2399 // 2400 // methods_default_annotations_typeArray { 2401 // element_value default_value; 2402 // } 2403 // 2404 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_default_annotations( 2405 InstanceKlass* scratch_class, TRAPS) { 2406 2407 for (int i = 0; i < scratch_class->methods()->length(); i++) { 2408 Method* m = scratch_class->methods()->at(i); 2409 AnnotationArray* method_default_annotations = m->constMethod()->default_annotations(); 2410 if (method_default_annotations == NULL 2411 || method_default_annotations->length() == 0) { 2412 // this method does not have any default annotations so skip it 2413 continue; 2414 } 2415 2416 int byte_i = 0; // byte index into method_default_annotations 2417 2418 if (!rewrite_cp_refs_in_element_value( 2419 method_default_annotations, byte_i, THREAD)) { 2420 log_debug(redefine, class, annotation)("bad default element_value at %d", i); 2421 // propagate failure back to caller 2422 return false; 2423 } 2424 } 2425 2426 return true; 2427 } // end rewrite_cp_refs_in_methods_default_annotations() 2428 2429 2430 // Rewrite constant pool references in a class_type_annotations field. 2431 bool VM_RedefineClasses::rewrite_cp_refs_in_class_type_annotations( 2432 InstanceKlass* scratch_class, TRAPS) { 2433 2434 AnnotationArray* class_type_annotations = scratch_class->class_type_annotations(); 2435 if (class_type_annotations == NULL || class_type_annotations->length() == 0) { 2436 // no class_type_annotations so nothing to do 2437 return true; 2438 } 2439 2440 log_debug(redefine, class, annotation)("class_type_annotations length=%d", class_type_annotations->length()); 2441 2442 int byte_i = 0; // byte index into class_type_annotations 2443 return rewrite_cp_refs_in_type_annotations_typeArray(class_type_annotations, 2444 byte_i, "ClassFile", THREAD); 2445 } // end rewrite_cp_refs_in_class_type_annotations() 2446 2447 2448 // Rewrite constant pool references in a fields_type_annotations field. 2449 bool VM_RedefineClasses::rewrite_cp_refs_in_fields_type_annotations( 2450 InstanceKlass* scratch_class, TRAPS) { 2451 2452 Array<AnnotationArray*>* fields_type_annotations = scratch_class->fields_type_annotations(); 2453 if (fields_type_annotations == NULL || fields_type_annotations->length() == 0) { 2454 // no fields_type_annotations so nothing to do 2455 return true; 2456 } 2457 2458 log_debug(redefine, class, annotation)("fields_type_annotations length=%d", fields_type_annotations->length()); 2459 2460 for (int i = 0; i < fields_type_annotations->length(); i++) { 2461 AnnotationArray* field_type_annotations = fields_type_annotations->at(i); 2462 if (field_type_annotations == NULL || field_type_annotations->length() == 0) { 2463 // this field does not have any annotations so skip it 2464 continue; 2465 } 2466 2467 int byte_i = 0; // byte index into field_type_annotations 2468 if (!rewrite_cp_refs_in_type_annotations_typeArray(field_type_annotations, 2469 byte_i, "field_info", THREAD)) { 2470 log_debug(redefine, class, annotation)("bad field_type_annotations at %d", i); 2471 // propagate failure back to caller 2472 return false; 2473 } 2474 } 2475 2476 return true; 2477 } // end rewrite_cp_refs_in_fields_type_annotations() 2478 2479 2480 // Rewrite constant pool references in a methods_type_annotations field. 2481 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_type_annotations( 2482 InstanceKlass* scratch_class, TRAPS) { 2483 2484 for (int i = 0; i < scratch_class->methods()->length(); i++) { 2485 Method* m = scratch_class->methods()->at(i); 2486 AnnotationArray* method_type_annotations = m->constMethod()->type_annotations(); 2487 2488 if (method_type_annotations == NULL || method_type_annotations->length() == 0) { 2489 // this method does not have any annotations so skip it 2490 continue; 2491 } 2492 2493 log_debug(redefine, class, annotation)("methods type_annotations length=%d", method_type_annotations->length()); 2494 2495 int byte_i = 0; // byte index into method_type_annotations 2496 if (!rewrite_cp_refs_in_type_annotations_typeArray(method_type_annotations, 2497 byte_i, "method_info", THREAD)) { 2498 log_debug(redefine, class, annotation)("bad method_type_annotations at %d", i); 2499 // propagate failure back to caller 2500 return false; 2501 } 2502 } 2503 2504 return true; 2505 } // end rewrite_cp_refs_in_methods_type_annotations() 2506 2507 2508 // Rewrite constant pool references in a type_annotations 2509 // field. This "structure" is adapted from the 2510 // RuntimeVisibleTypeAnnotations_attribute described in 2511 // section 4.7.20 of the Java SE 8 Edition of the VM spec: 2512 // 2513 // type_annotations_typeArray { 2514 // u2 num_annotations; 2515 // type_annotation annotations[num_annotations]; 2516 // } 2517 // 2518 bool VM_RedefineClasses::rewrite_cp_refs_in_type_annotations_typeArray( 2519 AnnotationArray* type_annotations_typeArray, int &byte_i_ref, 2520 const char * location_mesg, TRAPS) { 2521 2522 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) { 2523 // not enough room for num_annotations field 2524 log_debug(redefine, class, annotation)("length() is too small for num_annotations field"); 2525 return false; 2526 } 2527 2528 u2 num_annotations = Bytes::get_Java_u2((address) 2529 type_annotations_typeArray->adr_at(byte_i_ref)); 2530 byte_i_ref += 2; 2531 2532 log_debug(redefine, class, annotation)("num_type_annotations=%d", num_annotations); 2533 2534 int calc_num_annotations = 0; 2535 for (; calc_num_annotations < num_annotations; calc_num_annotations++) { 2536 if (!rewrite_cp_refs_in_type_annotation_struct(type_annotations_typeArray, 2537 byte_i_ref, location_mesg, THREAD)) { 2538 log_debug(redefine, class, annotation)("bad type_annotation_struct at %d", calc_num_annotations); 2539 // propagate failure back to caller 2540 return false; 2541 } 2542 } 2543 assert(num_annotations == calc_num_annotations, "sanity check"); 2544 2545 if (byte_i_ref != type_annotations_typeArray->length()) { 2546 log_debug(redefine, class, annotation) 2547 ("read wrong amount of bytes at end of processing type_annotations_typeArray (%d of %d bytes were read)", 2548 byte_i_ref, type_annotations_typeArray->length()); 2549 return false; 2550 } 2551 2552 return true; 2553 } // end rewrite_cp_refs_in_type_annotations_typeArray() 2554 2555 2556 // Rewrite constant pool references in a type_annotation 2557 // field. This "structure" is adapted from the 2558 // RuntimeVisibleTypeAnnotations_attribute described in 2559 // section 4.7.20 of the Java SE 8 Edition of the VM spec: 2560 // 2561 // type_annotation { 2562 // u1 target_type; 2563 // union { 2564 // type_parameter_target; 2565 // supertype_target; 2566 // type_parameter_bound_target; 2567 // empty_target; 2568 // method_formal_parameter_target; 2569 // throws_target; 2570 // localvar_target; 2571 // catch_target; 2572 // offset_target; 2573 // type_argument_target; 2574 // } target_info; 2575 // type_path target_path; 2576 // annotation anno; 2577 // } 2578 // 2579 bool VM_RedefineClasses::rewrite_cp_refs_in_type_annotation_struct( 2580 AnnotationArray* type_annotations_typeArray, int &byte_i_ref, 2581 const char * location_mesg, TRAPS) { 2582 2583 if (!skip_type_annotation_target(type_annotations_typeArray, 2584 byte_i_ref, location_mesg, THREAD)) { 2585 return false; 2586 } 2587 2588 if (!skip_type_annotation_type_path(type_annotations_typeArray, 2589 byte_i_ref, THREAD)) { 2590 return false; 2591 } 2592 2593 if (!rewrite_cp_refs_in_annotation_struct(type_annotations_typeArray, 2594 byte_i_ref, THREAD)) { 2595 return false; 2596 } 2597 2598 return true; 2599 } // end rewrite_cp_refs_in_type_annotation_struct() 2600 2601 2602 // Read, verify and skip over the target_type and target_info part 2603 // so that rewriting can continue in the later parts of the struct. 2604 // 2605 // u1 target_type; 2606 // union { 2607 // type_parameter_target; 2608 // supertype_target; 2609 // type_parameter_bound_target; 2610 // empty_target; 2611 // method_formal_parameter_target; 2612 // throws_target; 2613 // localvar_target; 2614 // catch_target; 2615 // offset_target; 2616 // type_argument_target; 2617 // } target_info; 2618 // 2619 bool VM_RedefineClasses::skip_type_annotation_target( 2620 AnnotationArray* type_annotations_typeArray, int &byte_i_ref, 2621 const char * location_mesg, TRAPS) { 2622 2623 if ((byte_i_ref + 1) > type_annotations_typeArray->length()) { 2624 // not enough room for a target_type let alone the rest of a type_annotation 2625 log_debug(redefine, class, annotation)("length() is too small for a target_type"); 2626 return false; 2627 } 2628 2629 u1 target_type = type_annotations_typeArray->at(byte_i_ref); 2630 byte_i_ref += 1; 2631 log_debug(redefine, class, annotation)("target_type=0x%.2x", target_type); 2632 log_debug(redefine, class, annotation)("location=%s", location_mesg); 2633 2634 // Skip over target_info 2635 switch (target_type) { 2636 case 0x00: 2637 // kind: type parameter declaration of generic class or interface 2638 // location: ClassFile 2639 case 0x01: 2640 // kind: type parameter declaration of generic method or constructor 2641 // location: method_info 2642 2643 { 2644 // struct: 2645 // type_parameter_target { 2646 // u1 type_parameter_index; 2647 // } 2648 // 2649 if ((byte_i_ref + 1) > type_annotations_typeArray->length()) { 2650 log_debug(redefine, class, annotation)("length() is too small for a type_parameter_target"); 2651 return false; 2652 } 2653 2654 u1 type_parameter_index = type_annotations_typeArray->at(byte_i_ref); 2655 byte_i_ref += 1; 2656 2657 log_debug(redefine, class, annotation)("type_parameter_target: type_parameter_index=%d", type_parameter_index); 2658 } break; 2659 2660 case 0x10: 2661 // kind: type in extends clause of class or interface declaration 2662 // (including the direct superclass of an unsafe anonymous class declaration), 2663 // or in implements clause of interface declaration 2664 // location: ClassFile 2665 2666 { 2667 // struct: 2668 // supertype_target { 2669 // u2 supertype_index; 2670 // } 2671 // 2672 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) { 2673 log_debug(redefine, class, annotation)("length() is too small for a supertype_target"); 2674 return false; 2675 } 2676 2677 u2 supertype_index = Bytes::get_Java_u2((address) 2678 type_annotations_typeArray->adr_at(byte_i_ref)); 2679 byte_i_ref += 2; 2680 2681 log_debug(redefine, class, annotation)("supertype_target: supertype_index=%d", supertype_index); 2682 } break; 2683 2684 case 0x11: 2685 // kind: type in bound of type parameter declaration of generic class or interface 2686 // location: ClassFile 2687 case 0x12: 2688 // kind: type in bound of type parameter declaration of generic method or constructor 2689 // location: method_info 2690 2691 { 2692 // struct: 2693 // type_parameter_bound_target { 2694 // u1 type_parameter_index; 2695 // u1 bound_index; 2696 // } 2697 // 2698 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) { 2699 log_debug(redefine, class, annotation)("length() is too small for a type_parameter_bound_target"); 2700 return false; 2701 } 2702 2703 u1 type_parameter_index = type_annotations_typeArray->at(byte_i_ref); 2704 byte_i_ref += 1; 2705 u1 bound_index = type_annotations_typeArray->at(byte_i_ref); 2706 byte_i_ref += 1; 2707 2708 log_debug(redefine, class, annotation) 2709 ("type_parameter_bound_target: type_parameter_index=%d, bound_index=%d", type_parameter_index, bound_index); 2710 } break; 2711 2712 case 0x13: 2713 // kind: type in field declaration 2714 // location: field_info 2715 case 0x14: 2716 // kind: return type of method, or type of newly constructed object 2717 // location: method_info 2718 case 0x15: 2719 // kind: receiver type of method or constructor 2720 // location: method_info 2721 2722 { 2723 // struct: 2724 // empty_target { 2725 // } 2726 // 2727 log_debug(redefine, class, annotation)("empty_target"); 2728 } break; 2729 2730 case 0x16: 2731 // kind: type in formal parameter declaration of method, constructor, or lambda expression 2732 // location: method_info 2733 2734 { 2735 // struct: 2736 // formal_parameter_target { 2737 // u1 formal_parameter_index; 2738 // } 2739 // 2740 if ((byte_i_ref + 1) > type_annotations_typeArray->length()) { 2741 log_debug(redefine, class, annotation)("length() is too small for a formal_parameter_target"); 2742 return false; 2743 } 2744 2745 u1 formal_parameter_index = type_annotations_typeArray->at(byte_i_ref); 2746 byte_i_ref += 1; 2747 2748 log_debug(redefine, class, annotation) 2749 ("formal_parameter_target: formal_parameter_index=%d", formal_parameter_index); 2750 } break; 2751 2752 case 0x17: 2753 // kind: type in throws clause of method or constructor 2754 // location: method_info 2755 2756 { 2757 // struct: 2758 // throws_target { 2759 // u2 throws_type_index 2760 // } 2761 // 2762 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) { 2763 log_debug(redefine, class, annotation)("length() is too small for a throws_target"); 2764 return false; 2765 } 2766 2767 u2 throws_type_index = Bytes::get_Java_u2((address) 2768 type_annotations_typeArray->adr_at(byte_i_ref)); 2769 byte_i_ref += 2; 2770 2771 log_debug(redefine, class, annotation)("throws_target: throws_type_index=%d", throws_type_index); 2772 } break; 2773 2774 case 0x40: 2775 // kind: type in local variable declaration 2776 // location: Code 2777 case 0x41: 2778 // kind: type in resource variable declaration 2779 // location: Code 2780 2781 { 2782 // struct: 2783 // localvar_target { 2784 // u2 table_length; 2785 // struct { 2786 // u2 start_pc; 2787 // u2 length; 2788 // u2 index; 2789 // } table[table_length]; 2790 // } 2791 // 2792 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) { 2793 // not enough room for a table_length let alone the rest of a localvar_target 2794 log_debug(redefine, class, annotation)("length() is too small for a localvar_target table_length"); 2795 return false; 2796 } 2797 2798 u2 table_length = Bytes::get_Java_u2((address) 2799 type_annotations_typeArray->adr_at(byte_i_ref)); 2800 byte_i_ref += 2; 2801 2802 log_debug(redefine, class, annotation)("localvar_target: table_length=%d", table_length); 2803 2804 int table_struct_size = 2 + 2 + 2; // 3 u2 variables per table entry 2805 int table_size = table_length * table_struct_size; 2806 2807 if ((byte_i_ref + table_size) > type_annotations_typeArray->length()) { 2808 // not enough room for a table 2809 log_debug(redefine, class, annotation)("length() is too small for a table array of length %d", table_length); 2810 return false; 2811 } 2812 2813 // Skip over table 2814 byte_i_ref += table_size; 2815 } break; 2816 2817 case 0x42: 2818 // kind: type in exception parameter declaration 2819 // location: Code 2820 2821 { 2822 // struct: 2823 // catch_target { 2824 // u2 exception_table_index; 2825 // } 2826 // 2827 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) { 2828 log_debug(redefine, class, annotation)("length() is too small for a catch_target"); 2829 return false; 2830 } 2831 2832 u2 exception_table_index = Bytes::get_Java_u2((address) 2833 type_annotations_typeArray->adr_at(byte_i_ref)); 2834 byte_i_ref += 2; 2835 2836 log_debug(redefine, class, annotation)("catch_target: exception_table_index=%d", exception_table_index); 2837 } break; 2838 2839 case 0x43: 2840 // kind: type in instanceof expression 2841 // location: Code 2842 case 0x44: 2843 // kind: type in new expression 2844 // location: Code 2845 case 0x45: 2846 // kind: type in method reference expression using ::new 2847 // location: Code 2848 case 0x46: 2849 // kind: type in method reference expression using ::Identifier 2850 // location: Code 2851 2852 { 2853 // struct: 2854 // offset_target { 2855 // u2 offset; 2856 // } 2857 // 2858 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) { 2859 log_debug(redefine, class, annotation)("length() is too small for a offset_target"); 2860 return false; 2861 } 2862 2863 u2 offset = Bytes::get_Java_u2((address) 2864 type_annotations_typeArray->adr_at(byte_i_ref)); 2865 byte_i_ref += 2; 2866 2867 log_debug(redefine, class, annotation)("offset_target: offset=%d", offset); 2868 } break; 2869 2870 case 0x47: 2871 // kind: type in cast expression 2872 // location: Code 2873 case 0x48: 2874 // kind: type argument for generic constructor in new expression or 2875 // explicit constructor invocation statement 2876 // location: Code 2877 case 0x49: 2878 // kind: type argument for generic method in method invocation expression 2879 // location: Code 2880 case 0x4A: 2881 // kind: type argument for generic constructor in method reference expression using ::new 2882 // location: Code 2883 case 0x4B: 2884 // kind: type argument for generic method in method reference expression using ::Identifier 2885 // location: Code 2886 2887 { 2888 // struct: 2889 // type_argument_target { 2890 // u2 offset; 2891 // u1 type_argument_index; 2892 // } 2893 // 2894 if ((byte_i_ref + 3) > type_annotations_typeArray->length()) { 2895 log_debug(redefine, class, annotation)("length() is too small for a type_argument_target"); 2896 return false; 2897 } 2898 2899 u2 offset = Bytes::get_Java_u2((address) 2900 type_annotations_typeArray->adr_at(byte_i_ref)); 2901 byte_i_ref += 2; 2902 u1 type_argument_index = type_annotations_typeArray->at(byte_i_ref); 2903 byte_i_ref += 1; 2904 2905 log_debug(redefine, class, annotation) 2906 ("type_argument_target: offset=%d, type_argument_index=%d", offset, type_argument_index); 2907 } break; 2908 2909 default: 2910 log_debug(redefine, class, annotation)("unknown target_type"); 2911 #ifdef ASSERT 2912 ShouldNotReachHere(); 2913 #endif 2914 return false; 2915 } 2916 2917 return true; 2918 } // end skip_type_annotation_target() 2919 2920 2921 // Read, verify and skip over the type_path part so that rewriting 2922 // can continue in the later parts of the struct. 2923 // 2924 // type_path { 2925 // u1 path_length; 2926 // { 2927 // u1 type_path_kind; 2928 // u1 type_argument_index; 2929 // } path[path_length]; 2930 // } 2931 // 2932 bool VM_RedefineClasses::skip_type_annotation_type_path( 2933 AnnotationArray* type_annotations_typeArray, int &byte_i_ref, TRAPS) { 2934 2935 if ((byte_i_ref + 1) > type_annotations_typeArray->length()) { 2936 // not enough room for a path_length let alone the rest of the type_path 2937 log_debug(redefine, class, annotation)("length() is too small for a type_path"); 2938 return false; 2939 } 2940 2941 u1 path_length = type_annotations_typeArray->at(byte_i_ref); 2942 byte_i_ref += 1; 2943 2944 log_debug(redefine, class, annotation)("type_path: path_length=%d", path_length); 2945 2946 int calc_path_length = 0; 2947 for (; calc_path_length < path_length; calc_path_length++) { 2948 if ((byte_i_ref + 1 + 1) > type_annotations_typeArray->length()) { 2949 // not enough room for a path 2950 log_debug(redefine, class, annotation) 2951 ("length() is too small for path entry %d of %d", calc_path_length, path_length); 2952 return false; 2953 } 2954 2955 u1 type_path_kind = type_annotations_typeArray->at(byte_i_ref); 2956 byte_i_ref += 1; 2957 u1 type_argument_index = type_annotations_typeArray->at(byte_i_ref); 2958 byte_i_ref += 1; 2959 2960 log_debug(redefine, class, annotation) 2961 ("type_path: path[%d]: type_path_kind=%d, type_argument_index=%d", 2962 calc_path_length, type_path_kind, type_argument_index); 2963 2964 if (type_path_kind > 3 || (type_path_kind != 3 && type_argument_index != 0)) { 2965 // not enough room for a path 2966 log_debug(redefine, class, annotation)("inconsistent type_path values"); 2967 return false; 2968 } 2969 } 2970 assert(path_length == calc_path_length, "sanity check"); 2971 2972 return true; 2973 } // end skip_type_annotation_type_path() 2974 2975 2976 // Rewrite constant pool references in the method's stackmap table. 2977 // These "structures" are adapted from the StackMapTable_attribute that 2978 // is described in section 4.8.4 of the 6.0 version of the VM spec 2979 // (dated 2005.10.26): 2980 // file:///net/quincunx.sfbay/export/gbracha/ClassFile-Java6.pdf 2981 // 2982 // stack_map { 2983 // u2 number_of_entries; 2984 // stack_map_frame entries[number_of_entries]; 2985 // } 2986 // 2987 void VM_RedefineClasses::rewrite_cp_refs_in_stack_map_table( 2988 const methodHandle& method, TRAPS) { 2989 2990 if (!method->has_stackmap_table()) { 2991 return; 2992 } 2993 2994 AnnotationArray* stackmap_data = method->stackmap_data(); 2995 address stackmap_p = (address)stackmap_data->adr_at(0); 2996 address stackmap_end = stackmap_p + stackmap_data->length(); 2997 2998 assert(stackmap_p + 2 <= stackmap_end, "no room for number_of_entries"); 2999 u2 number_of_entries = Bytes::get_Java_u2(stackmap_p); 3000 stackmap_p += 2; 3001 3002 log_debug(redefine, class, stackmap)("number_of_entries=%u", number_of_entries); 3003 3004 // walk through each stack_map_frame 3005 u2 calc_number_of_entries = 0; 3006 for (; calc_number_of_entries < number_of_entries; calc_number_of_entries++) { 3007 // The stack_map_frame structure is a u1 frame_type followed by 3008 // 0 or more bytes of data: 3009 // 3010 // union stack_map_frame { 3011 // same_frame; 3012 // same_locals_1_stack_item_frame; 3013 // same_locals_1_stack_item_frame_extended; 3014 // chop_frame; 3015 // same_frame_extended; 3016 // append_frame; 3017 // full_frame; 3018 // } 3019 3020 assert(stackmap_p + 1 <= stackmap_end, "no room for frame_type"); 3021 u1 frame_type = *stackmap_p; 3022 stackmap_p++; 3023 3024 // same_frame { 3025 // u1 frame_type = SAME; /* 0-63 */ 3026 // } 3027 if (frame_type <= 63) { 3028 // nothing more to do for same_frame 3029 } 3030 3031 // same_locals_1_stack_item_frame { 3032 // u1 frame_type = SAME_LOCALS_1_STACK_ITEM; /* 64-127 */ 3033 // verification_type_info stack[1]; 3034 // } 3035 else if (frame_type >= 64 && frame_type <= 127) { 3036 rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end, 3037 calc_number_of_entries, frame_type, THREAD); 3038 } 3039 3040 // reserved for future use 3041 else if (frame_type >= 128 && frame_type <= 246) { 3042 // nothing more to do for reserved frame_types 3043 } 3044 3045 // same_locals_1_stack_item_frame_extended { 3046 // u1 frame_type = SAME_LOCALS_1_STACK_ITEM_EXTENDED; /* 247 */ 3047 // u2 offset_delta; 3048 // verification_type_info stack[1]; 3049 // } 3050 else if (frame_type == 247) { 3051 stackmap_p += 2; 3052 rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end, 3053 calc_number_of_entries, frame_type, THREAD); 3054 } 3055 3056 // chop_frame { 3057 // u1 frame_type = CHOP; /* 248-250 */ 3058 // u2 offset_delta; 3059 // } 3060 else if (frame_type >= 248 && frame_type <= 250) { 3061 stackmap_p += 2; 3062 } 3063 3064 // same_frame_extended { 3065 // u1 frame_type = SAME_FRAME_EXTENDED; /* 251*/ 3066 // u2 offset_delta; 3067 // } 3068 else if (frame_type == 251) { 3069 stackmap_p += 2; 3070 } 3071 3072 // append_frame { 3073 // u1 frame_type = APPEND; /* 252-254 */ 3074 // u2 offset_delta; 3075 // verification_type_info locals[frame_type - 251]; 3076 // } 3077 else if (frame_type >= 252 && frame_type <= 254) { 3078 assert(stackmap_p + 2 <= stackmap_end, 3079 "no room for offset_delta"); 3080 stackmap_p += 2; 3081 u1 len = frame_type - 251; 3082 for (u1 i = 0; i < len; i++) { 3083 rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end, 3084 calc_number_of_entries, frame_type, THREAD); 3085 } 3086 } 3087 3088 // full_frame { 3089 // u1 frame_type = FULL_FRAME; /* 255 */ 3090 // u2 offset_delta; 3091 // u2 number_of_locals; 3092 // verification_type_info locals[number_of_locals]; 3093 // u2 number_of_stack_items; 3094 // verification_type_info stack[number_of_stack_items]; 3095 // } 3096 else if (frame_type == 255) { 3097 assert(stackmap_p + 2 + 2 <= stackmap_end, 3098 "no room for smallest full_frame"); 3099 stackmap_p += 2; 3100 3101 u2 number_of_locals = Bytes::get_Java_u2(stackmap_p); 3102 stackmap_p += 2; 3103 3104 for (u2 locals_i = 0; locals_i < number_of_locals; locals_i++) { 3105 rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end, 3106 calc_number_of_entries, frame_type, THREAD); 3107 } 3108 3109 // Use the largest size for the number_of_stack_items, but only get 3110 // the right number of bytes. 3111 u2 number_of_stack_items = Bytes::get_Java_u2(stackmap_p); 3112 stackmap_p += 2; 3113 3114 for (u2 stack_i = 0; stack_i < number_of_stack_items; stack_i++) { 3115 rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end, 3116 calc_number_of_entries, frame_type, THREAD); 3117 } 3118 } 3119 } // end while there is a stack_map_frame 3120 assert(number_of_entries == calc_number_of_entries, "sanity check"); 3121 } // end rewrite_cp_refs_in_stack_map_table() 3122 3123 3124 // Rewrite constant pool references in the verification type info 3125 // portion of the method's stackmap table. These "structures" are 3126 // adapted from the StackMapTable_attribute that is described in 3127 // section 4.8.4 of the 6.0 version of the VM spec (dated 2005.10.26): 3128 // file:///net/quincunx.sfbay/export/gbracha/ClassFile-Java6.pdf 3129 // 3130 // The verification_type_info structure is a u1 tag followed by 0 or 3131 // more bytes of data: 3132 // 3133 // union verification_type_info { 3134 // Top_variable_info; 3135 // Integer_variable_info; 3136 // Float_variable_info; 3137 // Long_variable_info; 3138 // Double_variable_info; 3139 // Null_variable_info; 3140 // UninitializedThis_variable_info; 3141 // Object_variable_info; 3142 // Uninitialized_variable_info; 3143 // } 3144 // 3145 void VM_RedefineClasses::rewrite_cp_refs_in_verification_type_info( 3146 address& stackmap_p_ref, address stackmap_end, u2 frame_i, 3147 u1 frame_type, TRAPS) { 3148 3149 assert(stackmap_p_ref + 1 <= stackmap_end, "no room for tag"); 3150 u1 tag = *stackmap_p_ref; 3151 stackmap_p_ref++; 3152 3153 switch (tag) { 3154 // Top_variable_info { 3155 // u1 tag = ITEM_Top; /* 0 */ 3156 // } 3157 // verificationType.hpp has zero as ITEM_Bogus instead of ITEM_Top 3158 case 0: // fall through 3159 3160 // Integer_variable_info { 3161 // u1 tag = ITEM_Integer; /* 1 */ 3162 // } 3163 case ITEM_Integer: // fall through 3164 3165 // Float_variable_info { 3166 // u1 tag = ITEM_Float; /* 2 */ 3167 // } 3168 case ITEM_Float: // fall through 3169 3170 // Double_variable_info { 3171 // u1 tag = ITEM_Double; /* 3 */ 3172 // } 3173 case ITEM_Double: // fall through 3174 3175 // Long_variable_info { 3176 // u1 tag = ITEM_Long; /* 4 */ 3177 // } 3178 case ITEM_Long: // fall through 3179 3180 // Null_variable_info { 3181 // u1 tag = ITEM_Null; /* 5 */ 3182 // } 3183 case ITEM_Null: // fall through 3184 3185 // UninitializedThis_variable_info { 3186 // u1 tag = ITEM_UninitializedThis; /* 6 */ 3187 // } 3188 case ITEM_UninitializedThis: 3189 // nothing more to do for the above tag types 3190 break; 3191 3192 // Object_variable_info { 3193 // u1 tag = ITEM_Object; /* 7 */ 3194 // u2 cpool_index; 3195 // } 3196 case ITEM_Object: 3197 { 3198 assert(stackmap_p_ref + 2 <= stackmap_end, "no room for cpool_index"); 3199 u2 cpool_index = Bytes::get_Java_u2(stackmap_p_ref); 3200 u2 new_cp_index = find_new_index(cpool_index); 3201 if (new_cp_index != 0) { 3202 log_debug(redefine, class, stackmap)("mapped old cpool_index=%d", cpool_index); 3203 Bytes::put_Java_u2(stackmap_p_ref, new_cp_index); 3204 cpool_index = new_cp_index; 3205 } 3206 stackmap_p_ref += 2; 3207 3208 log_debug(redefine, class, stackmap) 3209 ("frame_i=%u, frame_type=%u, cpool_index=%d", frame_i, frame_type, cpool_index); 3210 } break; 3211 3212 // Uninitialized_variable_info { 3213 // u1 tag = ITEM_Uninitialized; /* 8 */ 3214 // u2 offset; 3215 // } 3216 case ITEM_Uninitialized: 3217 assert(stackmap_p_ref + 2 <= stackmap_end, "no room for offset"); 3218 stackmap_p_ref += 2; 3219 break; 3220 3221 default: 3222 log_debug(redefine, class, stackmap)("frame_i=%u, frame_type=%u, bad tag=0x%x", frame_i, frame_type, tag); 3223 ShouldNotReachHere(); 3224 break; 3225 } // end switch (tag) 3226 } // end rewrite_cp_refs_in_verification_type_info() 3227 3228 3229 // Change the constant pool associated with klass scratch_class to 3230 // scratch_cp. If shrink is true, then scratch_cp_length elements 3231 // are copied from scratch_cp to a smaller constant pool and the 3232 // smaller constant pool is associated with scratch_class. 3233 void VM_RedefineClasses::set_new_constant_pool( 3234 ClassLoaderData* loader_data, 3235 InstanceKlass* scratch_class, constantPoolHandle scratch_cp, 3236 int scratch_cp_length, TRAPS) { 3237 assert(scratch_cp->length() >= scratch_cp_length, "sanity check"); 3238 3239 // scratch_cp is a merged constant pool and has enough space for a 3240 // worst case merge situation. We want to associate the minimum 3241 // sized constant pool with the klass to save space. 3242 ConstantPool* cp = ConstantPool::allocate(loader_data, scratch_cp_length, CHECK); 3243 constantPoolHandle smaller_cp(THREAD, cp); 3244 3245 // preserve version() value in the smaller copy 3246 int version = scratch_cp->version(); 3247 assert(version != 0, "sanity check"); 3248 smaller_cp->set_version(version); 3249 3250 // attach klass to new constant pool 3251 // reference to the cp holder is needed for copy_operands() 3252 smaller_cp->set_pool_holder(scratch_class); 3253 3254 if (scratch_cp->has_dynamic_constant()) { 3255 smaller_cp->set_has_dynamic_constant(); 3256 } 3257 3258 scratch_cp->copy_cp_to(1, scratch_cp_length - 1, smaller_cp, 1, THREAD); 3259 if (HAS_PENDING_EXCEPTION) { 3260 // Exception is handled in the caller 3261 loader_data->add_to_deallocate_list(smaller_cp()); 3262 return; 3263 } 3264 scratch_cp = smaller_cp; 3265 3266 // attach new constant pool to klass 3267 scratch_class->set_constants(scratch_cp()); 3268 scratch_cp->initialize_unresolved_klasses(loader_data, CHECK); 3269 3270 int i; // for portability 3271 3272 // update each field in klass to use new constant pool indices as needed 3273 for (JavaFieldStream fs(scratch_class); !fs.done(); fs.next()) { 3274 jshort cur_index = fs.name_index(); 3275 jshort new_index = find_new_index(cur_index); 3276 if (new_index != 0) { 3277 log_trace(redefine, class, constantpool)("field-name_index change: %d to %d", cur_index, new_index); 3278 fs.set_name_index(new_index); 3279 } 3280 cur_index = fs.signature_index(); 3281 new_index = find_new_index(cur_index); 3282 if (new_index != 0) { 3283 log_trace(redefine, class, constantpool)("field-signature_index change: %d to %d", cur_index, new_index); 3284 fs.set_signature_index(new_index); 3285 } 3286 cur_index = fs.initval_index(); 3287 new_index = find_new_index(cur_index); 3288 if (new_index != 0) { 3289 log_trace(redefine, class, constantpool)("field-initval_index change: %d to %d", cur_index, new_index); 3290 fs.set_initval_index(new_index); 3291 } 3292 cur_index = fs.generic_signature_index(); 3293 new_index = find_new_index(cur_index); 3294 if (new_index != 0) { 3295 log_trace(redefine, class, constantpool)("field-generic_signature change: %d to %d", cur_index, new_index); 3296 fs.set_generic_signature_index(new_index); 3297 } 3298 } // end for each field 3299 3300 // Update constant pool indices in the inner classes info to use 3301 // new constant indices as needed. The inner classes info is a 3302 // quadruple: 3303 // (inner_class_info, outer_class_info, inner_name, inner_access_flags) 3304 InnerClassesIterator iter(scratch_class); 3305 for (; !iter.done(); iter.next()) { 3306 int cur_index = iter.inner_class_info_index(); 3307 if (cur_index == 0) { 3308 continue; // JVM spec. allows null inner class refs so skip it 3309 } 3310 int new_index = find_new_index(cur_index); 3311 if (new_index != 0) { 3312 log_trace(redefine, class, constantpool)("inner_class_info change: %d to %d", cur_index, new_index); 3313 iter.set_inner_class_info_index(new_index); 3314 } 3315 cur_index = iter.outer_class_info_index(); 3316 new_index = find_new_index(cur_index); 3317 if (new_index != 0) { 3318 log_trace(redefine, class, constantpool)("outer_class_info change: %d to %d", cur_index, new_index); 3319 iter.set_outer_class_info_index(new_index); 3320 } 3321 cur_index = iter.inner_name_index(); 3322 new_index = find_new_index(cur_index); 3323 if (new_index != 0) { 3324 log_trace(redefine, class, constantpool)("inner_name change: %d to %d", cur_index, new_index); 3325 iter.set_inner_name_index(new_index); 3326 } 3327 } // end for each inner class 3328 3329 // Attach each method in klass to the new constant pool and update 3330 // to use new constant pool indices as needed: 3331 Array<Method*>* methods = scratch_class->methods(); 3332 for (i = methods->length() - 1; i >= 0; i--) { 3333 methodHandle method(THREAD, methods->at(i)); 3334 method->set_constants(scratch_cp()); 3335 3336 int new_index = find_new_index(method->name_index()); 3337 if (new_index != 0) { 3338 log_trace(redefine, class, constantpool) 3339 ("method-name_index change: %d to %d", method->name_index(), new_index); 3340 method->set_name_index(new_index); 3341 } 3342 new_index = find_new_index(method->signature_index()); 3343 if (new_index != 0) { 3344 log_trace(redefine, class, constantpool) 3345 ("method-signature_index change: %d to %d", method->signature_index(), new_index); 3346 method->set_signature_index(new_index); 3347 } 3348 new_index = find_new_index(method->generic_signature_index()); 3349 if (new_index != 0) { 3350 log_trace(redefine, class, constantpool) 3351 ("method-generic_signature_index change: %d to %d", method->generic_signature_index(), new_index); 3352 method->set_generic_signature_index(new_index); 3353 } 3354 3355 // Update constant pool indices in the method's checked exception 3356 // table to use new constant indices as needed. 3357 int cext_length = method->checked_exceptions_length(); 3358 if (cext_length > 0) { 3359 CheckedExceptionElement * cext_table = 3360 method->checked_exceptions_start(); 3361 for (int j = 0; j < cext_length; j++) { 3362 int cur_index = cext_table[j].class_cp_index; 3363 int new_index = find_new_index(cur_index); 3364 if (new_index != 0) { 3365 log_trace(redefine, class, constantpool)("cext-class_cp_index change: %d to %d", cur_index, new_index); 3366 cext_table[j].class_cp_index = (u2)new_index; 3367 } 3368 } // end for each checked exception table entry 3369 } // end if there are checked exception table entries 3370 3371 // Update each catch type index in the method's exception table 3372 // to use new constant pool indices as needed. The exception table 3373 // holds quadruple entries of the form: 3374 // (beg_bci, end_bci, handler_bci, klass_index) 3375 3376 ExceptionTable ex_table(method()); 3377 int ext_length = ex_table.length(); 3378 3379 for (int j = 0; j < ext_length; j ++) { 3380 int cur_index = ex_table.catch_type_index(j); 3381 int new_index = find_new_index(cur_index); 3382 if (new_index != 0) { 3383 log_trace(redefine, class, constantpool)("ext-klass_index change: %d to %d", cur_index, new_index); 3384 ex_table.set_catch_type_index(j, new_index); 3385 } 3386 } // end for each exception table entry 3387 3388 // Update constant pool indices in the method's local variable 3389 // table to use new constant indices as needed. The local variable 3390 // table hold sextuple entries of the form: 3391 // (start_pc, length, name_index, descriptor_index, signature_index, slot) 3392 int lvt_length = method->localvariable_table_length(); 3393 if (lvt_length > 0) { 3394 LocalVariableTableElement * lv_table = 3395 method->localvariable_table_start(); 3396 for (int j = 0; j < lvt_length; j++) { 3397 int cur_index = lv_table[j].name_cp_index; 3398 int new_index = find_new_index(cur_index); 3399 if (new_index != 0) { 3400 log_trace(redefine, class, constantpool)("lvt-name_cp_index change: %d to %d", cur_index, new_index); 3401 lv_table[j].name_cp_index = (u2)new_index; 3402 } 3403 cur_index = lv_table[j].descriptor_cp_index; 3404 new_index = find_new_index(cur_index); 3405 if (new_index != 0) { 3406 log_trace(redefine, class, constantpool)("lvt-descriptor_cp_index change: %d to %d", cur_index, new_index); 3407 lv_table[j].descriptor_cp_index = (u2)new_index; 3408 } 3409 cur_index = lv_table[j].signature_cp_index; 3410 new_index = find_new_index(cur_index); 3411 if (new_index != 0) { 3412 log_trace(redefine, class, constantpool)("lvt-signature_cp_index change: %d to %d", cur_index, new_index); 3413 lv_table[j].signature_cp_index = (u2)new_index; 3414 } 3415 } // end for each local variable table entry 3416 } // end if there are local variable table entries 3417 3418 rewrite_cp_refs_in_stack_map_table(method, THREAD); 3419 } // end for each method 3420 } // end set_new_constant_pool() 3421 3422 3423 // Unevolving classes may point to methods of the_class directly 3424 // from their constant pool caches, itables, and/or vtables. We 3425 // use the ClassLoaderDataGraph::classes_do() facility and this helper 3426 // to fix up these pointers. MethodData also points to old methods and 3427 // must be cleaned. 3428 3429 // Adjust cpools and vtables closure 3430 void VM_RedefineClasses::AdjustAndCleanMetadata::do_klass(Klass* k) { 3431 3432 // This is a very busy routine. We don't want too much tracing 3433 // printed out. 3434 bool trace_name_printed = false; 3435 3436 // If the class being redefined is java.lang.Object, we need to fix all 3437 // array class vtables also 3438 if (k->is_array_klass() && _has_redefined_Object) { 3439 k->vtable().adjust_method_entries(&trace_name_printed); 3440 3441 } else if (k->is_instance_klass()) { 3442 HandleMark hm(_thread); 3443 InstanceKlass *ik = InstanceKlass::cast(k); 3444 3445 // Clean MethodData of this class's methods so they don't refer to 3446 // old methods that are no longer running. 3447 Array<Method*>* methods = ik->methods(); 3448 int num_methods = methods->length(); 3449 for (int index = 0; index < num_methods; ++index) { 3450 if (methods->at(index)->method_data() != NULL) { 3451 methods->at(index)->method_data()->clean_weak_method_links(); 3452 } 3453 } 3454 3455 // HotSpot specific optimization! HotSpot does not currently 3456 // support delegation from the bootstrap class loader to a 3457 // user-defined class loader. This means that if the bootstrap 3458 // class loader is the initiating class loader, then it will also 3459 // be the defining class loader. This also means that classes 3460 // loaded by the bootstrap class loader cannot refer to classes 3461 // loaded by a user-defined class loader. Note: a user-defined 3462 // class loader can delegate to the bootstrap class loader. 3463 // 3464 // If the current class being redefined has a user-defined class 3465 // loader as its defining class loader, then we can skip all 3466 // classes loaded by the bootstrap class loader. 3467 if (!_has_null_class_loader && ik->class_loader() == NULL) { 3468 return; 3469 } 3470 3471 // Adjust all vtables, default methods and itables, to clean out old methods. 3472 ResourceMark rm(_thread); 3473 if (ik->vtable_length() > 0) { 3474 ik->vtable().adjust_method_entries(&trace_name_printed); 3475 ik->adjust_default_methods(&trace_name_printed); 3476 } 3477 3478 if (ik->itable_length() > 0) { 3479 ik->itable().adjust_method_entries(&trace_name_printed); 3480 } 3481 3482 // The constant pools in other classes (other_cp) can refer to 3483 // old methods. We have to update method information in 3484 // other_cp's cache. If other_cp has a previous version, then we 3485 // have to repeat the process for each previous version. The 3486 // constant pool cache holds the Method*s for non-virtual 3487 // methods and for virtual, final methods. 3488 // 3489 // Special case: if the current class being redefined, then new_cp 3490 // has already been attached to the_class and old_cp has already 3491 // been added as a previous version. The new_cp doesn't have any 3492 // cached references to old methods so it doesn't need to be 3493 // updated. We can simply start with the previous version(s) in 3494 // that case. 3495 constantPoolHandle other_cp; 3496 ConstantPoolCache* cp_cache; 3497 3498 if (!ik->is_being_redefined()) { 3499 // this klass' constant pool cache may need adjustment 3500 other_cp = constantPoolHandle(ik->constants()); 3501 cp_cache = other_cp->cache(); 3502 if (cp_cache != NULL) { 3503 cp_cache->adjust_method_entries(&trace_name_printed); 3504 } 3505 } 3506 3507 // the previous versions' constant pool caches may need adjustment 3508 for (InstanceKlass* pv_node = ik->previous_versions(); 3509 pv_node != NULL; 3510 pv_node = pv_node->previous_versions()) { 3511 cp_cache = pv_node->constants()->cache(); 3512 if (cp_cache != NULL) { 3513 cp_cache->adjust_method_entries(&trace_name_printed); 3514 } 3515 } 3516 } 3517 } 3518 3519 void VM_RedefineClasses::update_jmethod_ids() { 3520 for (int j = 0; j < _matching_methods_length; ++j) { 3521 Method* old_method = _matching_old_methods[j]; 3522 jmethodID jmid = old_method->find_jmethod_id_or_null(); 3523 if (jmid != NULL) { 3524 // There is a jmethodID, change it to point to the new method 3525 methodHandle new_method_h(_matching_new_methods[j]); 3526 Method::change_method_associated_with_jmethod_id(jmid, new_method_h()); 3527 assert(Method::resolve_jmethod_id(jmid) == _matching_new_methods[j], 3528 "should be replaced"); 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 }