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