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