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