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