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