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