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