1 /*
   2  * Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "cds/aotArtifactFinder.hpp"
  26 #include "cds/aotCacheAccess.hpp"
  27 #include "cds/aotClassLinker.hpp"
  28 #include "cds/aotCompressedPointers.hpp"
  29 #include "cds/aotLogging.hpp"
  30 #include "cds/aotMapLogger.hpp"
  31 #include "cds/aotMetaspace.hpp"
  32 #include "cds/archiveBuilder.hpp"
  33 #include "cds/archiveUtils.hpp"
  34 #include "cds/cdsConfig.hpp"
  35 #include "cds/cppVtables.hpp"
  36 #include "cds/dumpAllocStats.hpp"
  37 #include "cds/dynamicArchive.hpp"
  38 #include "cds/finalImageRecipes.hpp"
  39 #include "cds/heapShared.hpp"
  40 #include "cds/regeneratedClasses.hpp"
  41 #include "classfile/classLoader.hpp"
  42 #include "classfile/classLoaderDataShared.hpp"
  43 #include "classfile/javaClasses.hpp"
  44 #include "classfile/symbolTable.hpp"
  45 #include "classfile/systemDictionaryShared.hpp"
  46 #include "classfile/vmClasses.hpp"
  47 #include "code/aotCodeCache.hpp"
  48 #include "interpreter/abstractInterpreter.hpp"
  49 #include "jvm.h"
  50 #include "logging/log.hpp"
  51 #include "memory/allStatic.hpp"
  52 #include "memory/memoryReserver.hpp"
  53 #include "memory/memRegion.hpp"
  54 #include "memory/resourceArea.hpp"
  55 #include "oops/compressedKlass.inline.hpp"
  56 #include "oops/instanceKlass.hpp"
  57 #include "oops/methodCounters.hpp"
  58 #include "oops/methodData.hpp"
  59 #include "oops/objArrayKlass.hpp"
  60 #include "oops/objArrayOop.inline.hpp"
  61 #include "oops/oopHandle.inline.hpp"
  62 #include "oops/trainingData.hpp"
  63 #include "runtime/arguments.hpp"
  64 #include "runtime/globals_extension.hpp"
  65 #include "runtime/javaThread.hpp"
  66 #include "runtime/safepointVerifiers.hpp"
  67 #include "runtime/sharedRuntime.hpp"
  68 #include "utilities/align.hpp"
  69 #include "utilities/bitMap.inline.hpp"
  70 #include "utilities/formatBuffer.hpp"
  71 
  72 ArchiveBuilder* ArchiveBuilder::_current = nullptr;
  73 
  74 ArchiveBuilder::OtherROAllocMark::~OtherROAllocMark() {
  75   char* newtop = ArchiveBuilder::current()->_ro_region.top();
  76   ArchiveBuilder::alloc_stats()->record_other_type(int(newtop - _oldtop), true);
  77 }
  78 
  79 ArchiveBuilder::SourceObjList::SourceObjList() : _ptrmap(16 * K, mtClassShared) {
  80   _total_bytes = 0;
  81   _objs = new (mtClassShared) GrowableArray<SourceObjInfo*>(128 * K, mtClassShared);
  82 }
  83 
  84 ArchiveBuilder::SourceObjList::~SourceObjList() {
  85   delete _objs;
  86 }
  87 
  88 void ArchiveBuilder::SourceObjList::append(SourceObjInfo* src_info) {
  89   // Save this source object for copying
  90   src_info->set_id(_objs->length());
  91   _objs->append(src_info);
  92 
  93   // Prepare for marking the pointers in this source object
  94   assert(is_aligned(_total_bytes, sizeof(address)), "must be");
  95   src_info->set_ptrmap_start(_total_bytes / sizeof(address));
  96   _total_bytes = align_up(_total_bytes + (uintx)src_info->size_in_bytes(), sizeof(address));
  97   src_info->set_ptrmap_end(_total_bytes / sizeof(address));
  98 
  99   BitMap::idx_t bitmap_size_needed = BitMap::idx_t(src_info->ptrmap_end());
 100   if (_ptrmap.size() <= bitmap_size_needed) {
 101     _ptrmap.resize((bitmap_size_needed + 1) * 2);
 102   }
 103 }
 104 
 105 void ArchiveBuilder::SourceObjList::remember_embedded_pointer(SourceObjInfo* src_info, MetaspaceClosure::Ref* ref) {
 106   // src_obj contains a pointer. Remember the location of this pointer in _ptrmap,
 107   // so that we can copy/relocate it later.
 108   src_info->set_has_embedded_pointer();
 109   address src_obj = src_info->source_addr();
 110   address* field_addr = ref->addr();
 111   assert(src_info->ptrmap_start() < _total_bytes, "sanity");
 112   assert(src_info->ptrmap_end() <= _total_bytes, "sanity");
 113   assert(*field_addr != nullptr, "should have checked");
 114 
 115   intx field_offset_in_bytes = ((address)field_addr) - src_obj;
 116   DEBUG_ONLY(int src_obj_size = src_info->size_in_bytes();)
 117   assert(field_offset_in_bytes >= 0, "must be");
 118   assert(field_offset_in_bytes + intx(sizeof(intptr_t)) <= intx(src_obj_size), "must be");
 119   assert(is_aligned(field_offset_in_bytes, sizeof(address)), "must be");
 120 
 121   BitMap::idx_t idx = BitMap::idx_t(src_info->ptrmap_start() + (uintx)(field_offset_in_bytes / sizeof(address)));
 122   _ptrmap.set_bit(BitMap::idx_t(idx));
 123 }
 124 
 125 class RelocateEmbeddedPointers : public BitMapClosure {
 126   ArchiveBuilder* _builder;
 127   address _buffered_obj;
 128   BitMap::idx_t _start_idx;
 129 public:
 130   RelocateEmbeddedPointers(ArchiveBuilder* builder, address buffered_obj, BitMap::idx_t start_idx) :
 131     _builder(builder), _buffered_obj(buffered_obj), _start_idx(start_idx) {}
 132 
 133   bool do_bit(BitMap::idx_t bit_offset) {
 134     size_t field_offset = size_t(bit_offset - _start_idx) * sizeof(address);
 135     address* ptr_loc = (address*)(_buffered_obj + field_offset);
 136 
 137     address old_p_with_tags = *ptr_loc;
 138     assert(old_p_with_tags != nullptr, "null ptrs shouldn't have been marked");
 139 
 140     address old_p = MetaspaceClosure::strip_tags(old_p_with_tags);
 141     uintx tags = MetaspaceClosure::decode_tags(old_p_with_tags);
 142     address new_p = _builder->get_buffered_addr(old_p);
 143 
 144     bool nulled;
 145     if (new_p == nullptr) {
 146       // old_p had a FollowMode of set_to_null
 147       nulled = true;
 148     } else {
 149       new_p = MetaspaceClosure::add_tags(new_p, tags);
 150       nulled = false;
 151     }
 152 
 153     log_trace(aot)("Ref: [" PTR_FORMAT "] -> " PTR_FORMAT " => " PTR_FORMAT " %zu",
 154                    p2i(ptr_loc), p2i(old_p) + tags, p2i(new_p), tags);
 155 
 156     ArchivePtrMarker::set_and_mark_pointer(ptr_loc, new_p);
 157     ArchiveBuilder::current()->count_relocated_pointer(tags != 0, nulled);
 158     return true; // keep iterating the bitmap
 159   }
 160 };
 161 
 162 void ArchiveBuilder::SourceObjList::relocate(int i, ArchiveBuilder* builder) {
 163   SourceObjInfo* src_info = objs()->at(i);
 164   assert(src_info->should_copy(), "must be");
 165   BitMap::idx_t start = BitMap::idx_t(src_info->ptrmap_start()); // inclusive
 166   BitMap::idx_t end = BitMap::idx_t(src_info->ptrmap_end());     // exclusive
 167 
 168   RelocateEmbeddedPointers relocator(builder, src_info->buffered_addr(), start);
 169   _ptrmap.iterate(&relocator, start, end);
 170 }
 171 
 172 ArchiveBuilder::ArchiveBuilder() :
 173   _current_dump_region(nullptr),
 174   _buffer_bottom(nullptr),
 175   _requested_static_archive_bottom(nullptr),
 176   _requested_static_archive_top(nullptr),
 177   _requested_dynamic_archive_bottom(nullptr),
 178   _requested_dynamic_archive_top(nullptr),
 179   _mapped_static_archive_bottom(nullptr),
 180   _mapped_static_archive_top(nullptr),
 181   _buffer_to_requested_delta(0),
 182   _pz_region("pz"), // protection zone -- used only during dumping; does NOT exist in cds archive.
 183   _rw_region("rw"),
 184   _ro_region("ro"),
 185   _ac_region("ac"),
 186   _ptrmap(mtClassShared),
 187   _rw_ptrmap(mtClassShared),
 188   _ro_ptrmap(mtClassShared),
 189   _ac_ptrmap(mtClassShared),
 190   _rw_src_objs(),
 191   _ro_src_objs(),
 192   _src_obj_table(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE),
 193   _buffered_to_src_table(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE),
 194   _total_heap_region_size(0)
 195 {
 196   _klasses = new (mtClassShared) GrowableArray<Klass*>(4 * K, mtClassShared);
 197   _symbols = new (mtClassShared) GrowableArray<Symbol*>(256 * K, mtClassShared);
 198   _entropy_seed = 0x12345678;
 199   _relocated_ptr_info._num_ptrs = 0;
 200   _relocated_ptr_info._num_tagged_ptrs = 0;
 201   _relocated_ptr_info._num_nulled_ptrs = 0;
 202   assert(_current == nullptr, "must be");
 203   _current = this;
 204 }
 205 
 206 ArchiveBuilder::~ArchiveBuilder() {
 207   assert(_current == this, "must be");
 208   _current = nullptr;
 209 
 210   for (int i = 0; i < _symbols->length(); i++) {
 211     _symbols->at(i)->decrement_refcount();
 212   }
 213 
 214   delete _klasses;
 215   delete _symbols;
 216   if (_shared_rs.is_reserved()) {
 217     MemoryReserver::release(_shared_rs);
 218   }
 219 
 220   AOTArtifactFinder::dispose();
 221 }
 222 
 223 // Returns a deterministic sequence of pseudo random numbers. The main purpose is NOT
 224 // for randomness but to get good entropy for the identity_hash() of archived Symbols,
 225 // while keeping the contents of static CDS archives deterministic to ensure
 226 // reproducibility of JDK builds.
 227 int ArchiveBuilder::entropy() {
 228   assert(SafepointSynchronize::is_at_safepoint(), "needed to ensure deterministic sequence");
 229   _entropy_seed = os::next_random(_entropy_seed);
 230   return static_cast<int>(_entropy_seed);
 231 }
 232 
 233 class GatherKlassesAndSymbols : public UniqueMetaspaceClosure {
 234   ArchiveBuilder* _builder;
 235 
 236 public:
 237   GatherKlassesAndSymbols(ArchiveBuilder* builder) : _builder(builder) {}
 238 
 239   virtual bool do_unique_ref(Ref* ref, bool read_only) {
 240     return _builder->gather_klass_and_symbol(ref, read_only);
 241   }
 242 };
 243 
 244 bool ArchiveBuilder::gather_klass_and_symbol(MetaspaceClosure::Ref* ref, bool read_only) {
 245   if (ref->obj() == nullptr) {
 246     return false;
 247   }
 248   if (get_follow_mode(ref) != make_a_copy) {
 249     return false;
 250   }
 251   if (ref->type() == MetaspaceClosureType::ClassType) {
 252     Klass* klass = (Klass*)ref->obj();
 253     assert(klass->is_klass(), "must be");
 254     if (!is_excluded(klass)) {
 255       _klasses->append(klass);
 256       if (klass->is_hidden()) {
 257         assert(klass->is_instance_klass(), "must be");
 258       }
 259     }
 260   } else if (ref->type() == MetaspaceClosureType::SymbolType) {
 261     // Make sure the symbol won't be GC'ed while we are dumping the archive.
 262     Symbol* sym = (Symbol*)ref->obj();
 263     sym->increment_refcount();
 264     _symbols->append(sym);
 265   }
 266 
 267   return true; // recurse
 268 }
 269 
 270 void ArchiveBuilder::gather_klasses_and_symbols() {
 271   ResourceMark rm;
 272 
 273   AOTArtifactFinder::initialize();
 274   AOTArtifactFinder::find_artifacts();
 275 
 276   aot_log_info(aot)("Gathering classes and symbols ... ");
 277   GatherKlassesAndSymbols doit(this);
 278   iterate_roots(&doit);
 279   doit.finish();
 280 
 281   if (CDSConfig::is_dumping_static_archive()) {
 282     // To ensure deterministic contents in the static archive, we need to ensure that
 283     // we iterate the MetaspaceObjs in a deterministic order. It doesn't matter where
 284     // the MetaspaceObjs are located originally, as they are copied sequentially into
 285     // the archive during the iteration.
 286     //
 287     // The only issue here is that the symbol table and the system directories may be
 288     // randomly ordered, so we copy the symbols and klasses into two arrays and sort
 289     // them deterministically.
 290     //
 291     // During -Xshare:dump, the order of Symbol creation is strictly determined by
 292     // the SharedClassListFile (class loading is done in a single thread and the JIT
 293     // is disabled). Also, Symbols are allocated in monotonically increasing addresses
 294     // (see Symbol::operator new(size_t, int)). So if we iterate the Symbols by
 295     // ascending address order, we ensure that all Symbols are copied into deterministic
 296     // locations in the archive.
 297     //
 298     // TODO: in the future, if we want to produce deterministic contents in the
 299     // dynamic archive, we might need to sort the symbols alphabetically (also see
 300     // DynamicArchiveBuilder::sort_methods()).
 301     aot_log_info(aot)("Sorting symbols ... ");
 302     _symbols->sort(compare_symbols_by_address);
 303     sort_klasses();
 304   }
 305 
 306   AOTClassLinker::add_candidates();
 307 }
 308 
 309 int ArchiveBuilder::compare_symbols_by_address(Symbol** a, Symbol** b) {
 310   if (a[0] < b[0]) {
 311     return -1;
 312   } else {
 313     assert(a[0] > b[0], "Duplicated symbol %s unexpected", (*a)->as_C_string());
 314     return 1;
 315   }
 316 }
 317 
 318 int ArchiveBuilder::compare_klass_by_name(Klass** a, Klass** b) {
 319   return a[0]->name()->fast_compare(b[0]->name());
 320 }
 321 
 322 void ArchiveBuilder::sort_klasses() {
 323   aot_log_info(aot)("Sorting classes ... ");
 324   _klasses->sort(compare_klass_by_name);
 325 }
 326 
 327 address ArchiveBuilder::reserve_buffer() {
 328   // On 64-bit: reserve address space for archives up to the max encoded offset limit.
 329   // On 32-bit: use 256MB + AOT code size due to limited virtual address space.
 330   size_t buffer_size = LP64_ONLY(AOTCompressedPointers::MaxMetadataOffsetBytes)
 331                        NOT_LP64(256 * M + AOTCodeCache::max_aot_code_size());
 332   ReservedSpace rs = MemoryReserver::reserve(buffer_size,
 333                                              AOTMetaspace::core_region_alignment(),
 334                                              os::vm_page_size(),
 335                                              mtNone);
 336   if (!rs.is_reserved()) {
 337     aot_log_error(aot)("Failed to reserve %zu bytes of output buffer.", buffer_size);
 338     AOTMetaspace::unrecoverable_writing_error();
 339   }
 340 
 341   // buffer_bottom is the lowest address of the 2 core regions (rw, ro) when
 342   // we are copying the class metadata into the buffer.
 343   address buffer_bottom = (address)rs.base();
 344   aot_log_info(aot)("Reserved output buffer space at " PTR_FORMAT " [%zu bytes]",
 345                 p2i(buffer_bottom), buffer_size);
 346   _shared_rs = rs;
 347 
 348   _buffer_bottom = buffer_bottom;
 349 
 350   if (CDSConfig::is_dumping_static_archive()) {
 351     _current_dump_region = &_pz_region;
 352   } else {
 353     _current_dump_region = &_rw_region;
 354   }
 355   _current_dump_region->init(&_shared_rs, &_shared_vs);
 356 
 357   ArchivePtrMarker::initialize(&_ptrmap, &_shared_vs);
 358 
 359   // The bottom of the static archive should be mapped at this address by default.
 360   _requested_static_archive_bottom = (address)AOTMetaspace::requested_base_address();
 361 
 362   // The bottom of the archive (that I am writing now) should be mapped at this address by default.
 363   address my_archive_requested_bottom;
 364 
 365   if (CDSConfig::is_dumping_static_archive()) {
 366     my_archive_requested_bottom = _requested_static_archive_bottom;
 367   } else {
 368     _mapped_static_archive_bottom = (address)MetaspaceObj::aot_metaspace_base();
 369     _mapped_static_archive_top  = (address)MetaspaceObj::aot_metaspace_top();
 370     assert(_mapped_static_archive_top >= _mapped_static_archive_bottom, "must be");
 371     size_t static_archive_size = _mapped_static_archive_top - _mapped_static_archive_bottom;
 372 
 373     // At run time, we will mmap the dynamic archive at my_archive_requested_bottom
 374     _requested_static_archive_top = _requested_static_archive_bottom + static_archive_size;
 375     my_archive_requested_bottom = align_up(_requested_static_archive_top, AOTMetaspace::core_region_alignment());
 376 
 377     _requested_dynamic_archive_bottom = my_archive_requested_bottom;
 378   }
 379 
 380   _buffer_to_requested_delta = my_archive_requested_bottom - _buffer_bottom;
 381 
 382   address my_archive_requested_top = my_archive_requested_bottom + buffer_size;
 383   if (my_archive_requested_bottom <  _requested_static_archive_bottom ||
 384       my_archive_requested_top    <= _requested_static_archive_bottom) {
 385     // Size overflow.
 386     aot_log_error(aot)("my_archive_requested_bottom = " INTPTR_FORMAT, p2i(my_archive_requested_bottom));
 387     aot_log_error(aot)("my_archive_requested_top    = " INTPTR_FORMAT, p2i(my_archive_requested_top));
 388     aot_log_error(aot)("SharedBaseAddress (" INTPTR_FORMAT ") is too high. "
 389                    "Please rerun java -Xshare:dump with a lower value", p2i(_requested_static_archive_bottom));
 390     AOTMetaspace::unrecoverable_writing_error();
 391   }
 392 
 393   if (CDSConfig::is_dumping_static_archive()) {
 394     // We don't want any valid object to be at the very bottom of the archive.
 395     // See ArchivePtrMarker::mark_pointer().
 396     _pz_region.allocate(AOTMetaspace::protection_zone_size());
 397     start_dump_region(&_rw_region);
 398   }
 399 
 400   return buffer_bottom;
 401 }
 402 
 403 void ArchiveBuilder::iterate_sorted_roots(MetaspaceClosure* it) {
 404   int num_symbols = _symbols->length();
 405   for (int i = 0; i < num_symbols; i++) {
 406     it->push(_symbols->adr_at(i));
 407   }
 408 
 409   int num_klasses = _klasses->length();
 410   for (int i = 0; i < num_klasses; i++) {
 411     it->push(_klasses->adr_at(i));
 412   }
 413 
 414   iterate_roots(it);
 415 }
 416 
 417 class GatherSortedSourceObjs : public MetaspaceClosure {
 418   ArchiveBuilder* _builder;
 419 
 420 public:
 421   GatherSortedSourceObjs(ArchiveBuilder* builder) : _builder(builder) {}
 422 
 423   virtual bool do_ref(Ref* ref, bool read_only) {
 424     return _builder->gather_one_source_obj(ref, read_only);
 425   }
 426 };
 427 
 428 bool ArchiveBuilder::gather_one_source_obj(MetaspaceClosure::Ref* ref, bool read_only) {
 429   address src_obj = ref->obj();
 430   if (src_obj == nullptr) {
 431     return false;
 432   }
 433 
 434   remember_embedded_pointer_in_enclosing_obj(ref);
 435   if (RegeneratedClasses::has_been_regenerated(src_obj)) {
 436     // No need to copy it. We will later relocate it to point to the regenerated klass/method.
 437     return false;
 438   }
 439 
 440   FollowMode follow_mode = get_follow_mode(ref);
 441   SourceObjInfo src_info(ref, read_only, follow_mode);
 442   bool created;
 443   SourceObjInfo* p = _src_obj_table.put_if_absent(src_obj, src_info, &created);
 444   if (created) {
 445     if (_src_obj_table.maybe_grow()) {
 446       log_info(aot, hashtables)("Expanded _src_obj_table table to %d", _src_obj_table.table_size());
 447     }
 448   }
 449 
 450 #ifdef ASSERT
 451   if (ref->type() == MetaspaceClosureType::MethodType) {
 452     Method* m = (Method*)ref->obj();
 453     assert(!RegeneratedClasses::has_been_regenerated((address)m->method_holder()),
 454            "Should not archive methods in a class that has been regenerated");
 455   }
 456 #endif
 457 
 458   if (ref->type() == MetaspaceClosureType::MethodDataType) {
 459     MethodData* md = (MethodData*)ref->obj();
 460     md->clean_method_data(false /* always_clean */);
 461   }
 462 
 463   assert(p->read_only() == src_info.read_only(), "must be");
 464 
 465   if (created && src_info.should_copy()) {
 466     if (read_only) {
 467       _ro_src_objs.append(p);
 468     } else {
 469       _rw_src_objs.append(p);
 470     }
 471     return true; // Need to recurse into this ref only if we are copying it
 472   } else {
 473     return false;
 474   }
 475 }
 476 
 477 void ArchiveBuilder::record_regenerated_object(address orig_src_obj, address regen_src_obj) {
 478   // Record the fact that orig_src_obj has been replaced by regen_src_obj. All calls to get_buffered_addr(orig_src_obj)
 479   // should return the same value as get_buffered_addr(regen_src_obj).
 480   SourceObjInfo* p = _src_obj_table.get(regen_src_obj);
 481   assert(p != nullptr, "regenerated object should always be dumped");
 482   SourceObjInfo orig_src_info(orig_src_obj, p);
 483   bool created;
 484   _src_obj_table.put_if_absent(orig_src_obj, orig_src_info, &created);
 485   assert(created, "We shouldn't have archived the original copy of a regenerated object");
 486 }
 487 
 488 // Remember that we have a pointer inside ref->enclosing_obj() that points to ref->obj()
 489 void ArchiveBuilder::remember_embedded_pointer_in_enclosing_obj(MetaspaceClosure::Ref* ref) {
 490   assert(ref->obj() != nullptr, "should have checked");
 491 
 492   address enclosing_obj = ref->enclosing_obj();
 493   if (enclosing_obj == nullptr) {
 494     return;
 495   }
 496 
 497   // We are dealing with 3 addresses:
 498   // address o    = ref->obj(): We have found an object whose address is o.
 499   // address* mpp = ref->mpp(): The object o is pointed to by a pointer whose address is mpp.
 500   //                            I.e., (*mpp == o)
 501   // enclosing_obj            : If non-null, it is the object which has a field that points to o.
 502   //                            mpp is the address if that field.
 503   //
 504   // Example: We have an array whose first element points to a Method:
 505   //     Method* o                     = 0x0000abcd;
 506   //     Array<Method*>* enclosing_obj = 0x00001000;
 507   //     enclosing_obj->at_put(0, o);
 508   //
 509   // We the MetaspaceClosure iterates on the very first element of this array, we have
 510   //     ref->obj()           == 0x0000abcd   (the Method)
 511   //     ref->mpp()           == 0x00001008   (the location of the first element in the array)
 512   //     ref->enclosing_obj() == 0x00001000   (the Array that contains the Method)
 513   //
 514   // We use the above information to mark the bitmap to indicate that there's a pointer on address 0x00001008.
 515   SourceObjInfo* src_info = _src_obj_table.get(enclosing_obj);
 516   if (src_info == nullptr || !src_info->should_copy()) {
 517     // source objects of point_to_it/set_to_null types are not copied
 518     // so we don't need to remember their pointers.
 519   } else {
 520     if (src_info->read_only()) {
 521       _ro_src_objs.remember_embedded_pointer(src_info, ref);
 522     } else {
 523       _rw_src_objs.remember_embedded_pointer(src_info, ref);
 524     }
 525   }
 526 }
 527 
 528 void ArchiveBuilder::gather_source_objs() {
 529   ResourceMark rm;
 530   aot_log_info(aot)("Gathering all archivable objects ... ");
 531   gather_klasses_and_symbols();
 532   GatherSortedSourceObjs doit(this);
 533   iterate_sorted_roots(&doit);
 534   doit.finish();
 535 }
 536 
 537 bool ArchiveBuilder::is_excluded(Klass* klass) {
 538   if (klass->is_instance_klass()) {
 539     InstanceKlass* ik = InstanceKlass::cast(klass);
 540     return SystemDictionaryShared::is_excluded_class(ik);
 541   } else if (klass->is_objArray_klass()) {
 542     Klass* bottom = ObjArrayKlass::cast(klass)->bottom_klass();
 543     if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache_static_region(bottom)) {
 544       // The bottom class is in the static archive so it's clearly not excluded.
 545       return false;
 546     } else if (bottom->is_instance_klass()) {
 547       return SystemDictionaryShared::is_excluded_class(InstanceKlass::cast(bottom));
 548     }
 549   }
 550 
 551   return false;
 552 }
 553 
 554 ArchiveBuilder::FollowMode ArchiveBuilder::get_follow_mode(MetaspaceClosure::Ref *ref) {
 555   address obj = ref->obj();
 556   if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(obj)) {
 557     // Don't dump existing shared metadata again.
 558     return point_to_it;
 559   } else if (ref->type() == MetaspaceClosureType::MethodDataType ||
 560              ref->type() == MetaspaceClosureType::MethodCountersType ||
 561              ref->type() == MetaspaceClosureType::KlassTrainingDataType ||
 562              ref->type() == MetaspaceClosureType::MethodTrainingDataType ||
 563              ref->type() == MetaspaceClosureType::CompileTrainingDataType) {
 564     return (TrainingData::need_data() || TrainingData::assembling_data()) ? make_a_copy : set_to_null;
 565   } else if (ref->type() == MetaspaceClosureType::AdapterHandlerEntryType) {
 566     return CDSConfig::is_dumping_adapters() ? make_a_copy : set_to_null;
 567   } else {
 568     if (ref->type() == MetaspaceClosureType::ClassType) {
 569       Klass* klass = (Klass*)ref->obj();
 570       assert(klass->is_klass(), "must be");
 571       if (RegeneratedClasses::has_been_regenerated(klass)) {
 572         klass = RegeneratedClasses::get_regenerated_object(klass);
 573       }
 574       if (is_excluded(klass)) {
 575         ResourceMark rm;
 576         aot_log_trace(aot)("pointer set to null: class (excluded): %s", klass->external_name());
 577         return set_to_null;
 578       }
 579       if (klass->is_array_klass() && CDSConfig::is_dumping_dynamic_archive()) {
 580         ResourceMark rm;
 581         aot_log_trace(aot)("pointer set to null: array class not supported in dynamic region: %s", klass->external_name());
 582         return set_to_null;
 583       }
 584     }
 585 
 586     return make_a_copy;
 587   }
 588 }
 589 
 590 void ArchiveBuilder::start_dump_region(DumpRegion* next) {
 591   current_dump_region()->pack(next);
 592   _current_dump_region = next;
 593 }
 594 
 595 char* ArchiveBuilder::ro_strdup(const char* s) {
 596   char* archived_str = ro_region_alloc((int)strlen(s) + 1);
 597   strcpy(archived_str, s);
 598   return archived_str;
 599 }
 600 
 601 // The objects that have embedded pointers will sink
 602 // towards the end of the list. This ensures we have a maximum
 603 // number of leading zero bits in the relocation bitmap.
 604 int ArchiveBuilder::compare_src_objs(SourceObjInfo** a, SourceObjInfo** b) {
 605   if ((*a)->has_embedded_pointer() && !(*b)->has_embedded_pointer()) {
 606     return 1;
 607   } else if (!(*a)->has_embedded_pointer() && (*b)->has_embedded_pointer()) {
 608     return -1;
 609   } else {
 610     // This is necessary to keep the sorting order stable. Otherwise the
 611     // archive's contents may not be deterministic.
 612     return (*a)->id() - (*b)->id();
 613   }
 614 }
 615 
 616 void ArchiveBuilder::sort_metadata_objs() {
 617   _rw_src_objs.objs()->sort(compare_src_objs);
 618   _ro_src_objs.objs()->sort(compare_src_objs);
 619 }
 620 
 621 void ArchiveBuilder::dump_rw_metadata() {
 622   ResourceMark rm;
 623   aot_log_info(aot)("Allocating RW objects ... ");
 624   make_shallow_copies(&_rw_region, &_rw_src_objs);
 625 }
 626 
 627 void ArchiveBuilder::dump_ro_metadata() {
 628   ResourceMark rm;
 629   aot_log_info(aot)("Allocating RO objects ... ");
 630 
 631   start_dump_region(&_ro_region);
 632   make_shallow_copies(&_ro_region, &_ro_src_objs);
 633   RegeneratedClasses::record_regenerated_objects();
 634   DumpRegion::report_gaps(&_alloc_stats);
 635 }
 636 
 637 void ArchiveBuilder::make_shallow_copies(DumpRegion *dump_region,
 638                                          const ArchiveBuilder::SourceObjList* src_objs) {
 639   for (int i = 0; i < src_objs->objs()->length(); i++) {
 640     make_shallow_copy(dump_region, src_objs->objs()->at(i));
 641   }
 642   aot_log_info(aot)("done (%d objects)", src_objs->objs()->length());
 643 }
 644 
 645 void ArchiveBuilder::make_shallow_copy(DumpRegion *dump_region, SourceObjInfo* src_info) {
 646   address src = src_info->source_addr();
 647   int bytes = src_info->size_in_bytes();
 648   char* dest = dump_region->allocate_metaspace_obj(bytes, src, src_info->type(),
 649                                                    src_info->read_only(), &_alloc_stats);
 650 
 651   memcpy(dest, src, bytes);
 652 
 653   // Update the hash of buffered sorted symbols for static dump so that the symbols have deterministic contents
 654   if (CDSConfig::is_dumping_static_archive() && (src_info->type() == MetaspaceClosureType::SymbolType)) {
 655     Symbol* buffered_symbol = (Symbol*)dest;
 656     assert(((Symbol*)src)->is_permanent(), "archived symbols must be permanent");
 657     buffered_symbol->update_identity_hash();
 658   }
 659 
 660   {
 661     bool created;
 662     _buffered_to_src_table.put_if_absent((address)dest, src, &created);
 663     assert(created, "must be");
 664     if (_buffered_to_src_table.maybe_grow()) {
 665       log_info(aot, hashtables)("Expanded _buffered_to_src_table table to %d", _buffered_to_src_table.table_size());
 666     }
 667   }
 668 
 669   intptr_t* archived_vtable = CppVtables::get_archived_vtable(src_info->type(), (address)dest);
 670   if (archived_vtable != nullptr) {
 671     *(address*)dest = (address)archived_vtable;
 672     ArchivePtrMarker::mark_pointer((address*)dest);
 673   }
 674 
 675   log_trace(aot)("Copy: " PTR_FORMAT " ==> " PTR_FORMAT " %d", p2i(src), p2i(dest), bytes);
 676   src_info->set_buffered_addr((address)dest);
 677 }
 678 
 679 // This is used by code that hand-assembles data structures, such as the LambdaProxyClassKey, that are
 680 // not handled by MetaspaceClosure.
 681 void ArchiveBuilder::write_pointer_in_buffer(address* ptr_location, address src_addr) {
 682   assert(is_in_buffer_space(ptr_location), "must be");
 683   if (src_addr == nullptr) {
 684     *ptr_location = nullptr;
 685     ArchivePtrMarker::clear_pointer(ptr_location);
 686   } else {
 687     *ptr_location = get_buffered_addr(src_addr);
 688     ArchivePtrMarker::mark_pointer(ptr_location);
 689   }
 690 }
 691 
 692 void ArchiveBuilder::mark_and_relocate_to_buffered_addr(address* ptr_location) {
 693   assert(*ptr_location != nullptr, "sanity");
 694   if (!is_in_mapped_static_archive(*ptr_location)) {
 695     *ptr_location = get_buffered_addr(*ptr_location);
 696   }
 697   ArchivePtrMarker::mark_pointer(ptr_location);
 698 }
 699 
 700 bool ArchiveBuilder::has_been_archived(address src_addr) const {
 701   SourceObjInfo* p = _src_obj_table.get(src_addr);
 702   if (p == nullptr) {
 703     // This object has never been seen by ArchiveBuilder
 704     return false;
 705   }
 706   if (p->buffered_addr() == nullptr) {
 707     // ArchiveBuilder has seen this object, but decided not to archive it. So
 708     // Any reference to this object will be modified to nullptr inside the buffer.
 709     assert(p->follow_mode() == set_to_null, "must be");
 710     return false;
 711   }
 712 
 713   DEBUG_ONLY({
 714     // This is a class/method that belongs to one of the "original" classes that
 715     // have been regenerated by lambdaFormInvokers.cpp. We must have archived
 716     // the "regenerated" version of it.
 717     if (RegeneratedClasses::has_been_regenerated(src_addr)) {
 718       address regen_obj = RegeneratedClasses::get_regenerated_object(src_addr);
 719       precond(regen_obj != nullptr && regen_obj != src_addr);
 720       assert(has_been_archived(regen_obj), "must be");
 721       assert(get_buffered_addr(src_addr) == get_buffered_addr(regen_obj), "must be");
 722     }});
 723 
 724   return true;
 725 }
 726 
 727 address ArchiveBuilder::get_buffered_addr(address src_addr) const {
 728   SourceObjInfo* p = _src_obj_table.get(src_addr);
 729   assert(p != nullptr, "src_addr " INTPTR_FORMAT " is used but has not been archived",
 730          p2i(src_addr));
 731 
 732   return p->buffered_addr();
 733 }
 734 
 735 address ArchiveBuilder::get_source_addr(address buffered_addr) const {
 736   assert(is_in_buffer_space(buffered_addr), "must be");
 737   address* src_p = _buffered_to_src_table.get(buffered_addr);
 738   assert(src_p != nullptr && *src_p != nullptr, "must be");
 739   return *src_p;
 740 }
 741 
 742 void ArchiveBuilder::relocate_embedded_pointers(ArchiveBuilder::SourceObjList* src_objs) {
 743   for (int i = 0; i < src_objs->objs()->length(); i++) {
 744     src_objs->relocate(i, this);
 745   }
 746 }
 747 
 748 void ArchiveBuilder::relocate_metaspaceobj_embedded_pointers() {
 749   aot_log_info(aot)("Relocating embedded pointers in core regions ... ");
 750   relocate_embedded_pointers(&_rw_src_objs);
 751   relocate_embedded_pointers(&_ro_src_objs);
 752   log_info(cds)("Relocating %zu pointers, %zu tagged, %zu nulled",
 753                 _relocated_ptr_info._num_ptrs,
 754                 _relocated_ptr_info._num_tagged_ptrs,
 755                 _relocated_ptr_info._num_nulled_ptrs);
 756 }
 757 
 758 #define ADD_COUNT(x) \
 759   x += 1; \
 760   x ## _a += aotlinked ? 1 : 0; \
 761   x ## _i += inited ? 1 : 0;
 762 
 763 #define DECLARE_INSTANCE_KLASS_COUNTER(x) \
 764   int x = 0; \
 765   int x ## _a = 0; \
 766   int x ## _i = 0;
 767 
 768 void ArchiveBuilder::make_klasses_shareable() {
 769   DECLARE_INSTANCE_KLASS_COUNTER(num_instance_klasses);
 770   DECLARE_INSTANCE_KLASS_COUNTER(num_boot_klasses);
 771   DECLARE_INSTANCE_KLASS_COUNTER(num_vm_klasses);
 772   DECLARE_INSTANCE_KLASS_COUNTER(num_platform_klasses);
 773   DECLARE_INSTANCE_KLASS_COUNTER(num_app_klasses);
 774   DECLARE_INSTANCE_KLASS_COUNTER(num_old_klasses);
 775   DECLARE_INSTANCE_KLASS_COUNTER(num_hidden_klasses);
 776   DECLARE_INSTANCE_KLASS_COUNTER(num_enum_klasses);
 777   DECLARE_INSTANCE_KLASS_COUNTER(num_unregistered_klasses);
 778   int num_unlinked_klasses = 0;
 779   int num_obj_array_klasses = 0;
 780   int num_type_array_klasses = 0;
 781 
 782   int boot_unlinked = 0;
 783   int platform_unlinked = 0;
 784   int app_unlinked = 0;
 785   int unreg_unlinked = 0;
 786 
 787   for (int i = 0; i < klasses()->length(); i++) {
 788     // Some of the code in ConstantPool::remove_unshareable_info() requires the classes
 789     // to be in linked state, so it must be call here before the next loop, which returns
 790     // all classes to unlinked state.
 791     Klass* k = get_buffered_addr(klasses()->at(i));
 792     if (k->is_instance_klass()) {
 793       InstanceKlass::cast(k)->constants()->remove_unshareable_info();
 794     }
 795   }
 796 
 797   for (int i = 0; i < klasses()->length(); i++) {
 798     const char* type;
 799     const char* unlinked = "";
 800     const char* kind = "";
 801     const char* hidden = "";
 802     const char* old = "";
 803     const char* generated = "";
 804     const char* aotlinked_msg = "";
 805     const char* inited_msg = "";
 806     const char* early_init_msg = "";
 807     Klass* k = get_buffered_addr(klasses()->at(i));
 808     bool inited = false;
 809     k->remove_java_mirror();
 810 #ifdef _LP64
 811     if (UseCompactObjectHeaders) {
 812       Klass* requested_k = to_requested(k);
 813       address narrow_klass_base = _requested_static_archive_bottom; // runtime encoding base == runtime mapping start
 814       const int narrow_klass_shift = precomputed_narrow_klass_shift();
 815       narrowKlass nk = CompressedKlassPointers::encode_not_null_without_asserts(requested_k, narrow_klass_base, narrow_klass_shift);
 816       k->set_prototype_header(markWord::prototype().set_narrow_klass(nk));
 817     }
 818 #endif //_LP64
 819     if (k->is_objArray_klass()) {
 820       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
 821       // on their array classes.
 822       num_obj_array_klasses ++;
 823       type = "array";
 824     } else if (k->is_typeArray_klass()) {
 825       num_type_array_klasses ++;
 826       type = "array";
 827       k->remove_unshareable_info();
 828     } else {
 829       assert(k->is_instance_klass(), " must be");
 830       InstanceKlass* ik = InstanceKlass::cast(k);
 831       InstanceKlass* src_ik = get_source_addr(ik);
 832       bool aotlinked = AOTClassLinker::is_candidate(src_ik);
 833       inited = ik->has_aot_initialized_mirror();
 834       ADD_COUNT(num_instance_klasses);
 835       if (ik->is_hidden()) {
 836         ADD_COUNT(num_hidden_klasses);
 837         hidden = " hidden";
 838         oop loader = k->class_loader();
 839         if (loader == nullptr) {
 840           type = "boot";
 841           ADD_COUNT(num_boot_klasses);
 842         } else if (loader == SystemDictionary::java_platform_loader()) {
 843           type = "plat";
 844           ADD_COUNT(num_platform_klasses);
 845         } else if (loader == SystemDictionary::java_system_loader()) {
 846           type = "app";
 847           ADD_COUNT(num_app_klasses);
 848         } else {
 849           type = "bad";
 850           assert(0, "shouldn't happen");
 851         }
 852         if (CDSConfig::is_dumping_method_handles()) {
 853           assert(HeapShared::is_archivable_hidden_klass(ik), "sanity");
 854         } else {
 855           // Legacy CDS support for lambda proxies
 856           CDS_JAVA_HEAP_ONLY(assert(HeapShared::is_lambda_proxy_klass(ik), "sanity");)
 857         }
 858       } else if (ik->defined_by_boot_loader()) {
 859         type = "boot";
 860         ADD_COUNT(num_boot_klasses);
 861       } else if (ik->defined_by_platform_loader()) {
 862         type = "plat";
 863         ADD_COUNT(num_platform_klasses);
 864       } else if (ik->defined_by_app_loader()) {
 865         type = "app";
 866         ADD_COUNT(num_app_klasses);
 867       } else {
 868         assert(ik->defined_by_other_loaders(), "must be");
 869         type = "unreg";
 870         ADD_COUNT(num_unregistered_klasses);
 871       }
 872 
 873       if (AOTClassLinker::is_vm_class(src_ik)) {
 874         ADD_COUNT(num_vm_klasses);
 875       }
 876 
 877       if (!ik->is_linked()) {
 878         num_unlinked_klasses ++;
 879         unlinked = " unlinked";
 880         if (ik->defined_by_boot_loader()) {
 881           boot_unlinked ++;
 882         } else if (ik->defined_by_platform_loader()) {
 883           platform_unlinked ++;
 884         } else if (ik->defined_by_app_loader()) {
 885           app_unlinked ++;
 886         } else {
 887           unreg_unlinked ++;
 888         }
 889       }
 890 
 891       if (ik->is_interface()) {
 892         kind = " interface";
 893       } else if (src_ik->is_enum_subclass()) {
 894         kind = " enum";
 895         ADD_COUNT(num_enum_klasses);
 896       }
 897 
 898       if (CDSConfig::is_old_class_for_verifier(ik)) {
 899         ADD_COUNT(num_old_klasses);
 900         old = " old";
 901       }
 902 
 903       if (ik->is_aot_generated_class()) {
 904         generated = " generated";
 905       }
 906       if (aotlinked) {
 907         aotlinked_msg = " aot-linked";
 908       }
 909       if (inited) {
 910         if (InstanceKlass::cast(k)->static_field_size() == 0) {
 911           inited_msg = " inited (no static fields)";
 912         } else {
 913           inited_msg = " inited";
 914         }
 915         if (AOTCacheAccess::is_early_aot_inited_class(ik)) {
 916           early_init_msg = " early";
 917         }
 918       }
 919 
 920       AOTMetaspace::rewrite_bytecodes_and_calculate_fingerprints(Thread::current(), ik);
 921       ik->remove_unshareable_info();
 922     }
 923 
 924     if (aot_log_is_enabled(Debug, aot, class)) {
 925       ResourceMark rm;
 926       aot_log_debug(aot, class)("klasses[%5d] = " PTR_FORMAT " %-5s %s%s%s%s%s%s%s%s%s", i,
 927                             p2i(to_requested(k)), type, k->external_name(),
 928                             kind, hidden, old, unlinked, generated, aotlinked_msg, early_init_msg, inited_msg);
 929     }
 930   }
 931 
 932 #define STATS_FORMAT    "= %5d, aot-linked = %5d, inited = %5d"
 933 #define STATS_PARAMS(x) num_ ## x, num_ ## x ## _a, num_ ## x ## _i
 934 
 935   aot_log_info(aot)("Number of classes %d", num_instance_klasses + num_obj_array_klasses + num_type_array_klasses);
 936   aot_log_info(aot)("    instance classes   " STATS_FORMAT, STATS_PARAMS(instance_klasses));
 937   aot_log_info(aot)("      boot             " STATS_FORMAT, STATS_PARAMS(boot_klasses));
 938   aot_log_info(aot)("        vm             " STATS_FORMAT, STATS_PARAMS(vm_klasses));
 939   aot_log_info(aot)("      platform         " STATS_FORMAT, STATS_PARAMS(platform_klasses));
 940   aot_log_info(aot)("      app              " STATS_FORMAT, STATS_PARAMS(app_klasses));
 941   aot_log_info(aot)("      unregistered     " STATS_FORMAT, STATS_PARAMS(unregistered_klasses));
 942   aot_log_info(aot)("      (enum)           " STATS_FORMAT, STATS_PARAMS(enum_klasses));
 943   aot_log_info(aot)("      (hidden)         " STATS_FORMAT, STATS_PARAMS(hidden_klasses));
 944   aot_log_info(aot)("      (old)            " STATS_FORMAT, STATS_PARAMS(old_klasses));
 945   aot_log_info(aot)("      (unlinked)       = %5d, boot = %d, plat = %d, app = %d, unreg = %d",
 946                 num_unlinked_klasses, boot_unlinked, platform_unlinked, app_unlinked, unreg_unlinked);
 947   aot_log_info(aot)("    obj array classes  = %5d", num_obj_array_klasses);
 948   aot_log_info(aot)("    type array classes = %5d", num_type_array_klasses);
 949   aot_log_info(aot)("               symbols = %5d", _symbols->length());
 950 
 951 #undef STATS_FORMAT
 952 #undef STATS_PARAMS
 953 }
 954 
 955 void ArchiveBuilder::make_training_data_shareable() {
 956   auto clean_td = [&] (address& src_obj,  SourceObjInfo& info) {
 957     if (!is_in_buffer_space(info.buffered_addr())) {
 958       return;
 959     }
 960 
 961     if (info.type() == MetaspaceClosureType::KlassTrainingDataType ||
 962         info.type() == MetaspaceClosureType::MethodTrainingDataType ||
 963         info.type() == MetaspaceClosureType::CompileTrainingDataType) {
 964       TrainingData* buffered_td = (TrainingData*)info.buffered_addr();
 965       buffered_td->remove_unshareable_info();
 966     } else if (info.type() == MetaspaceClosureType::MethodDataType) {
 967       MethodData* buffered_mdo = (MethodData*)info.buffered_addr();
 968       buffered_mdo->remove_unshareable_info();
 969     } else if (info.type() == MetaspaceClosureType::MethodCountersType) {
 970       MethodCounters* buffered_mc = (MethodCounters*)info.buffered_addr();
 971       buffered_mc->remove_unshareable_info();
 972     }
 973   };
 974   _src_obj_table.iterate_all(clean_td);
 975 }
 976 
 977 size_t ArchiveBuilder::buffer_to_offset(address p) const {
 978   address requested_p = to_requested(p);
 979   return pointer_delta(requested_p, _requested_static_archive_bottom, 1);
 980 }
 981 
 982 size_t ArchiveBuilder::any_to_offset(address p) const {
 983   if (is_in_mapped_static_archive(p)) {
 984     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
 985     return pointer_delta(p, _mapped_static_archive_bottom, 1);
 986   }
 987   if (!is_in_buffer_space(p)) {
 988     // p must be a "source" address
 989     p = get_buffered_addr(p);
 990   }
 991   return buffer_to_offset(p);
 992 }
 993 
 994 address ArchiveBuilder::offset_to_buffered_address(size_t offset) const {
 995   address requested_addr = _requested_static_archive_bottom + offset;
 996   address buffered_addr = requested_addr - _buffer_to_requested_delta;
 997   assert(is_in_buffer_space(buffered_addr), "bad offset");
 998   return buffered_addr;
 999 }
