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