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