1000 
1001 void ArchiveBuilder::start_ac_region() {
1002   ro_region()->pack();
1003   start_dump_region(&_ac_region);
1004 }
1005 
1006 void ArchiveBuilder::end_ac_region() {
1007   _ac_region.pack();
1008 }
1009 
1010 #if INCLUDE_CDS_JAVA_HEAP
1011 narrowKlass ArchiveBuilder::get_requested_narrow_klass(Klass* k) {
1012   assert(CDSConfig::is_dumping_heap(), "sanity");
1013   k = get_buffered_klass(k);
1014   Klass* requested_k = to_requested(k);
1015   const int narrow_klass_shift = ArchiveBuilder::precomputed_narrow_klass_shift();
1016 #ifdef ASSERT
1017   const size_t klass_alignment = MAX2(SharedSpaceObjectAlignment, (size_t)nth_bit(narrow_klass_shift));
1018   assert(is_aligned(k, klass_alignment), "Klass " PTR_FORMAT " misaligned.", p2i(k));
1019 #endif
1020   address narrow_klass_base = _requested_static_archive_bottom; // runtime encoding base == runtime mapping start
1021   // Note: use the "raw" version of encode that takes explicit narrow klass base and shift. Don't use any
1022   // of the variants that do sanity checks, nor any of those that use the current - dump - JVM's encoding setting.
1023   return CompressedKlassPointers::encode_not_null_without_asserts(requested_k, narrow_klass_base, narrow_klass_shift);
1024 }
1025 #endif // INCLUDE_CDS_JAVA_HEAP
1026 
1027 // RelocateBufferToRequested --- Relocate all the pointers in rw/ro,
1028 // so that the archive can be mapped to the "requested" location without runtime relocation.
1029 //
1030 // - See ArchiveBuilder header for the definition of "buffer", "mapped" and "requested"
1031 // - ArchivePtrMarker::ptrmap() marks all the pointers in the rw/ro regions
1032 // - Every pointer must have one of the following values:
1033 //   [a] nullptr:
1034 //       No relocation is needed. Remove this pointer from ptrmap so we don't need to
1035 //       consider it at runtime.
1036 //   [b] Points into an object X which is inside the buffer:
1037 //       Adjust this pointer by _buffer_to_requested_delta, so it points to X
1038 //       when the archive is mapped at the requested location.
1039 //   [c] Points into an object Y which is inside mapped static archive:
1040 //       - This happens only during dynamic dump
1041 //       - Adjust this pointer by _mapped_to_requested_static_archive_delta,
1042 //         so it points to Y when the static archive is mapped at the requested location.
1043 template <bool STATIC_DUMP>
1044 class RelocateBufferToRequested : public BitMapClosure {
1045   ArchiveBuilder* _builder;
1046   address _buffer_bottom;
1047   intx _buffer_to_requested_delta;
1048   intx _mapped_to_requested_static_archive_delta;
1049   size_t _max_non_null_offset;
1050 
1051  public:
1052   RelocateBufferToRequested(ArchiveBuilder* builder) {
1053     _builder = builder;
1054     _buffer_bottom = _builder->buffer_bottom();
1055     _buffer_to_requested_delta = builder->buffer_to_requested_delta();
1056     _mapped_to_requested_static_archive_delta = builder->requested_static_archive_bottom() - builder->mapped_static_archive_bottom();
1057     _max_non_null_offset = 0;
1058 
1059     address bottom = _builder->buffer_bottom();
1060     address top = _builder->buffer_top();
1061     address new_bottom = bottom + _buffer_to_requested_delta;
1062     address new_top = top + _buffer_to_requested_delta;
1063     aot_log_debug(aot)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT "] to "
1064                    "[" INTPTR_FORMAT " - " INTPTR_FORMAT "]",
1065                    p2i(bottom), p2i(top),
1066                    p2i(new_bottom), p2i(new_top));
1067   }
1068 
1069   bool do_bit(size_t offset) {
1070     address* p = (address*)_buffer_bottom + offset;
1071     assert(_builder->is_in_buffer_space(p), "pointer must live in buffer space");
1072 
1073     if (*p == nullptr) {
1074       // todo -- clear bit, etc
1075       ArchivePtrMarker::ptrmap()->clear_bit(offset);
1076     } else {
1077       if (STATIC_DUMP) {
1078         assert(_builder->is_in_buffer_space(*p), "old pointer must point inside buffer space");
1079         *p += _buffer_to_requested_delta;
1080         assert(_builder->is_in_requested_static_archive(*p), "new pointer must point inside requested archive");
1081       } else {
1082         if (_builder->is_in_buffer_space(*p)) {
1083           *p += _buffer_to_requested_delta;
1084           // assert is in requested dynamic archive
1085         } else {
1086           assert(_builder->is_in_mapped_static_archive(*p), "old pointer must point inside buffer space or mapped static archive");
1087           *p += _mapped_to_requested_static_archive_delta;
1088           assert(_builder->is_in_requested_static_archive(*p), "new pointer must point inside requested archive");
1089         }
1090       }
1091       _max_non_null_offset = offset;
1092     }
1093 
1094     return true; // keep iterating
1095   }
1096 
1097   void doit() {
1098     ArchivePtrMarker::ptrmap()->iterate(this);
1099     ArchivePtrMarker::compact(_max_non_null_offset);
1100   }
1101 };
1102 
1103 #ifdef _LP64
1104 int ArchiveBuilder::precomputed_narrow_klass_shift() {
1105   // Legacy Mode:
1106   //    We use 32 bits for narrowKlass, which should cover the full 4G Klass range. Shift can be 0.
1107   // CompactObjectHeader Mode:
1108   //    narrowKlass is much smaller, and we use the highest possible shift value to later get the maximum
1109   //    Klass encoding range.
1110   //
1111   // Note that all of this may change in the future, if we decide to correct the pre-calculated
1112   // narrow Klass IDs at archive load time.
1113   assert(UseCompressedClassPointers, "Only needed for compressed class pointers");
1114   return UseCompactObjectHeaders ?  CompressedKlassPointers::max_shift() : 0;
1115 }
1116 #endif // _LP64
1117 
1118 void ArchiveBuilder::relocate_to_requested() {
1119   if (!ro_region()->is_packed()) {
1120     ro_region()->pack();
1121   }
1122   size_t my_archive_size = buffer_top() - buffer_bottom();
1123 
1124   if (CDSConfig::is_dumping_static_archive()) {
1125     _requested_static_archive_top = _requested_static_archive_bottom + my_archive_size;
1126     RelocateBufferToRequested<true> patcher(this);
1127     patcher.doit();
1128   } else {
1129     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1130     _requested_dynamic_archive_top = _requested_dynamic_archive_bottom + my_archive_size;
1131     RelocateBufferToRequested<false> patcher(this);
1132     patcher.doit();
1133   }
1134 }
1135 
1136 void ArchiveBuilder::print_stats() {
1137   _alloc_stats.print_stats(int(_ro_region.used()), int(_rw_region.used()));
1138 }
1139 
1140 void ArchiveBuilder::write_archive(FileMapInfo* mapinfo, AOTMappedHeapInfo* mapped_heap_info, AOTStreamedHeapInfo* streamed_heap_info) {
1141   // Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with
1142   // AOTMetaspace::n_regions (internal to hotspot).
1143   assert(NUM_CDS_REGIONS == AOTMetaspace::n_regions, "sanity");
1144 
1145   ResourceMark rm;
1146 
1147   write_region(mapinfo, AOTMetaspace::rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);
1148   write_region(mapinfo, AOTMetaspace::ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);
1149   write_region(mapinfo, AOTMetaspace::ac, &_ac_region, /*read_only=*/false,/*allow_exec=*/false);
1150 
1151   // Split pointer map into read-write and read-only bitmaps
1152   ArchivePtrMarker::initialize_rw_ro_ac_maps(&_rw_ptrmap, &_ro_ptrmap, &_ac_ptrmap);
1153 
1154   size_t bitmap_size_in_bytes;
1155   char* bitmap = mapinfo->write_bitmap_region(ArchivePtrMarker::rw_ptrmap(),
1156                                               ArchivePtrMarker::ro_ptrmap(),
1157                                               ArchivePtrMarker::ac_ptrmap(),
1158                                               mapped_heap_info,
1159                                               streamed_heap_info,
1160                                               bitmap_size_in_bytes);
1161 
1162   if (mapped_heap_info != nullptr && mapped_heap_info->is_used()) {
1163     _total_heap_region_size = mapinfo->write_mapped_heap_region(mapped_heap_info);
1164   } else if (streamed_heap_info != nullptr && streamed_heap_info->is_used()) {
1165     _total_heap_region_size = mapinfo->write_streamed_heap_region(streamed_heap_info);
1166   }
1167 
1168   print_region_stats(mapinfo, mapped_heap_info, streamed_heap_info);
1169 
1170   mapinfo->set_requested_base((char*)AOTMetaspace::requested_base_address());
1171   mapinfo->set_header_crc(mapinfo->compute_header_crc());
1172   // After this point, we should not write any data into mapinfo->header() since this
1173   // would corrupt its checksum we have calculated before.
1174   mapinfo->write_header();
1175   mapinfo->close();
1176 
1177   aot_log_info(aot)("Full module graph = %s", CDSConfig::is_dumping_full_module_graph() ? "enabled" : "disabled");
1178   if (log_is_enabled(Info, aot)) {
1179     print_stats();
1180   }
1181 
1182   if (log_is_enabled(Info, aot, map)) {
1183     AOTMapLogger::dumptime_log(this, mapinfo, mapped_heap_info, streamed_heap_info, bitmap, bitmap_size_in_bytes);
1184   }
1185   CDS_JAVA_HEAP_ONLY(HeapShared::destroy_archived_object_cache());
1186   FREE_C_HEAP_ARRAY(char, bitmap);
1187 }
1188 
1189 void ArchiveBuilder::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only,  bool allow_exec) {
1190   mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);
1191 }
1192 
1193 void ArchiveBuilder::count_relocated_pointer(bool tagged, bool nulled) {
1194   _relocated_ptr_info._num_ptrs ++;
1195   _relocated_ptr_info._num_tagged_ptrs += tagged ? 1 : 0;
1196   _relocated_ptr_info._num_nulled_ptrs += nulled ? 1 : 0;
1197 }
1198 
1199 void ArchiveBuilder::print_region_stats(FileMapInfo *mapinfo,
1200                                         AOTMappedHeapInfo* mapped_heap_info,
1201                                         AOTStreamedHeapInfo* streamed_heap_info) {
1202   // Print statistics of all the regions
1203   const size_t bitmap_used = mapinfo->region_at(AOTMetaspace::bm)->used();
1204   const size_t bitmap_reserved = mapinfo->region_at(AOTMetaspace::bm)->used_aligned();
1205   const size_t total_reserved = _ro_region.reserved()  + _rw_region.reserved() +
1206                                 bitmap_reserved +
1207                                 _total_heap_region_size;
1208   const size_t total_bytes = _ro_region.used()  + _rw_region.used() +
1209                              bitmap_used +
1210                              _total_heap_region_size;
1211   const double total_u_perc = percent_of(total_bytes, total_reserved);
1212 
1213   _rw_region.print(total_reserved);
1214   _ro_region.print(total_reserved);
1215   _ac_region.print(total_reserved);
1216 
1217   print_bitmap_region_stats(bitmap_used, total_reserved);
1218 
1219   if (mapped_heap_info != nullptr && mapped_heap_info->is_used()) {
1220     print_heap_region_stats(mapped_heap_info->buffer_start(), mapped_heap_info->buffer_byte_size(), total_reserved);
1221   } else if (streamed_heap_info != nullptr && streamed_heap_info->is_used()) {
1222     print_heap_region_stats(streamed_heap_info->buffer_start(), streamed_heap_info->buffer_byte_size(), total_reserved);
1223   }
1224 
1225   aot_log_debug(aot)("total   : %9zu [100.0%% of total] out of %9zu bytes [%5.1f%% used]",
1226                      total_bytes, total_reserved, total_u_perc);
1227 }
1228 
1229 void ArchiveBuilder::print_bitmap_region_stats(size_t size, size_t total_size) {
1230   aot_log_debug(aot)("bm space: %9zu [ %4.1f%% of total] out of %9zu bytes [100.0%% used]",
1231                      size, size/double(total_size)*100.0, size);
1232 }
1233 
1234 void ArchiveBuilder::print_heap_region_stats(char* start, size_t size, size_t total_size) {
1235   char* top = start + size;
1236   aot_log_debug(aot)("hp space: %9zu [ %4.1f%% of total] out of %9zu bytes [100.0%% used] at " INTPTR_FORMAT,
1237                      size, size/double(total_size)*100.0, size, p2i(start));
1238 }
1239 
1240 void ArchiveBuilder::report_out_of_space(const char* name, size_t needed_bytes) {
1241   // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space.
1242   // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes
1243   // or so.
1244   _rw_region.print_out_of_space_msg(name, needed_bytes);
1245   _ro_region.print_out_of_space_msg(name, needed_bytes);
1246 
1247   log_error(aot)("Unable to allocate from '%s' region: Please reduce the number of shared classes.", name);
1248   AOTMetaspace::unrecoverable_writing_error();
1249 }