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