1 /*
  2  * Copyright (c) 2024, 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 "precompiled.hpp"
 26 #include "cds/archiveHeapWriter.hpp"
 27 #include "cds/cdsConfig.hpp"
 28 #include "cds/filemap.hpp"
 29 #include "cds/heapShared.hpp"
 30 #include "classfile/systemDictionary.hpp"
 31 #include "gc/shared/collectedHeap.hpp"
 32 #include "memory/iterator.inline.hpp"
 33 #include "memory/oopFactory.hpp"
 34 #include "memory/universe.hpp"
 35 #include "oops/compressedOops.hpp"
 36 #include "oops/oop.inline.hpp"
 37 #include "oops/objArrayOop.inline.hpp"
 38 #include "oops/oopHandle.inline.hpp"
 39 #include "oops/typeArrayKlass.hpp"
 40 #include "oops/typeArrayOop.hpp"
 41 #include "runtime/java.hpp"
 42 #include "runtime/mutexLocker.hpp"
 43 #include "utilities/bitMap.inline.hpp"
 44 #if INCLUDE_G1GC
 45 #include "gc/g1/g1CollectedHeap.hpp"
 46 #include "gc/g1/g1HeapRegion.hpp"
 47 #endif
 48 
 49 #if INCLUDE_CDS_JAVA_HEAP
 50 
 51 GrowableArrayCHeap<u1, mtClassShared>* ArchiveHeapWriter::_buffer = nullptr;
 52 
 53 // The following are offsets from buffer_bottom()
 54 size_t ArchiveHeapWriter::_buffer_used;
 55 size_t ArchiveHeapWriter::_heap_roots_offset;
 56 
 57 size_t ArchiveHeapWriter::_heap_roots_word_size;
 58 
 59 address ArchiveHeapWriter::_requested_bottom;
 60 address ArchiveHeapWriter::_requested_top;
 61 
 62 GrowableArrayCHeap<ArchiveHeapWriter::NativePointerInfo, mtClassShared>* ArchiveHeapWriter::_native_pointers;
 63 GrowableArrayCHeap<oop, mtClassShared>* ArchiveHeapWriter::_source_objs;
 64 GrowableArrayCHeap<ArchiveHeapWriter::HeapObjOrder, mtClassShared>* ArchiveHeapWriter::_source_objs_order;
 65 
 66 ArchiveHeapWriter::BufferOffsetToSourceObjectTable*
 67   ArchiveHeapWriter::_buffer_offset_to_source_obj_table = nullptr;
 68 
 69 
 70 typedef ResourceHashtable<
 71       size_t,    // offset of a filler from ArchiveHeapWriter::buffer_bottom()
 72       size_t,    // size of this filler (in bytes)
 73       127,       // prime number
 74       AnyObj::C_HEAP,
 75       mtClassShared> FillersTable;
 76 static FillersTable* _fillers;
 77 static int _num_native_ptrs = 0;
 78 
 79 void ArchiveHeapWriter::init() {
 80   if (HeapShared::can_write()) {
 81     Universe::heap()->collect(GCCause::_java_lang_system_gc);
 82 
 83     _buffer_offset_to_source_obj_table = new BufferOffsetToSourceObjectTable(/*size (prime)*/36137, /*max size*/1 * M);
 84     _fillers = new FillersTable();
 85     _requested_bottom = nullptr;
 86     _requested_top = nullptr;
 87 
 88     _native_pointers = new GrowableArrayCHeap<NativePointerInfo, mtClassShared>(2048);
 89     _source_objs = new GrowableArrayCHeap<oop, mtClassShared>(10000);
 90 
 91     guarantee(UseG1GC, "implementation limitation");
 92     guarantee(MIN_GC_REGION_ALIGNMENT <= G1HeapRegion::min_region_size_in_words() * HeapWordSize, "must be");
 93   }
 94 }
 95 
 96 void ArchiveHeapWriter::add_source_obj(oop src_obj) {
 97   _source_objs->append(src_obj);
 98 }
 99 
