1 /*
2 * Copyright (c) 2023, 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/aotReferenceObjSupport.hpp"
26 #include "cds/archiveHeapWriter.hpp"
27 #include "cds/cdsConfig.hpp"
28 #include "cds/filemap.hpp"
29 #include "cds/heapShared.hpp"
30 #include "cds/regeneratedClasses.hpp"
31 #include "classfile/javaClasses.hpp"
32 #include "classfile/modules.hpp"
33 #include "classfile/systemDictionary.hpp"
34 #include "gc/shared/collectedHeap.hpp"
35 #include "memory/iterator.inline.hpp"
36 #include "memory/oopFactory.hpp"
37 #include "memory/universe.hpp"
38 #include "oops/compressedOops.hpp"
39 #include "oops/objArrayOop.inline.hpp"
40 #include "oops/oop.inline.hpp"
41 #include "oops/oopHandle.inline.hpp"
42 #include "oops/typeArrayKlass.hpp"
43 #include "oops/typeArrayOop.hpp"
44 #include "runtime/java.hpp"
45 #include "runtime/mutexLocker.hpp"
46 #include "utilities/bitMap.inline.hpp"
47 #if INCLUDE_G1GC
48 #include "gc/g1/g1CollectedHeap.hpp"
49 #include "gc/g1/g1HeapRegion.hpp"
50 #endif
51
52 #if INCLUDE_CDS_JAVA_HEAP
53
54 GrowableArrayCHeap<u1, mtClassShared>* ArchiveHeapWriter::_buffer = nullptr;
55
56 // The following are offsets from buffer_bottom()
57 size_t ArchiveHeapWriter::_buffer_used;
58
59 // Heap root segments
60 HeapRootSegments ArchiveHeapWriter::_heap_root_segments;
61
62 address ArchiveHeapWriter::_requested_bottom;
63 address ArchiveHeapWriter::_requested_top;
64
65 GrowableArrayCHeap<ArchiveHeapWriter::NativePointerInfo, mtClassShared>* ArchiveHeapWriter::_native_pointers;
66 GrowableArrayCHeap<oop, mtClassShared>* ArchiveHeapWriter::_source_objs;
67 GrowableArrayCHeap<ArchiveHeapWriter::HeapObjOrder, mtClassShared>* ArchiveHeapWriter::_source_objs_order;
68
69 ArchiveHeapWriter::BufferOffsetToSourceObjectTable*
70 ArchiveHeapWriter::_buffer_offset_to_source_obj_table = nullptr;
71
72
73 typedef ResourceHashtable<
74 size_t, // offset of a filler from ArchiveHeapWriter::buffer_bottom()
75 size_t, // size of this filler (in bytes)
76 127, // prime number
77 AnyObj::C_HEAP,
78 mtClassShared> FillersTable;
79 static FillersTable* _fillers;
80 static int _num_native_ptrs = 0;
81
82 void ArchiveHeapWriter::init() {
83 if (CDSConfig::is_dumping_heap()) {
84 Universe::heap()->collect(GCCause::_java_lang_system_gc);
85
86 _buffer_offset_to_source_obj_table = new BufferOffsetToSourceObjectTable(/*size (prime)*/36137, /*max size*/1 * M);
87 _fillers = new FillersTable();
88 _requested_bottom = nullptr;
89 _requested_top = nullptr;
90
91 _native_pointers = new GrowableArrayCHeap<NativePointerInfo, mtClassShared>(2048);
92 _source_objs = new GrowableArrayCHeap<oop, mtClassShared>(10000);
93
94 guarantee(MIN_GC_REGION_ALIGNMENT <= G1HeapRegion::min_region_size_in_words() * HeapWordSize, "must be");
95 }
96 }
97
98 void ArchiveHeapWriter::add_source_obj(oop src_obj) {
99 _source_objs->append(src_obj);
100 }
101
102 void ArchiveHeapWriter::write(GrowableArrayCHeap<oop, mtClassShared>* roots,
103 ArchiveHeapInfo* heap_info) {
104 assert(CDSConfig::is_dumping_heap(), "sanity");
105 allocate_buffer();
106 copy_source_objs_to_buffer(roots);
107 set_requested_address(heap_info);
108 relocate_embedded_oops(roots, heap_info);
109 }
110
111 bool ArchiveHeapWriter::is_too_large_to_archive(oop o) {
112 return is_too_large_to_archive(o->size());
113 }
114
115 bool ArchiveHeapWriter::is_string_too_large_to_archive(oop string) {
116 typeArrayOop value = java_lang_String::value_no_keepalive(string);
117 return is_too_large_to_archive(value);
118 }
119
120 bool ArchiveHeapWriter::is_too_large_to_archive(size_t size) {
121 assert(size > 0, "no zero-size object");
122 assert(size * HeapWordSize > size, "no overflow");
123 static_assert(MIN_GC_REGION_ALIGNMENT > 0, "must be positive");
124
125 size_t byte_size = size * HeapWordSize;
126 if (byte_size > size_t(MIN_GC_REGION_ALIGNMENT)) {
127 return true;
128 } else {
129 return false;
130 }
131 }
132
133 // Various lookup functions between source_obj, buffered_obj and requested_obj
134 bool ArchiveHeapWriter::is_in_requested_range(oop o) {
135 assert(_requested_bottom != nullptr, "do not call before _requested_bottom is initialized");
136 address a = cast_from_oop<address>(o);
137 return (_requested_bottom <= a && a < _requested_top);
138 }
139
140 oop ArchiveHeapWriter::requested_obj_from_buffer_offset(size_t offset) {
141 oop req_obj = cast_to_oop(_requested_bottom + offset);
142 assert(is_in_requested_range(req_obj), "must be");
143 return req_obj;
144 }
145
146 oop ArchiveHeapWriter::source_obj_to_requested_obj(oop src_obj) {
147 assert(CDSConfig::is_dumping_heap(), "dump-time only");
148 HeapShared::CachedOopInfo* p = HeapShared::archived_object_cache()->get(src_obj);
149 if (p != nullptr) {
150 return requested_obj_from_buffer_offset(p->buffer_offset());
151 } else {
152 return nullptr;
153 }
154 }
155
156 oop ArchiveHeapWriter::buffered_addr_to_source_obj(address buffered_addr) {
157 oop* p = _buffer_offset_to_source_obj_table->get(buffered_address_to_offset(buffered_addr));
158 if (p != nullptr) {
159 return *p;
160 } else {
161 return nullptr;
162 }
163 }
164
165 address ArchiveHeapWriter::buffered_addr_to_requested_addr(address buffered_addr) {
166 return _requested_bottom + buffered_address_to_offset(buffered_addr);
167 }
168
169 address ArchiveHeapWriter::requested_address() {
170 assert(_buffer != nullptr, "must be initialized");
171 return _requested_bottom;
172 }
173
174 void ArchiveHeapWriter::allocate_buffer() {
175 int initial_buffer_size = 100000;
176 _buffer = new GrowableArrayCHeap<u1, mtClassShared>(initial_buffer_size);
177 _buffer_used = 0;
178 ensure_buffer_space(1); // so that buffer_bottom() works
179 }
180
181 void ArchiveHeapWriter::ensure_buffer_space(size_t min_bytes) {
182 // We usually have very small heaps. If we get a huge one it's probably caused by a bug.
183 guarantee(min_bytes <= max_jint, "we dont support archiving more than 2G of objects");
184 _buffer->at_grow(to_array_index(min_bytes));
185 }
186
187 objArrayOop ArchiveHeapWriter::allocate_root_segment(size_t offset, int element_count) {
188 HeapWord* mem = offset_to_buffered_address<HeapWord *>(offset);
189 memset(mem, 0, objArrayOopDesc::object_size(element_count));
190
191 // The initialization code is copied from MemAllocator::finish and ObjArrayAllocator::initialize.
192 if (UseCompactObjectHeaders) {
193 oopDesc::release_set_mark(mem, Universe::objectArrayKlass()->prototype_header());
194 } else {
195 oopDesc::set_mark(mem, markWord::prototype());
196 oopDesc::release_set_klass(mem, Universe::objectArrayKlass());
197 }
198 arrayOopDesc::set_length(mem, element_count);
199 return objArrayOop(cast_to_oop(mem));
200 }
201
202 void ArchiveHeapWriter::root_segment_at_put(objArrayOop segment, int index, oop root) {
203 // Do not use arrayOop->obj_at_put(i, o) as arrayOop is outside the real heap!
204 if (UseCompressedOops) {
205 *segment->obj_at_addr<narrowOop>(index) = CompressedOops::encode(root);
206 } else {
207 *segment->obj_at_addr<oop>(index) = root;
208 }
209 }
210
211 void ArchiveHeapWriter::copy_roots_to_buffer(GrowableArrayCHeap<oop, mtClassShared>* roots) {
212 // Depending on the number of classes we are archiving, a single roots array may be
213 // larger than MIN_GC_REGION_ALIGNMENT. Roots are allocated first in the buffer, which
214 // allows us to chop the large array into a series of "segments". Current layout
215 // starts with zero or more segments exactly fitting MIN_GC_REGION_ALIGNMENT, and end
216 // with a single segment that may be smaller than MIN_GC_REGION_ALIGNMENT.
217 // This is simple and efficient. We do not need filler objects anywhere between the segments,
218 // or immediately after the last segment. This allows starting the object dump immediately
219 // after the roots.
220
221 assert((_buffer_used % MIN_GC_REGION_ALIGNMENT) == 0,
222 "Pre-condition: Roots start at aligned boundary: %zu", _buffer_used);
223
224 int max_elem_count = ((MIN_GC_REGION_ALIGNMENT - arrayOopDesc::header_size_in_bytes()) / heapOopSize);
225 assert(objArrayOopDesc::object_size(max_elem_count)*HeapWordSize == MIN_GC_REGION_ALIGNMENT,
226 "Should match exactly");
227
228 HeapRootSegments segments(_buffer_used,
229 roots->length(),
230 MIN_GC_REGION_ALIGNMENT,
231 max_elem_count);
232
233 int root_index = 0;
234 for (size_t seg_idx = 0; seg_idx < segments.count(); seg_idx++) {
235 int size_elems = segments.size_in_elems(seg_idx);
236 size_t size_bytes = segments.size_in_bytes(seg_idx);
237
238 size_t oop_offset = _buffer_used;
239 _buffer_used = oop_offset + size_bytes;
240 ensure_buffer_space(_buffer_used);
241
242 assert((oop_offset % MIN_GC_REGION_ALIGNMENT) == 0,
243 "Roots segment %zu start is not aligned: %zu",
244 segments.count(), oop_offset);
245
246 objArrayOop seg_oop = allocate_root_segment(oop_offset, size_elems);
247 for (int i = 0; i < size_elems; i++) {
248 root_segment_at_put(seg_oop, i, roots->at(root_index++));
249 }
250
251 log_info(aot, heap)("archived obj root segment [%d] = %zu bytes, obj = " PTR_FORMAT,
252 size_elems, size_bytes, p2i(seg_oop));
253 }
254
255 assert(root_index == roots->length(), "Post-condition: All roots are handled");
256
257 _heap_root_segments = segments;
258 }
259
260 // The goal is to sort the objects in increasing order of:
261 // - objects that have only oop pointers
262 // - objects that have both native and oop pointers
263 // - objects that have only native pointers
264 // - objects that have no pointers
265 static int oop_sorting_rank(oop o) {
266 bool has_oop_ptr, has_native_ptr;
267 HeapShared::get_pointer_info(o, has_oop_ptr, has_native_ptr);
268
269 if (has_oop_ptr) {
270 if (!has_native_ptr) {
271 return 0;
272 } else {
273 return 1;
274 }
275 } else {
276 if (has_native_ptr) {
277 return 2;
278 } else {
279 return 3;
280 }
281 }
282 }
283
284 int ArchiveHeapWriter::compare_objs_by_oop_fields(HeapObjOrder* a, HeapObjOrder* b) {
285 int rank_a = a->_rank;
286 int rank_b = b->_rank;
287
288 if (rank_a != rank_b) {
289 return rank_a - rank_b;
290 } else {
291 // If they are the same rank, sort them by their position in the _source_objs array
292 return a->_index - b->_index;
293 }
294 }
295
296 void ArchiveHeapWriter::sort_source_objs() {
297 log_info(aot)("sorting heap objects");
298 int len = _source_objs->length();
299 _source_objs_order = new GrowableArrayCHeap<HeapObjOrder, mtClassShared>(len);
300
301 for (int i = 0; i < len; i++) {
302 oop o = _source_objs->at(i);
303 int rank = oop_sorting_rank(o);
304 HeapObjOrder os = {i, rank};
305 _source_objs_order->append(os);
306 }
307 log_info(aot)("computed ranks");
308 _source_objs_order->sort(compare_objs_by_oop_fields);
309 log_info(aot)("sorting heap objects done");
310 }
311
312 void ArchiveHeapWriter::copy_source_objs_to_buffer(GrowableArrayCHeap<oop, mtClassShared>* roots) {
313 // There could be multiple root segments, which we want to be aligned by region.
314 // Putting them ahead of objects makes sure we waste no space.
315 copy_roots_to_buffer(roots);
316
317 sort_source_objs();
318 for (int i = 0; i < _source_objs_order->length(); i++) {
319 int src_obj_index = _source_objs_order->at(i)._index;
320 oop src_obj = _source_objs->at(src_obj_index);
321 HeapShared::CachedOopInfo* info = HeapShared::archived_object_cache()->get(src_obj);
322 assert(info != nullptr, "must be");
323 size_t buffer_offset = copy_one_source_obj_to_buffer(src_obj);
324 info->set_buffer_offset(buffer_offset);
325
326 _buffer_offset_to_source_obj_table->put_when_absent(buffer_offset, src_obj);
327 _buffer_offset_to_source_obj_table->maybe_grow();
328
329 if (java_lang_Module::is_instance(src_obj)) {
330 Modules::check_archived_module_oop(src_obj);
331 }
332 }
333
334 log_info(aot)("Size of heap region = %zu bytes, %d objects, %d roots, %d native ptrs",
335 _buffer_used, _source_objs->length() + 1, roots->length(), _num_native_ptrs);
336 }
337
338 size_t ArchiveHeapWriter::filler_array_byte_size(int length) {
339 size_t byte_size = objArrayOopDesc::object_size(length) * HeapWordSize;
340 return byte_size;
341 }
342
343 int ArchiveHeapWriter::filler_array_length(size_t fill_bytes) {
344 assert(is_object_aligned(fill_bytes), "must be");
345 size_t elemSize = (UseCompressedOops ? sizeof(narrowOop) : sizeof(oop));
346
347 int initial_length = to_array_length(fill_bytes / elemSize);
348 for (int length = initial_length; length >= 0; length --) {
349 size_t array_byte_size = filler_array_byte_size(length);
350 if (array_byte_size == fill_bytes) {
351 return length;
352 }
353 }
354
355 ShouldNotReachHere();
356 return -1;
357 }
358
359 HeapWord* ArchiveHeapWriter::init_filler_array_at_buffer_top(int array_length, size_t fill_bytes) {
360 assert(UseCompressedClassPointers, "Archived heap only supported for compressed klasses");
361 Klass* oak = Universe::objectArrayKlass(); // already relocated to point to archived klass
362 HeapWord* mem = offset_to_buffered_address<HeapWord*>(_buffer_used);
363 memset(mem, 0, fill_bytes);
364 narrowKlass nk = ArchiveBuilder::current()->get_requested_narrow_klass(oak);
365 if (UseCompactObjectHeaders) {
366 oopDesc::release_set_mark(mem, markWord::prototype().set_narrow_klass(nk));
367 } else {
368 oopDesc::set_mark(mem, markWord::prototype());
369 cast_to_oop(mem)->set_narrow_klass(nk);
370 }
371 arrayOopDesc::set_length(mem, array_length);
372 return mem;
373 }
374
375 void ArchiveHeapWriter::maybe_fill_gc_region_gap(size_t required_byte_size) {
376 // We fill only with arrays (so we don't need to use a single HeapWord filler if the
377 // leftover space is smaller than a zero-sized array object). Therefore, we need to
378 // make sure there's enough space of min_filler_byte_size in the current region after
379 // required_byte_size has been allocated. If not, fill the remainder of the current
380 // region.
381 size_t min_filler_byte_size = filler_array_byte_size(0);
382 size_t new_used = _buffer_used + required_byte_size + min_filler_byte_size;
383
384 const size_t cur_min_region_bottom = align_down(_buffer_used, MIN_GC_REGION_ALIGNMENT);
385 const size_t next_min_region_bottom = align_down(new_used, MIN_GC_REGION_ALIGNMENT);
386
387 if (cur_min_region_bottom != next_min_region_bottom) {
388 // Make sure that no objects span across MIN_GC_REGION_ALIGNMENT. This way
389 // we can map the region in any region-based collector.
390 assert(next_min_region_bottom > cur_min_region_bottom, "must be");
391 assert(next_min_region_bottom - cur_min_region_bottom == MIN_GC_REGION_ALIGNMENT,
392 "no buffered object can be larger than %d bytes", MIN_GC_REGION_ALIGNMENT);
393
394 const size_t filler_end = next_min_region_bottom;
395 const size_t fill_bytes = filler_end - _buffer_used;
396 assert(fill_bytes > 0, "must be");
397 ensure_buffer_space(filler_end);
398
399 int array_length = filler_array_length(fill_bytes);
400 log_info(aot, heap)("Inserting filler obj array of %d elements (%zu bytes total) @ buffer offset %zu",
401 array_length, fill_bytes, _buffer_used);
402 HeapWord* filler = init_filler_array_at_buffer_top(array_length, fill_bytes);
403 _buffer_used = filler_end;
404 _fillers->put(buffered_address_to_offset((address)filler), fill_bytes);
405 }
406 }
407
408 size_t ArchiveHeapWriter::get_filler_size_at(address buffered_addr) {
409 size_t* p = _fillers->get(buffered_address_to_offset(buffered_addr));
410 if (p != nullptr) {
411 assert(*p > 0, "filler must be larger than zero bytes");
412 return *p;
413 } else {
414 return 0; // buffered_addr is not a filler
415 }
416 }
417
418 template <typename T>
419 void update_buffered_object_field(address buffered_obj, int field_offset, T value) {
420 T* field_addr = cast_to_oop(buffered_obj)->field_addr<T>(field_offset);
421 *field_addr = value;
422 }
423
424 size_t ArchiveHeapWriter::copy_one_source_obj_to_buffer(oop src_obj) {
425 assert(!is_too_large_to_archive(src_obj), "already checked");
426 size_t old_size = src_obj->size();
427 size_t new_size = src_obj->copy_size_cds(old_size, src_obj->mark());
428 size_t byte_size = new_size * HeapWordSize;
429 assert(byte_size > 0, "no zero-size objects");
430
431 // For region-based collectors such as G1, the archive heap may be mapped into
432 // multiple regions. We need to make sure that we don't have an object that can possible
433 // span across two regions.
434 maybe_fill_gc_region_gap(byte_size);
435
436 size_t new_used = _buffer_used + byte_size;
437 assert(new_used > _buffer_used, "no wrap around");
438
439 size_t cur_min_region_bottom = align_down(_buffer_used, MIN_GC_REGION_ALIGNMENT);
440 size_t next_min_region_bottom = align_down(new_used, MIN_GC_REGION_ALIGNMENT);
441 assert(cur_min_region_bottom == next_min_region_bottom, "no object should cross minimal GC region boundaries");
442
443 ensure_buffer_space(new_used);
444
445 address from = cast_from_oop<address>(src_obj);
446 address to = offset_to_buffered_address<address>(_buffer_used);
447 assert(is_object_aligned(_buffer_used), "sanity");
448 assert(is_object_aligned(byte_size), "sanity");
449 memcpy(to, from, old_size * HeapWordSize);
450
451 // These native pointers will be restored explicitly at run time.
452 if (java_lang_Module::is_instance(src_obj)) {
453 update_buffered_object_field<ModuleEntry*>(to, java_lang_Module::module_entry_offset(), nullptr);
454 } else if (java_lang_ClassLoader::is_instance(src_obj)) {
455 #ifdef ASSERT
456 // We only archive these loaders
457 if (src_obj != SystemDictionary::java_platform_loader() &&
458 src_obj != SystemDictionary::java_system_loader()) {
459 assert(src_obj->klass()->name()->equals("jdk/internal/loader/ClassLoaders$BootClassLoader"), "must be");
460 }
461 #endif
462 update_buffered_object_field<ClassLoaderData*>(to, java_lang_ClassLoader::loader_data_offset(), nullptr);
463 }
464
465 size_t buffered_obj_offset = _buffer_used;
466 _buffer_used = new_used;
467
468 return buffered_obj_offset;
469 }
470
471 void ArchiveHeapWriter::set_requested_address(ArchiveHeapInfo* info) {
472 assert(!info->is_used(), "only set once");
473
474 size_t heap_region_byte_size = _buffer_used;
475 assert(heap_region_byte_size > 0, "must archived at least one object!");
476
477 if (UseCompressedOops) {
478 if (UseG1GC) {
479 address heap_end = (address)G1CollectedHeap::heap()->reserved().end();
480 log_info(aot, heap)("Heap end = %p", heap_end);
481 _requested_bottom = align_down(heap_end - heap_region_byte_size, G1HeapRegion::GrainBytes);
482 _requested_bottom = align_down(_requested_bottom, MIN_GC_REGION_ALIGNMENT);
483 assert(is_aligned(_requested_bottom, G1HeapRegion::GrainBytes), "sanity");
484 } else {
485 _requested_bottom = align_up(CompressedOops::begin(), MIN_GC_REGION_ALIGNMENT);
486 }
487 } else {
488 // We always write the objects as if the heap started at this address. This
489 // makes the contents of the archive heap deterministic.
490 //
491 // Note that at runtime, the heap address is selected by the OS, so the archive
492 // heap will not be mapped at 0x10000000, and the contents need to be patched.
493 _requested_bottom = align_up((address)NOCOOPS_REQUESTED_BASE, MIN_GC_REGION_ALIGNMENT);
494 }
495
496 assert(is_aligned(_requested_bottom, MIN_GC_REGION_ALIGNMENT), "sanity");
497
498 _requested_top = _requested_bottom + _buffer_used;
499
500 info->set_buffer_region(MemRegion(offset_to_buffered_address<HeapWord*>(0),
501 offset_to_buffered_address<HeapWord*>(_buffer_used)));
502 info->set_heap_root_segments(_heap_root_segments);
503 }
504
505 // Oop relocation
506
507 template <typename T> T* ArchiveHeapWriter::requested_addr_to_buffered_addr(T* p) {
508 assert(is_in_requested_range(cast_to_oop(p)), "must be");
509
510 address addr = address(p);
511 assert(addr >= _requested_bottom, "must be");
512 size_t offset = addr - _requested_bottom;
513 return offset_to_buffered_address<T*>(offset);
514 }
515
516 template <typename T> oop ArchiveHeapWriter::load_source_oop_from_buffer(T* buffered_addr) {
517 oop o = load_oop_from_buffer(buffered_addr);
518 assert(!in_buffer(cast_from_oop<address>(o)), "must point to source oop");
519 return o;
520 }
521
522 template <typename T> void ArchiveHeapWriter::store_requested_oop_in_buffer(T* buffered_addr,
523 oop request_oop) {
524 assert(is_in_requested_range(request_oop), "must be");
525 store_oop_in_buffer(buffered_addr, request_oop);
526 }
527
528 inline void ArchiveHeapWriter::store_oop_in_buffer(oop* buffered_addr, oop requested_obj) {
529 *buffered_addr = requested_obj;
530 }
531
532 inline void ArchiveHeapWriter::store_oop_in_buffer(narrowOop* buffered_addr, oop requested_obj) {
533 narrowOop val = CompressedOops::encode_not_null(requested_obj);
534 *buffered_addr = val;
535 }
536
537 oop ArchiveHeapWriter::load_oop_from_buffer(oop* buffered_addr) {
538 return *buffered_addr;
539 }
540
541 oop ArchiveHeapWriter::load_oop_from_buffer(narrowOop* buffered_addr) {
542 return CompressedOops::decode(*buffered_addr);
543 }
544
545 template <typename T> void ArchiveHeapWriter::relocate_field_in_buffer(T* field_addr_in_buffer, CHeapBitMap* oopmap) {
546 oop source_referent = load_source_oop_from_buffer<T>(field_addr_in_buffer);
547 if (source_referent != nullptr) {
548 if (java_lang_Class::is_instance(source_referent)) {
549 Klass* k = java_lang_Class::as_Klass(source_referent);
550 if (RegeneratedClasses::has_been_regenerated(k)) {
551 source_referent = RegeneratedClasses::get_regenerated_object(k)->java_mirror();
552 }
553 // When the source object points to a "real" mirror, the buffered object should point
554 // to the "scratch" mirror, which has all unarchivable fields scrubbed (to be reinstated
555 // at run time).
556 source_referent = HeapShared::scratch_java_mirror(source_referent);
557 assert(source_referent != nullptr, "must be");
558 }
559 oop request_referent = source_obj_to_requested_obj(source_referent);
560 store_requested_oop_in_buffer<T>(field_addr_in_buffer, request_referent);
561 mark_oop_pointer<T>(field_addr_in_buffer, oopmap);
562 }
563 }
564
565 template <typename T> void ArchiveHeapWriter::mark_oop_pointer(T* buffered_addr, CHeapBitMap* oopmap) {
566 T* request_p = (T*)(buffered_addr_to_requested_addr((address)buffered_addr));
567 address requested_region_bottom;
568
569 assert(request_p >= (T*)_requested_bottom, "sanity");
570 assert(request_p < (T*)_requested_top, "sanity");
571 requested_region_bottom = _requested_bottom;
572
573 // Mark the pointer in the oopmap
574 T* region_bottom = (T*)requested_region_bottom;
575 assert(request_p >= region_bottom, "must be");
576 BitMap::idx_t idx = request_p - region_bottom;
577 assert(idx < oopmap->size(), "overflow");
578 oopmap->set_bit(idx);
579 }
580
581 void ArchiveHeapWriter::update_header_for_requested_obj(oop requested_obj, oop src_obj, Klass* src_klass) {
582 assert(UseCompressedClassPointers, "Archived heap only supported for compressed klasses");
583 narrowKlass nk = ArchiveBuilder::current()->get_requested_narrow_klass(src_klass);
584 address buffered_addr = requested_addr_to_buffered_addr(cast_from_oop<address>(requested_obj));
585
586 oop fake_oop = cast_to_oop(buffered_addr);
587 if (UseCompactObjectHeaders) {
588 fake_oop->set_mark(markWord::prototype().set_narrow_klass(nk));
589 assert(fake_oop->mark().narrow_klass() != 0, "must not be null");
590 } else {
591 fake_oop->set_narrow_klass(nk);
592 }
593
594 if (src_obj == nullptr) {
595 return;
596 }
597 // We need to retain the identity_hash, because it may have been used by some hashtables
598 // in the shared heap.
599 if (!src_obj->fast_no_hash_check()) {
600 intptr_t src_hash = src_obj->identity_hash();
601 if (UseCompactObjectHeaders) {
602 markWord m = markWord::prototype().set_narrow_klass(nk);
603 m = m.copy_hashctrl_from(src_obj->mark());
604 fake_oop->set_mark(m);
605 if (m.is_hashed_not_expanded()) {
606 fake_oop->initialize_hash_if_necessary(src_obj, src_klass, m);
607 }
608 assert(!fake_oop->mark().is_not_hashed_expanded() && !fake_oop->mark().is_hashed_not_expanded(), "must not be not-hashed-moved and not be hashed-not-moved");
609 } else {
610 fake_oop->set_mark(markWord::prototype().copy_set_hash(src_hash));
611 DEBUG_ONLY(intptr_t archived_hash = fake_oop->identity_hash());
612 assert(src_hash == archived_hash, "Different hash codes: original " INTPTR_FORMAT ", archived " INTPTR_FORMAT, src_hash, archived_hash);
613 }
614 assert(fake_oop->mark().is_unlocked(), "sanity");
615 }
616 // Strip age bits.
617 fake_oop->set_mark(fake_oop->mark().set_age(0));
618 }
619
620 class ArchiveHeapWriter::EmbeddedOopRelocator: public BasicOopIterateClosure {
621 oop _src_obj;
622 address _buffered_obj;
623 CHeapBitMap* _oopmap;
624 bool _is_java_lang_ref;
625 public:
626 EmbeddedOopRelocator(oop src_obj, address buffered_obj, CHeapBitMap* oopmap) :
627 _src_obj(src_obj), _buffered_obj(buffered_obj), _oopmap(oopmap)
628 {
629 _is_java_lang_ref = AOTReferenceObjSupport::check_if_ref_obj(src_obj);
630 }
631
632 void do_oop(narrowOop *p) { EmbeddedOopRelocator::do_oop_work(p); }
633 void do_oop( oop *p) { EmbeddedOopRelocator::do_oop_work(p); }
634
635 private:
636 template <class T> void do_oop_work(T *p) {
637 int field_offset = pointer_delta_as_int((char*)p, cast_from_oop<char*>(_src_obj));
638 T* field_addr = (T*)(_buffered_obj + field_offset);
639 if (_is_java_lang_ref && AOTReferenceObjSupport::skip_field(field_offset)) {
640 // Do not copy these fields. Set them to null
641 *field_addr = (T)0x0;
642 } else {
643 ArchiveHeapWriter::relocate_field_in_buffer<T>(field_addr, _oopmap);
644 }
645 }
646 };
647
648 static void log_bitmap_usage(const char* which, BitMap* bitmap, size_t total_bits) {
649 // The whole heap is covered by total_bits, but there are only non-zero bits within [start ... end).
650 size_t start = bitmap->find_first_set_bit(0);
651 size_t end = bitmap->size();
652 log_info(aot)("%s = %7zu ... %7zu (%3zu%% ... %3zu%% = %3zu%%)", which,
653 start, end,
654 start * 100 / total_bits,
655 end * 100 / total_bits,
656 (end - start) * 100 / total_bits);
657 }
658
659 // Update all oop fields embedded in the buffered objects
660 void ArchiveHeapWriter::relocate_embedded_oops(GrowableArrayCHeap<oop, mtClassShared>* roots,
661 ArchiveHeapInfo* heap_info) {
662 size_t oopmap_unit = (UseCompressedOops ? sizeof(narrowOop) : sizeof(oop));
663 size_t heap_region_byte_size = _buffer_used;
664 heap_info->oopmap()->resize(heap_region_byte_size / oopmap_unit);
665
666 for (int i = 0; i < _source_objs_order->length(); i++) {
667 int src_obj_index = _source_objs_order->at(i)._index;
668 oop src_obj = _source_objs->at(src_obj_index);
669 HeapShared::CachedOopInfo* info = HeapShared::archived_object_cache()->get(src_obj);
670 assert(info != nullptr, "must be");
671 oop requested_obj = requested_obj_from_buffer_offset(info->buffer_offset());
672 update_header_for_requested_obj(requested_obj, src_obj, src_obj->klass());
673 address buffered_obj = offset_to_buffered_address<address>(info->buffer_offset());
674 EmbeddedOopRelocator relocator(src_obj, buffered_obj, heap_info->oopmap());
675 src_obj->oop_iterate(&relocator);
676 };
677
678 // Relocate HeapShared::roots(), which is created in copy_roots_to_buffer() and
679 // doesn't have a corresponding src_obj, so we can't use EmbeddedOopRelocator on it.
680 for (size_t seg_idx = 0; seg_idx < _heap_root_segments.count(); seg_idx++) {
681 size_t seg_offset = _heap_root_segments.segment_offset(seg_idx);
682
683 objArrayOop requested_obj = (objArrayOop)requested_obj_from_buffer_offset(seg_offset);
684 update_header_for_requested_obj(requested_obj, nullptr, Universe::objectArrayKlass());
685 address buffered_obj = offset_to_buffered_address<address>(seg_offset);
686 int length = _heap_root_segments.size_in_elems(seg_idx);
687
688 if (UseCompressedOops) {
689 for (int i = 0; i < length; i++) {
690 narrowOop* addr = (narrowOop*)(buffered_obj + objArrayOopDesc::obj_at_offset<narrowOop>(i));
691 relocate_field_in_buffer<narrowOop>(addr, heap_info->oopmap());
692 }
693 } else {
694 for (int i = 0; i < length; i++) {
695 oop* addr = (oop*)(buffered_obj + objArrayOopDesc::obj_at_offset<oop>(i));
696 relocate_field_in_buffer<oop>(addr, heap_info->oopmap());
697 }
698 }
699 }
700
701 compute_ptrmap(heap_info);
702
703 size_t total_bytes = (size_t)_buffer->length();
704 log_bitmap_usage("oopmap", heap_info->oopmap(), total_bytes / (UseCompressedOops ? sizeof(narrowOop) : sizeof(oop)));
705 log_bitmap_usage("ptrmap", heap_info->ptrmap(), total_bytes / sizeof(address));
706 }
707
708 void ArchiveHeapWriter::mark_native_pointer(oop src_obj, int field_offset) {
709 Metadata* ptr = src_obj->metadata_field_acquire(field_offset);
710 if (ptr != nullptr) {
711 NativePointerInfo info;
712 info._src_obj = src_obj;
713 info._field_offset = field_offset;
714 _native_pointers->append(info);
715 HeapShared::set_has_native_pointers(src_obj);
716 _num_native_ptrs ++;
717 }
718 }
719
720 // Do we have a jlong/jint field that's actually a pointer to a MetaspaceObj?
721 bool ArchiveHeapWriter::is_marked_as_native_pointer(ArchiveHeapInfo* heap_info, oop src_obj, int field_offset) {
722 HeapShared::CachedOopInfo* p = HeapShared::archived_object_cache()->get(src_obj);
723 assert(p != nullptr, "must be");
724
725 // requested_field_addr = the address of this field in the requested space
726 oop requested_obj = requested_obj_from_buffer_offset(p->buffer_offset());
727 Metadata** requested_field_addr = (Metadata**)(cast_from_oop<address>(requested_obj) + field_offset);
728 assert((Metadata**)_requested_bottom <= requested_field_addr && requested_field_addr < (Metadata**) _requested_top, "range check");
729
730 BitMap::idx_t idx = requested_field_addr - (Metadata**) _requested_bottom;
731 // Leading zeros have been removed so some addresses may not be in the ptrmap
732 size_t start_pos = FileMapInfo::current_info()->heap_ptrmap_start_pos();
733 if (idx < start_pos) {
734 return false;
735 } else {
736 idx -= start_pos;
737 }
738 return (idx < heap_info->ptrmap()->size()) && (heap_info->ptrmap()->at(idx) == true);
739 }
740
741 void ArchiveHeapWriter::compute_ptrmap(ArchiveHeapInfo* heap_info) {
742 int num_non_null_ptrs = 0;
743 Metadata** bottom = (Metadata**) _requested_bottom;
744 Metadata** top = (Metadata**) _requested_top; // exclusive
745 heap_info->ptrmap()->resize(top - bottom);
746
747 BitMap::idx_t max_idx = 32; // paranoid - don't make it too small
748 for (int i = 0; i < _native_pointers->length(); i++) {
749 NativePointerInfo info = _native_pointers->at(i);
750 oop src_obj = info._src_obj;
751 int field_offset = info._field_offset;
752 HeapShared::CachedOopInfo* p = HeapShared::archived_object_cache()->get(src_obj);
753 // requested_field_addr = the address of this field in the requested space
754 oop requested_obj = requested_obj_from_buffer_offset(p->buffer_offset());
755 Metadata** requested_field_addr = (Metadata**)(cast_from_oop<address>(requested_obj) + field_offset);
756 assert(bottom <= requested_field_addr && requested_field_addr < top, "range check");
757
758 // Mark this field in the bitmap
759 BitMap::idx_t idx = requested_field_addr - bottom;
760 heap_info->ptrmap()->set_bit(idx);
761 num_non_null_ptrs ++;
762 max_idx = MAX2(max_idx, idx);
763
764 // Set the native pointer to the requested address of the metadata (at runtime, the metadata will have
765 // this address if the RO/RW regions are mapped at the default location).
766
767 Metadata** buffered_field_addr = requested_addr_to_buffered_addr(requested_field_addr);
768 Metadata* native_ptr = *buffered_field_addr;
769 guarantee(native_ptr != nullptr, "sanity");
770
771 if (RegeneratedClasses::has_been_regenerated(native_ptr)) {
772 native_ptr = RegeneratedClasses::get_regenerated_object(native_ptr);
773 }
774
775 guarantee(ArchiveBuilder::current()->has_been_buffered((address)native_ptr),
776 "Metadata %p should have been archived", native_ptr);
777
778 address buffered_native_ptr = ArchiveBuilder::current()->get_buffered_addr((address)native_ptr);
779 address requested_native_ptr = ArchiveBuilder::current()->to_requested(buffered_native_ptr);
780 *buffered_field_addr = (Metadata*)requested_native_ptr;
781 }
782
783 heap_info->ptrmap()->resize(max_idx + 1);
784 log_info(aot, heap)("calculate_ptrmap: marked %d non-null native pointers for heap region (%zu bits)",
785 num_non_null_ptrs, size_t(heap_info->ptrmap()->size()));
786 }
787
788 #endif // INCLUDE_CDS_JAVA_HEAP