1 /* 2 * Copyright (c) 2018, 2025, 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 "cds/aotArtifactFinder.hpp" 26 #include "cds/aotClassInitializer.hpp" 27 #include "cds/aotClassLocation.hpp" 28 #include "cds/archiveBuilder.hpp" 29 #include "cds/archiveHeapLoader.hpp" 30 #include "cds/archiveHeapWriter.hpp" 31 #include "cds/archiveUtils.hpp" 32 #include "cds/cdsConfig.hpp" 33 #include "cds/cdsEnumKlass.hpp" 34 #include "cds/cdsHeapVerifier.hpp" 35 #include "cds/heapShared.hpp" 36 #include "cds/metaspaceShared.hpp" 37 #include "classfile/classLoaderData.hpp" 38 #include "classfile/classLoaderExt.hpp" 39 #include "classfile/javaClasses.inline.hpp" 40 #include "classfile/modules.hpp" 41 #include "classfile/stringTable.hpp" 42 #include "classfile/symbolTable.hpp" 43 #include "classfile/systemDictionary.hpp" 44 #include "classfile/systemDictionaryShared.hpp" 45 #include "classfile/vmClasses.hpp" 46 #include "classfile/vmSymbols.hpp" 47 #include "gc/shared/collectedHeap.hpp" 48 #include "gc/shared/gcLocker.hpp" 49 #include "gc/shared/gcVMOperations.hpp" 50 #include "logging/log.hpp" 51 #include "logging/logStream.hpp" 52 #include "memory/iterator.inline.hpp" 53 #include "memory/resourceArea.hpp" 54 #include "memory/universe.hpp" 55 #include "oops/compressedOops.inline.hpp" 56 #include "oops/fieldStreams.inline.hpp" 57 #include "oops/objArrayOop.inline.hpp" 58 #include "oops/oop.inline.hpp" 59 #include "oops/typeArrayOop.inline.hpp" 60 #include "prims/jvmtiExport.hpp" 61 #include "runtime/arguments.hpp" 62 #include "runtime/fieldDescriptor.inline.hpp" 63 #include "runtime/init.hpp" 64 #include "runtime/javaCalls.hpp" 65 #include "runtime/mutexLocker.hpp" 66 #include "runtime/safepointVerifiers.hpp" 67 #include "utilities/bitMap.inline.hpp" 68 #include "utilities/copy.hpp" 69 #if INCLUDE_G1GC 70 #include "gc/g1/g1CollectedHeap.hpp" 71 #endif 72 73 #if INCLUDE_CDS_JAVA_HEAP 74 75 struct ArchivableStaticFieldInfo { 76 const char* klass_name; 77 const char* field_name; 78 InstanceKlass* klass; 79 int offset; 80 BasicType type; 81 82 ArchivableStaticFieldInfo(const char* k, const char* f) 83 : klass_name(k), field_name(f), klass(nullptr), offset(0), type(T_ILLEGAL) {} 84 85 bool valid() { 86 return klass_name != nullptr; 87 } 88 }; 89 90 DumpedInternedStrings *HeapShared::_dumped_interned_strings = nullptr; 91 92 size_t HeapShared::_alloc_count[HeapShared::ALLOC_STAT_SLOTS]; 93 size_t HeapShared::_alloc_size[HeapShared::ALLOC_STAT_SLOTS]; 94 size_t HeapShared::_total_obj_count; 95 size_t HeapShared::_total_obj_size; 96 97 #ifndef PRODUCT 98 #define ARCHIVE_TEST_FIELD_NAME "archivedObjects" 99 static Array<char>* _archived_ArchiveHeapTestClass = nullptr; 100 static const char* _test_class_name = nullptr; 101 static Klass* _test_class = nullptr; 102 static const ArchivedKlassSubGraphInfoRecord* _test_class_record = nullptr; 103 #endif 104 105 106 // 107 // If you add new entries to the following tables, you should know what you're doing! 108 // 109 110 static ArchivableStaticFieldInfo archive_subgraph_entry_fields[] = { 111 {"java/lang/Integer$IntegerCache", "archivedCache"}, 112 {"java/lang/Long$LongCache", "archivedCache"}, 113 {"java/lang/Byte$ByteCache", "archivedCache"}, 114 {"java/lang/Short$ShortCache", "archivedCache"}, 115 {"java/lang/Character$CharacterCache", "archivedCache"}, 116 {"java/util/jar/Attributes$Name", "KNOWN_NAMES"}, 117 {"sun/util/locale/BaseLocale", "constantBaseLocales"}, 118 {"jdk/internal/module/ArchivedModuleGraph", "archivedModuleGraph"}, 119 {"java/util/ImmutableCollections", "archivedObjects"}, 120 {"java/lang/ModuleLayer", "EMPTY_LAYER"}, 121 {"java/lang/module/Configuration", "EMPTY_CONFIGURATION"}, 122 {"jdk/internal/math/FDBigInteger", "archivedCaches"}, 123 124 #ifndef PRODUCT 125 {nullptr, nullptr}, // Extra slot for -XX:ArchiveHeapTestClass 126 #endif 127 {nullptr, nullptr}, 128 }; 129 130 // full module graph 131 static ArchivableStaticFieldInfo fmg_archive_subgraph_entry_fields[] = { 132 {"jdk/internal/loader/ArchivedClassLoaders", "archivedClassLoaders"}, 133 {ARCHIVED_BOOT_LAYER_CLASS, ARCHIVED_BOOT_LAYER_FIELD}, 134 {"java/lang/Module$ArchivedData", "archivedData"}, 135 {nullptr, nullptr}, 136 }; 137 138 KlassSubGraphInfo* HeapShared::_dump_time_special_subgraph; 139 ArchivedKlassSubGraphInfoRecord* HeapShared::_run_time_special_subgraph; 140 GrowableArrayCHeap<oop, mtClassShared>* HeapShared::_pending_roots = nullptr; 141 GrowableArrayCHeap<OopHandle, mtClassShared>* HeapShared::_root_segments; 142 int HeapShared::_root_segment_max_size_elems; 143 OopHandle HeapShared::_scratch_basic_type_mirrors[T_VOID+1]; 144 MetaspaceObjToOopHandleTable* HeapShared::_scratch_objects_table = nullptr; 145 146 static bool is_subgraph_root_class_of(ArchivableStaticFieldInfo fields[], InstanceKlass* ik) { 147 for (int i = 0; fields[i].valid(); i++) { 148 if (fields[i].klass == ik) { 149 return true; 150 } 151 } 152 return false; 153 } 154 155 bool HeapShared::is_subgraph_root_class(InstanceKlass* ik) { 156 return is_subgraph_root_class_of(archive_subgraph_entry_fields, ik) || 157 is_subgraph_root_class_of(fmg_archive_subgraph_entry_fields, ik); 158 } 159 160 unsigned HeapShared::oop_hash(oop const& p) { 161 // Do not call p->identity_hash() as that will update the 162 // object header. 163 return primitive_hash(cast_from_oop<intptr_t>(p)); 164 } 165 166 static void reset_states(oop obj, TRAPS) { 167 Handle h_obj(THREAD, obj); 168 InstanceKlass* klass = InstanceKlass::cast(obj->klass()); 169 TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates"); 170 Symbol* method_sig = vmSymbols::void_method_signature(); 171 172 while (klass != nullptr) { 173 Method* method = klass->find_method(method_name, method_sig); 174 if (method != nullptr) { 175 assert(method->is_private(), "must be"); 176 if (log_is_enabled(Debug, cds)) { 177 ResourceMark rm(THREAD); 178 log_debug(cds)(" calling %s", method->name_and_sig_as_C_string()); 179 } 180 JavaValue result(T_VOID); 181 JavaCalls::call_special(&result, h_obj, klass, 182 method_name, method_sig, CHECK); 183 } 184 klass = klass->java_super(); 185 } 186 } 187 188 void HeapShared::reset_archived_object_states(TRAPS) { 189 assert(CDSConfig::is_dumping_heap(), "dump-time only"); 190 log_debug(cds)("Resetting platform loader"); 191 reset_states(SystemDictionary::java_platform_loader(), CHECK); 192 log_debug(cds)("Resetting system loader"); 193 reset_states(SystemDictionary::java_system_loader(), CHECK); 194 195 // Clean up jdk.internal.loader.ClassLoaders::bootLoader(), which is not 196 // directly used for class loading, but rather is used by the core library 197 // to keep track of resources, etc, loaded by the null class loader. 198 // 199 // Note, this object is non-null, and is not the same as 200 // ClassLoaderData::the_null_class_loader_data()->class_loader(), 201 // which is null. 202 log_debug(cds)("Resetting boot loader"); 203 JavaValue result(T_OBJECT); 204 JavaCalls::call_static(&result, 205 vmClasses::jdk_internal_loader_ClassLoaders_klass(), 206 vmSymbols::bootLoader_name(), 207 vmSymbols::void_BuiltinClassLoader_signature(), 208 CHECK); 209 Handle boot_loader(THREAD, result.get_oop()); 210 reset_states(boot_loader(), CHECK); 211 } 212 213 HeapShared::ArchivedObjectCache* HeapShared::_archived_object_cache = nullptr; 214 215 bool HeapShared::has_been_archived(oop obj) { 216 assert(CDSConfig::is_dumping_heap(), "dump-time only"); 217 return archived_object_cache()->get(obj) != nullptr; 218 } 219 220 int HeapShared::append_root(oop obj) { 221 assert(CDSConfig::is_dumping_heap(), "dump-time only"); 222 if (obj != nullptr) { 223 assert(has_been_archived(obj), "must be"); 224 } 225 // No GC should happen since we aren't scanning _pending_roots. 226 assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread"); 227 228 if (_pending_roots == nullptr) { 229 _pending_roots = new GrowableArrayCHeap<oop, mtClassShared>(500); 230 } 231 232 return _pending_roots->append(obj); 233 } 234 235 objArrayOop HeapShared::root_segment(int segment_idx) { 236 if (CDSConfig::is_dumping_heap()) { 237 assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread"); 238 } else { 239 assert(CDSConfig::is_using_archive(), "must be"); 240 } 241 242 objArrayOop segment = (objArrayOop)_root_segments->at(segment_idx).resolve(); 243 assert(segment != nullptr, "should have been initialized"); 244 return segment; 245 } 246 247 void HeapShared::get_segment_indexes(int idx, int& seg_idx, int& int_idx) { 248 assert(_root_segment_max_size_elems > 0, "sanity"); 249 250 // Try to avoid divisions for the common case. 251 if (idx < _root_segment_max_size_elems) { 252 seg_idx = 0; 253 int_idx = idx; 254 } else { 255 seg_idx = idx / _root_segment_max_size_elems; 256 int_idx = idx % _root_segment_max_size_elems; 257 } 258 259 assert(idx == seg_idx * _root_segment_max_size_elems + int_idx, 260 "sanity: %d index maps to %d segment and %d internal", idx, seg_idx, int_idx); 261 } 262 263 // Returns an objArray that contains all the roots of the archived objects 264 oop HeapShared::get_root(int index, bool clear) { 265 assert(index >= 0, "sanity"); 266 assert(!CDSConfig::is_dumping_heap() && CDSConfig::is_using_archive(), "runtime only"); 267 assert(!_root_segments->is_empty(), "must have loaded shared heap"); 268 int seg_idx, int_idx; 269 get_segment_indexes(index, seg_idx, int_idx); 270 oop result = root_segment(seg_idx)->obj_at(int_idx); 271 if (clear) { 272 clear_root(index); 273 } 274 return result; 275 } 276 277 void HeapShared::clear_root(int index) { 278 assert(index >= 0, "sanity"); 279 assert(CDSConfig::is_using_archive(), "must be"); 280 if (ArchiveHeapLoader::is_in_use()) { 281 int seg_idx, int_idx; 282 get_segment_indexes(index, seg_idx, int_idx); 283 if (log_is_enabled(Debug, cds, heap)) { 284 oop old = root_segment(seg_idx)->obj_at(int_idx); 285 log_debug(cds, heap)("Clearing root %d: was " PTR_FORMAT, index, p2i(old)); 286 } 287 root_segment(seg_idx)->obj_at_put(int_idx, nullptr); 288 } 289 } 290 291 bool HeapShared::archive_object(oop obj, KlassSubGraphInfo* subgraph_info) { 292 assert(CDSConfig::is_dumping_heap(), "dump-time only"); 293 294 assert(!obj->is_stackChunk(), "do not archive stack chunks"); 295 if (has_been_archived(obj)) { 296 return true; 297 } 298 299 if (ArchiveHeapWriter::is_too_large_to_archive(obj->size())) { 300 log_debug(cds, heap)("Cannot archive, object (" PTR_FORMAT ") is too large: %zu", 301 p2i(obj), obj->size()); 302 debug_trace(); 303 return false; 304 } else { 305 count_allocation(obj->size()); 306 ArchiveHeapWriter::add_source_obj(obj); 307 CachedOopInfo info = make_cached_oop_info(obj); 308 archived_object_cache()->put_when_absent(obj, info); 309 archived_object_cache()->maybe_grow(); 310 mark_native_pointers(obj); 311 312 Klass* k = obj->klass(); 313 if (k->is_instance_klass()) { 314 // Whenever we see a non-array Java object of type X, we mark X to be aot-initialized. 315 // This ensures that during the production run, whenever Java code sees a cached object 316 // of type X, we know that X is already initialized. (see TODO comment below ...) 317 318 if (InstanceKlass::cast(k)->is_enum_subclass() 319 // We can't rerun <clinit> of enum classes (see cdsEnumKlass.cpp) so 320 // we must store them as AOT-initialized. 321 || (subgraph_info == _dump_time_special_subgraph)) 322 // TODO: we do this only for the special subgraph for now. Extending this to 323 // other subgraphs would require more refactoring of the core library (such as 324 // move some initialization logic into runtimeSetup()). 325 // 326 // For the other subgraphs, we have a weaker mechanism to ensure that 327 // all classes in a subgraph are initialized before the subgraph is programmatically 328 // returned from jdk.internal.misc.CDS::initializeFromArchive(). 329 // See HeapShared::initialize_from_archived_subgraph(). 330 { 331 AOTArtifactFinder::add_aot_inited_class(InstanceKlass::cast(k)); 332 } 333 334 if (java_lang_Class::is_instance(obj)) { 335 Klass* mirror_k = java_lang_Class::as_Klass(obj); 336 if (mirror_k != nullptr) { 337 AOTArtifactFinder::add_cached_class(mirror_k); 338 } 339 } 340 } 341 342 if (log_is_enabled(Debug, cds, heap)) { 343 ResourceMark rm; 344 LogTarget(Debug, cds, heap) log; 345 LogStream out(log); 346 out.print("Archived heap object " PTR_FORMAT " : %s ", 347 p2i(obj), obj->klass()->external_name()); 348 if (java_lang_Class::is_instance(obj)) { 349 Klass* k = java_lang_Class::as_Klass(obj); 350 if (k != nullptr) { 351 out.print("%s", k->external_name()); 352 } else { 353 out.print("primitive"); 354 } 355 } 356 out.cr(); 357 } 358 359 return true; 360 } 361 } 362 363 class MetaspaceObjToOopHandleTable: public ResourceHashtable<MetaspaceObj*, OopHandle, 364 36137, // prime number 365 AnyObj::C_HEAP, 366 mtClassShared> { 367 public: 368 oop get_oop(MetaspaceObj* ptr) { 369 MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag); 370 OopHandle* handle = get(ptr); 371 if (handle != nullptr) { 372 return handle->resolve(); 373 } else { 374 return nullptr; 375 } 376 } 377 void set_oop(MetaspaceObj* ptr, oop o) { 378 MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag); 379 OopHandle handle(Universe::vm_global(), o); 380 bool is_new = put(ptr, handle); 381 assert(is_new, "cannot set twice"); 382 } 383 void remove_oop(MetaspaceObj* ptr) { 384 MutexLocker ml(ScratchObjects_lock, Mutex::_no_safepoint_check_flag); 385 OopHandle* handle = get(ptr); 386 if (handle != nullptr) { 387 handle->release(Universe::vm_global()); 388 remove(ptr); 389 } 390 } 391 }; 392 393 void HeapShared::add_scratch_resolved_references(ConstantPool* src, objArrayOop dest) { 394 if (SystemDictionaryShared::is_builtin_loader(src->pool_holder()->class_loader_data())) { 395 _scratch_objects_table->set_oop(src, dest); 396 } 397 } 398 399 objArrayOop HeapShared::scratch_resolved_references(ConstantPool* src) { 400 return (objArrayOop)_scratch_objects_table->get_oop(src); 401 } 402 403 void HeapShared::init_dumping() { 404 _scratch_objects_table = new (mtClass)MetaspaceObjToOopHandleTable(); 405 } 406 407 void HeapShared::init_scratch_objects_for_basic_type_mirrors(TRAPS) { 408 for (int i = T_BOOLEAN; i < T_VOID+1; i++) { 409 BasicType bt = (BasicType)i; 410 if (!is_reference_type(bt)) { 411 oop m = java_lang_Class::create_basic_type_mirror(type2name(bt), bt, CHECK); 412 _scratch_basic_type_mirrors[i] = OopHandle(Universe::vm_global(), m); 413 } 414 } 415 } 416 417 // Given java_mirror that represents a (primitive or reference) type T, 418 // return the "scratch" version that represents the same type T. 419 // Note that if java_mirror will be returned if it's already a 420 // scratch mirror. 421 // 422 // See java_lang_Class::create_scratch_mirror() for more info. 423 oop HeapShared::scratch_java_mirror(oop java_mirror) { 424 assert(java_lang_Class::is_instance(java_mirror), "must be"); 425 426 for (int i = T_BOOLEAN; i < T_VOID+1; i++) { 427 BasicType bt = (BasicType)i; 428 if (!is_reference_type(bt)) { 429 if (_scratch_basic_type_mirrors[i].resolve() == java_mirror) { 430 return java_mirror; 431 } 432 } 433 } 434 435 if (java_lang_Class::is_primitive(java_mirror)) { 436 return scratch_java_mirror(java_lang_Class::as_BasicType(java_mirror)); 437 } else { 438 return scratch_java_mirror(java_lang_Class::as_Klass(java_mirror)); 439 } 440 } 441 442 oop HeapShared::scratch_java_mirror(BasicType t) { 443 assert((uint)t < T_VOID+1, "range check"); 444 assert(!is_reference_type(t), "sanity"); 445 return _scratch_basic_type_mirrors[t].resolve(); 446 } 447 448 oop HeapShared::scratch_java_mirror(Klass* k) { 449 return _scratch_objects_table->get_oop(k); 450 } 451 452 void HeapShared::set_scratch_java_mirror(Klass* k, oop mirror) { 453 _scratch_objects_table->set_oop(k, mirror); 454 } 455 456 void HeapShared::remove_scratch_objects(Klass* k) { 457 // Klass is being deallocated. Java mirror can still be alive, and it should not 458 // point to dead klass. We need to break the link from mirror to the Klass. 459 // See how InstanceKlass::deallocate_contents does it for normal mirrors. 460 oop mirror = _scratch_objects_table->get_oop(k); 461 if (mirror != nullptr) { 462 java_lang_Class::set_klass(mirror, nullptr); 463 } 464 _scratch_objects_table->remove_oop(k); 465 if (k->is_instance_klass()) { 466 _scratch_objects_table->remove(InstanceKlass::cast(k)->constants()); 467 } 468 } 469 470 //TODO: we eventually want a more direct test for these kinds of things. 471 //For example the JVM could record some bit of context from the creation 472 //of the klass, such as who called the hidden class factory. Using 473 //string compares on names is fragile and will break as soon as somebody 474 //changes the names in the JDK code. See discussion in JDK-8342481 for 475 //related ideas about marking AOT-related classes. 476 bool HeapShared::is_lambda_form_klass(InstanceKlass* ik) { 477 return ik->is_hidden() && 478 (ik->name()->starts_with("java/lang/invoke/LambdaForm$MH+") || 479 ik->name()->starts_with("java/lang/invoke/LambdaForm$DMH+") || 480 ik->name()->starts_with("java/lang/invoke/LambdaForm$BMH+") || 481 ik->name()->starts_with("java/lang/invoke/LambdaForm$VH+")); 482 } 483 484 bool HeapShared::is_lambda_proxy_klass(InstanceKlass* ik) { 485 return ik->is_hidden() && (ik->name()->index_of_at(0, "$$Lambda+", 9) > 0); 486 } 487 488 bool HeapShared::is_string_concat_klass(InstanceKlass* ik) { 489 return ik->is_hidden() && ik->name()->starts_with("java/lang/String$$StringConcat"); 490 } 491 492 bool HeapShared::is_archivable_hidden_klass(InstanceKlass* ik) { 493 return CDSConfig::is_dumping_method_handles() && 494 (is_lambda_form_klass(ik) || is_lambda_proxy_klass(ik) || is_string_concat_klass(ik)); 495 } 496 497 498 void HeapShared::copy_and_rescan_aot_inited_mirror(InstanceKlass* ik) { 499 ik->set_has_aot_initialized_mirror(); 500 if (AOTClassInitializer::is_runtime_setup_required(ik)) { 501 ik->set_is_runtime_setup_required(); 502 } 503 504 oop orig_mirror = ik->java_mirror(); 505 oop m = scratch_java_mirror(ik); 506 assert(ik->is_initialized(), "must be"); 507 508 int nfields = 0; 509 for (JavaFieldStream fs(ik); !fs.done(); fs.next()) { 510 if (fs.access_flags().is_static()) { 511 fieldDescriptor& fd = fs.field_descriptor(); 512 int offset = fd.offset(); 513 switch (fd.field_type()) { 514 case T_OBJECT: 515 case T_ARRAY: 516 { 517 oop field_obj = orig_mirror->obj_field(offset); 518 if (offset == java_lang_Class::reflection_data_offset()) { 519 // Class::reflectData use SoftReference, which cannot be archived. Set it 520 // to null and it will be recreated at runtime. 521 field_obj = nullptr; 522 } 523 m->obj_field_put(offset, field_obj); 524 if (field_obj != nullptr) { 525 bool success = archive_reachable_objects_from(1, _dump_time_special_subgraph, field_obj); 526 assert(success, "sanity"); 527 } 528 } 529 break; 530 case T_BOOLEAN: 531 m->bool_field_put(offset, orig_mirror->bool_field(offset)); 532 break; 533 case T_BYTE: 534 m->byte_field_put(offset, orig_mirror->byte_field(offset)); 535 break; 536 case T_SHORT: 537 m->short_field_put(offset, orig_mirror->short_field(offset)); 538 break; 539 case T_CHAR: 540 m->char_field_put(offset, orig_mirror->char_field(offset)); 541 break; 542 case T_INT: 543 m->int_field_put(offset, orig_mirror->int_field(offset)); 544 break; 545 case T_LONG: 546 m->long_field_put(offset, orig_mirror->long_field(offset)); 547 break; 548 case T_FLOAT: 549 m->float_field_put(offset, orig_mirror->float_field(offset)); 550 break; 551 case T_DOUBLE: 552 m->double_field_put(offset, orig_mirror->double_field(offset)); 553 break; 554 default: 555 ShouldNotReachHere(); 556 } 557 nfields ++; 558 } 559 } 560 561 oop class_data = java_lang_Class::class_data(orig_mirror); 562 java_lang_Class::set_class_data(m, class_data); 563 if (class_data != nullptr) { 564 bool success = archive_reachable_objects_from(1, _dump_time_special_subgraph, class_data); 565 assert(success, "sanity"); 566 } 567 568 if (log_is_enabled(Info, cds, init)) { 569 ResourceMark rm; 570 log_debug(cds, init)("copied %3d field(s) in aot-initialized mirror %s%s%s", nfields, ik->external_name(), 571 ik->is_hidden() ? " (hidden)" : "", 572 ik->is_enum_subclass() ? " (enum)" : ""); 573 } 574 } 575 576 static void copy_java_mirror_hashcode(oop orig_mirror, oop scratch_m) { 577 // We need to retain the identity_hash, because it may have been used by some hashtables 578 // in the shared heap. 579 if (!orig_mirror->fast_no_hash_check()) { 580 intptr_t src_hash = orig_mirror->identity_hash(); 581 if (UseCompactObjectHeaders) { 582 narrowKlass nk = CompressedKlassPointers::encode(orig_mirror->klass()); 583 scratch_m->set_mark(markWord::prototype().set_narrow_klass(nk).copy_set_hash(src_hash)); 584 } else { 585 scratch_m->set_mark(markWord::prototype().copy_set_hash(src_hash)); 586 } 587 assert(scratch_m->mark().is_unlocked(), "sanity"); 588 589 DEBUG_ONLY(intptr_t archived_hash = scratch_m->identity_hash()); 590 assert(src_hash == archived_hash, "Different hash codes: original " INTPTR_FORMAT ", archived " INTPTR_FORMAT, src_hash, archived_hash); 591 } 592 } 593 594 static objArrayOop get_archived_resolved_references(InstanceKlass* src_ik) { 595 if (SystemDictionaryShared::is_builtin_loader(src_ik->class_loader_data())) { 596 objArrayOop rr = src_ik->constants()->resolved_references_or_null(); 597 if (rr != nullptr && !ArchiveHeapWriter::is_too_large_to_archive(rr)) { 598 return HeapShared::scratch_resolved_references(src_ik->constants()); 599 } 600 } 601 return nullptr; 602 } 603 604 void HeapShared::archive_strings() { 605 oop shared_strings_array = StringTable::init_shared_strings_array(_dumped_interned_strings); 606 bool success = archive_reachable_objects_from(1, _dump_time_special_subgraph, shared_strings_array); 607 // We must succeed because: 608 // - _dumped_interned_strings do not contain any large strings. 609 // - StringTable::init_shared_table() doesn't create any large arrays. 610 assert(success, "shared strings array must not point to arrays or strings that are too large to archive"); 611 StringTable::set_shared_strings_array_index(append_root(shared_strings_array)); 612 } 613 614 int HeapShared::archive_exception_instance(oop exception) { 615 bool success = archive_reachable_objects_from(1, _dump_time_special_subgraph, exception); 616 assert(success, "sanity"); 617 return append_root(exception); 618 } 619 620 void HeapShared::mark_native_pointers(oop orig_obj) { 621 if (java_lang_Class::is_instance(orig_obj)) { 622 ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_Class::klass_offset()); 623 ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_Class::array_klass_offset()); 624 } else if (java_lang_invoke_ResolvedMethodName::is_instance(orig_obj)) { 625 ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_invoke_ResolvedMethodName::vmtarget_offset()); 626 } 627 } 628 629 void HeapShared::get_pointer_info(oop src_obj, bool& has_oop_pointers, bool& has_native_pointers) { 630 CachedOopInfo* info = archived_object_cache()->get(src_obj); 631 assert(info != nullptr, "must be"); 632 has_oop_pointers = info->has_oop_pointers(); 633 has_native_pointers = info->has_native_pointers(); 634 } 635 636 void HeapShared::set_has_native_pointers(oop src_obj) { 637 CachedOopInfo* info = archived_object_cache()->get(src_obj); 638 assert(info != nullptr, "must be"); 639 info->set_has_native_pointers(); 640 } 641 642 // Between start_scanning_for_oops() and end_scanning_for_oops(), we discover all Java heap objects that 643 // should be stored in the AOT cache. The scanning is coordinated by AOTArtifactFinder. 644 void HeapShared::start_scanning_for_oops() { 645 { 646 NoSafepointVerifier nsv; 647 648 // The special subgraph doesn't belong to any class. We use Object_klass() here just 649 // for convenience. 650 _dump_time_special_subgraph = init_subgraph_info(vmClasses::Object_klass(), false); 651 652 // Cache for recording where the archived objects are copied to 653 create_archived_object_cache(); 654 655 if (UseCompressedOops || UseG1GC) { 656 log_info(cds)("Heap range = [" PTR_FORMAT " - " PTR_FORMAT "]", 657 UseCompressedOops ? p2i(CompressedOops::begin()) : 658 p2i((address)G1CollectedHeap::heap()->reserved().start()), 659 UseCompressedOops ? p2i(CompressedOops::end()) : 660 p2i((address)G1CollectedHeap::heap()->reserved().end())); 661 } 662 663 archive_subgraphs(); 664 } 665 666 init_seen_objects_table(); 667 Universe::archive_exception_instances(); 668 } 669 670 void HeapShared::end_scanning_for_oops() { 671 archive_strings(); 672 delete_seen_objects_table(); 673 } 674 675 void HeapShared::write_heap(ArchiveHeapInfo *heap_info) { 676 { 677 NoSafepointVerifier nsv; 678 CDSHeapVerifier::verify(); 679 check_special_subgraph_classes(); 680 } 681 682 StringTable::write_shared_table(_dumped_interned_strings); 683 ArchiveHeapWriter::write(_pending_roots, heap_info); 684 685 ArchiveBuilder::OtherROAllocMark mark; 686 write_subgraph_info_table(); 687 } 688 689 void HeapShared::scan_java_mirror(oop orig_mirror) { 690 oop m = scratch_java_mirror(orig_mirror); 691 if (m != nullptr) { // nullptr if for custom class loader 692 copy_java_mirror_hashcode(orig_mirror, m); 693 bool success = archive_reachable_objects_from(1, _dump_time_special_subgraph, m); 694 assert(success, "sanity"); 695 } 696 } 697 698 void HeapShared::scan_java_class(Klass* orig_k) { 699 scan_java_mirror(orig_k->java_mirror()); 700 701 if (orig_k->is_instance_klass()) { 702 InstanceKlass* orig_ik = InstanceKlass::cast(orig_k); 703 orig_ik->constants()->prepare_resolved_references_for_archiving(); 704 objArrayOop rr = get_archived_resolved_references(orig_ik); 705 if (rr != nullptr) { 706 bool success = HeapShared::archive_reachable_objects_from(1, _dump_time_special_subgraph, rr); 707 assert(success, "must be"); 708 } 709 710 orig_ik->constants()->add_dumped_interned_strings(); 711 } 712 } 713 714 void HeapShared::archive_subgraphs() { 715 assert(CDSConfig::is_dumping_heap(), "must be"); 716 717 archive_object_subgraphs(archive_subgraph_entry_fields, 718 false /* is_full_module_graph */); 719 720 if (CDSConfig::is_dumping_full_module_graph()) { 721 archive_object_subgraphs(fmg_archive_subgraph_entry_fields, 722 true /* is_full_module_graph */); 723 Modules::verify_archived_modules(); 724 } 725 } 726 727 // 728 // Subgraph archiving support 729 // 730 HeapShared::DumpTimeKlassSubGraphInfoTable* HeapShared::_dump_time_subgraph_info_table = nullptr; 731 HeapShared::RunTimeKlassSubGraphInfoTable HeapShared::_run_time_subgraph_info_table; 732 733 // Get the subgraph_info for Klass k. A new subgraph_info is created if 734 // there is no existing one for k. The subgraph_info records the "buffered" 735 // address of the class. 736 KlassSubGraphInfo* HeapShared::init_subgraph_info(Klass* k, bool is_full_module_graph) { 737 assert(CDSConfig::is_dumping_heap(), "dump time only"); 738 bool created; 739 KlassSubGraphInfo* info = 740 _dump_time_subgraph_info_table->put_if_absent(k, KlassSubGraphInfo(k, is_full_module_graph), 741 &created); 742 assert(created, "must not initialize twice"); 743 return info; 744 } 745 746 KlassSubGraphInfo* HeapShared::get_subgraph_info(Klass* k) { 747 assert(CDSConfig::is_dumping_heap(), "dump time only"); 748 KlassSubGraphInfo* info = _dump_time_subgraph_info_table->get(k); 749 assert(info != nullptr, "must have been initialized"); 750 return info; 751 } 752 753 // Add an entry field to the current KlassSubGraphInfo. 754 void KlassSubGraphInfo::add_subgraph_entry_field(int static_field_offset, oop v) { 755 assert(CDSConfig::is_dumping_heap(), "dump time only"); 756 if (_subgraph_entry_fields == nullptr) { 757 _subgraph_entry_fields = 758 new (mtClass) GrowableArray<int>(10, mtClass); 759 } 760 _subgraph_entry_fields->append(static_field_offset); 761 _subgraph_entry_fields->append(HeapShared::append_root(v)); 762 } 763 764 // Add the Klass* for an object in the current KlassSubGraphInfo's subgraphs. 765 // Only objects of boot classes can be included in sub-graph. 766 void KlassSubGraphInfo::add_subgraph_object_klass(Klass* orig_k) { 767 assert(CDSConfig::is_dumping_heap(), "dump time only"); 768 769 if (_subgraph_object_klasses == nullptr) { 770 _subgraph_object_klasses = 771 new (mtClass) GrowableArray<Klass*>(50, mtClass); 772 } 773 774 if (_k == orig_k) { 775 // Don't add the Klass containing the sub-graph to it's own klass 776 // initialization list. 777 return; 778 } 779 780 if (orig_k->is_instance_klass()) { 781 #ifdef ASSERT 782 InstanceKlass* ik = InstanceKlass::cast(orig_k); 783 if (CDSConfig::is_dumping_method_handles()) { 784 assert(ik->class_loader() == nullptr || 785 HeapShared::is_lambda_proxy_klass(ik), 786 "we can archive only instances of boot classes or lambda proxy classes"); 787 } else { 788 assert(ik->class_loader() == nullptr, "must be boot class"); 789 } 790 #endif 791 // vmClasses::xxx_klass() are not updated, need to check 792 // the original Klass* 793 if (orig_k == vmClasses::String_klass() || 794 orig_k == vmClasses::Object_klass()) { 795 // Initialized early during VM initialization. No need to be added 796 // to the sub-graph object class list. 797 return; 798 } 799 check_allowed_klass(InstanceKlass::cast(orig_k)); 800 } else if (orig_k->is_objArray_klass()) { 801 Klass* abk = ObjArrayKlass::cast(orig_k)->bottom_klass(); 802 if (abk->is_instance_klass()) { 803 assert(InstanceKlass::cast(abk)->is_shared_boot_class(), 804 "must be boot class"); 805 check_allowed_klass(InstanceKlass::cast(ObjArrayKlass::cast(orig_k)->bottom_klass())); 806 } 807 if (orig_k == Universe::objectArrayKlass()) { 808 // Initialized early during Universe::genesis. No need to be added 809 // to the list. 810 return; 811 } 812 } else { 813 assert(orig_k->is_typeArray_klass(), "must be"); 814 // Primitive type arrays are created early during Universe::genesis. 815 return; 816 } 817 818 if (log_is_enabled(Debug, cds, heap)) { 819 if (!_subgraph_object_klasses->contains(orig_k)) { 820 ResourceMark rm; 821 log_debug(cds, heap)("Adding klass %s", orig_k->external_name()); 822 } 823 } 824 825 _subgraph_object_klasses->append_if_missing(orig_k); 826 _has_non_early_klasses |= is_non_early_klass(orig_k); 827 } 828 829 void KlassSubGraphInfo::check_allowed_klass(InstanceKlass* ik) { 830 if (ik->module()->name() == vmSymbols::java_base()) { 831 assert(ik->package() != nullptr, "classes in java.base cannot be in unnamed package"); 832 return; 833 } 834 835 const char* lambda_msg = ""; 836 if (CDSConfig::is_dumping_method_handles()) { 837 lambda_msg = ", or a lambda proxy class"; 838 if (HeapShared::is_lambda_proxy_klass(ik) && 839 (ik->class_loader() == nullptr || 840 ik->class_loader() == SystemDictionary::java_platform_loader() || 841 ik->class_loader() == SystemDictionary::java_system_loader())) { 842 return; 843 } 844 } 845 846 #ifndef PRODUCT 847 if (!ik->module()->is_named() && ik->package() == nullptr && ArchiveHeapTestClass != nullptr) { 848 // This class is loaded by ArchiveHeapTestClass 849 return; 850 } 851 const char* testcls_msg = ", or a test class in an unnamed package of an unnamed module"; 852 #else 853 const char* testcls_msg = ""; 854 #endif 855 856 ResourceMark rm; 857 log_error(cds, heap)("Class %s not allowed in archive heap. Must be in java.base%s%s", 858 ik->external_name(), lambda_msg, testcls_msg); 859 MetaspaceShared::unrecoverable_writing_error(); 860 } 861 862 bool KlassSubGraphInfo::is_non_early_klass(Klass* k) { 863 if (k->is_objArray_klass()) { 864 k = ObjArrayKlass::cast(k)->bottom_klass(); 865 } 866 if (k->is_instance_klass()) { 867 if (!SystemDictionaryShared::is_early_klass(InstanceKlass::cast(k))) { 868 ResourceMark rm; 869 log_info(cds, heap)("non-early: %s", k->external_name()); 870 return true; 871 } else { 872 return false; 873 } 874 } else { 875 return false; 876 } 877 } 878 879 // Initialize an archived subgraph_info_record from the given KlassSubGraphInfo. 880 void ArchivedKlassSubGraphInfoRecord::init(KlassSubGraphInfo* info) { 881 _k = ArchiveBuilder::get_buffered_klass(info->klass()); 882 _entry_field_records = nullptr; 883 _subgraph_object_klasses = nullptr; 884 _is_full_module_graph = info->is_full_module_graph(); 885 886 if (_is_full_module_graph) { 887 // Consider all classes referenced by the full module graph as early -- we will be 888 // allocating objects of these classes during JVMTI early phase, so they cannot 889 // be processed by (non-early) JVMTI ClassFileLoadHook 890 _has_non_early_klasses = false; 891 } else { 892 _has_non_early_klasses = info->has_non_early_klasses(); 893 } 894 895 if (_has_non_early_klasses) { 896 ResourceMark rm; 897 log_info(cds, heap)( 898 "Subgraph of klass %s has non-early klasses and cannot be used when JVMTI ClassFileLoadHook is enabled", 899 _k->external_name()); 900 } 901 902 // populate the entry fields 903 GrowableArray<int>* entry_fields = info->subgraph_entry_fields(); 904 if (entry_fields != nullptr) { 905 int num_entry_fields = entry_fields->length(); 906 assert(num_entry_fields % 2 == 0, "sanity"); 907 _entry_field_records = 908 ArchiveBuilder::new_ro_array<int>(num_entry_fields); 909 for (int i = 0 ; i < num_entry_fields; i++) { 910 _entry_field_records->at_put(i, entry_fields->at(i)); 911 } 912 } 913 914 // <recorded_klasses> has the Klasses of all the objects that are referenced by this subgraph. 915 // Copy those that need to be explicitly initialized into <_subgraph_object_klasses>. 916 GrowableArray<Klass*>* recorded_klasses = info->subgraph_object_klasses(); 917 if (recorded_klasses != nullptr) { 918 // AOT-inited classes are automatically marked as "initialized" during bootstrap. When 919 // programmatically loading a subgraph, we only need to explicitly initialize the classes 920 // that are not aot-inited. 921 int num_to_copy = 0; 922 for (int i = 0; i < recorded_klasses->length(); i++) { 923 Klass* subgraph_k = ArchiveBuilder::get_buffered_klass(recorded_klasses->at(i)); 924 if (!subgraph_k->has_aot_initialized_mirror()) { 925 num_to_copy ++; 926 } 927 } 928 929 _subgraph_object_klasses = ArchiveBuilder::new_ro_array<Klass*>(num_to_copy); 930 bool is_special = (_k == ArchiveBuilder::get_buffered_klass(vmClasses::Object_klass())); 931 for (int i = 0, n = 0; i < recorded_klasses->length(); i++) { 932 Klass* subgraph_k = ArchiveBuilder::get_buffered_klass(recorded_klasses->at(i)); 933 if (subgraph_k->has_aot_initialized_mirror()) { 934 continue; 935 } 936 if (log_is_enabled(Info, cds, heap)) { 937 ResourceMark rm; 938 const char* owner_name = is_special ? "<special>" : _k->external_name(); 939 if (subgraph_k->is_instance_klass()) { 940 InstanceKlass* src_ik = InstanceKlass::cast(ArchiveBuilder::current()->get_source_addr(subgraph_k)); 941 } 942 log_info(cds, heap)( 943 "Archived object klass %s (%2d) => %s", 944 owner_name, n, subgraph_k->external_name()); 945 } 946 _subgraph_object_klasses->at_put(n, subgraph_k); 947 ArchivePtrMarker::mark_pointer(_subgraph_object_klasses->adr_at(n)); 948 n++; 949 } 950 } 951 952 ArchivePtrMarker::mark_pointer(&_k); 953 ArchivePtrMarker::mark_pointer(&_entry_field_records); 954 ArchivePtrMarker::mark_pointer(&_subgraph_object_klasses); 955 } 956 957 class HeapShared::CopyKlassSubGraphInfoToArchive : StackObj { 958 CompactHashtableWriter* _writer; 959 public: 960 CopyKlassSubGraphInfoToArchive(CompactHashtableWriter* writer) : _writer(writer) {} 961 962 bool do_entry(Klass* klass, KlassSubGraphInfo& info) { 963 if (info.subgraph_object_klasses() != nullptr || info.subgraph_entry_fields() != nullptr) { 964 ArchivedKlassSubGraphInfoRecord* record = HeapShared::archive_subgraph_info(&info); 965 Klass* buffered_k = ArchiveBuilder::get_buffered_klass(klass); 966 unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary((address)buffered_k); 967 u4 delta = ArchiveBuilder::current()->any_to_offset_u4(record); 968 _writer->add(hash, delta); 969 } 970 return true; // keep on iterating 971 } 972 }; 973 974 ArchivedKlassSubGraphInfoRecord* HeapShared::archive_subgraph_info(KlassSubGraphInfo* info) { 975 ArchivedKlassSubGraphInfoRecord* record = 976 (ArchivedKlassSubGraphInfoRecord*)ArchiveBuilder::ro_region_alloc(sizeof(ArchivedKlassSubGraphInfoRecord)); 977 record->init(info); 978 if (info == _dump_time_special_subgraph) { 979 _run_time_special_subgraph = record; 980 } 981 return record; 982 } 983 984 // Build the records of archived subgraph infos, which include: 985 // - Entry points to all subgraphs from the containing class mirror. The entry 986 // points are static fields in the mirror. For each entry point, the field 987 // offset, and value are recorded in the sub-graph 988 // info. The value is stored back to the corresponding field at runtime. 989 // - A list of klasses that need to be loaded/initialized before archived 990 // java object sub-graph can be accessed at runtime. 991 void HeapShared::write_subgraph_info_table() { 992 // Allocate the contents of the hashtable(s) inside the RO region of the CDS archive. 993 DumpTimeKlassSubGraphInfoTable* d_table = _dump_time_subgraph_info_table; 994 CompactHashtableStats stats; 995 996 _run_time_subgraph_info_table.reset(); 997 998 CompactHashtableWriter writer(d_table->_count, &stats); 999 CopyKlassSubGraphInfoToArchive copy(&writer); 1000 d_table->iterate(©); 1001 writer.dump(&_run_time_subgraph_info_table, "subgraphs"); 1002 1003 #ifndef PRODUCT 1004 if (ArchiveHeapTestClass != nullptr) { 1005 size_t len = strlen(ArchiveHeapTestClass) + 1; 1006 Array<char>* array = ArchiveBuilder::new_ro_array<char>((int)len); 1007 strncpy(array->adr_at(0), ArchiveHeapTestClass, len); 1008 _archived_ArchiveHeapTestClass = array; 1009 } 1010 #endif 1011 if (log_is_enabled(Info, cds, heap)) { 1012 print_stats(); 1013 } 1014 } 1015 1016 void HeapShared::add_root_segment(objArrayOop segment_oop) { 1017 assert(segment_oop != nullptr, "must be"); 1018 assert(ArchiveHeapLoader::is_in_use(), "must be"); 1019 if (_root_segments == nullptr) { 1020 _root_segments = new GrowableArrayCHeap<OopHandle, mtClassShared>(10); 1021 } 1022 _root_segments->push(OopHandle(Universe::vm_global(), segment_oop)); 1023 } 1024 1025 void HeapShared::init_root_segment_sizes(int max_size_elems) { 1026 _root_segment_max_size_elems = max_size_elems; 1027 } 1028 1029 void HeapShared::serialize_tables(SerializeClosure* soc) { 1030 1031 #ifndef PRODUCT 1032 soc->do_ptr(&_archived_ArchiveHeapTestClass); 1033 if (soc->reading() && _archived_ArchiveHeapTestClass != nullptr) { 1034 _test_class_name = _archived_ArchiveHeapTestClass->adr_at(0); 1035 setup_test_class(_test_class_name); 1036 } 1037 #endif 1038 1039 _run_time_subgraph_info_table.serialize_header(soc); 1040 soc->do_ptr(&_run_time_special_subgraph); 1041 } 1042 1043 static void verify_the_heap(Klass* k, const char* which) { 1044 if (VerifyArchivedFields > 0) { 1045 ResourceMark rm; 1046 log_info(cds, heap)("Verify heap %s initializing static field(s) in %s", 1047 which, k->external_name()); 1048 1049 VM_Verify verify_op; 1050 VMThread::execute(&verify_op); 1051 1052 if (VerifyArchivedFields > 1 && is_init_completed()) { 1053 // At this time, the oop->klass() of some archived objects in the heap may not 1054 // have been loaded into the system dictionary yet. Nevertheless, oop->klass() should 1055 // have enough information (object size, oop maps, etc) so that a GC can be safely 1056 // performed. 1057 // 1058 // -XX:VerifyArchivedFields=2 force a GC to happen in such an early stage 1059 // to check for GC safety. 1060 log_info(cds, heap)("Trigger GC %s initializing static field(s) in %s", 1061 which, k->external_name()); 1062 FlagSetting fs1(VerifyBeforeGC, true); 1063 FlagSetting fs2(VerifyDuringGC, true); 1064 FlagSetting fs3(VerifyAfterGC, true); 1065 Universe::heap()->collect(GCCause::_java_lang_system_gc); 1066 } 1067 } 1068 } 1069 1070 // Before GC can execute, we must ensure that all oops reachable from HeapShared::roots() 1071 // have a valid klass. I.e., oopDesc::klass() must have already been resolved. 1072 // 1073 // Note: if a ArchivedKlassSubGraphInfoRecord contains non-early classes, and JVMTI 1074 // ClassFileLoadHook is enabled, it's possible for this class to be dynamically replaced. In 1075 // this case, we will not load the ArchivedKlassSubGraphInfoRecord and will clear its roots. 1076 void HeapShared::resolve_classes(JavaThread* current) { 1077 assert(CDSConfig::is_using_archive(), "runtime only!"); 1078 if (!ArchiveHeapLoader::is_in_use()) { 1079 return; // nothing to do 1080 } 1081 resolve_classes_for_subgraphs(current, archive_subgraph_entry_fields); 1082 resolve_classes_for_subgraphs(current, fmg_archive_subgraph_entry_fields); 1083 } 1084 1085 void HeapShared::resolve_classes_for_subgraphs(JavaThread* current, ArchivableStaticFieldInfo fields[]) { 1086 for (int i = 0; fields[i].valid(); i++) { 1087 ArchivableStaticFieldInfo* info = &fields[i]; 1088 TempNewSymbol klass_name = SymbolTable::new_symbol(info->klass_name); 1089 InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name); 1090 assert(k != nullptr && k->is_shared_boot_class(), "sanity"); 1091 resolve_classes_for_subgraph_of(current, k); 1092 } 1093 } 1094 1095 void HeapShared::resolve_classes_for_subgraph_of(JavaThread* current, Klass* k) { 1096 JavaThread* THREAD = current; 1097 ExceptionMark em(THREAD); 1098 const ArchivedKlassSubGraphInfoRecord* record = 1099 resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/false, THREAD); 1100 if (HAS_PENDING_EXCEPTION) { 1101 CLEAR_PENDING_EXCEPTION; 1102 } 1103 if (record == nullptr) { 1104 clear_archived_roots_of(k); 1105 } 1106 } 1107 1108 void HeapShared::initialize_java_lang_invoke(TRAPS) { 1109 if (CDSConfig::is_using_aot_linked_classes() || CDSConfig::is_dumping_method_handles()) { 1110 resolve_or_init("java/lang/invoke/Invokers$Holder", true, CHECK); 1111 resolve_or_init("java/lang/invoke/MethodHandle", true, CHECK); 1112 resolve_or_init("java/lang/invoke/MethodHandleNatives", true, CHECK); 1113 resolve_or_init("java/lang/invoke/DirectMethodHandle$Holder", true, CHECK); 1114 resolve_or_init("java/lang/invoke/DelegatingMethodHandle$Holder", true, CHECK); 1115 resolve_or_init("java/lang/invoke/LambdaForm$Holder", true, CHECK); 1116 resolve_or_init("java/lang/invoke/BoundMethodHandle$Species_L", true, CHECK); 1117 } 1118 } 1119 1120 // Initialize the InstanceKlasses of objects that are reachable from the following roots: 1121 // - interned strings 1122 // - Klass::java_mirror() -- including aot-initialized mirrors such as those of Enum klasses. 1123 // - ConstantPool::resolved_references() 1124 // - Universe::<xxx>_exception_instance() 1125 // 1126 // For example, if this enum class is initialized at AOT cache assembly time: 1127 // 1128 // enum Fruit { 1129 // APPLE, ORANGE, BANANA; 1130 // static final Set<Fruit> HAVE_SEEDS = new HashSet<>(Arrays.asList(APPLE, ORANGE)); 1131 // } 1132 // 1133 // the aot-initialized mirror of Fruit has a static field that references HashSet, which 1134 // should be initialized before any Java code can access the Fruit class. Note that 1135 // HashSet itself doesn't necessary need to be an aot-initialized class. 1136 void HeapShared::init_classes_for_special_subgraph(Handle class_loader, TRAPS) { 1137 if (!ArchiveHeapLoader::is_in_use()) { 1138 return; 1139 } 1140 1141 assert( _run_time_special_subgraph != nullptr, "must be"); 1142 Array<Klass*>* klasses = _run_time_special_subgraph->subgraph_object_klasses(); 1143 if (klasses != nullptr) { 1144 for (int pass = 0; pass < 2; pass ++) { 1145 for (int i = 0; i < klasses->length(); i++) { 1146 Klass* k = klasses->at(i); 1147 if (k->class_loader_data() == nullptr) { 1148 // This class is not yet loaded. We will initialize it in a later phase. 1149 // For example, we have loaded only AOTLinkedClassCategory::BOOT1 classes 1150 // but k is part of AOTLinkedClassCategory::BOOT2. 1151 continue; 1152 } 1153 if (k->class_loader() == class_loader()) { 1154 if (pass == 0) { 1155 if (k->is_instance_klass()) { 1156 InstanceKlass::cast(k)->link_class(CHECK); 1157 } 1158 } else { 1159 resolve_or_init(k, /*do_init*/true, CHECK); 1160 } 1161 } 1162 } 1163 } 1164 } 1165 } 1166 1167 void HeapShared::initialize_from_archived_subgraph(JavaThread* current, Klass* k) { 1168 JavaThread* THREAD = current; 1169 if (!ArchiveHeapLoader::is_in_use()) { 1170 return; // nothing to do 1171 } 1172 1173 if (k->name()->equals("jdk/internal/module/ArchivedModuleGraph") && 1174 !CDSConfig::is_using_optimized_module_handling() && 1175 // archive was created with --module-path 1176 AOTClassLocationConfig::runtime()->num_module_paths() > 0) { 1177 // ArchivedModuleGraph was created with a --module-path that's different than the runtime --module-path. 1178 // Thus, it might contain references to modules that do not exist at runtime. We cannot use it. 1179 log_info(cds, heap)("Skip initializing ArchivedModuleGraph subgraph: is_using_optimized_module_handling=%s num_module_paths=%d", 1180 BOOL_TO_STR(CDSConfig::is_using_optimized_module_handling()), 1181 AOTClassLocationConfig::runtime()->num_module_paths()); 1182 return; 1183 } 1184 1185 ExceptionMark em(THREAD); 1186 const ArchivedKlassSubGraphInfoRecord* record = 1187 resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/true, THREAD); 1188 1189 if (HAS_PENDING_EXCEPTION) { 1190 CLEAR_PENDING_EXCEPTION; 1191 // None of the field value will be set if there was an exception when initializing the classes. 1192 // The java code will not see any of the archived objects in the 1193 // subgraphs referenced from k in this case. 1194 return; 1195 } 1196 1197 if (record != nullptr) { 1198 init_archived_fields_for(k, record); 1199 } 1200 } 1201 1202 const ArchivedKlassSubGraphInfoRecord* 1203 HeapShared::resolve_or_init_classes_for_subgraph_of(Klass* k, bool do_init, TRAPS) { 1204 assert(!CDSConfig::is_dumping_heap(), "Should not be called when dumping heap"); 1205 1206 if (!k->is_shared()) { 1207 return nullptr; 1208 } 1209 unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k); 1210 const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0); 1211 1212 #ifndef PRODUCT 1213 if (_test_class_name != nullptr && k->name()->equals(_test_class_name) && record != nullptr) { 1214 _test_class = k; 1215 _test_class_record = record; 1216 } 1217 #endif 1218 1219 // Initialize from archived data. Currently this is done only 1220 // during VM initialization time. No lock is needed. 1221 if (record == nullptr) { 1222 if (log_is_enabled(Info, cds, heap)) { 1223 ResourceMark rm(THREAD); 1224 log_info(cds, heap)("subgraph %s is not recorded", 1225 k->external_name()); 1226 } 1227 return nullptr; 1228 } else { 1229 if (record->is_full_module_graph() && !CDSConfig::is_using_full_module_graph()) { 1230 if (log_is_enabled(Info, cds, heap)) { 1231 ResourceMark rm(THREAD); 1232 log_info(cds, heap)("subgraph %s cannot be used because full module graph is disabled", 1233 k->external_name()); 1234 } 1235 return nullptr; 1236 } 1237 1238 if (record->has_non_early_klasses() && JvmtiExport::should_post_class_file_load_hook()) { 1239 if (log_is_enabled(Info, cds, heap)) { 1240 ResourceMark rm(THREAD); 1241 log_info(cds, heap)("subgraph %s cannot be used because JVMTI ClassFileLoadHook is enabled", 1242 k->external_name()); 1243 } 1244 return nullptr; 1245 } 1246 1247 if (log_is_enabled(Info, cds, heap)) { 1248 ResourceMark rm; 1249 log_info(cds, heap)("%s subgraph %s ", do_init ? "init" : "resolve", k->external_name()); 1250 } 1251 1252 resolve_or_init(k, do_init, CHECK_NULL); 1253 1254 // Load/link/initialize the klasses of the objects in the subgraph. 1255 // nullptr class loader is used. 1256 Array<Klass*>* klasses = record->subgraph_object_klasses(); 1257 if (klasses != nullptr) { 1258 for (int i = 0; i < klasses->length(); i++) { 1259 Klass* klass = klasses->at(i); 1260 if (!klass->is_shared()) { 1261 return nullptr; 1262 } 1263 resolve_or_init(klass, do_init, CHECK_NULL); 1264 } 1265 } 1266 } 1267 1268 return record; 1269 } 1270 1271 void HeapShared::resolve_or_init(const char* klass_name, bool do_init, TRAPS) { 1272 TempNewSymbol klass_name_sym = SymbolTable::new_symbol(klass_name); 1273 InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name_sym); 1274 if (k == nullptr) { 1275 return; 1276 } 1277 assert(k->is_shared_boot_class(), "sanity"); 1278 resolve_or_init(k, false, CHECK); 1279 if (do_init) { 1280 resolve_or_init(k, true, CHECK); 1281 } 1282 } 1283 1284 void HeapShared::resolve_or_init(Klass* k, bool do_init, TRAPS) { 1285 if (!do_init) { 1286 if (k->class_loader_data() == nullptr) { 1287 Klass* resolved_k = SystemDictionary::resolve_or_null(k->name(), CHECK); 1288 assert(resolved_k == k, "classes used by archived heap must not be replaced by JVMTI ClassFileLoadHook"); 1289 } 1290 } else { 1291 assert(k->class_loader_data() != nullptr, "must have been resolved by HeapShared::resolve_classes"); 1292 if (k->is_instance_klass()) { 1293 InstanceKlass* ik = InstanceKlass::cast(k); 1294 ik->initialize(CHECK); 1295 } else if (k->is_objArray_klass()) { 1296 ObjArrayKlass* oak = ObjArrayKlass::cast(k); 1297 oak->initialize(CHECK); 1298 } 1299 } 1300 } 1301 1302 void HeapShared::init_archived_fields_for(Klass* k, const ArchivedKlassSubGraphInfoRecord* record) { 1303 verify_the_heap(k, "before"); 1304 1305 // Load the subgraph entry fields from the record and store them back to 1306 // the corresponding fields within the mirror. 1307 oop m = k->java_mirror(); 1308 Array<int>* entry_field_records = record->entry_field_records(); 1309 if (entry_field_records != nullptr) { 1310 int efr_len = entry_field_records->length(); 1311 assert(efr_len % 2 == 0, "sanity"); 1312 for (int i = 0; i < efr_len; i += 2) { 1313 int field_offset = entry_field_records->at(i); 1314 int root_index = entry_field_records->at(i+1); 1315 oop v = get_root(root_index, /*clear=*/true); 1316 if (k->has_aot_initialized_mirror()) { 1317 assert(v == m->obj_field(field_offset), "must be aot-initialized"); 1318 } else { 1319 m->obj_field_put(field_offset, v); 1320 } 1321 log_debug(cds, heap)(" " PTR_FORMAT " init field @ %2d = " PTR_FORMAT, p2i(k), field_offset, p2i(v)); 1322 } 1323 1324 // Done. Java code can see the archived sub-graphs referenced from k's 1325 // mirror after this point. 1326 if (log_is_enabled(Info, cds, heap)) { 1327 ResourceMark rm; 1328 log_info(cds, heap)("initialize_from_archived_subgraph %s " PTR_FORMAT "%s%s", 1329 k->external_name(), p2i(k), JvmtiExport::is_early_phase() ? " (early)" : "", 1330 k->has_aot_initialized_mirror() ? " (aot-inited)" : ""); 1331 } 1332 } 1333 1334 verify_the_heap(k, "after "); 1335 } 1336 1337 void HeapShared::clear_archived_roots_of(Klass* k) { 1338 unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(k); 1339 const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0); 1340 if (record != nullptr) { 1341 Array<int>* entry_field_records = record->entry_field_records(); 1342 if (entry_field_records != nullptr) { 1343 int efr_len = entry_field_records->length(); 1344 assert(efr_len % 2 == 0, "sanity"); 1345 for (int i = 0; i < efr_len; i += 2) { 1346 int root_index = entry_field_records->at(i+1); 1347 clear_root(root_index); 1348 } 1349 } 1350 } 1351 } 1352 1353 class WalkOopAndArchiveClosure: public BasicOopIterateClosure { 1354 int _level; 1355 bool _record_klasses_only; 1356 KlassSubGraphInfo* _subgraph_info; 1357 oop _referencing_obj; 1358 1359 // The following are for maintaining a stack for determining 1360 // CachedOopInfo::_referrer 1361 static WalkOopAndArchiveClosure* _current; 1362 WalkOopAndArchiveClosure* _last; 1363 public: 1364 WalkOopAndArchiveClosure(int level, 1365 bool record_klasses_only, 1366 KlassSubGraphInfo* subgraph_info, 1367 oop orig) : 1368 _level(level), 1369 _record_klasses_only(record_klasses_only), 1370 _subgraph_info(subgraph_info), 1371 _referencing_obj(orig) { 1372 _last = _current; 1373 _current = this; 1374 } 1375 ~WalkOopAndArchiveClosure() { 1376 _current = _last; 1377 } 1378 void do_oop(narrowOop *p) { WalkOopAndArchiveClosure::do_oop_work(p); } 1379 void do_oop( oop *p) { WalkOopAndArchiveClosure::do_oop_work(p); } 1380 1381 protected: 1382 template <class T> void do_oop_work(T *p) { 1383 oop obj = RawAccess<>::oop_load(p); 1384 if (!CompressedOops::is_null(obj)) { 1385 size_t field_delta = pointer_delta(p, _referencing_obj, sizeof(char)); 1386 1387 if (!_record_klasses_only && log_is_enabled(Debug, cds, heap)) { 1388 ResourceMark rm; 1389 log_debug(cds, heap)("(%d) %s[%zu] ==> " PTR_FORMAT " size %zu %s", _level, 1390 _referencing_obj->klass()->external_name(), field_delta, 1391 p2i(obj), obj->size() * HeapWordSize, obj->klass()->external_name()); 1392 if (log_is_enabled(Trace, cds, heap)) { 1393 LogTarget(Trace, cds, heap) log; 1394 LogStream out(log); 1395 obj->print_on(&out); 1396 } 1397 } 1398 1399 bool success = HeapShared::archive_reachable_objects_from( 1400 _level + 1, _subgraph_info, obj); 1401 assert(success, "VM should have exited with unarchivable objects for _level > 1"); 1402 } 1403 } 1404 1405 public: 1406 static WalkOopAndArchiveClosure* current() { return _current; } 1407 oop referencing_obj() { return _referencing_obj; } 1408 KlassSubGraphInfo* subgraph_info() { return _subgraph_info; } 1409 }; 1410 1411 WalkOopAndArchiveClosure* WalkOopAndArchiveClosure::_current = nullptr; 1412 1413 // Checks if an oop has any non-null oop fields 1414 class PointsToOopsChecker : public BasicOopIterateClosure { 1415 bool _result; 1416 1417 template <class T> void check(T *p) { 1418 _result |= (HeapAccess<>::oop_load(p) != nullptr); 1419 } 1420 1421 public: 1422 PointsToOopsChecker() : _result(false) {} 1423 void do_oop(narrowOop *p) { check(p); } 1424 void do_oop( oop *p) { check(p); } 1425 bool result() { return _result; } 1426 }; 1427 1428 HeapShared::CachedOopInfo HeapShared::make_cached_oop_info(oop obj) { 1429 WalkOopAndArchiveClosure* walker = WalkOopAndArchiveClosure::current(); 1430 oop referrer = (walker == nullptr) ? nullptr : walker->referencing_obj(); 1431 PointsToOopsChecker points_to_oops_checker; 1432 obj->oop_iterate(&points_to_oops_checker); 1433 return CachedOopInfo(referrer, points_to_oops_checker.result()); 1434 } 1435 1436 void HeapShared::init_box_classes(TRAPS) { 1437 if (ArchiveHeapLoader::is_in_use()) { 1438 vmClasses::Boolean_klass()->initialize(CHECK); 1439 vmClasses::Character_klass()->initialize(CHECK); 1440 vmClasses::Float_klass()->initialize(CHECK); 1441 vmClasses::Double_klass()->initialize(CHECK); 1442 vmClasses::Byte_klass()->initialize(CHECK); 1443 vmClasses::Short_klass()->initialize(CHECK); 1444 vmClasses::Integer_klass()->initialize(CHECK); 1445 vmClasses::Long_klass()->initialize(CHECK); 1446 vmClasses::Void_klass()->initialize(CHECK); 1447 } 1448 } 1449 1450 // (1) If orig_obj has not been archived yet, archive it. 1451 // (2) If orig_obj has not been seen yet (since start_recording_subgraph() was called), 1452 // trace all objects that are reachable from it, and make sure these objects are archived. 1453 // (3) Record the klasses of all orig_obj and all reachable objects. 1454 bool HeapShared::archive_reachable_objects_from(int level, 1455 KlassSubGraphInfo* subgraph_info, 1456 oop orig_obj) { 1457 assert(orig_obj != nullptr, "must be"); 1458 1459 if (!JavaClasses::is_supported_for_archiving(orig_obj)) { 1460 // This object has injected fields that cannot be supported easily, so we disallow them for now. 1461 // If you get an error here, you probably made a change in the JDK library that has added 1462 // these objects that are referenced (directly or indirectly) by static fields. 1463 ResourceMark rm; 1464 log_error(cds, heap)("Cannot archive object " PTR_FORMAT " of class %s", p2i(orig_obj), orig_obj->klass()->external_name()); 1465 debug_trace(); 1466 MetaspaceShared::unrecoverable_writing_error(); 1467 } 1468 1469 if (log_is_enabled(Debug, cds, heap) && java_lang_Class::is_instance(orig_obj)) { 1470 ResourceMark rm; 1471 LogTarget(Debug, cds, heap) log; 1472 LogStream out(log); 1473 out.print("Found java mirror " PTR_FORMAT " ", p2i(orig_obj)); 1474 Klass* k = java_lang_Class::as_Klass(orig_obj); 1475 if (k != nullptr) { 1476 out.print("%s", k->external_name()); 1477 } else { 1478 out.print("primitive"); 1479 } 1480 out.print_cr("; scratch mirror = " PTR_FORMAT, 1481 p2i(scratch_java_mirror(orig_obj))); 1482 } 1483 1484 if (CDSConfig::is_initing_classes_at_dump_time()) { 1485 if (java_lang_Class::is_instance(orig_obj)) { 1486 orig_obj = scratch_java_mirror(orig_obj); 1487 assert(orig_obj != nullptr, "must be archived"); 1488 } 1489 } else if (java_lang_Class::is_instance(orig_obj) && subgraph_info != _dump_time_special_subgraph) { 1490 // Without CDSConfig::is_initing_classes_at_dump_time(), we only allow archived objects to 1491 // point to the mirrors of (1) j.l.Object, (2) primitive classes, and (3) box classes. These are initialized 1492 // very early by HeapShared::init_box_classes(). 1493 if (orig_obj == vmClasses::Object_klass()->java_mirror() 1494 || java_lang_Class::is_primitive(orig_obj) 1495 || orig_obj == vmClasses::Boolean_klass()->java_mirror() 1496 || orig_obj == vmClasses::Character_klass()->java_mirror() 1497 || orig_obj == vmClasses::Float_klass()->java_mirror() 1498 || orig_obj == vmClasses::Double_klass()->java_mirror() 1499 || orig_obj == vmClasses::Byte_klass()->java_mirror() 1500 || orig_obj == vmClasses::Short_klass()->java_mirror() 1501 || orig_obj == vmClasses::Integer_klass()->java_mirror() 1502 || orig_obj == vmClasses::Long_klass()->java_mirror() 1503 || orig_obj == vmClasses::Void_klass()->java_mirror()) { 1504 orig_obj = scratch_java_mirror(orig_obj); 1505 assert(orig_obj != nullptr, "must be archived"); 1506 } else { 1507 // If you get an error here, you probably made a change in the JDK library that has added a Class 1508 // object that is referenced (directly or indirectly) by an ArchivableStaticFieldInfo 1509 // defined at the top of this file. 1510 log_error(cds, heap)("(%d) Unknown java.lang.Class object is in the archived sub-graph", level); 1511 debug_trace(); 1512 MetaspaceShared::unrecoverable_writing_error(); 1513 } 1514 } 1515 1516 if (has_been_seen_during_subgraph_recording(orig_obj)) { 1517 // orig_obj has already been archived and traced. Nothing more to do. 1518 return true; 1519 } else { 1520 set_has_been_seen_during_subgraph_recording(orig_obj); 1521 } 1522 1523 bool already_archived = has_been_archived(orig_obj); 1524 bool record_klasses_only = already_archived; 1525 if (!already_archived) { 1526 ++_num_new_archived_objs; 1527 if (!archive_object(orig_obj, subgraph_info)) { 1528 // Skip archiving the sub-graph referenced from the current entry field. 1529 ResourceMark rm; 1530 log_error(cds, heap)( 1531 "Cannot archive the sub-graph referenced from %s object (" 1532 PTR_FORMAT ") size %zu, skipped.", 1533 orig_obj->klass()->external_name(), p2i(orig_obj), orig_obj->size() * HeapWordSize); 1534 if (level == 1) { 1535 // Don't archive a subgraph root that's too big. For archives static fields, that's OK 1536 // as the Java code will take care of initializing this field dynamically. 1537 return false; 1538 } else { 1539 // We don't know how to handle an object that has been archived, but some of its reachable 1540 // objects cannot be archived. Bail out for now. We might need to fix this in the future if 1541 // we have a real use case. 1542 MetaspaceShared::unrecoverable_writing_error(); 1543 } 1544 } 1545 } 1546 1547 Klass *orig_k = orig_obj->klass(); 1548 subgraph_info->add_subgraph_object_klass(orig_k); 1549 1550 WalkOopAndArchiveClosure walker(level, record_klasses_only, subgraph_info, orig_obj); 1551 orig_obj->oop_iterate(&walker); 1552 1553 if (CDSConfig::is_initing_classes_at_dump_time()) { 1554 // The enum klasses are archived with aot-initialized mirror. 1555 // See AOTClassInitializer::can_archive_initialized_mirror(). 1556 } else { 1557 if (CDSEnumKlass::is_enum_obj(orig_obj)) { 1558 CDSEnumKlass::handle_enum_obj(level + 1, subgraph_info, orig_obj); 1559 } 1560 } 1561 1562 return true; 1563 } 1564 1565 // 1566 // Start from the given static field in a java mirror and archive the 1567 // complete sub-graph of java heap objects that are reached directly 1568 // or indirectly from the starting object by following references. 1569 // Sub-graph archiving restrictions (current): 1570 // 1571 // - All classes of objects in the archived sub-graph (including the 1572 // entry class) must be boot class only. 1573 // - No java.lang.Class instance (java mirror) can be included inside 1574 // an archived sub-graph. Mirror can only be the sub-graph entry object. 1575 // 1576 // The Java heap object sub-graph archiving process (see 1577 // WalkOopAndArchiveClosure): 1578 // 1579 // 1) Java object sub-graph archiving starts from a given static field 1580 // within a Class instance (java mirror). If the static field is a 1581 // reference field and points to a non-null java object, proceed to 1582 // the next step. 1583 // 1584 // 2) Archives the referenced java object. If an archived copy of the 1585 // current object already exists, updates the pointer in the archived 1586 // copy of the referencing object to point to the current archived object. 1587 // Otherwise, proceed to the next step. 1588 // 1589 // 3) Follows all references within the current java object and recursively 1590 // archive the sub-graph of objects starting from each reference. 1591 // 1592 // 4) Updates the pointer in the archived copy of referencing object to 1593 // point to the current archived object. 1594 // 1595 // 5) The Klass of the current java object is added to the list of Klasses 1596 // for loading and initializing before any object in the archived graph can 1597 // be accessed at runtime. 1598 // 1599 void HeapShared::archive_reachable_objects_from_static_field(InstanceKlass *k, 1600 const char* klass_name, 1601 int field_offset, 1602 const char* field_name) { 1603 assert(CDSConfig::is_dumping_heap(), "dump time only"); 1604 assert(k->is_shared_boot_class(), "must be boot class"); 1605 1606 oop m = k->java_mirror(); 1607 1608 KlassSubGraphInfo* subgraph_info = get_subgraph_info(k); 1609 oop f = m->obj_field(field_offset); 1610 1611 log_debug(cds, heap)("Start archiving from: %s::%s (" PTR_FORMAT ")", klass_name, field_name, p2i(f)); 1612 1613 if (!CompressedOops::is_null(f)) { 1614 if (log_is_enabled(Trace, cds, heap)) { 1615 LogTarget(Trace, cds, heap) log; 1616 LogStream out(log); 1617 f->print_on(&out); 1618 } 1619 1620 bool success = archive_reachable_objects_from(1, subgraph_info, f); 1621 if (!success) { 1622 log_error(cds, heap)("Archiving failed %s::%s (some reachable objects cannot be archived)", 1623 klass_name, field_name); 1624 } else { 1625 // Note: the field value is not preserved in the archived mirror. 1626 // Record the field as a new subGraph entry point. The recorded 1627 // information is restored from the archive at runtime. 1628 subgraph_info->add_subgraph_entry_field(field_offset, f); 1629 log_info(cds, heap)("Archived field %s::%s => " PTR_FORMAT, klass_name, field_name, p2i(f)); 1630 } 1631 } else { 1632 // The field contains null, we still need to record the entry point, 1633 // so it can be restored at runtime. 1634 subgraph_info->add_subgraph_entry_field(field_offset, nullptr); 1635 } 1636 } 1637 1638 #ifndef PRODUCT 1639 class VerifySharedOopClosure: public BasicOopIterateClosure { 1640 public: 1641 void do_oop(narrowOop *p) { VerifySharedOopClosure::do_oop_work(p); } 1642 void do_oop( oop *p) { VerifySharedOopClosure::do_oop_work(p); } 1643 1644 protected: 1645 template <class T> void do_oop_work(T *p) { 1646 oop obj = RawAccess<>::oop_load(p); 1647 if (!CompressedOops::is_null(obj)) { 1648 HeapShared::verify_reachable_objects_from(obj); 1649 } 1650 } 1651 }; 1652 1653 void HeapShared::verify_subgraph_from_static_field(InstanceKlass* k, int field_offset) { 1654 assert(CDSConfig::is_dumping_heap(), "dump time only"); 1655 assert(k->is_shared_boot_class(), "must be boot class"); 1656 1657 oop m = k->java_mirror(); 1658 oop f = m->obj_field(field_offset); 1659 if (!CompressedOops::is_null(f)) { 1660 verify_subgraph_from(f); 1661 } 1662 } 1663 1664 void HeapShared::verify_subgraph_from(oop orig_obj) { 1665 if (!has_been_archived(orig_obj)) { 1666 // It's OK for the root of a subgraph to be not archived. See comments in 1667 // archive_reachable_objects_from(). 1668 return; 1669 } 1670 1671 // Verify that all objects reachable from orig_obj are archived. 1672 init_seen_objects_table(); 1673 verify_reachable_objects_from(orig_obj); 1674 delete_seen_objects_table(); 1675 } 1676 1677 void HeapShared::verify_reachable_objects_from(oop obj) { 1678 _num_total_verifications ++; 1679 if (java_lang_Class::is_instance(obj)) { 1680 obj = scratch_java_mirror(obj); 1681 assert(obj != nullptr, "must be"); 1682 } 1683 if (!has_been_seen_during_subgraph_recording(obj)) { 1684 set_has_been_seen_during_subgraph_recording(obj); 1685 assert(has_been_archived(obj), "must be"); 1686 VerifySharedOopClosure walker; 1687 obj->oop_iterate(&walker); 1688 } 1689 } 1690 #endif 1691 1692 void HeapShared::check_special_subgraph_classes() { 1693 if (CDSConfig::is_initing_classes_at_dump_time()) { 1694 // We can have aot-initialized classes (such as Enums) that can reference objects 1695 // of arbitrary types. Currently, we trust the JEP 483 implementation to only 1696 // aot-initialize classes that are "safe". 1697 // 1698 // TODO: we need an automatic tool that checks the safety of aot-initialized 1699 // classes (when we extend the set of aot-initialized classes beyond JEP 483) 1700 return; 1701 } else { 1702 // In this case, the special subgraph should contain a few specific types 1703 GrowableArray<Klass*>* klasses = _dump_time_special_subgraph->subgraph_object_klasses(); 1704 int num = klasses->length(); 1705 for (int i = 0; i < num; i++) { 1706 Klass* subgraph_k = klasses->at(i); 1707 Symbol* name = subgraph_k->name(); 1708 if (subgraph_k->is_instance_klass() && 1709 name != vmSymbols::java_lang_Class() && 1710 name != vmSymbols::java_lang_String() && 1711 name != vmSymbols::java_lang_ArithmeticException() && 1712 name != vmSymbols::java_lang_ArrayIndexOutOfBoundsException() && 1713 name != vmSymbols::java_lang_ArrayStoreException() && 1714 name != vmSymbols::java_lang_ClassCastException() && 1715 name != vmSymbols::java_lang_InternalError() && 1716 name != vmSymbols::java_lang_NullPointerException()) { 1717 ResourceMark rm; 1718 fatal("special subgraph cannot have objects of type %s", subgraph_k->external_name()); 1719 } 1720 } 1721 } 1722 } 1723 1724 HeapShared::SeenObjectsTable* HeapShared::_seen_objects_table = nullptr; 1725 int HeapShared::_num_new_walked_objs; 1726 int HeapShared::_num_new_archived_objs; 1727 int HeapShared::_num_old_recorded_klasses; 1728 1729 int HeapShared::_num_total_subgraph_recordings = 0; 1730 int HeapShared::_num_total_walked_objs = 0; 1731 int HeapShared::_num_total_archived_objs = 0; 1732 int HeapShared::_num_total_recorded_klasses = 0; 1733 int HeapShared::_num_total_verifications = 0; 1734 1735 bool HeapShared::has_been_seen_during_subgraph_recording(oop obj) { 1736 return _seen_objects_table->get(obj) != nullptr; 1737 } 1738 1739 void HeapShared::set_has_been_seen_during_subgraph_recording(oop obj) { 1740 assert(!has_been_seen_during_subgraph_recording(obj), "sanity"); 1741 _seen_objects_table->put_when_absent(obj, true); 1742 _seen_objects_table->maybe_grow(); 1743 ++ _num_new_walked_objs; 1744 } 1745 1746 void HeapShared::start_recording_subgraph(InstanceKlass *k, const char* class_name, bool is_full_module_graph) { 1747 log_info(cds, heap)("Start recording subgraph(s) for archived fields in %s", class_name); 1748 init_subgraph_info(k, is_full_module_graph); 1749 init_seen_objects_table(); 1750 _num_new_walked_objs = 0; 1751 _num_new_archived_objs = 0; 1752 _num_old_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses(); 1753 } 1754 1755 void HeapShared::done_recording_subgraph(InstanceKlass *k, const char* class_name) { 1756 int num_new_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses() - 1757 _num_old_recorded_klasses; 1758 log_info(cds, heap)("Done recording subgraph(s) for archived fields in %s: " 1759 "walked %d objs, archived %d new objs, recorded %d classes", 1760 class_name, _num_new_walked_objs, _num_new_archived_objs, 1761 num_new_recorded_klasses); 1762 1763 delete_seen_objects_table(); 1764 1765 _num_total_subgraph_recordings ++; 1766 _num_total_walked_objs += _num_new_walked_objs; 1767 _num_total_archived_objs += _num_new_archived_objs; 1768 _num_total_recorded_klasses += num_new_recorded_klasses; 1769 } 1770 1771 class ArchivableStaticFieldFinder: public FieldClosure { 1772 InstanceKlass* _ik; 1773 Symbol* _field_name; 1774 bool _found; 1775 int _offset; 1776 public: 1777 ArchivableStaticFieldFinder(InstanceKlass* ik, Symbol* field_name) : 1778 _ik(ik), _field_name(field_name), _found(false), _offset(-1) {} 1779 1780 virtual void do_field(fieldDescriptor* fd) { 1781 if (fd->name() == _field_name) { 1782 assert(!_found, "fields can never be overloaded"); 1783 if (is_reference_type(fd->field_type())) { 1784 _found = true; 1785 _offset = fd->offset(); 1786 } 1787 } 1788 } 1789 bool found() { return _found; } 1790 int offset() { return _offset; } 1791 }; 1792 1793 void HeapShared::init_subgraph_entry_fields(ArchivableStaticFieldInfo fields[], 1794 TRAPS) { 1795 for (int i = 0; fields[i].valid(); i++) { 1796 ArchivableStaticFieldInfo* info = &fields[i]; 1797 TempNewSymbol klass_name = SymbolTable::new_symbol(info->klass_name); 1798 TempNewSymbol field_name = SymbolTable::new_symbol(info->field_name); 1799 ResourceMark rm; // for stringStream::as_string() etc. 1800 1801 #ifndef PRODUCT 1802 bool is_test_class = (ArchiveHeapTestClass != nullptr) && (strcmp(info->klass_name, ArchiveHeapTestClass) == 0); 1803 const char* test_class_name = ArchiveHeapTestClass; 1804 #else 1805 bool is_test_class = false; 1806 const char* test_class_name = ""; // avoid C++ printf checks warnings. 1807 #endif 1808 1809 if (is_test_class) { 1810 log_warning(cds)("Loading ArchiveHeapTestClass %s ...", test_class_name); 1811 } 1812 1813 Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, THREAD); 1814 if (HAS_PENDING_EXCEPTION) { 1815 CLEAR_PENDING_EXCEPTION; 1816 stringStream st; 1817 st.print("Fail to initialize archive heap: %s cannot be loaded by the boot loader", info->klass_name); 1818 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string()); 1819 } 1820 1821 if (!k->is_instance_klass()) { 1822 stringStream st; 1823 st.print("Fail to initialize archive heap: %s is not an instance class", info->klass_name); 1824 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string()); 1825 } 1826 1827 InstanceKlass* ik = InstanceKlass::cast(k); 1828 assert(InstanceKlass::cast(ik)->is_shared_boot_class(), 1829 "Only support boot classes"); 1830 1831 if (is_test_class) { 1832 if (ik->module()->is_named()) { 1833 // We don't want ArchiveHeapTestClass to be abused to easily load/initialize arbitrary 1834 // core-lib classes. You need to at least append to the bootclasspath. 1835 stringStream st; 1836 st.print("ArchiveHeapTestClass %s is not in unnamed module", test_class_name); 1837 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string()); 1838 } 1839 1840 if (ik->package() != nullptr) { 1841 // This restriction makes HeapShared::is_a_test_class_in_unnamed_module() easy. 1842 stringStream st; 1843 st.print("ArchiveHeapTestClass %s is not in unnamed package", test_class_name); 1844 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string()); 1845 } 1846 } else { 1847 if (ik->module()->name() != vmSymbols::java_base()) { 1848 // We don't want to deal with cases when a module is unavailable at runtime. 1849 // FUTURE -- load from archived heap only when module graph has not changed 1850 // between dump and runtime. 1851 stringStream st; 1852 st.print("%s is not in java.base module", info->klass_name); 1853 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string()); 1854 } 1855 } 1856 1857 if (is_test_class) { 1858 log_warning(cds)("Initializing ArchiveHeapTestClass %s ...", test_class_name); 1859 } 1860 ik->initialize(CHECK); 1861 1862 ArchivableStaticFieldFinder finder(ik, field_name); 1863 ik->do_local_static_fields(&finder); 1864 if (!finder.found()) { 1865 stringStream st; 1866 st.print("Unable to find the static T_OBJECT field %s::%s", info->klass_name, info->field_name); 1867 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), st.as_string()); 1868 } 1869 1870 info->klass = ik; 1871 info->offset = finder.offset(); 1872 } 1873 } 1874 1875 void HeapShared::init_subgraph_entry_fields(TRAPS) { 1876 assert(CDSConfig::is_dumping_heap(), "must be"); 1877 _dump_time_subgraph_info_table = new (mtClass)DumpTimeKlassSubGraphInfoTable(); 1878 init_subgraph_entry_fields(archive_subgraph_entry_fields, CHECK); 1879 if (CDSConfig::is_dumping_full_module_graph()) { 1880 init_subgraph_entry_fields(fmg_archive_subgraph_entry_fields, CHECK); 1881 } 1882 } 1883 1884 #ifndef PRODUCT 1885 void HeapShared::setup_test_class(const char* test_class_name) { 1886 ArchivableStaticFieldInfo* p = archive_subgraph_entry_fields; 1887 int num_slots = sizeof(archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo); 1888 assert(p[num_slots - 2].klass_name == nullptr, "must have empty slot that's patched below"); 1889 assert(p[num_slots - 1].klass_name == nullptr, "must have empty slot that marks the end of the list"); 1890 1891 if (test_class_name != nullptr) { 1892 p[num_slots - 2].klass_name = test_class_name; 1893 p[num_slots - 2].field_name = ARCHIVE_TEST_FIELD_NAME; 1894 } 1895 } 1896 1897 // See if ik is one of the test classes that are pulled in by -XX:ArchiveHeapTestClass 1898 // during runtime. This may be called before the module system is initialized so 1899 // we cannot rely on InstanceKlass::module(), etc. 1900 bool HeapShared::is_a_test_class_in_unnamed_module(Klass* ik) { 1901 if (_test_class != nullptr) { 1902 if (ik == _test_class) { 1903 return true; 1904 } 1905 Array<Klass*>* klasses = _test_class_record->subgraph_object_klasses(); 1906 if (klasses == nullptr) { 1907 return false; 1908 } 1909 1910 for (int i = 0; i < klasses->length(); i++) { 1911 Klass* k = klasses->at(i); 1912 if (k == ik) { 1913 Symbol* name; 1914 if (k->is_instance_klass()) { 1915 name = InstanceKlass::cast(k)->name(); 1916 } else if (k->is_objArray_klass()) { 1917 Klass* bk = ObjArrayKlass::cast(k)->bottom_klass(); 1918 if (!bk->is_instance_klass()) { 1919 return false; 1920 } 1921 name = bk->name(); 1922 } else { 1923 return false; 1924 } 1925 1926 // See KlassSubGraphInfo::check_allowed_klass() - we only allow test classes 1927 // to be: 1928 // (A) java.base classes (which must not be in the unnamed module) 1929 // (B) test classes which must be in the unnamed package of the unnamed module. 1930 // So if we see a '/' character in the class name, it must be in (A); 1931 // otherwise it must be in (B). 1932 if (name->index_of_at(0, "/", 1) >= 0) { 1933 return false; // (A) 1934 } 1935 1936 return true; // (B) 1937 } 1938 } 1939 } 1940 1941 return false; 1942 } 1943 1944 void HeapShared::initialize_test_class_from_archive(JavaThread* current) { 1945 Klass* k = _test_class; 1946 if (k != nullptr && ArchiveHeapLoader::is_in_use()) { 1947 JavaThread* THREAD = current; 1948 ExceptionMark em(THREAD); 1949 const ArchivedKlassSubGraphInfoRecord* record = 1950 resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/false, THREAD); 1951 1952 // The _test_class is in the unnamed module, so it can't call CDS.initializeFromArchive() 1953 // from its <clinit> method. So we set up its "archivedObjects" field first, before 1954 // calling its <clinit>. This is not strictly clean, but it's a convenient way to write unit 1955 // test cases (see test/hotspot/jtreg/runtime/cds/appcds/cacheObject/ArchiveHeapTestClass.java). 1956 if (record != nullptr) { 1957 init_archived_fields_for(k, record); 1958 } 1959 resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/true, THREAD); 1960 } 1961 } 1962 #endif 1963 1964 void HeapShared::init_for_dumping(TRAPS) { 1965 if (CDSConfig::is_dumping_heap()) { 1966 setup_test_class(ArchiveHeapTestClass); 1967 _dumped_interned_strings = new (mtClass)DumpedInternedStrings(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE); 1968 init_subgraph_entry_fields(CHECK); 1969 } 1970 } 1971 1972 void HeapShared::archive_object_subgraphs(ArchivableStaticFieldInfo fields[], 1973 bool is_full_module_graph) { 1974 _num_total_subgraph_recordings = 0; 1975 _num_total_walked_objs = 0; 1976 _num_total_archived_objs = 0; 1977 _num_total_recorded_klasses = 0; 1978 _num_total_verifications = 0; 1979 1980 // For each class X that has one or more archived fields: 1981 // [1] Dump the subgraph of each archived field 1982 // [2] Create a list of all the class of the objects that can be reached 1983 // by any of these static fields. 1984 // At runtime, these classes are initialized before X's archived fields 1985 // are restored by HeapShared::initialize_from_archived_subgraph(). 1986 for (int i = 0; fields[i].valid(); ) { 1987 ArchivableStaticFieldInfo* info = &fields[i]; 1988 const char* klass_name = info->klass_name; 1989 1990 if (CDSConfig::is_valhalla_preview() && strcmp(klass_name, "jdk/internal/module/ArchivedModuleGraph") == 0) { 1991 // FIXME -- ArchivedModuleGraph doesn't work when java.base is patched with valhalla classes. 1992 i++; 1993 continue; 1994 } 1995 1996 start_recording_subgraph(info->klass, klass_name, is_full_module_graph); 1997 1998 // If you have specified consecutive fields of the same klass in 1999 // fields[], these will be archived in the same 2000 // {start_recording_subgraph ... done_recording_subgraph} pass to 2001 // save time. 2002 for (; fields[i].valid(); i++) { 2003 ArchivableStaticFieldInfo* f = &fields[i]; 2004 if (f->klass_name != klass_name) { 2005 break; 2006 } 2007 2008 archive_reachable_objects_from_static_field(f->klass, f->klass_name, 2009 f->offset, f->field_name); 2010 } 2011 done_recording_subgraph(info->klass, klass_name); 2012 } 2013 2014 log_info(cds, heap)("Archived subgraph records = %d", 2015 _num_total_subgraph_recordings); 2016 log_info(cds, heap)(" Walked %d objects", _num_total_walked_objs); 2017 log_info(cds, heap)(" Archived %d objects", _num_total_archived_objs); 2018 log_info(cds, heap)(" Recorded %d klasses", _num_total_recorded_klasses); 2019 2020 #ifndef PRODUCT 2021 for (int i = 0; fields[i].valid(); i++) { 2022 ArchivableStaticFieldInfo* f = &fields[i]; 2023 verify_subgraph_from_static_field(f->klass, f->offset); 2024 } 2025 log_info(cds, heap)(" Verified %d references", _num_total_verifications); 2026 #endif 2027 } 2028 2029 // Not all the strings in the global StringTable are dumped into the archive, because 2030 // some of those strings may be only referenced by classes that are excluded from 2031 // the archive. We need to explicitly mark the strings that are: 2032 // [1] used by classes that WILL be archived; 2033 // [2] included in the SharedArchiveConfigFile. 2034 void HeapShared::add_to_dumped_interned_strings(oop string) { 2035 assert_at_safepoint(); // DumpedInternedStrings uses raw oops 2036 assert(!ArchiveHeapWriter::is_string_too_large_to_archive(string), "must be"); 2037 bool created; 2038 _dumped_interned_strings->put_if_absent(string, true, &created); 2039 if (created) { 2040 // Prevent string deduplication from changing the value field to 2041 // something not in the archive. 2042 java_lang_String::set_deduplication_forbidden(string); 2043 _dumped_interned_strings->maybe_grow(); 2044 } 2045 } 2046 2047 bool HeapShared::is_dumped_interned_string(oop o) { 2048 return _dumped_interned_strings->get(o) != nullptr; 2049 } 2050 2051 void HeapShared::debug_trace() { 2052 ResourceMark rm; 2053 WalkOopAndArchiveClosure* walker = WalkOopAndArchiveClosure::current(); 2054 if (walker != nullptr) { 2055 LogStream ls(Log(cds, heap)::error()); 2056 CDSHeapVerifier::trace_to_root(&ls, walker->referencing_obj()); 2057 } 2058 } 2059 2060 #ifndef PRODUCT 2061 // At dump-time, find the location of all the non-null oop pointers in an archived heap 2062 // region. This way we can quickly relocate all the pointers without using 2063 // BasicOopIterateClosure at runtime. 2064 class FindEmbeddedNonNullPointers: public BasicOopIterateClosure { 2065 void* _start; 2066 BitMap *_oopmap; 2067 int _num_total_oops; 2068 int _num_null_oops; 2069 public: 2070 FindEmbeddedNonNullPointers(void* start, BitMap* oopmap) 2071 : _start(start), _oopmap(oopmap), _num_total_oops(0), _num_null_oops(0) {} 2072 2073 virtual void do_oop(narrowOop* p) { 2074 assert(UseCompressedOops, "sanity"); 2075 _num_total_oops ++; 2076 narrowOop v = *p; 2077 if (!CompressedOops::is_null(v)) { 2078 size_t idx = p - (narrowOop*)_start; 2079 _oopmap->set_bit(idx); 2080 } else { 2081 _num_null_oops ++; 2082 } 2083 } 2084 virtual void do_oop(oop* p) { 2085 assert(!UseCompressedOops, "sanity"); 2086 _num_total_oops ++; 2087 if ((*p) != nullptr) { 2088 size_t idx = p - (oop*)_start; 2089 _oopmap->set_bit(idx); 2090 } else { 2091 _num_null_oops ++; 2092 } 2093 } 2094 int num_total_oops() const { return _num_total_oops; } 2095 int num_null_oops() const { return _num_null_oops; } 2096 }; 2097 #endif 2098 2099 void HeapShared::count_allocation(size_t size) { 2100 _total_obj_count ++; 2101 _total_obj_size += size; 2102 for (int i = 0; i < ALLOC_STAT_SLOTS; i++) { 2103 if (size <= (size_t(1) << i)) { 2104 _alloc_count[i] ++; 2105 _alloc_size[i] += size; 2106 return; 2107 } 2108 } 2109 } 2110 2111 static double avg_size(size_t size, size_t count) { 2112 double avg = 0; 2113 if (count > 0) { 2114 avg = double(size * HeapWordSize) / double(count); 2115 } 2116 return avg; 2117 } 2118 2119 void HeapShared::print_stats() { 2120 size_t huge_count = _total_obj_count; 2121 size_t huge_size = _total_obj_size; 2122 2123 for (int i = 0; i < ALLOC_STAT_SLOTS; i++) { 2124 size_t byte_size_limit = (size_t(1) << i) * HeapWordSize; 2125 size_t count = _alloc_count[i]; 2126 size_t size = _alloc_size[i]; 2127 log_info(cds, heap)("%8zu objects are <= %-6zu" 2128 " bytes (total %8zu bytes, avg %8.1f bytes)", 2129 count, byte_size_limit, size * HeapWordSize, avg_size(size, count)); 2130 huge_count -= count; 2131 huge_size -= size; 2132 } 2133 2134 log_info(cds, heap)("%8zu huge objects (total %8zu bytes" 2135 ", avg %8.1f bytes)", 2136 huge_count, huge_size * HeapWordSize, 2137 avg_size(huge_size, huge_count)); 2138 log_info(cds, heap)("%8zu total objects (total %8zu bytes" 2139 ", avg %8.1f bytes)", 2140 _total_obj_count, _total_obj_size * HeapWordSize, 2141 avg_size(_total_obj_size, _total_obj_count)); 2142 } 2143 2144 bool HeapShared::is_archived_boot_layer_available(JavaThread* current) { 2145 TempNewSymbol klass_name = SymbolTable::new_symbol(ARCHIVED_BOOT_LAYER_CLASS); 2146 InstanceKlass* k = SystemDictionary::find_instance_klass(current, klass_name, Handle()); 2147 if (k == nullptr) { 2148 return false; 2149 } else { 2150 TempNewSymbol field_name = SymbolTable::new_symbol(ARCHIVED_BOOT_LAYER_FIELD); 2151 TempNewSymbol field_signature = SymbolTable::new_symbol("Ljdk/internal/module/ArchivedBootLayer;"); 2152 fieldDescriptor fd; 2153 if (k->find_field(field_name, field_signature, true, &fd) != nullptr) { 2154 oop m = k->java_mirror(); 2155 oop f = m->obj_field(fd.offset()); 2156 if (CompressedOops::is_null(f)) { 2157 return false; 2158 } 2159 } else { 2160 return false; 2161 } 2162 } 2163 return true; 2164 } 2165 2166 #endif // INCLUDE_CDS_JAVA_HEAP