1 /*
2 * Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #ifndef SHARE_CDS_HEAPSHARED_HPP
26 #define SHARE_CDS_HEAPSHARED_HPP
27
28 #include "cds/aotMetaspace.hpp"
29 #include "cds/dumpTimeClassInfo.hpp"
30 #include "classfile/compactHashtable.hpp"
31 #include "classfile/javaClasses.hpp"
32 #include "gc/shared/gc_globals.hpp"
33 #include "memory/allocation.hpp"
34 #include "memory/allStatic.hpp"
35 #include "oops/compressedOops.hpp"
36 #include "oops/oop.hpp"
37 #include "oops/oopHandle.hpp"
38 #include "oops/oopsHierarchy.hpp"
39 #include "utilities/growableArray.hpp"
40 #include "utilities/hashTable.hpp"
41
42 #if INCLUDE_CDS_JAVA_HEAP
43 class DumpedInternedStrings;
44 class FileMapInfo;
45 class KlassSubGraphInfo;
46 class MetaspaceObjToOopHandleTable;
47 class ResourceBitMap;
48
49 struct ArchivableStaticFieldInfo;
50
51 #define ARCHIVED_BOOT_LAYER_CLASS "jdk/internal/module/ArchivedBootLayer"
52 #define ARCHIVED_BOOT_LAYER_FIELD "archivedBootLayer"
53
54 // A dump time sub-graph info for Klass _k. It includes the entry points
55 // (static fields in _k's mirror) of the archived sub-graphs reachable
56 // from _k's mirror. It also contains a list of Klasses of the objects
57 // within the sub-graphs.
58 class KlassSubGraphInfo: public CHeapObj<mtClass> {
59 private:
60 // The class that contains the static field(s) as the entry point(s)
61 // of archived object sub-graph(s).
62 Klass* _k;
63 // A list of classes need to be loaded and initialized before the archived
64 // object sub-graphs can be accessed at runtime.
65 GrowableArray<Klass*>* _subgraph_object_klasses;
66 // A list of _k's static fields as the entry points of archived sub-graphs.
67 // For each entry field, it is a tuple of field_offset, field_value
68 GrowableArray<int>* _subgraph_entry_fields;
69
70 // Does this KlassSubGraphInfo belong to the archived full module graph
71 bool _is_full_module_graph;
72
73 // Does this KlassSubGraphInfo references any classes that were loaded while
74 // JvmtiExport::is_early_phase()!=true. If so, this KlassSubGraphInfo cannot be
75 // used at runtime if JVMTI ClassFileLoadHook is enabled.
76 bool _has_non_early_klasses;
77 static bool is_non_early_klass(Klass* k);
78 static void check_allowed_klass(InstanceKlass* ik);
79 public:
80 KlassSubGraphInfo(Klass* k, bool is_full_module_graph) :
81 _k(k), _subgraph_object_klasses(nullptr),
82 _subgraph_entry_fields(nullptr),
83 _is_full_module_graph(is_full_module_graph),
84 _has_non_early_klasses(false) {}
85
86 ~KlassSubGraphInfo() {
87 if (_subgraph_object_klasses != nullptr) {
88 delete _subgraph_object_klasses;
89 }
90 if (_subgraph_entry_fields != nullptr) {
91 delete _subgraph_entry_fields;
92 }
93 };
94
95 Klass* klass() { return _k; }
96 GrowableArray<Klass*>* subgraph_object_klasses() {
97 return _subgraph_object_klasses;
98 }
99 GrowableArray<int>* subgraph_entry_fields() {
100 return _subgraph_entry_fields;
101 }
102 void add_subgraph_entry_field(int static_field_offset, oop v);
103 void add_subgraph_object_klass(Klass *orig_k);
104 int num_subgraph_object_klasses() {
105 return _subgraph_object_klasses == nullptr ? 0 :
106 _subgraph_object_klasses->length();
107 }
108 bool is_full_module_graph() const { return _is_full_module_graph; }
109 bool has_non_early_klasses() const { return _has_non_early_klasses; }
110 };
111
112 // An archived record of object sub-graphs reachable from static
113 // fields within _k's mirror. The record is reloaded from the archive
114 // at runtime.
115 class ArchivedKlassSubGraphInfoRecord {
116 private:
117 Klass* _k;
118 bool _is_full_module_graph;
119 bool _has_non_early_klasses;
120
121 // contains pairs of field offset and value for each subgraph entry field
122 Array<int>* _entry_field_records;
123
124 // klasses of objects in archived sub-graphs referenced from the entry points
125 // (static fields) in the containing class
126 Array<Klass*>* _subgraph_object_klasses;
127 public:
128 ArchivedKlassSubGraphInfoRecord() :
129 _k(nullptr), _entry_field_records(nullptr), _subgraph_object_klasses(nullptr) {}
130 void init(KlassSubGraphInfo* info);
131 Klass* klass() const { return _k; }
132 Array<int>* entry_field_records() const { return _entry_field_records; }
133 Array<Klass*>* subgraph_object_klasses() const { return _subgraph_object_klasses; }
134 bool is_full_module_graph() const { return _is_full_module_graph; }
135 bool has_non_early_klasses() const { return _has_non_early_klasses; }
136 };
137 #endif // INCLUDE_CDS_JAVA_HEAP
138
139 enum class HeapArchiveMode {
140 _uninitialized,
141 _mapping,
142 _streaming
143 };
144
145 class HeapShared: AllStatic {
146 friend class VerifySharedOopClosure;
147
148 public:
149 static void initialize_loading_mode(HeapArchiveMode mode) NOT_CDS_JAVA_HEAP_RETURN;
150 static void initialize_writing_mode() NOT_CDS_JAVA_HEAP_RETURN;
151
152 inline static bool is_loading() NOT_CDS_JAVA_HEAP_RETURN_(false);
153
154 inline static bool is_loading_streaming_mode() NOT_CDS_JAVA_HEAP_RETURN_(false);
155 inline static bool is_loading_mapping_mode() NOT_CDS_JAVA_HEAP_RETURN_(false);
156
157 inline static bool is_writing() NOT_CDS_JAVA_HEAP_RETURN_(false);
158
159 inline static bool is_writing_streaming_mode() NOT_CDS_JAVA_HEAP_RETURN_(false);
160 inline static bool is_writing_mapping_mode() NOT_CDS_JAVA_HEAP_RETURN_(false);
161
162 static bool is_subgraph_root_class(InstanceKlass* ik);
163
164 // Scratch objects for archiving Klass::java_mirror()
165 static oop scratch_java_mirror(BasicType t) NOT_CDS_JAVA_HEAP_RETURN_(nullptr);
166 static oop scratch_java_mirror(Klass* k) NOT_CDS_JAVA_HEAP_RETURN_(nullptr);
167 static oop scratch_java_mirror(oop java_mirror) NOT_CDS_JAVA_HEAP_RETURN_(nullptr);
168 static bool is_archived_boot_layer_available(JavaThread* current) NOT_CDS_JAVA_HEAP_RETURN_(false);
169
170 static bool is_archived_heap_in_use() NOT_CDS_JAVA_HEAP_RETURN_(false);
171 static bool can_use_archived_heap() NOT_CDS_JAVA_HEAP_RETURN_(false);
172 static bool is_too_large_to_archive(size_t size);
173 static bool is_string_too_large_to_archive(oop string);
174 static bool is_too_large_to_archive(oop obj);
175
176 static void initialize_streaming() NOT_CDS_JAVA_HEAP_RETURN;
177 static void enable_gc() NOT_CDS_JAVA_HEAP_RETURN;
178 static void materialize_thread_object() NOT_CDS_JAVA_HEAP_RETURN;
179 static void add_to_dumped_interned_strings(oop string) NOT_CDS_JAVA_HEAP_RETURN;
180 static void finalize_initialization(FileMapInfo* static_mapinfo) NOT_CDS_JAVA_HEAP_RETURN;
181
182 private:
183 #if INCLUDE_CDS_JAVA_HEAP
184 static HeapArchiveMode _heap_load_mode;
185 static HeapArchiveMode _heap_write_mode;
186
187 // statistics
188 constexpr static int ALLOC_STAT_SLOTS = 16;
189 static size_t _alloc_count[ALLOC_STAT_SLOTS];
190 static size_t _alloc_size[ALLOC_STAT_SLOTS];
191 static size_t _total_obj_count;
192 static size_t _total_obj_size; // in HeapWords
193
194 static void count_allocation(size_t size);
195 static void print_stats();
196 public:
197 static void debug_trace();
198 static unsigned oop_hash(oop const& p);
199 static unsigned oop_handle_hash(OopHandle const& oh);
200 static unsigned oop_handle_hash_raw(OopHandle const& oh);
201 static bool oop_handle_equals(const OopHandle& a, const OopHandle& b);
202 static unsigned string_oop_hash(oop const& string) {
203 return java_lang_String::hash_code(string);
204 }
205
206 class CopyKlassSubGraphInfoToArchive;
207
208 class CachedOopInfo {
209 // Used by CDSHeapVerifier.
210 OopHandle _orig_referrer;
211
212 // The location of this object inside {AOTMappedHeapWriter, AOTStreamedHeapWriter}::_buffer
213 size_t _buffer_offset;
214
215 // One or more fields in this object are pointing to non-null oops.
216 bool _has_oop_pointers;
217
218 // One or more fields in this object are pointing to MetaspaceObj
219 bool _has_native_pointers;
220 public:
221 CachedOopInfo(OopHandle orig_referrer, bool has_oop_pointers)
222 : _orig_referrer(orig_referrer),
223 _buffer_offset(0),
224 _has_oop_pointers(has_oop_pointers),
225 _has_native_pointers(false) {}
226 oop orig_referrer() const;
227 void set_buffer_offset(size_t offset) { _buffer_offset = offset; }
228 size_t buffer_offset() const { return _buffer_offset; }
229 bool has_oop_pointers() const { return _has_oop_pointers; }
230 bool has_native_pointers() const { return _has_native_pointers; }
231 void set_has_native_pointers() { _has_native_pointers = true; }
232 };
233
234 private:
235 static const int INITIAL_TABLE_SIZE = 15889; // prime number
236 static const int MAX_TABLE_SIZE = 1000000;
237 typedef ResizeableHashTable<OopHandle, CachedOopInfo,
238 AnyObj::C_HEAP,
239 mtClassShared,
240 HeapShared::oop_handle_hash_raw,
241 HeapShared::oop_handle_equals> ArchivedObjectCache;
242 static ArchivedObjectCache* _archived_object_cache;
243
244 class DumpTimeKlassSubGraphInfoTable
245 : public HashTable<Klass*, KlassSubGraphInfo,
246 137, // prime number
247 AnyObj::C_HEAP,
248 mtClassShared,
249 DumpTimeSharedClassTable_hash> {};
250
251 public: // solaris compiler wants this for RunTimeKlassSubGraphInfoTable
252 inline static bool record_equals_compact_hashtable_entry(
253 const ArchivedKlassSubGraphInfoRecord* value, const Klass* key, int len_unused) {
254 return (value->klass() == key);
255 }
256
257 private:
258 typedef OffsetCompactHashtable<
259 const Klass*,
260 const ArchivedKlassSubGraphInfoRecord*,
261 record_equals_compact_hashtable_entry
262 > RunTimeKlassSubGraphInfoTable;
263
264 static DumpTimeKlassSubGraphInfoTable* _dump_time_subgraph_info_table;
265 static RunTimeKlassSubGraphInfoTable _run_time_subgraph_info_table;
266
267 static CachedOopInfo make_cached_oop_info(oop obj, oop referrer);
268 static ArchivedKlassSubGraphInfoRecord* archive_subgraph_info(KlassSubGraphInfo* info);
269 static void archive_object_subgraphs(ArchivableStaticFieldInfo fields[],
270 bool is_full_module_graph);
271
272 // Archive object sub-graph starting from the given static field
273 // in Klass k's mirror.
274 static void archive_reachable_objects_from_static_field(
275 InstanceKlass* k, const char* klass_name,
276 int field_offset, const char* field_name);
277
278 static void verify_subgraph_from_static_field(
279 InstanceKlass* k, int field_offset) PRODUCT_RETURN;
280 static void verify_reachable_objects_from(oop obj) PRODUCT_RETURN;
281 static void verify_subgraph_from(oop orig_obj) PRODUCT_RETURN;
282 static void check_special_subgraph_classes();
283
284 static KlassSubGraphInfo* init_subgraph_info(Klass *k, bool is_full_module_graph);
285 static KlassSubGraphInfo* get_subgraph_info(Klass *k);
286
287 static void init_subgraph_entry_fields(TRAPS) NOT_CDS_JAVA_HEAP_RETURN;
288 static void init_subgraph_entry_fields(ArchivableStaticFieldInfo fields[], TRAPS);
289
290 // UseCompressedOops only: Used by decode_from_archive
291 static address _narrow_oop_base;
292 static int _narrow_oop_shift;
293
294 // !UseCompressedOops only: used to relocate pointers to the archived objects
295 static ptrdiff_t _runtime_delta;
296
297 typedef ResizeableHashTable<oop, bool,
298 AnyObj::C_HEAP,
299 mtClassShared,
300 HeapShared::oop_hash> SeenObjectsTable;
301
302 static SeenObjectsTable *_seen_objects_table;
303
304 // The "special subgraph" contains all the archived objects that are reachable
305 // from the following roots:
306 // - interned strings
307 // - Klass::java_mirror() -- including aot-initialized mirrors such as those of Enum klasses.
308 // - ConstantPool::resolved_references()
309 // - Universe::<xxx>_exception_instance()
310 static KlassSubGraphInfo* _dump_time_special_subgraph; // for collecting info during dump time
311 static ArchivedKlassSubGraphInfoRecord* _run_time_special_subgraph; // for initializing classes during run time.
312
313 static GrowableArrayCHeap<oop, mtClassShared>* _pending_roots;
314 static OopHandle _scratch_basic_type_mirrors[T_VOID+1];
315 static MetaspaceObjToOopHandleTable* _scratch_objects_table;
316
317 static void init_seen_objects_table() {
318 assert(_seen_objects_table == nullptr, "must be");
319 _seen_objects_table = new (mtClass)SeenObjectsTable(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE);
320 }
321 static void delete_seen_objects_table() {
322 assert(_seen_objects_table != nullptr, "must be");
323 delete _seen_objects_table;
324 _seen_objects_table = nullptr;
325 }
326
327 // Statistics (for one round of start_recording_subgraph ... done_recording_subgraph)
328 static size_t _num_new_walked_objs;
329 static size_t _num_new_archived_objs;
330 static size_t _num_old_recorded_klasses;
331
332 // Statistics (for all archived subgraphs)
333 static size_t _num_total_subgraph_recordings;
334 static size_t _num_total_walked_objs;
335 static size_t _num_total_archived_objs;
336 static size_t _num_total_recorded_klasses;
337 static size_t _num_total_verifications;
338
339 static void start_recording_subgraph(InstanceKlass *k, const char* klass_name,
340 bool is_full_module_graph);
341 static void done_recording_subgraph(InstanceKlass *k, const char* klass_name);
342
343 static bool has_been_seen_during_subgraph_recording(oop obj);
344 static void set_has_been_seen_during_subgraph_recording(oop obj);
345 static bool archive_object(oop obj, oop referrer, KlassSubGraphInfo* subgraph_info);
346
347 static void resolve_classes_for_subgraphs(JavaThread* current, ArchivableStaticFieldInfo fields[]);
348 static void resolve_classes_for_subgraph_of(JavaThread* current, Klass* k);
349 static void clear_archived_roots_of(Klass* k);
350 static const ArchivedKlassSubGraphInfoRecord*
351 resolve_or_init_classes_for_subgraph_of(Klass* k, bool do_init, TRAPS);
352 static void resolve_or_init(const char* klass_name, bool do_init, TRAPS);
353 static void resolve_or_init(Klass* k, bool do_init, TRAPS);
354 static void init_archived_fields_for(Klass* k, const ArchivedKlassSubGraphInfoRecord* record);
355
356 static bool has_been_archived(oop orig_obj);
357 static void prepare_resolved_references();
358 static void archive_subgraphs();
359 static void copy_java_mirror(oop orig_mirror, oop scratch_m);
360
361 // PendingOop and PendingOopStack are used for recursively discovering all cacheable
362 // heap objects. The recursion is done using PendingOopStack so we won't overflow the
363 // C stack with deep reference chains.
364 class PendingOop {
365 oop _obj;
366 oop _referrer;
367 int _level;
368
369 public:
370 PendingOop() : _obj(nullptr), _referrer(nullptr), _level(-1) {}
371 PendingOop(oop obj, oop referrer, int level) : _obj(obj), _referrer(referrer), _level(level) {}
372
373 oop obj() const { return _obj; }
374 oop referrer() const { return _referrer; }
375 int level() const { return _level; }
376 };
377
378 class OopFieldPusher;
379 using PendingOopStack = GrowableArrayCHeap<PendingOop, mtClassShared>;
380
381 static PendingOop _object_being_archived;
382 static bool walk_one_object(PendingOopStack* stack, int level, KlassSubGraphInfo* subgraph_info,
383 oop orig_obj, oop referrer);
384
385 static void reset_archived_object_states(TRAPS);
386 static void ensure_determinism(TRAPS);
387 public:
388 static void prepare_for_archiving(TRAPS);
389 static void create_archived_object_cache() {
390 _archived_object_cache =
391 new (mtClass)ArchivedObjectCache(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE);
392 }
393 static void destroy_archived_object_cache() {
394 delete _archived_object_cache;
395 _archived_object_cache = nullptr;
396 }
397 static ArchivedObjectCache* archived_object_cache() {
398 return _archived_object_cache;
399 }
400
401 static CachedOopInfo* get_cached_oop_info(oop orig_obj);
402
403 static int archive_exception_instance(oop exception);
404
405 static bool archive_reachable_objects_from(int level,
406 KlassSubGraphInfo* subgraph_info,
407 oop orig_obj);
408
409 static bool is_dumped_interned_string(oop o);
410
411 // Scratch objects for archiving Klass::java_mirror()
412 static void set_scratch_java_mirror(Klass* k, oop mirror);
413 static void remove_scratch_objects(Klass* k);
414 static bool is_metadata_field(oop src_obj, int offset);
415 template <typename T> static void do_metadata_offsets(oop src_obj, T callback);
416 static void remap_dumped_metadata(oop src_obj, address archived_object);
417 inline static void remap_loaded_metadata(oop obj);
418 inline static oop maybe_remap_referent(bool is_java_lang_ref, size_t field_offset, oop referent);
419 static void get_pointer_info(oop src_obj, bool& has_oop_pointers, bool& has_native_pointers);
420 static void set_has_native_pointers(oop src_obj);
421 static uintptr_t archive_location(oop src_obj);
422
423 // We use the HeapShared::roots() array to make sure that objects stored in the
424 // archived heap region are not prematurely collected. These roots include:
425 //
426 // - mirrors of classes that have not yet been loaded.
427 // - ConstantPool::resolved_references() of classes that have not yet been loaded.
428 // - ArchivedKlassSubGraphInfoRecords that have not been initialized
429 // - java.lang.Module objects that have not yet been added to the module graph
430 //
431 // When a mirror M becomes referenced by a newly loaded class K, M will be removed
432 // from HeapShared::roots() via clear_root(), and K will be responsible for
433 // keeping M alive.
434 //
435 // Other types of roots are also cleared similarly when they become referenced.
436
437 // Dump-time only. Returns the index of the root, which can be used at run time to read
438 // the root using get_root(index, ...).
439 static int append_root(oop obj);
440 static GrowableArrayCHeap<oop, mtClassShared>* pending_roots() { return _pending_roots; }
441
442 // Dump-time and runtime
443 static objArrayOop root_segment(int segment_idx);
444 static oop get_root(int index, bool clear=false);
445
446 // Run-time only
447 static void clear_root(int index);
448
449 static void get_segment_indexes(int index, int& segment_index, int& internal_index);
450
451 static void setup_test_class(const char* test_class_name) PRODUCT_RETURN;
452 #endif // INCLUDE_CDS_JAVA_HEAP
453
454 public:
455 static void finish_materialize_objects() NOT_CDS_JAVA_HEAP_RETURN;
456
457 static void write_heap(AOTMappedHeapInfo* mapped_heap_info, AOTStreamedHeapInfo* streamed_heap_info) NOT_CDS_JAVA_HEAP_RETURN;
458 static objArrayOop scratch_resolved_references(ConstantPool* src);
459 static void add_scratch_resolved_references(ConstantPool* src, objArrayOop dest) NOT_CDS_JAVA_HEAP_RETURN;
460 static void init_dumping() NOT_CDS_JAVA_HEAP_RETURN;
461 static void init_scratch_objects_for_basic_type_mirrors(TRAPS) NOT_CDS_JAVA_HEAP_RETURN;
462 static void init_box_classes(TRAPS) NOT_CDS_JAVA_HEAP_RETURN;
463 static bool is_heap_region(int idx) {
464 CDS_JAVA_HEAP_ONLY(return (idx == AOTMetaspace::hp);)
465 NOT_CDS_JAVA_HEAP_RETURN_(false);
466 }
467 static void delete_tables_with_raw_oops() NOT_CDS_JAVA_HEAP_RETURN;
468
469 static void resolve_classes(JavaThread* current) NOT_CDS_JAVA_HEAP_RETURN;
470 static void initialize_from_archived_subgraph(JavaThread* current, Klass* k) NOT_CDS_JAVA_HEAP_RETURN;
471
472 static void init_for_dumping(TRAPS) NOT_CDS_JAVA_HEAP_RETURN;
473 static void init_heap_writer() NOT_CDS_JAVA_HEAP_RETURN;
474 static void write_subgraph_info_table() NOT_CDS_JAVA_HEAP_RETURN;
475 static void serialize_tables(SerializeClosure* soc) NOT_CDS_JAVA_HEAP_RETURN;
476
477 #ifndef PRODUCT
478 static bool is_a_test_class_in_unnamed_module(Klass* ik) NOT_CDS_JAVA_HEAP_RETURN_(false);
479 static void initialize_test_class_from_archive(TRAPS) NOT_CDS_JAVA_HEAP_RETURN;
480 #endif
481
482 static void initialize_java_lang_invoke(TRAPS) NOT_CDS_JAVA_HEAP_RETURN;
483 static void init_classes_for_special_subgraph(Handle loader, TRAPS) NOT_CDS_JAVA_HEAP_RETURN;
484
485 static bool is_lambda_form_klass(InstanceKlass* ik) NOT_CDS_JAVA_HEAP_RETURN_(false);
486 static bool is_lambda_proxy_klass(InstanceKlass* ik) NOT_CDS_JAVA_HEAP_RETURN_(false);
487 static bool is_string_concat_klass(InstanceKlass* ik) NOT_CDS_JAVA_HEAP_RETURN_(false);
488 static bool is_archivable_hidden_klass(InstanceKlass* ik) NOT_CDS_JAVA_HEAP_RETURN_(false);
489
490 // Used by AOTArtifactFinder
491 static void start_scanning_for_oops();
492 static void end_scanning_for_oops();
493 static void scan_java_class(Klass* k);
494 static void scan_java_mirror(oop orig_mirror);
495 static void copy_and_rescan_aot_inited_mirror(InstanceKlass* ik);
496
497 static void log_heap_roots();
498
499 static intptr_t log_target_location(oop source_oop);
500 static void log_oop_info(outputStream* st, oop source_oop, address archived_object_start, address archived_object_end);
501 static void log_oop_info(outputStream* st, oop source_oop);
502 static void log_oop_details(oop source_oop, address buffered_addr);
503 };
504
505 #endif // SHARE_CDS_HEAPSHARED_HPP