100 void ArchiveHeapWriter::write(GrowableArrayCHeap<oop, mtClassShared>* roots,
101                               ArchiveHeapInfo* heap_info) {
102   assert(HeapShared::can_write(), "sanity");
103   allocate_buffer();
104   copy_source_objs_to_buffer(roots);
105   set_requested_address(heap_info);
106   relocate_embedded_oops(roots, heap_info);
107 }
108 
109 bool ArchiveHeapWriter::is_too_large_to_archive(oop o) {
110   return is_too_large_to_archive(o->size());
111 }
112 
113 bool ArchiveHeapWriter::is_string_too_large_to_archive(oop string) {
114   typeArrayOop value = java_lang_String::value_no_keepalive(string);
115   return is_too_large_to_archive(value);
116 }
117 
118 bool ArchiveHeapWriter::is_too_large_to_archive(size_t size) {
119   assert(size > 0, "no zero-size object");
120   assert(size * HeapWordSize > size, "no overflow");
121   static_assert(MIN_GC_REGION_ALIGNMENT > 0, "must be positive");
122 
123   size_t byte_size = size * HeapWordSize;
124   if (byte_size > size_t(MIN_GC_REGION_ALIGNMENT)) {
125     return true;
126   } else {
127     return false;
128   }
129 }
130 
131 // Various lookup functions between source_obj, buffered_obj and requested_obj
132 bool ArchiveHeapWriter::is_in_requested_range(oop o) {
133   assert(_requested_bottom != nullptr, "do not call before _requested_bottom is initialized");
134   address a = cast_from_oop<address>(o);
135   return (_requested_bottom <= a && a < _requested_top);
136 }
137 
138 oop ArchiveHeapWriter::requested_obj_from_buffer_offset(size_t offset) {
139   oop req_obj = cast_to_oop(_requested_bottom + offset);
140   assert(is_in_requested_range(req_obj), "must be");
141   return req_obj;
142 }
143 
144 oop ArchiveHeapWriter::source_obj_to_requested_obj(oop src_obj) {
145   assert(CDSConfig::is_dumping_heap(), "dump-time only");
146   HeapShared::CachedOopInfo* p = HeapShared::archived_object_cache()->get(src_obj);
147   if (p != nullptr) {
148     return requested_obj_from_buffer_offset(p->buffer_offset());
149   } else {
150     return nullptr;
151   }
152 }
153 
154 oop ArchiveHeapWriter::buffered_addr_to_source_obj(address buffered_addr) {
155   oop* p = _buffer_offset_to_source_obj_table->get(buffered_address_to_offset(buffered_addr));
156   if (p != nullptr) {
157     return *p;
158   } else {
159     return nullptr;
160   }
161 }
162 
163 address ArchiveHeapWriter::buffered_addr_to_requested_addr(address buffered_addr) {
164   return _requested_bottom + buffered_address_to_offset(buffered_addr);
165 }
166 
167 oop ArchiveHeapWriter::heap_roots_requested_address() {
168   return cast_to_oop(_requested_bottom + _heap_roots_offset);
169 }
170 
171 address ArchiveHeapWriter::requested_address() {
172   assert(_buffer != nullptr, "must be initialized");
173   return _requested_bottom;
174 }
175 
176 void ArchiveHeapWriter::allocate_buffer() {
177   int initial_buffer_size = 100000;
178   _buffer = new GrowableArrayCHeap<u1, mtClassShared>(initial_buffer_size);
179   _buffer_used = 0;
180   ensure_buffer_space(1); // so that buffer_bottom() works
181 }
182 
183 void ArchiveHeapWriter::ensure_buffer_space(size_t min_bytes) {
184   // We usually have very small heaps. If we get a huge one it's probably caused by a bug.
185   guarantee(min_bytes <= max_jint, "we dont support archiving more than 2G of objects");
186   _buffer->at_grow(to_array_index(min_bytes));
187 }
188 
189 void ArchiveHeapWriter::copy_roots_to_buffer(GrowableArrayCHeap<oop, mtClassShared>* roots) {
190   Klass* k = Universe::objectArrayKlass(); // already relocated to point to archived klass
191   int length = roots->length();
192   _heap_roots_word_size = objArrayOopDesc::object_size(length);
193   size_t byte_size = _heap_roots_word_size * HeapWordSize;
194   if (byte_size >= MIN_GC_REGION_ALIGNMENT) {
195     log_error(cds, heap)("roots array is too large. Please reduce the number of classes");
196     vm_exit(1);
197   }
198 
199   maybe_fill_gc_region_gap(byte_size);
200 
201   size_t new_used = _buffer_used + byte_size;
202   ensure_buffer_space(new_used);
203 
204   HeapWord* mem = offset_to_buffered_address<HeapWord*>(_buffer_used);
205   memset(mem, 0, byte_size);
206   {
207     // This is copied from MemAllocator::finish
208     if (UseCompactObjectHeaders) {
209       narrowKlass nk = ArchiveBuilder::current()->get_requested_narrow_klass(k);
210       oopDesc::release_set_mark(mem, markWord::prototype().set_narrow_klass(nk));
211     } else {
212       oopDesc::set_mark(mem, markWord::prototype());
213       oopDesc::release_set_klass(mem, k);
214     }
215   }
216   {
217     // This is copied from ObjArrayAllocator::initialize
218     arrayOopDesc::set_length(mem, length);
219   }
220 
221   objArrayOop arrayOop = objArrayOop(cast_to_oop(mem));
222   for (int i = 0; i < length; i++) {
223     // Do not use arrayOop->obj_at_put(i, o) as arrayOop is outside of the real heap!
224     oop o = roots->at(i);
225     if (UseCompressedOops) {
226       * arrayOop->obj_at_addr<narrowOop>(i) = CompressedOops::encode(o);
227     } else {
228       * arrayOop->obj_at_addr<oop>(i) = o;
229     }
230   }
231   log_info(cds, heap)("archived obj roots[%d] = " SIZE_FORMAT " bytes, klass = %p, obj = %p", length, byte_size, k, mem);
232 
233   _heap_roots_offset = _buffer_used;
234   _buffer_used = new_used;
235 }
236 
237 static int oop_sorting_rank(oop o) {
238   bool has_oop_ptr, has_native_ptr;
239   HeapShared::get_pointer_info(o, has_oop_ptr, has_native_ptr);
240 
241   if (!has_oop_ptr) {
242     if (!has_native_ptr) {
243       return 0;
244     } else {
245       return 1;
246     }
247   } else {
248     if (has_native_ptr) {
249       return 2;
250     } else {
251       return 3;
252     }
253   }
254 }
255 
256 // The goal is to sort the objects in increasing order of:
257 // - objects that have no pointers
258 // - objects that have only native pointers
259 // - objects that have both native and oop pointers
260 // - objects that have only oop pointers
261 int ArchiveHeapWriter::compare_objs_by_oop_fields(HeapObjOrder* a, HeapObjOrder* b) {
262   int rank_a = a->_rank;
263   int rank_b = b->_rank;
264 
265   if (rank_a != rank_b) {
266     return rank_a - rank_b;
267   } else {
268     // If they are the same rank, sort them by their position in the _source_objs array
269     return a->_index - b->_index;
270   }
271 }
272 
273 void ArchiveHeapWriter::sort_source_objs() {
274   log_info(cds)("sorting heap objects");
275   int len = _source_objs->length();
276   _source_objs_order = new GrowableArrayCHeap<HeapObjOrder, mtClassShared>(len);
277 
278   for (int i = 0; i < len; i++) {
279     oop o = _source_objs->at(i);
280     int rank = oop_sorting_rank(o);
281     HeapObjOrder os = {i, rank};
282     _source_objs_order->append(os);
283   }
284   log_info(cds)("computed ranks");
285   _source_objs_order->sort(compare_objs_by_oop_fields);
286   log_info(cds)("sorting heap objects done");
287 }
288 
289 void ArchiveHeapWriter::copy_source_objs_to_buffer(GrowableArrayCHeap<oop, mtClassShared>* roots) {
290   sort_source_objs();
291   for (int i = 0; i < _source_objs_order->length(); i++) {
292     int src_obj_index = _source_objs_order->at(i)._index;
293     oop src_obj = _source_objs->at(src_obj_index);
294     HeapShared::CachedOopInfo* info = HeapShared::archived_object_cache()->get(src_obj);
295     assert(info != nullptr, "must be");
296     size_t buffer_offset = copy_one_source_obj_to_buffer(src_obj);
297     info->set_buffer_offset(buffer_offset);
298 
299     _buffer_offset_to_source_obj_table->put_when_absent(buffer_offset, src_obj);
300     _buffer_offset_to_source_obj_table->maybe_grow();
301   }
302 
303   copy_roots_to_buffer(roots);
304 
305   log_info(cds)("Size of heap region = " SIZE_FORMAT " bytes, %d objects, %d roots, %d native ptrs",
306                 _buffer_used, _source_objs->length() + 1, roots->length(), _num_native_ptrs);
307 }
308 
309 size_t ArchiveHeapWriter::filler_array_byte_size(int length) {
310   size_t byte_size = objArrayOopDesc::object_size(length) * HeapWordSize;
311   return byte_size;
312 }
313 
314 int ArchiveHeapWriter::filler_array_length(size_t fill_bytes) {
315   assert(is_object_aligned(fill_bytes), "must be");
316   size_t elemSize = (UseCompressedOops ? sizeof(narrowOop) : sizeof(oop));
317 
318   int initial_length = to_array_length(fill_bytes / elemSize);
319   for (int length = initial_length; length >= 0; length --) {
320     size_t array_byte_size = filler_array_byte_size(length);
321     if (array_byte_size == fill_bytes) {
322       return length;
323     }
324   }
325 
326   ShouldNotReachHere();
327   return -1;
328 }
329 
330 HeapWord* ArchiveHeapWriter::init_filler_array_at_buffer_top(int array_length, size_t fill_bytes) {
331   assert(UseCompressedClassPointers, "Archived heap only supported for compressed klasses");
332   Klass* oak = Universe::objectArrayKlass(); // already relocated to point to archived klass
333   HeapWord* mem = offset_to_buffered_address<HeapWord*>(_buffer_used);
334   memset(mem, 0, fill_bytes);

335   narrowKlass nk = ArchiveBuilder::current()->get_requested_narrow_klass(oak);
336   if (UseCompactObjectHeaders) {
337     oopDesc::release_set_mark(mem, markWord::prototype().set_narrow_klass(nk));
338   } else {
339     oopDesc::set_mark(mem, markWord::prototype());
340     cast_to_oop(mem)->set_narrow_klass(nk);
341   }
342   arrayOopDesc::set_length(mem, array_length);
343   return mem;
344 }
345 
346 void ArchiveHeapWriter::maybe_fill_gc_region_gap(size_t required_byte_size) {
347   // We fill only with arrays (so we don't need to use a single HeapWord filler if the
348   // leftover space is smaller than a zero-sized array object). Therefore, we need to
349   // make sure there's enough space of min_filler_byte_size in the current region after
350   // required_byte_size has been allocated. If not, fill the remainder of the current
351   // region.
352   size_t min_filler_byte_size = filler_array_byte_size(0);
353   size_t new_used = _buffer_used + required_byte_size + min_filler_byte_size;
354 
355   const size_t cur_min_region_bottom = align_down(_buffer_used, MIN_GC_REGION_ALIGNMENT);
356   const size_t next_min_region_bottom = align_down(new_used, MIN_GC_REGION_ALIGNMENT);
357 
358   if (cur_min_region_bottom != next_min_region_bottom) {
359     // Make sure that no objects span across MIN_GC_REGION_ALIGNMENT. This way
360     // we can map the region in any region-based collector.
361     assert(next_min_region_bottom > cur_min_region_bottom, "must be");
362     assert(next_min_region_bottom - cur_min_region_bottom == MIN_GC_REGION_ALIGNMENT,
363            "no buffered object can be larger than %d bytes",  MIN_GC_REGION_ALIGNMENT);
364 
365     const size_t filler_end = next_min_region_bottom;
366     const size_t fill_bytes = filler_end - _buffer_used;
367     assert(fill_bytes > 0, "must be");
368     ensure_buffer_space(filler_end);
369 
370     int array_length = filler_array_length(fill_bytes);
371     log_info(cds, heap)("Inserting filler obj array of %d elements (" SIZE_FORMAT " bytes total) @ buffer offset " SIZE_FORMAT,
372                         array_length, fill_bytes, _buffer_used);
373     HeapWord* filler = init_filler_array_at_buffer_top(array_length, fill_bytes);
374     _buffer_used = filler_end;
375     _fillers->put(buffered_address_to_offset((address)filler), fill_bytes);
376   }
377 }
378 
379 size_t ArchiveHeapWriter::get_filler_size_at(address buffered_addr) {
380   size_t* p = _fillers->get(buffered_address_to_offset(buffered_addr));
381   if (p != nullptr) {
382     assert(*p > 0, "filler must be larger than zero bytes");
383     return *p;
384   } else {
385     return 0; // buffered_addr is not a filler
386   }
387 }
388 
389 template <typename T>
390 void update_buffered_object_field(address buffered_obj, int field_offset, T value) {
391   T* field_addr = cast_to_oop(buffered_obj)->field_addr<T>(field_offset);
392   *field_addr = value;
393 }
394 
395 size_t ArchiveHeapWriter::copy_one_source_obj_to_buffer(oop src_obj) {
396   assert(!is_too_large_to_archive(src_obj), "already checked");
397   size_t byte_size = src_obj->size() * HeapWordSize;
398   assert(byte_size > 0, "no zero-size objects");
399 
400   // For region-based collectors such as G1, the archive heap may be mapped into
401   // multiple regions. We need to make sure that we don't have an object that can possible
402   // span across two regions.
403   maybe_fill_gc_region_gap(byte_size);
404 
405   size_t new_used = _buffer_used + byte_size;
406   assert(new_used > _buffer_used, "no wrap around");
407 
408   size_t cur_min_region_bottom = align_down(_buffer_used, MIN_GC_REGION_ALIGNMENT);
409   size_t next_min_region_bottom = align_down(new_used, MIN_GC_REGION_ALIGNMENT);
410   assert(cur_min_region_bottom == next_min_region_bottom, "no object should cross minimal GC region boundaries");
411 
412   ensure_buffer_space(new_used);
413 
414   address from = cast_from_oop<address>(src_obj);
415   address to = offset_to_buffered_address<address>(_buffer_used);
416   assert(is_object_aligned(_buffer_used), "sanity");
417   assert(is_object_aligned(byte_size), "sanity");
418   memcpy(to, from, byte_size);
419 
420   // These native pointers will be restored explicitly at run time.
421   if (java_lang_Module::is_instance(src_obj)) {
422     update_buffered_object_field<ModuleEntry*>(to, java_lang_Module::module_entry_offset(), nullptr);
423   } else if (java_lang_ClassLoader::is_instance(src_obj)) {
424 #ifdef ASSERT
425     // We only archive these loaders
426     if (src_obj != SystemDictionary::java_platform_loader() &&
427         src_obj != SystemDictionary::java_system_loader()) {
428       assert(src_obj->klass()->name()->equals("jdk/internal/loader/ClassLoaders$BootClassLoader"), "must be");
429     }
430 #endif
431     update_buffered_object_field<ClassLoaderData*>(to, java_lang_ClassLoader::loader_data_offset(), nullptr);
432   }
433 
434   size_t buffered_obj_offset = _buffer_used;
435   _buffer_used = new_used;
436 
437   return buffered_obj_offset;
438 }
439 
440 void ArchiveHeapWriter::set_requested_address(ArchiveHeapInfo* info) {
441   assert(!info->is_used(), "only set once");
442   assert(UseG1GC, "must be");
443   address heap_end = (address)G1CollectedHeap::heap()->reserved().end();
444   log_info(cds, heap)("Heap end = %p", heap_end);
445 
446   size_t heap_region_byte_size = _buffer_used;
447   assert(heap_region_byte_size > 0, "must archived at least one object!");
448 
449 
450   if (UseCompressedOops) {
451     _requested_bottom = align_down(heap_end - heap_region_byte_size, G1HeapRegion::GrainBytes);
452   } else {
453     // We always write the objects as if the heap started at this address. This
454     // makes the contents of the archive heap deterministic.
455     //
456     // Note that at runtime, the heap address is selected by the OS, so the archive
457     // heap will not be mapped at 0x10000000, and the contents need to be patched.
458     _requested_bottom = (address)NOCOOPS_REQUESTED_BASE;
459   }
460 
461   assert(is_aligned(_requested_bottom, G1HeapRegion::GrainBytes), "sanity");
462 
463   _requested_top = _requested_bottom + _buffer_used;
464 
465   info->set_buffer_region(MemRegion(offset_to_buffered_address<HeapWord*>(0),
466                                     offset_to_buffered_address<HeapWord*>(_buffer_used)));
467   info->set_heap_roots_offset(_heap_roots_offset);
468 }
469 
470 // Oop relocation
471 
472 template <typename T> T* ArchiveHeapWriter::requested_addr_to_buffered_addr(T* p) {
473   assert(is_in_requested_range(cast_to_oop(p)), "must be");
474 
475   address addr = address(p);
476   assert(addr >= _requested_bottom, "must be");
477   size_t offset = addr - _requested_bottom;
478   return offset_to_buffered_address<T*>(offset);
479 }
480 
481 template <typename T> oop ArchiveHeapWriter::load_source_oop_from_buffer(T* buffered_addr) {
482   oop o = load_oop_from_buffer(buffered_addr);
483   assert(!in_buffer(cast_from_oop<address>(o)), "must point to source oop");
484   return o;
485 }
486 
487 template <typename T> void ArchiveHeapWriter::store_requested_oop_in_buffer(T* buffered_addr,
488                                                                             oop request_oop) {
489   assert(is_in_requested_range(request_oop), "must be");
490   store_oop_in_buffer(buffered_addr, request_oop);
491 }
492 
493 inline void ArchiveHeapWriter::store_oop_in_buffer(oop* buffered_addr, oop requested_obj) {
494   *buffered_addr = requested_obj;
495 }
496 
497 inline void ArchiveHeapWriter::store_oop_in_buffer(narrowOop* buffered_addr, oop requested_obj) {
498   narrowOop val = CompressedOops::encode_not_null(requested_obj);
499   *buffered_addr = val;
500 }
501 
502 oop ArchiveHeapWriter::load_oop_from_buffer(oop* buffered_addr) {
503   return *buffered_addr;
504 }
505 
506 oop ArchiveHeapWriter::load_oop_from_buffer(narrowOop* buffered_addr) {
507   return CompressedOops::decode(*buffered_addr);
508 }
509 
510 template <typename T> void ArchiveHeapWriter::relocate_field_in_buffer(T* field_addr_in_buffer, CHeapBitMap* oopmap) {
511   oop source_referent = load_source_oop_from_buffer<T>(field_addr_in_buffer);
512   if (!CompressedOops::is_null(source_referent)) {
513     oop request_referent = source_obj_to_requested_obj(source_referent);
514     store_requested_oop_in_buffer<T>(field_addr_in_buffer, request_referent);
515     mark_oop_pointer<T>(field_addr_in_buffer, oopmap);
516   }
517 }
518 
519 template <typename T> void ArchiveHeapWriter::mark_oop_pointer(T* buffered_addr, CHeapBitMap* oopmap) {
520   T* request_p = (T*)(buffered_addr_to_requested_addr((address)buffered_addr));
521   address requested_region_bottom;
522 
523   assert(request_p >= (T*)_requested_bottom, "sanity");
524   assert(request_p <  (T*)_requested_top, "sanity");
525   requested_region_bottom = _requested_bottom;
526 
527   // Mark the pointer in the oopmap
528   T* region_bottom = (T*)requested_region_bottom;
529   assert(request_p >= region_bottom, "must be");
530   BitMap::idx_t idx = request_p - region_bottom;
531   assert(idx < oopmap->size(), "overflow");
532   oopmap->set_bit(idx);
533 }
534 
535 void ArchiveHeapWriter::update_header_for_requested_obj(oop requested_obj, oop src_obj,  Klass* src_klass) {
536   assert(UseCompressedClassPointers, "Archived heap only supported for compressed klasses");
537   narrowKlass nk = ArchiveBuilder::current()->get_requested_narrow_klass(src_klass);
538   address buffered_addr = requested_addr_to_buffered_addr(cast_from_oop<address>(requested_obj));
539 
540   oop fake_oop = cast_to_oop(buffered_addr);
541   if (UseCompactObjectHeaders) {
542     fake_oop->set_mark(markWord::prototype().set_narrow_klass(nk));
543   } else {
544     fake_oop->set_narrow_klass(nk);
545   }
546 
547   // We need to retain the identity_hash, because it may have been used by some hashtables
548   // in the shared heap.
549   if (src_obj != nullptr && !src_obj->fast_no_hash_check()) {
550     intptr_t src_hash = src_obj->identity_hash();
551     if (UseCompactObjectHeaders) {
552       fake_oop->set_mark(markWord::prototype().set_narrow_klass(nk).copy_set_hash(src_hash));
553     } else {
554       fake_oop->set_mark(markWord::prototype().copy_set_hash(src_hash));
555     }
556     assert(fake_oop->mark().is_unlocked(), "sanity");
557 
558     DEBUG_ONLY(intptr_t archived_hash = fake_oop->identity_hash());
559     assert(src_hash == archived_hash, "Different hash codes: original " INTPTR_FORMAT ", archived " INTPTR_FORMAT, src_hash, archived_hash);
560   }
561 }
562 
563 // Relocate an element in the buffered copy of HeapShared::roots()
564 template <typename T> void ArchiveHeapWriter::relocate_root_at(oop requested_roots, int index, CHeapBitMap* oopmap) {
565   size_t offset = (size_t)((objArrayOop)requested_roots)->obj_at_offset<T>(index);
566   relocate_field_in_buffer<T>((T*)(buffered_heap_roots_addr() + offset), oopmap);
567 }
568 
569 class ArchiveHeapWriter::EmbeddedOopRelocator: public BasicOopIterateClosure {
570   oop _src_obj;
571   address _buffered_obj;
572   CHeapBitMap* _oopmap;
573 
574 public:
575   EmbeddedOopRelocator(oop src_obj, address buffered_obj, CHeapBitMap* oopmap) :
576     _src_obj(src_obj), _buffered_obj(buffered_obj), _oopmap(oopmap) {}
577 
578   void do_oop(narrowOop *p) { EmbeddedOopRelocator::do_oop_work(p); }
579   void do_oop(      oop *p) { EmbeddedOopRelocator::do_oop_work(p); }
580 
581 private:
582   template <class T> void do_oop_work(T *p) {
583     size_t field_offset = pointer_delta(p, _src_obj, sizeof(char));
584     ArchiveHeapWriter::relocate_field_in_buffer<T>((T*)(_buffered_obj + field_offset), _oopmap);
585   }
586 };
587 
588 static void log_bitmap_usage(const char* which, BitMap* bitmap, size_t total_bits) {
589   // The whole heap is covered by total_bits, but there are only non-zero bits within [start ... end).
590   size_t start = bitmap->find_first_set_bit(0);
591   size_t end = bitmap->size();
592   log_info(cds)("%s = " SIZE_FORMAT_W(7) " ... " SIZE_FORMAT_W(7) " (%3zu%% ... %3zu%% = %3zu%%)", which,
593                 start, end,
594                 start * 100 / total_bits,
595                 end * 100 / total_bits,
596                 (end - start) * 100 / total_bits);
597 }
598 
599 // Update all oop fields embedded in the buffered objects
600 void ArchiveHeapWriter::relocate_embedded_oops(GrowableArrayCHeap<oop, mtClassShared>* roots,
601                                                ArchiveHeapInfo* heap_info) {
602   size_t oopmap_unit = (UseCompressedOops ? sizeof(narrowOop) : sizeof(oop));
603   size_t heap_region_byte_size = _buffer_used;
604   heap_info->oopmap()->resize(heap_region_byte_size   / oopmap_unit);
605 
606   for (int i = 0; i < _source_objs_order->length(); i++) {
607     int src_obj_index = _source_objs_order->at(i)._index;
608     oop src_obj = _source_objs->at(src_obj_index);
609     HeapShared::CachedOopInfo* info = HeapShared::archived_object_cache()->get(src_obj);
610     assert(info != nullptr, "must be");
611     oop requested_obj = requested_obj_from_buffer_offset(info->buffer_offset());
612     update_header_for_requested_obj(requested_obj, src_obj, src_obj->klass());
613     address buffered_obj = offset_to_buffered_address<address>(info->buffer_offset());
614     EmbeddedOopRelocator relocator(src_obj, buffered_obj, heap_info->oopmap());
615     src_obj->oop_iterate(&relocator);
616   };
617 
618   // Relocate HeapShared::roots(), which is created in copy_roots_to_buffer() and
619   // doesn't have a corresponding src_obj, so we can't use EmbeddedOopRelocator on it.
620   oop requested_roots = requested_obj_from_buffer_offset(_heap_roots_offset);
621   update_header_for_requested_obj(requested_roots, nullptr, Universe::objectArrayKlass());
622   int length = roots != nullptr ? roots->length() : 0;
623   for (int i = 0; i < length; i++) {
624     if (UseCompressedOops) {
625       relocate_root_at<narrowOop>(requested_roots, i, heap_info->oopmap());
626     } else {
627       relocate_root_at<oop>(requested_roots, i, heap_info->oopmap());
628     }
629   }
630 
631   compute_ptrmap(heap_info);
632 
633   size_t total_bytes = (size_t)_buffer->length();
634   log_bitmap_usage("oopmap", heap_info->oopmap(), total_bytes / (UseCompressedOops ? sizeof(narrowOop) : sizeof(oop)));
635   log_bitmap_usage("ptrmap", heap_info->ptrmap(), total_bytes / sizeof(address));
636 }
637 
638 void ArchiveHeapWriter::mark_native_pointer(oop src_obj, int field_offset) {
639   Metadata* ptr = src_obj->metadata_field_acquire(field_offset);
640   if (ptr != nullptr) {
641     NativePointerInfo info;
642     info._src_obj = src_obj;
643     info._field_offset = field_offset;
644     _native_pointers->append(info);
645     HeapShared::set_has_native_pointers(src_obj);
646     _num_native_ptrs ++;
647   }
648 }
649 
650 // Do we have a jlong/jint field that's actually a pointer to a MetaspaceObj?
651 bool ArchiveHeapWriter::is_marked_as_native_pointer(ArchiveHeapInfo* heap_info, oop src_obj, int field_offset) {
652   HeapShared::CachedOopInfo* p = HeapShared::archived_object_cache()->get(src_obj);
653   assert(p != nullptr, "must be");
654 
655   // requested_field_addr = the address of this field in the requested space
656   oop requested_obj = requested_obj_from_buffer_offset(p->buffer_offset());
657   Metadata** requested_field_addr = (Metadata**)(cast_from_oop<address>(requested_obj) + field_offset);
658   assert((Metadata**)_requested_bottom <= requested_field_addr && requested_field_addr < (Metadata**) _requested_top, "range check");
659 
660   BitMap::idx_t idx = requested_field_addr - (Metadata**) _requested_bottom;
661   // Leading zeros have been removed so some addresses may not be in the ptrmap
662   size_t start_pos = FileMapInfo::current_info()->heap_ptrmap_start_pos();
663   if (idx < start_pos) {
664     return false;
665   } else {
666     idx -= start_pos;
667   }
668   return (idx < heap_info->ptrmap()->size()) && (heap_info->ptrmap()->at(idx) == true);
669 }
670 
671 void ArchiveHeapWriter::compute_ptrmap(ArchiveHeapInfo* heap_info) {
672   int num_non_null_ptrs = 0;
673   Metadata** bottom = (Metadata**) _requested_bottom;
674   Metadata** top = (Metadata**) _requested_top; // exclusive
675   heap_info->ptrmap()->resize(top - bottom);
676 
677   BitMap::idx_t max_idx = 32; // paranoid - don't make it too small
678   for (int i = 0; i < _native_pointers->length(); i++) {
679     NativePointerInfo info = _native_pointers->at(i);
680     oop src_obj = info._src_obj;
681     int field_offset = info._field_offset;
682     HeapShared::CachedOopInfo* p = HeapShared::archived_object_cache()->get(src_obj);
683     // requested_field_addr = the address of this field in the requested space
684     oop requested_obj = requested_obj_from_buffer_offset(p->buffer_offset());
685     Metadata** requested_field_addr = (Metadata**)(cast_from_oop<address>(requested_obj) + field_offset);
686     assert(bottom <= requested_field_addr && requested_field_addr < top, "range check");
687 
688     // Mark this field in the bitmap
689     BitMap::idx_t idx = requested_field_addr - bottom;
690     heap_info->ptrmap()->set_bit(idx);
691     num_non_null_ptrs ++;
692     max_idx = MAX2(max_idx, idx);
693 
694     // Set the native pointer to the requested address of the metadata (at runtime, the metadata will have
695     // this address if the RO/RW regions are mapped at the default location).
696 
697     Metadata** buffered_field_addr = requested_addr_to_buffered_addr(requested_field_addr);
698     Metadata* native_ptr = *buffered_field_addr;
699     assert(native_ptr != nullptr, "sanity");
700 
701     address buffered_native_ptr = ArchiveBuilder::current()->get_buffered_addr((address)native_ptr);
702     address requested_native_ptr = ArchiveBuilder::current()->to_requested(buffered_native_ptr);
703     *buffered_field_addr = (Metadata*)requested_native_ptr;
704   }
705 
706   heap_info->ptrmap()->resize(max_idx + 1);
707   log_info(cds, heap)("calculate_ptrmap: marked %d non-null native pointers for heap region (" SIZE_FORMAT " bits)",
708                       num_non_null_ptrs, size_t(heap_info->ptrmap()->size()));
709 }
710 
711 #endif // INCLUDE_CDS_JAVA_HEAP
--- EOF ---