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