1 /*
  2  * Copyright (c) 2023, 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 "cds/regeneratedClasses.hpp"
 31 #include "classfile/javaClasses.hpp"
 32 #include "classfile/systemDictionary.hpp"
 33 #include "gc/shared/collectedHeap.hpp"
 34 #include "memory/iterator.inline.hpp"
 35 #include "memory/oopFactory.hpp"
 36 #include "memory/universe.hpp"
 37 #include "oops/compressedOops.hpp"
 38 #include "oops/oop.inline.hpp"
 39 #include "oops/objArrayOop.inline.hpp"
 40 #include "oops/oopHandle.inline.hpp"
 41 #include "oops/typeArrayKlass.hpp"
 42 #include "oops/typeArrayOop.hpp"
 43 #include "runtime/java.hpp"
 44 #include "runtime/mutexLocker.hpp"
 45 #include "utilities/bitMap.inline.hpp"
 46 
 47 #if INCLUDE_G1GC
 48 #include "gc/g1/g1CollectedHeap.hpp"
 49 #include "gc/g1/heapRegion.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 size_t ArchiveHeapWriter::_heap_roots_offset;
 59 
 60 size_t ArchiveHeapWriter::_heap_roots_word_size;
 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<oop, mtClassShared>* ArchiveHeapWriter::_perm_objs = nullptr;
 68 
 69 static GrowableArrayCHeap<size_t, mtClassShared> *_permobj_seg_buffered_addrs = nullptr;
 70 static GrowableArrayCHeap<size_t, mtClassShared> *_permobj_seg_bytesizes = nullptr;
 71 static GrowableArrayCHeap<int, mtClassShared> *_permobj_seg_lengths = nullptr;
 72 
 73 ArchiveHeapWriter::BufferOffsetToSourceObjectTable*
 74   ArchiveHeapWriter::_buffer_offset_to_source_obj_table = nullptr;
 75 
 76 
 77 typedef ResourceHashtable<size_t, size_t,
 78       127, // prime number
 79       AnyObj::C_HEAP,
 80       mtClassShared> FillersTable;
 81 static FillersTable* _fillers;
 82 
 83 void ArchiveHeapWriter::init() {
 84   if (HeapShared::can_write()) {
 85     Universe::heap()->collect(GCCause::_java_lang_system_gc);
 86 
 87     _buffer_offset_to_source_obj_table = new BufferOffsetToSourceObjectTable();
 88     _fillers = new FillersTable();
 89     _requested_bottom = nullptr;
 90     _requested_top = nullptr;
 91 
 92     _native_pointers = new GrowableArrayCHeap<NativePointerInfo, mtClassShared>(2048);
 93     _source_objs = new GrowableArrayCHeap<oop, mtClassShared>(10000);
 94     _permobj_seg_buffered_addrs = new GrowableArrayCHeap<size_t, mtClassShared>(5);
 95     _permobj_seg_bytesizes = new GrowableArrayCHeap<size_t, mtClassShared>(5);
 96     _permobj_seg_lengths = new GrowableArrayCHeap<int, mtClassShared>(5);
 97 
 98     guarantee(UseG1GC, "implementation limitation");
 99     guarantee(MIN_GC_REGION_ALIGNMENT <= /*G1*/HeapRegion::min_region_size_in_words() * HeapWordSize, "must be");
