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