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