100   }
101 }
102 
103 void ArchiveHeapWriter::add_source_obj(oop src_obj) {
104   _source_objs->append(src_obj);
105 }
106 
107 void ArchiveHeapWriter::write(GrowableArrayCHeap<oop, mtClassShared>* roots,
108                               ArchiveHeapInfo* heap_info) {
109   ResourceMark rm;
110   GrowableArray<size_t> permobj_seg_offsets;
111   assert(HeapShared::can_write(), "sanity");
112   allocate_buffer();
113   int num_permobj = copy_source_objs_to_buffer(roots, &permobj_seg_offsets);
114   set_requested_address(heap_info);
115   relocate_embedded_oops(roots, heap_info, &permobj_seg_offsets, num_permobj);
116   if (UseCompressedOops) {
117     add_permobj_segments_to_roots<narrowOop>(roots, heap_info, &permobj_seg_offsets);
118   } else {
119     add_permobj_segments_to_roots<oop>(roots, heap_info, &permobj_seg_offsets);
120   }
121 }
122 
123 bool ArchiveHeapWriter::is_too_large_to_archive(oop o) {
124   return is_too_large_to_archive(o->size());
125 }
126 
127 bool ArchiveHeapWriter::is_string_too_large_to_archive(oop string) {
128   typeArrayOop value = java_lang_String::value_no_keepalive(string);
129   return is_too_large_to_archive(value);
130 }
131 
132 bool ArchiveHeapWriter::is_too_large_to_archive(size_t size) {
133   assert(size > 0, "no zero-size object");
134   assert(size * HeapWordSize > size, "no overflow");
135   static_assert(MIN_GC_REGION_ALIGNMENT > 0, "must be positive");
136 
137   size_t byte_size = size * HeapWordSize;
138   if (byte_size > size_t(MIN_GC_REGION_ALIGNMENT)) {
139     return true;
140   } else {
141     return false;
142   }
143 }
144 
145 // Various lookup functions between source_obj, buffered_obj and requested_obj
146 bool ArchiveHeapWriter::is_in_requested_range(oop o) {
147   assert(_requested_bottom != nullptr, "do not call before _requested_bottom is initialized");
148   address a = cast_from_oop<address>(o);
149   return (_requested_bottom <= a && a < _requested_top);
150 }
151 
152 oop ArchiveHeapWriter::requested_obj_from_buffer_offset(size_t offset) {
153   oop req_obj = cast_to_oop(_requested_bottom + offset);
154   assert(is_in_requested_range(req_obj), "must be");
155   return req_obj;
156 }
157 
158 oop ArchiveHeapWriter::source_obj_to_requested_obj(oop src_obj) {
159   assert(CDSConfig::is_dumping_heap(), "dump-time only");
160   HeapShared::CachedOopInfo* p = HeapShared::archived_object_cache()->get(src_obj);
161   if (p != nullptr) {
162     return requested_obj_from_buffer_offset(p->buffer_offset());
163   } else {
164     return nullptr;
165   }
166 }
167 
168 oop ArchiveHeapWriter::buffered_addr_to_source_obj(address buffered_addr) {
169   oop* p = _buffer_offset_to_source_obj_table->get(buffered_address_to_offset(buffered_addr));
170   if (p != nullptr) {
171     return *p;
172   } else {
173     return nullptr;
174   }
175 }
176 
177 address ArchiveHeapWriter::buffered_addr_to_requested_addr(address buffered_addr) {
178   return _requested_bottom + buffered_address_to_offset(buffered_addr);
179 }
180 
181 oop ArchiveHeapWriter::heap_roots_requested_address() {
182   return cast_to_oop(_requested_bottom + _heap_roots_offset);
183 }
184 
185 address ArchiveHeapWriter::requested_address() {
186   assert(_buffer != nullptr, "must be initialized");
187   return _requested_bottom;
188 }
189 
190 void ArchiveHeapWriter::allocate_buffer() {
191   int initial_buffer_size = 100000;
192   _buffer = new GrowableArrayCHeap<u1, mtClassShared>(initial_buffer_size);
193   _buffer_used = 0;
194   ensure_buffer_space(1); // so that buffer_bottom() works
195 }
196 
197 void ArchiveHeapWriter::ensure_buffer_space(size_t min_bytes) {
198   // We usually have very small heaps. If we get a huge one it's probably caused by a bug.
199   guarantee(min_bytes <= max_jint, "we dont support archiving more than 2G of objects");
200   _buffer->at_grow(to_array_index(min_bytes));
201 }
202 
203 size_t ArchiveHeapWriter::create_objarray_in_buffer(GrowableArrayCHeap<oop, mtClassShared>* input,
204                                                     int from,         // copy from this index in input
205                                                     int num_elms,     // copy this number of elements from input
206                                                     int extra_length, // add extra elements at the end of the copy
207                                                     size_t& objarray_word_size) {
208   Klass* k = Universe::objectArrayKlassObj(); // already relocated to point to archived klass
209   int length = num_elms + extra_length;
210   objarray_word_size = objArrayOopDesc::object_size(length);
211   size_t byte_size = objarray_word_size * HeapWordSize;
212   if (byte_size >= MIN_GC_REGION_ALIGNMENT) {
213     log_error(cds, heap)("input array is too large. Please reduce the number of classes");
214     vm_exit(1);
215   }
216 
217   maybe_fill_gc_region_gap(byte_size);
218 
219   size_t new_used = _buffer_used + byte_size;
220   ensure_buffer_space(new_used);
221 
222   HeapWord* mem = offset_to_buffered_address<HeapWord*>(_buffer_used);
223   memset(mem, 0, byte_size);
224   {
225     // This is copied from MemAllocator::finish
226     oopDesc::set_mark(mem, markWord::prototype());
227     oopDesc::release_set_klass(mem, k);
228   }
229   {
230     // This is copied from ObjArrayAllocator::initialize
231     arrayOopDesc::set_length(mem, length);
232   }
233 
234   objArrayOop arrayOop = objArrayOop(cast_to_oop(mem));
235   for (int i = 0; i < num_elms; i++) {
236     // Do not use arrayOop->obj_at_put(i, o) as arrayOop is outside of the real heap!
237     oop o = input->at(i + from);
238     if (UseCompressedOops) {
239       * arrayOop->obj_at_addr<narrowOop>(i) = CompressedOops::encode(o);
240     } else {
241       * arrayOop->obj_at_addr<oop>(i) = o;
242     }
243   }
244   log_info(cds, heap)("archived obj roots[%d] = " SIZE_FORMAT " bytes, klass = %p, obj = %p", length, byte_size, k, mem);
245 
246   size_t roots_bottom_offset = _buffer_used;
247   _buffer_used = new_used;
248 
249   return roots_bottom_offset;
250 }
251 
252 int ArchiveHeapWriter::copy_source_objs_to_buffer(GrowableArrayCHeap<oop, mtClassShared>* roots,
253                                                   GrowableArray<size_t>* permobj_seg_offsets) {
254   // Copy the contents of all the archived objects in _source_objs into the output buffer.
255   _perm_objs = new GrowableArrayCHeap<oop, mtClassShared>();
256   for (int i = 0; i < _source_objs->length(); i++) {
257     oop src_obj = _source_objs->at(i);
258     HeapShared::CachedOopInfo* info = HeapShared::archived_object_cache()->get(src_obj);
259     assert(info != nullptr, "must be");
260     size_t buffer_offset = copy_one_source_obj_to_buffer(src_obj);
261     info->set_buffer_offset(buffer_offset);
262 
263     _buffer_offset_to_source_obj_table->put(buffer_offset, src_obj);
264     // FIXME: Let's keep _perm_objs and _source_objs separate for now. We might
265     // want to add only the objects that are needed by AOT. (How??)
266     int perm_index = _perm_objs->length();
267     HeapShared::add_to_permanent_index_table(src_obj, perm_index);
268     _perm_objs->append(src_obj);
269   }
270 
271   // Create HeapShared::roots() in the output buffer. Reserve some extra slots at the end of it
272   // for the permobj_segments
273   int permobj_segments = (_perm_objs->length() + PERMOBJ_SEGMENT_MAX_LENGTH - 1) / PERMOBJ_SEGMENT_MAX_LENGTH;
274   _heap_roots_offset = create_objarray_in_buffer(roots, 0, roots->length(), permobj_segments, _heap_roots_word_size);
275 
276   // Create the permobj_segments in the output buffer.
277   for (int from = 0; from < _perm_objs->length(); from += PERMOBJ_SEGMENT_MAX_LENGTH) {
278     int num_elems = MIN2(PERMOBJ_SEGMENT_MAX_LENGTH, _perm_objs->length() - from);
279     size_t word_size;
280     size_t permobj_seg_bottom_offset = create_objarray_in_buffer(_perm_objs, from, num_elems, 0, word_size);
281     permobj_seg_offsets->append(permobj_seg_bottom_offset);
282     _permobj_seg_buffered_addrs->append(permobj_seg_bottom_offset);
283     _permobj_seg_bytesizes->append(word_size * HeapWordSize);
284     _permobj_seg_lengths->append(num_elems);
285   }
286 
287   log_info(cds)("Size of heap region = " SIZE_FORMAT " bytes, %d objects, %d roots, %d permobjs in %d segments",
288                 _buffer_used, _source_objs->length() + 2, roots->length(), _perm_objs->length(), permobj_segments);
289   assert(permobj_seg_offsets->length() == permobj_segments, "sanity");
290   HeapShared::set_permobj_segments(permobj_segments);
291   int n = _perm_objs->length();
292   return n;
293 }
294 
295 oop ArchiveHeapWriter::get_perm_object_by_index(int permanent_index) {
296   if (_perm_objs != nullptr && 0 <= permanent_index && permanent_index < _perm_objs->length()) {
297     return _perm_objs->at(permanent_index);
298   } else {
299     return nullptr;
300   }
301 }
302 
303 size_t ArchiveHeapWriter::filler_array_byte_size(int length) {
304   size_t byte_size = objArrayOopDesc::object_size(length) * HeapWordSize;
305   return byte_size;
306 }
307 
308 int ArchiveHeapWriter::filler_array_length(size_t fill_bytes) {
309   assert(is_object_aligned(fill_bytes), "must be");
310   size_t elemSize = (UseCompressedOops ? sizeof(narrowOop) : sizeof(oop));
311 
312   int initial_length = to_array_length(fill_bytes / elemSize);
313   for (int length = initial_length; length >= 0; length --) {
314     size_t array_byte_size = filler_array_byte_size(length);
315     if (array_byte_size == fill_bytes) {
316       return length;
317     }
318   }
319 
320   ShouldNotReachHere();
321   return -1;
322 }
323 
324 HeapWord* ArchiveHeapWriter::init_filler_array_at_buffer_top(int array_length, size_t fill_bytes) {
325   assert(UseCompressedClassPointers, "Archived heap only supported for compressed klasses");
326   Klass* oak = Universe::objectArrayKlassObj(); // already relocated to point to archived klass
327   HeapWord* mem = offset_to_buffered_address<HeapWord*>(_buffer_used);
328   memset(mem, 0, fill_bytes);
329   oopDesc::set_mark(mem, markWord::prototype());
330   narrowKlass nk = ArchiveBuilder::current()->get_requested_narrow_klass(oak);
331   cast_to_oop(mem)->set_narrow_klass(nk);
332   arrayOopDesc::set_length(mem, array_length);
333   return mem;
334 }
335 
336 void ArchiveHeapWriter::maybe_fill_gc_region_gap(size_t required_byte_size) {
337   // We fill only with arrays (so we don't need to use a single HeapWord filler if the
338   // leftover space is smaller than a zero-sized array object). Therefore, we need to
339   // make sure there's enough space of min_filler_byte_size in the current region after
340   // required_byte_size has been allocated. If not, fill the remainder of the current
341   // region.
342   size_t min_filler_byte_size = filler_array_byte_size(0);
343   size_t new_used = _buffer_used + required_byte_size + min_filler_byte_size;
344 
345   const size_t cur_min_region_bottom = align_down(_buffer_used, MIN_GC_REGION_ALIGNMENT);
346   const size_t next_min_region_bottom = align_down(new_used, MIN_GC_REGION_ALIGNMENT);
347 
348   if (cur_min_region_bottom != next_min_region_bottom) {
349     // Make sure that no objects span across MIN_GC_REGION_ALIGNMENT. This way
350     // we can map the region in any region-based collector.
351     assert(next_min_region_bottom > cur_min_region_bottom, "must be");
352     assert(next_min_region_bottom - cur_min_region_bottom == MIN_GC_REGION_ALIGNMENT,
353            "no buffered object can be larger than %d bytes",  MIN_GC_REGION_ALIGNMENT);
354 
355     const size_t filler_end = next_min_region_bottom;
356     const size_t fill_bytes = filler_end - _buffer_used;
357     assert(fill_bytes > 0, "must be");
358     ensure_buffer_space(filler_end);
359 
360     int array_length = filler_array_length(fill_bytes);
361     log_info(cds, heap)("Inserting filler obj array of %d elements (" SIZE_FORMAT " bytes total) @ buffer offset " SIZE_FORMAT,
362                         array_length, fill_bytes, _buffer_used);
363     HeapWord* filler = init_filler_array_at_buffer_top(array_length, fill_bytes);
364     _fillers->put(_buffer_used, fill_bytes);
365     _buffer_used = filler_end;
366   }
367 }
368 
369 size_t ArchiveHeapWriter::get_filler_size_at(address buffered_addr) {
370   size_t* p = _fillers->get(buffered_addr - buffer_bottom());
371   if (p != nullptr) {
372     assert(*p > 0, "filler must be larger than zero bytes");
373     return *p;
374   } else {
375     return 0; // buffered_addr is not a filler
376   }
377 }
378 
379 template <typename T>
380 void update_buffered_object_field(address buffered_obj, int field_offset, T value) {
381   T* field_addr = cast_to_oop(buffered_obj)->field_addr<T>(field_offset);
382   *field_addr = value;
383 }
384 
385 size_t ArchiveHeapWriter::copy_one_source_obj_to_buffer(oop src_obj) {
386   assert(!is_too_large_to_archive(src_obj), "already checked");
387   size_t byte_size = src_obj->size() * HeapWordSize;
388   assert(byte_size > 0, "no zero-size objects");
389 
390   // For region-based collectors such as G1, the archive heap may be mapped into
391   // multiple regions. We need to make sure that we don't have an object that can possible
392   // span across two regions.
393   maybe_fill_gc_region_gap(byte_size);
394 
395   size_t new_used = _buffer_used + byte_size;
396   assert(new_used > _buffer_used, "no wrap around");
397 
398   size_t cur_min_region_bottom = align_down(_buffer_used, MIN_GC_REGION_ALIGNMENT);
399   size_t next_min_region_bottom = align_down(new_used, MIN_GC_REGION_ALIGNMENT);
400   assert(cur_min_region_bottom == next_min_region_bottom, "no object should cross minimal GC region boundaries");
401 
402   ensure_buffer_space(new_used);
403 
404   address from = cast_from_oop<address>(src_obj);
405   address to = offset_to_buffered_address<address>(_buffer_used);
406   assert(is_object_aligned(_buffer_used), "sanity");
407   assert(is_object_aligned(byte_size), "sanity");
408   memcpy(to, from, byte_size);
409 
410   // These native pointers will be restored explicitly at run time.
411   if (java_lang_Module::is_instance(src_obj)) {
412     update_buffered_object_field<ModuleEntry*>(to, java_lang_Module::module_entry_offset(), nullptr);
413   } else if (java_lang_ClassLoader::is_instance(src_obj)) {
414 #ifdef ASSERT
415     // We only archive these loaders
416     if (src_obj != SystemDictionary::java_platform_loader() &&
417         src_obj != SystemDictionary::java_system_loader()) {
418       assert(src_obj->klass()->name()->equals("jdk/internal/loader/ClassLoaders$BootClassLoader"), "must be");
419     }
420 #endif
421     update_buffered_object_field<ClassLoaderData*>(to, java_lang_ClassLoader::loader_data_offset(), nullptr);
422   }
423 
424   size_t buffered_obj_offset = _buffer_used;
425   _buffer_used = new_used;
426 
427   return buffered_obj_offset;
428 }
429 
430 void ArchiveHeapWriter::set_requested_address(ArchiveHeapInfo* info) {
431   assert(!info->is_used(), "only set once");
432   assert(UseG1GC, "must be");
433   address heap_end = (address)G1CollectedHeap::heap()->reserved().end();
434   log_info(cds, heap)("Heap end = %p", heap_end);
435 
436   size_t heap_region_byte_size = _buffer_used;
437   assert(heap_region_byte_size > 0, "must archived at least one object!");
438 
439 
440   if (UseCompressedOops) {
441     _requested_bottom = align_down(heap_end - heap_region_byte_size, HeapRegion::GrainBytes);
442   } else {
443     // We always write the objects as if the heap started at this address. This
444     // makes the contents of the archive heap deterministic.
445     //
446     // Note that at runtime, the heap address is selected by the OS, so the archive
447     // heap will not be mapped at 0x10000000, and the contents need to be patched.
448     _requested_bottom = (address)NOCOOPS_REQUESTED_BASE;
449   }
450 
451   assert(is_aligned(_requested_bottom, HeapRegion::GrainBytes), "sanity");
452 
453   _requested_top = _requested_bottom + _buffer_used;
454 
455   info->set_buffer_region(MemRegion(offset_to_buffered_address<HeapWord*>(0),
456                                     offset_to_buffered_address<HeapWord*>(_buffer_used)));
457   info->set_heap_roots_offset(_heap_roots_offset);
458 }
459 
460 // Oop relocation
461 
462 template <typename T> T* ArchiveHeapWriter::requested_addr_to_buffered_addr(T* p) {
463   assert(is_in_requested_range(cast_to_oop(p)), "must be");
464 
465   address addr = address(p);
466   assert(addr >= _requested_bottom, "must be");
467   size_t offset = addr - _requested_bottom;
468   return offset_to_buffered_address<T*>(offset);
469 }
470 
471 template <typename T> oop ArchiveHeapWriter::load_source_oop_from_buffer(T* buffered_addr) {
472   oop o = load_oop_from_buffer(buffered_addr);
473   assert(!in_buffer(cast_from_oop<address>(o)), "must point to source oop");
474   return o;
475 }
476 
477 template <typename T> void ArchiveHeapWriter::store_requested_oop_in_buffer(T* buffered_addr,
478                                                                             oop request_oop) {
479   assert(is_in_requested_range(request_oop), "must be");
480   store_oop_in_buffer(buffered_addr, request_oop);
481 }
482 
483 inline void ArchiveHeapWriter::store_oop_in_buffer(oop* buffered_addr, oop requested_obj) {
484   *buffered_addr = requested_obj;
485 }
486 
487 inline void ArchiveHeapWriter::store_oop_in_buffer(narrowOop* buffered_addr, oop requested_obj) {
488   narrowOop val = CompressedOops::encode_not_null(requested_obj);
489   *buffered_addr = val;
490 }
491 
492 oop ArchiveHeapWriter::load_oop_from_buffer(oop* buffered_addr) {
493   return *buffered_addr;
494 }
495 
496 oop ArchiveHeapWriter::load_oop_from_buffer(narrowOop* buffered_addr) {
497   return CompressedOops::decode(*buffered_addr);
498 }
499 
500 template <typename T> void ArchiveHeapWriter::relocate_field_in_buffer(T* field_addr_in_buffer, CHeapBitMap* oopmap) {
501   oop source_referent = load_source_oop_from_buffer<T>(field_addr_in_buffer);
502   if (source_referent != nullptr) {
503     if (java_lang_Class::is_instance(source_referent)) {
504       source_referent = HeapShared::scratch_java_mirror(source_referent);
505       assert(source_referent != nullptr, "must be");
506     }
507     oop request_referent = source_obj_to_requested_obj(source_referent);
508     store_requested_oop_in_buffer<T>(field_addr_in_buffer, request_referent);
509     mark_oop_pointer<T>(field_addr_in_buffer, oopmap);
510   }
511 }
512 
513 template <typename T> void ArchiveHeapWriter::mark_oop_pointer(T* buffered_addr, CHeapBitMap* oopmap) {
514   T* request_p = (T*)(buffered_addr_to_requested_addr((address)buffered_addr));
515   address requested_region_bottom;
516 
517   assert(request_p >= (T*)_requested_bottom, "sanity");
518   assert(request_p <  (T*)_requested_top, "sanity");
519   requested_region_bottom = _requested_bottom;
520 
521   // Mark the pointer in the oopmap
522   T* region_bottom = (T*)requested_region_bottom;
523   assert(request_p >= region_bottom, "must be");
524   BitMap::idx_t idx = request_p - region_bottom;
525   assert(idx < oopmap->size(), "overflow");
526   oopmap->set_bit(idx);
527 }
528 
529 void ArchiveHeapWriter::update_header_for_requested_obj(oop requested_obj, oop src_obj,  Klass* src_klass) {
530   assert(UseCompressedClassPointers, "Archived heap only supported for compressed klasses");
531   narrowKlass nk = ArchiveBuilder::current()->get_requested_narrow_klass(src_klass);
532   address buffered_addr = requested_addr_to_buffered_addr(cast_from_oop<address>(requested_obj));
533 
534   oop fake_oop = cast_to_oop(buffered_addr);
535   fake_oop->set_narrow_klass(nk);
536 
537   // We need to retain the identity_hash, because it may have been used by some hashtables
538   // in the shared heap. This also has the side effect of pre-initializing the
539   // identity_hash for all shared objects, so they are less likely to be written
540   // into during run time, increasing the potential of memory sharing.
541   if (src_obj != nullptr) {
542     intptr_t src_hash = src_obj->identity_hash();
543     fake_oop->set_mark(markWord::prototype().copy_set_hash(src_hash));
544     assert(fake_oop->mark().is_unlocked(), "sanity");
545 
546     DEBUG_ONLY(intptr_t archived_hash = fake_oop->identity_hash());
547     assert(src_hash == archived_hash, "Different hash codes: original " INTPTR_FORMAT ", archived " INTPTR_FORMAT, src_hash, archived_hash);
548   }
549 }
550 
551 // Relocate an element in the buffered copy of HeapShared::roots()
552 template <typename T> void ArchiveHeapWriter::relocate_root_at(oop requested_roots, address buffered_roots_addr, int index, CHeapBitMap* oopmap) {
553   size_t offset = (size_t)((objArrayOop)requested_roots)->obj_at_offset<T>(index);
554   relocate_field_in_buffer<T>((T*)(buffered_roots_addr + offset), oopmap);
555 }
556 
557 class ArchiveHeapWriter::EmbeddedOopRelocator: public BasicOopIterateClosure {
558   oop _src_obj;
559   address _buffered_obj;
560   CHeapBitMap* _oopmap;
561 
562 public:
563   EmbeddedOopRelocator(oop src_obj, address buffered_obj, CHeapBitMap* oopmap) :
564     _src_obj(src_obj), _buffered_obj(buffered_obj), _oopmap(oopmap) {}
565 
566   void do_oop(narrowOop *p) { EmbeddedOopRelocator::do_oop_work(p); }
567   void do_oop(      oop *p) { EmbeddedOopRelocator::do_oop_work(p); }
568 
569 private:
570   template <class T> void do_oop_work(T *p) {
571     size_t field_offset = pointer_delta(p, _src_obj, sizeof(char));
572     ArchiveHeapWriter::relocate_field_in_buffer<T>((T*)(_buffered_obj + field_offset), _oopmap);
573   }
574 };
575 
576 // Update all oop fields embedded in the buffered objects
577 void ArchiveHeapWriter::relocate_embedded_oops(GrowableArrayCHeap<oop, mtClassShared>* roots,
578                                                ArchiveHeapInfo* heap_info,
579                                                GrowableArray<size_t>* permobj_seg_offsets,
580                                                int num_permobjs) {
581   size_t oopmap_unit = (UseCompressedOops ? sizeof(narrowOop) : sizeof(oop));
582   size_t heap_region_byte_size = _buffer_used;
583   heap_info->oopmap()->resize(heap_region_byte_size   / oopmap_unit);
584 
585   auto iterator = [&] (oop src_obj, HeapShared::CachedOopInfo& info) {
586     oop requested_obj = requested_obj_from_buffer_offset(info.buffer_offset());
587     update_header_for_requested_obj(requested_obj, src_obj, src_obj->klass());
588     address buffered_obj = offset_to_buffered_address<address>(info.buffer_offset());
589     EmbeddedOopRelocator relocator(src_obj, buffered_obj, heap_info->oopmap());
590     src_obj->oop_iterate(&relocator);
591   };
592   HeapShared::archived_object_cache()->iterate_all(iterator);
593 
594   // Relocate HeapShared::roots(), which is created in create_objarray_in_buffer() and
595   // doesn't have a corresponding src_obj, so we can't use EmbeddedOopRelocator on it.
596   oop requested_roots = requested_obj_from_buffer_offset(_heap_roots_offset);
597   update_header_for_requested_obj(requested_roots, nullptr, Universe::objectArrayKlassObj());
598   int length = roots != nullptr ? roots->length() : 0;
599   for (int i = 0; i < length; i++) {
600     if (UseCompressedOops) {
601       relocate_root_at<narrowOop>(requested_roots, buffered_heap_roots_addr(), i, heap_info->oopmap());
602     } else {
603       relocate_root_at<oop>(requested_roots, buffered_heap_roots_addr(), i, heap_info->oopmap());
604     }
605   }
606 
607   int num_permobjs_relocated = 0;
608   for (int i = 0; i < permobj_seg_offsets->length(); i++) {
609     int length = MIN2(PERMOBJ_SEGMENT_MAX_LENGTH, num_permobjs - num_permobjs_relocated);
610     // Relocate each of the segments. They were created in create_objarray_in_buffer() and
611     // don't have a corresponding src_obj, so we can't use EmbeddedOopRelocator.
612     size_t permobj_seg_bottom_offset = permobj_seg_offsets->at(i);
613     oop requested_permobj_seg = requested_obj_from_buffer_offset(permobj_seg_bottom_offset);
614     update_header_for_requested_obj(requested_permobj_seg, nullptr, Universe::objectArrayKlassObj());
615     for (int i = 0; i < length; i++) {
616       address buffered_addr = offset_to_buffered_address<address>(permobj_seg_bottom_offset);
617       if (UseCompressedOops) {
618         relocate_root_at<narrowOop>(requested_permobj_seg, buffered_addr, i, heap_info->oopmap());
619       } else {
620         relocate_root_at<oop>(requested_permobj_seg, buffered_addr, i, heap_info->oopmap());
621       }
622     }
623     num_permobjs_relocated += length;
624   }
625 
626   compute_ptrmap(heap_info);
627 }
628 
629 // Put the permobj_segments in the extra space that we have reserved at the end of the HeapShared::roots() array.
630 template <typename T> void ArchiveHeapWriter::add_permobj_segments_to_roots(GrowableArrayCHeap<oop, mtClassShared>* roots,
631                                                                             ArchiveHeapInfo* heap_info,
632                                                                             GrowableArray<size_t>* permobj_seg_offsets) {
633   for (int i = 0; i <  permobj_seg_offsets->length(); i++) {
634     size_t permobj_seg_bottom_offset = permobj_seg_offsets->at(i);
635     oop requested_roots = requested_obj_from_buffer_offset(_heap_roots_offset);
636     oop requested_permobj_seg = requested_obj_from_buffer_offset(permobj_seg_bottom_offset);
637     int permobj_index = roots->length() + i;
638 
639     size_t offset = (size_t)((objArrayOop)requested_roots)->obj_at_offset<T>(permobj_index);
640     T* addr = (T*)(buffered_heap_roots_addr() + offset);
641     store_requested_oop_in_buffer<T>(addr, requested_permobj_seg);
642     mark_oop_pointer<T>(addr, heap_info->oopmap());
643   }
644 }
645 
646 // If the buffered_addr is one of the permobj segments, returns the size information about this segment.
647 int ArchiveHeapWriter::get_permobj_segment_at(address buffered_addr, size_t* byte_size, int* permobj_segment_length) {
648   size_t offset = buffered_addr - buffer_bottom();
649   for (int i = 0; i < _permobj_seg_buffered_addrs->length(); i++) {
650     if (offset == _permobj_seg_buffered_addrs->at(i)) {
651       *byte_size = _permobj_seg_bytesizes->at(i);
652       *permobj_segment_length = _permobj_seg_lengths->at(i);
653       return i;
654     }
655   }
656   return -1;
657 }
658 
659 oop ArchiveHeapWriter::get_permobj_source_addr(int permobj_segment, int index) {
660   for (int i = 0; i < permobj_segment; i++) {
661     index += _permobj_seg_lengths->at(i);
662   }
663 
664   return _source_objs->at(index);
665 }
666 
667 void ArchiveHeapWriter::mark_native_pointer(oop src_obj, int field_offset) {
668   Metadata* ptr = src_obj->metadata_field_acquire(field_offset);
669   if (ptr != nullptr) {
670     NativePointerInfo info;
671     info._src_obj = src_obj;
672     info._field_offset = field_offset;
673     _native_pointers->append(info);
674     assert(ArchiveBuilder::current()->has_been_archived((address)ptr), "must be archived %p", ptr);
675   }
676 }
677 
678 // Do we have a jlong/jint field that's actually a pointer to a MetaspaceObj?
679 bool ArchiveHeapWriter::is_marked_as_native_pointer(ArchiveHeapInfo* heap_info, oop src_obj, int field_offset) {
680   HeapShared::CachedOopInfo* p = HeapShared::archived_object_cache()->get(src_obj);
681   assert(p != nullptr, "must be");
682 
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((Metadata**)_requested_bottom <= requested_field_addr && requested_field_addr < (Metadata**) _requested_top, "range check");
687 
688   BitMap::idx_t idx = requested_field_addr - (Metadata**) _requested_bottom;
689   return (idx < heap_info->ptrmap()->size()) && (heap_info->ptrmap()->at(idx) == true);
690 }
691 
692 void ArchiveHeapWriter::compute_ptrmap(ArchiveHeapInfo* heap_info) {
693   int num_non_null_ptrs = 0;
694   Metadata** bottom = (Metadata**) _requested_bottom;
695   Metadata** top = (Metadata**) _requested_top; // exclusive
696   heap_info->ptrmap()->resize(top - bottom);
697 
698   BitMap::idx_t max_idx = 32; // paranoid - don't make it too small
699   for (int i = 0; i < _native_pointers->length(); i++) {
700     NativePointerInfo info = _native_pointers->at(i);
701     oop src_obj = info._src_obj;
702     int field_offset = info._field_offset;
703     HeapShared::CachedOopInfo* p = HeapShared::archived_object_cache()->get(src_obj);
704     // requested_field_addr = the address of this field in the requested space
705     oop requested_obj = requested_obj_from_buffer_offset(p->buffer_offset());
706     Metadata** requested_field_addr = (Metadata**)(cast_from_oop<address>(requested_obj) + field_offset);
707     assert(bottom <= requested_field_addr && requested_field_addr < top, "range check");
708 
709     // Mark this field in the bitmap
710     BitMap::idx_t idx = requested_field_addr - bottom;
711     heap_info->ptrmap()->set_bit(idx);
712     num_non_null_ptrs ++;
713     max_idx = MAX2(max_idx, idx);
714 
715     // Set the native pointer to the requested address of the metadata (at runtime, the metadata will have
716     // this address if the RO/RW regions are mapped at the default location).
717 
718     Metadata** buffered_field_addr = requested_addr_to_buffered_addr(requested_field_addr);
719     Metadata* native_ptr = *buffered_field_addr;
720     assert(native_ptr != nullptr, "sanity");
721 
722     if (RegeneratedClasses::has_been_regenerated((address)native_ptr)) {
723       native_ptr = (Metadata*)RegeneratedClasses::get_regenerated_object((address)native_ptr);
724     }
725 
726     address buffered_native_ptr = ArchiveBuilder::current()->get_buffered_addr((address)native_ptr);
727     address requested_native_ptr = ArchiveBuilder::current()->to_requested(buffered_native_ptr);
728     *buffered_field_addr = (Metadata*)requested_native_ptr;
729   }
730 
731   heap_info->ptrmap()->resize(max_idx + 1);
732   log_info(cds, heap)("calculate_ptrmap: marked %d non-null native pointers for heap region (" SIZE_FORMAT " bits)",
733                       num_non_null_ptrs, size_t(heap_info->ptrmap()->size()));
734 }
735 
736 #endif // INCLUDE_CDS_JAVA_HEAP