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