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