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