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/aotLinkedClassBulkLoader.hpp"
  28 #include "cds/aotLogging.hpp"
  29 #include "cds/archiveBuilder.hpp"
  30 #include "cds/archiveHeapWriter.hpp"
  31 #include "cds/archiveUtils.hpp"
  32 #include "cds/cdsConfig.hpp"
  33 #include "cds/cppVtables.hpp"
  34 #include "cds/dumpAllocStats.hpp"
  35 #include "cds/dynamicArchive.hpp"
  36 #include "cds/finalImageRecipes.hpp"
  37 #include "cds/heapShared.hpp"
  38 #include "cds/metaspaceShared.hpp"
  39 #include "cds/regeneratedClasses.hpp"
  40 #include "classfile/classLoader.hpp"
  41 #include "classfile/classLoaderDataShared.hpp"
  42 #include "classfile/classLoaderExt.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 "logging/logStream.hpp"
  52 #include "memory/allStatic.hpp"
  53 #include "memory/memoryReserver.hpp"
  54 #include "memory/memRegion.hpp"
  55 #include "memory/resourceArea.hpp"
  56 #include "oops/compressedKlass.inline.hpp"
  57 #include "oops/instanceKlass.hpp"
  58 #include "oops/methodCounters.hpp"
  59 #include "oops/methodData.hpp"
  60 #include "oops/objArrayKlass.hpp"
  61 #include "oops/objArrayOop.inline.hpp"
  62 #include "oops/oopHandle.inline.hpp"
  63 #include "oops/trainingData.hpp"
  64 #include "runtime/arguments.hpp"
  65 #include "runtime/fieldDescriptor.inline.hpp"
  66 #include "runtime/globals_extension.hpp"
  67 #include "runtime/javaThread.hpp"
  68 #include "runtime/sharedRuntime.hpp"
  69 #include "utilities/align.hpp"
  70 #include "utilities/bitMap.inline.hpp"
  71 #include "utilities/formatBuffer.hpp"
  72 
  73 ArchiveBuilder* ArchiveBuilder::_current = nullptr;
  74 
  75 ArchiveBuilder::OtherROAllocMark::~OtherROAllocMark() {
  76   char* newtop = ArchiveBuilder::current()->_ro_region.top();
  77   ArchiveBuilder::alloc_stats()->record_other_type(int(newtop - _oldtop), true);
  78 }
  79 
  80 ArchiveBuilder::SourceObjList::SourceObjList() : _ptrmap(16 * K, mtClassShared) {
  81   _total_bytes = 0;
  82   _objs = new (mtClassShared) GrowableArray<SourceObjInfo*>(128 * K, mtClassShared);
  83 }
  84 
  85 ArchiveBuilder::SourceObjList::~SourceObjList() {
  86   delete _objs;
  87 }
  88 
  89 void ArchiveBuilder::SourceObjList::append(SourceObjInfo* src_info) {
  90   // Save this source object for copying
  91   src_info->set_id(_objs->length());
  92   _objs->append(src_info);
  93 
  94   // Prepare for marking the pointers in this source object
  95   assert(is_aligned(_total_bytes, sizeof(address)), "must be");
  96   src_info->set_ptrmap_start(_total_bytes / sizeof(address));
  97   _total_bytes = align_up(_total_bytes + (uintx)src_info->size_in_bytes(), sizeof(address));
  98   src_info->set_ptrmap_end(_total_bytes / sizeof(address));
  99 
 100   BitMap::idx_t bitmap_size_needed = BitMap::idx_t(src_info->ptrmap_end());
 101   if (_ptrmap.size() <= bitmap_size_needed) {
 102     _ptrmap.resize((bitmap_size_needed + 1) * 2);
 103   }
 104 }
 105 
 106 void ArchiveBuilder::SourceObjList::remember_embedded_pointer(SourceObjInfo* src_info, MetaspaceClosure::Ref* ref) {
 107   // src_obj contains a pointer. Remember the location of this pointer in _ptrmap,
 108   // so that we can copy/relocate it later.
 109   src_info->set_has_embedded_pointer();
 110   address src_obj = src_info->source_addr();
 111   address* field_addr = ref->addr();
 112   assert(src_info->ptrmap_start() < _total_bytes, "sanity");
 113   assert(src_info->ptrmap_end() <= _total_bytes, "sanity");
 114   assert(*field_addr != nullptr, "should have checked");
 115 
 116   intx field_offset_in_bytes = ((address)field_addr) - src_obj;
 117   DEBUG_ONLY(int src_obj_size = src_info->size_in_bytes();)
 118   assert(field_offset_in_bytes >= 0, "must be");
 119   assert(field_offset_in_bytes + intx(sizeof(intptr_t)) <= intx(src_obj_size), "must be");
 120   assert(is_aligned(field_offset_in_bytes, sizeof(address)), "must be");
 121 
 122   BitMap::idx_t idx = BitMap::idx_t(src_info->ptrmap_start() + (uintx)(field_offset_in_bytes / sizeof(address)));
 123   _ptrmap.set_bit(BitMap::idx_t(idx));
 124 }
 125 
 126 class RelocateEmbeddedPointers : public BitMapClosure {
 127   ArchiveBuilder* _builder;
 128   address _buffered_obj;
 129   BitMap::idx_t _start_idx;
 130 public:
 131   RelocateEmbeddedPointers(ArchiveBuilder* builder, address buffered_obj, BitMap::idx_t start_idx) :
 132     _builder(builder), _buffered_obj(buffered_obj), _start_idx(start_idx) {}
 133 
 134   bool do_bit(BitMap::idx_t bit_offset) {
 135     size_t field_offset = size_t(bit_offset - _start_idx) * sizeof(address);
 136     address* ptr_loc = (address*)(_buffered_obj + field_offset);
 137 
 138     address old_p_with_tags = *ptr_loc;
 139     assert(old_p_with_tags != nullptr, "null ptrs shouldn't have been marked");
 140 
 141     address old_p = MetaspaceClosure::strip_tags(old_p_with_tags);
 142     uintx tags = MetaspaceClosure::decode_tags(old_p_with_tags);
 143     address new_p = _builder->get_buffered_addr(old_p);
 144 
 145     bool nulled;
 146     if (new_p == nullptr) {
 147       // old_p had a FollowMode of set_to_null
 148       nulled = true;
 149     } else {
 150       new_p = MetaspaceClosure::add_tags(new_p, tags);
 151       nulled = false;
 152     }
 153 
 154     log_trace(aot)("Ref: [" PTR_FORMAT "] -> " PTR_FORMAT " => " PTR_FORMAT " %zu",
 155                    p2i(ptr_loc), p2i(old_p) + tags, p2i(new_p), tags);
 156 
 157     ArchivePtrMarker::set_and_mark_pointer(ptr_loc, new_p);
 158     ArchiveBuilder::current()->count_relocated_pointer(tags != 0, nulled);
 159     return true; // keep iterating the bitmap
 160   }
 161 };
 162 
 163 void ArchiveBuilder::SourceObjList::relocate(int i, ArchiveBuilder* builder) {
 164   SourceObjInfo* src_info = objs()->at(i);
 165   assert(src_info->should_copy(), "must be");
 166   BitMap::idx_t start = BitMap::idx_t(src_info->ptrmap_start()); // inclusive
 167   BitMap::idx_t end = BitMap::idx_t(src_info->ptrmap_end());     // exclusive
 168 
 169   RelocateEmbeddedPointers relocator(builder, src_info->buffered_addr(), start);
 170   _ptrmap.iterate(&relocator, start, end);
 171 }
 172 
 173 ArchiveBuilder::ArchiveBuilder() :
 174   _current_dump_region(nullptr),
 175   _buffer_bottom(nullptr),
 176   _requested_static_archive_bottom(nullptr),
 177   _requested_static_archive_top(nullptr),
 178   _requested_dynamic_archive_bottom(nullptr),
 179   _requested_dynamic_archive_top(nullptr),
 180   _mapped_static_archive_bottom(nullptr),
 181   _mapped_static_archive_top(nullptr),
 182   _buffer_to_requested_delta(0),
 183   _pz_region("pz", MAX_SHARED_DELTA), // protection zone -- used only during dumping; does NOT exist in cds archive.
 184   _rw_region("rw", MAX_SHARED_DELTA),
 185   _ro_region("ro", MAX_SHARED_DELTA),
 186   _ac_region("ac", MAX_SHARED_DELTA),
 187   _ptrmap(mtClassShared),
 188   _rw_ptrmap(mtClassShared),
 189   _ro_ptrmap(mtClassShared),
 190   _ac_ptrmap(mtClassShared),
 191   _rw_src_objs(),
 192   _ro_src_objs(),
 193   _src_obj_table(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE),
 194   _buffered_to_src_table(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE),
 195   _total_heap_region_size(0)
 196 {
 197   _klasses = new (mtClassShared) GrowableArray<Klass*>(4 * K, mtClassShared);
 198   _symbols = new (mtClassShared) GrowableArray<Symbol*>(256 * K, mtClassShared);
 199   _entropy_seed = 0x12345678;
 200   _relocated_ptr_info._num_ptrs = 0;
 201   _relocated_ptr_info._num_tagged_ptrs = 0;
 202   _relocated_ptr_info._num_nulled_ptrs = 0;
 203   assert(_current == nullptr, "must be");
 204   _current = this;
 205 }
 206 
 207 ArchiveBuilder::~ArchiveBuilder() {
 208   assert(_current == this, "must be");
 209   _current = nullptr;
 210 
 211   for (int i = 0; i < _symbols->length(); i++) {
 212     _symbols->at(i)->decrement_refcount();
 213   }
 214 
 215   delete _klasses;
 216   delete _symbols;
 217   if (_shared_rs.is_reserved()) {
 218     MemoryReserver::release(_shared_rs);
 219   }
 220 
 221   AOTArtifactFinder::dispose();
 222 }
 223 
 224 // Returns a deterministic sequence of pseudo random numbers. The main purpose is NOT
 225 // for randomness but to get good entropy for the identity_hash() of archived Symbols,
 226 // while keeping the contents of static CDS archives deterministic to ensure
 227 // reproducibility of JDK builds.
 228 int ArchiveBuilder::entropy() {
 229   assert(SafepointSynchronize::is_at_safepoint(), "needed to ensure deterministic sequence");
 230   _entropy_seed = os::next_random(_entropy_seed);
 231   return static_cast<int>(_entropy_seed);
 232 }
 233 
 234 class GatherKlassesAndSymbols : public UniqueMetaspaceClosure {
 235   ArchiveBuilder* _builder;
 236 
 237 public:
 238   GatherKlassesAndSymbols(ArchiveBuilder* builder) : _builder(builder) {}
 239 
 240   virtual bool do_unique_ref(Ref* ref, bool read_only) {
 241     return _builder->gather_klass_and_symbol(ref, read_only);
 242   }
 243 };
 244 
 245 bool ArchiveBuilder::gather_klass_and_symbol(MetaspaceClosure::Ref* ref, bool read_only) {
 246   if (ref->obj() == nullptr) {
 247     return false;
 248   }
 249   if (get_follow_mode(ref) != make_a_copy) {
 250     return false;
 251   }
 252   if (ref->msotype() == MetaspaceObj::ClassType) {
 253     Klass* klass = (Klass*)ref->obj();
 254     assert(klass->is_klass(), "must be");
 255     if (!is_excluded(klass)) {
 256       _klasses->append(klass);
 257       if (klass->is_hidden()) {
 258         assert(klass->is_instance_klass(), "must be");
 259       }
 260     }
 261   } else if (ref->msotype() == MetaspaceObj::SymbolType) {
 262     // Make sure the symbol won't be GC'ed while we are dumping the archive.
 263     Symbol* sym = (Symbol*)ref->obj();
 264     sym->increment_refcount();
 265     _symbols->append(sym);
 266   }
 267 
 268   return true; // recurse
 269 }
 270 
 271 void ArchiveBuilder::gather_klasses_and_symbols() {
 272   ResourceMark rm;
 273 
 274   AOTArtifactFinder::initialize();
 275   AOTArtifactFinder::find_artifacts();
 276 
 277   aot_log_info(aot)("Gathering classes and symbols ... ");
 278   GatherKlassesAndSymbols doit(this);
 279   iterate_roots(&doit);
 280 #if INCLUDE_CDS_JAVA_HEAP
 281   if (CDSConfig::is_dumping_full_module_graph()) {
 282     ClassLoaderDataShared::iterate_symbols(&doit);
 283   }
 284 #endif
 285   doit.finish();
 286 
 287   if (CDSConfig::is_dumping_static_archive()) {
 288     // To ensure deterministic contents in the static archive, we need to ensure that
 289     // we iterate the MetaspaceObjs in a deterministic order. It doesn't matter where
 290     // the MetaspaceObjs are located originally, as they are copied sequentially into
 291     // the archive during the iteration.
 292     //
 293     // The only issue here is that the symbol table and the system directories may be
 294     // randomly ordered, so we copy the symbols and klasses into two arrays and sort
 295     // them deterministically.
 296     //
 297     // During -Xshare:dump, the order of Symbol creation is strictly determined by
 298     // the SharedClassListFile (class loading is done in a single thread and the JIT
 299     // is disabled). Also, Symbols are allocated in monotonically increasing addresses
 300     // (see Symbol::operator new(size_t, int)). So if we iterate the Symbols by
 301     // ascending address order, we ensure that all Symbols are copied into deterministic
 302     // locations in the archive.
 303     //
 304     // TODO: in the future, if we want to produce deterministic contents in the
 305     // dynamic archive, we might need to sort the symbols alphabetically (also see
 306     // DynamicArchiveBuilder::sort_methods()).
 307     aot_log_info(aot)("Sorting symbols ... ");
 308     _symbols->sort(compare_symbols_by_address);
 309     sort_klasses();
 310   }
 311 
 312   AOTClassLinker::add_candidates();
 313 }
 314 
 315 int ArchiveBuilder::compare_symbols_by_address(Symbol** a, Symbol** b) {
 316   if (a[0] < b[0]) {
 317     return -1;
 318   } else {
 319     assert(a[0] > b[0], "Duplicated symbol %s unexpected", (*a)->as_C_string());
 320     return 1;
 321   }
 322 }
 323 
 324 int ArchiveBuilder::compare_klass_by_name(Klass** a, Klass** b) {
 325   return a[0]->name()->fast_compare(b[0]->name());
 326 }
 327 
 328 void ArchiveBuilder::sort_klasses() {
 329   aot_log_info(aot)("Sorting classes ... ");
 330   _klasses->sort(compare_klass_by_name);
 331 }
 332 
 333 address ArchiveBuilder::reserve_buffer() {
 334   // AOTCodeCache::max_aot_code_size() accounts for aot code region.
 335   size_t buffer_size = LP64_ONLY(CompressedClassSpaceSize) NOT_LP64(256 * M) + AOTCodeCache::max_aot_code_size();
 336   ReservedSpace rs = MemoryReserver::reserve(buffer_size,
 337                                              MetaspaceShared::core_region_alignment(),
 338                                              os::vm_page_size(),
 339                                              mtNone);
 340   if (!rs.is_reserved()) {
 341     aot_log_error(aot)("Failed to reserve %zu bytes of output buffer.", buffer_size);
 342     MetaspaceShared::unrecoverable_writing_error();
 343   }
 344 
 345   // buffer_bottom is the lowest address of the 2 core regions (rw, ro) when
 346   // we are copying the class metadata into the buffer.
 347   address buffer_bottom = (address)rs.base();
 348   aot_log_info(aot)("Reserved output buffer space at " PTR_FORMAT " [%zu bytes]",
 349                 p2i(buffer_bottom), buffer_size);
 350   _shared_rs = rs;
 351 
 352   _buffer_bottom = buffer_bottom;
 353 
 354   if (CDSConfig::is_dumping_static_archive()) {
 355     _current_dump_region = &_pz_region;
 356   } else {
 357     _current_dump_region = &_rw_region;
 358   }
 359   _current_dump_region->init(&_shared_rs, &_shared_vs);
 360 
 361   ArchivePtrMarker::initialize(&_ptrmap, &_shared_vs);
 362 
 363   // The bottom of the static archive should be mapped at this address by default.
 364   _requested_static_archive_bottom = (address)MetaspaceShared::requested_base_address();
 365 
 366   // The bottom of the archive (that I am writing now) should be mapped at this address by default.
 367   address my_archive_requested_bottom;
 368 
 369   if (CDSConfig::is_dumping_static_archive()) {
 370     my_archive_requested_bottom = _requested_static_archive_bottom;
 371   } else {
 372     _mapped_static_archive_bottom = (address)MetaspaceObj::shared_metaspace_base();
 373     _mapped_static_archive_top  = (address)MetaspaceObj::shared_metaspace_top();
 374     assert(_mapped_static_archive_top >= _mapped_static_archive_bottom, "must be");
 375     size_t static_archive_size = _mapped_static_archive_top - _mapped_static_archive_bottom;
 376 
 377     // At run time, we will mmap the dynamic archive at my_archive_requested_bottom
 378     _requested_static_archive_top = _requested_static_archive_bottom + static_archive_size;
 379     my_archive_requested_bottom = align_up(_requested_static_archive_top, MetaspaceShared::core_region_alignment());
 380 
 381     _requested_dynamic_archive_bottom = my_archive_requested_bottom;
 382   }
 383 
 384   _buffer_to_requested_delta = my_archive_requested_bottom - _buffer_bottom;
 385 
 386   address my_archive_requested_top = my_archive_requested_bottom + buffer_size;
 387   if (my_archive_requested_bottom <  _requested_static_archive_bottom ||
 388       my_archive_requested_top    <= _requested_static_archive_bottom) {
 389     // Size overflow.
 390     aot_log_error(aot)("my_archive_requested_bottom = " INTPTR_FORMAT, p2i(my_archive_requested_bottom));
 391     aot_log_error(aot)("my_archive_requested_top    = " INTPTR_FORMAT, p2i(my_archive_requested_top));
 392     aot_log_error(aot)("SharedBaseAddress (" INTPTR_FORMAT ") is too high. "
 393                    "Please rerun java -Xshare:dump with a lower value", p2i(_requested_static_archive_bottom));
 394     MetaspaceShared::unrecoverable_writing_error();
 395   }
 396 
 397   if (CDSConfig::is_dumping_static_archive()) {
 398     // We don't want any valid object to be at the very bottom of the archive.
 399     // See ArchivePtrMarker::mark_pointer().
 400     _pz_region.allocate(MetaspaceShared::protection_zone_size());
 401     start_dump_region(&_rw_region);
 402   }
 403 
 404   return buffer_bottom;
 405 }
 406 
 407 void ArchiveBuilder::iterate_sorted_roots(MetaspaceClosure* it) {
 408   int num_symbols = _symbols->length();
 409   for (int i = 0; i < num_symbols; i++) {
 410     it->push(_symbols->adr_at(i));
 411   }
 412 
 413   int num_klasses = _klasses->length();
 414   for (int i = 0; i < num_klasses; i++) {
 415     it->push(_klasses->adr_at(i));
 416   }
 417 
 418   iterate_roots(it);
 419 }
 420 
 421 class GatherSortedSourceObjs : public MetaspaceClosure {
 422   ArchiveBuilder* _builder;
 423 
 424 public:
 425   GatherSortedSourceObjs(ArchiveBuilder* builder) : _builder(builder) {}
 426 
 427   virtual bool do_ref(Ref* ref, bool read_only) {
 428     return _builder->gather_one_source_obj(ref, read_only);
 429   }
 430 };
 431 
 432 bool ArchiveBuilder::gather_one_source_obj(MetaspaceClosure::Ref* ref, bool read_only) {
 433   address src_obj = ref->obj();
 434   if (src_obj == nullptr) {
 435     return false;
 436   }
 437 
 438   remember_embedded_pointer_in_enclosing_obj(ref);
 439   if (RegeneratedClasses::has_been_regenerated(src_obj)) {
 440     // No need to copy it. We will later relocate it to point to the regenerated klass/method.
 441     return false;
 442   }
 443 
 444   FollowMode follow_mode = get_follow_mode(ref);
 445   SourceObjInfo src_info(ref, read_only, follow_mode);
 446   bool created;
 447   SourceObjInfo* p = _src_obj_table.put_if_absent(src_obj, src_info, &created);
 448   if (created) {
 449     if (_src_obj_table.maybe_grow()) {
 450       log_info(aot, hashtables)("Expanded _src_obj_table table to %d", _src_obj_table.table_size());
 451     }
 452   }
 453 
 454 #ifdef ASSERT
 455   if (ref->msotype() == MetaspaceObj::MethodType) {
 456     Method* m = (Method*)ref->obj();
 457     assert(!RegeneratedClasses::has_been_regenerated((address)m->method_holder()),
 458            "Should not archive methods in a class that has been regenerated");
 459   }
 460 #endif
 461 
 462   if (ref->msotype() == MetaspaceObj::MethodDataType) {
 463     MethodData* md = (MethodData*)ref->obj();
 464     md->clean_method_data(false /* always_clean */);
 465   }
 466 
 467   assert(p->read_only() == src_info.read_only(), "must be");
 468 
 469   if (created && src_info.should_copy()) {
 470     if (read_only) {
 471       _ro_src_objs.append(p);
 472     } else {
 473       _rw_src_objs.append(p);
 474     }
 475     return true; // Need to recurse into this ref only if we are copying it
 476   } else {
 477     return false;
 478   }
 479 }
 480 
 481 void ArchiveBuilder::record_regenerated_object(address orig_src_obj, address regen_src_obj) {
 482   // Record the fact that orig_src_obj has been replaced by regen_src_obj. All calls to get_buffered_addr(orig_src_obj)
 483   // should return the same value as get_buffered_addr(regen_src_obj).
 484   SourceObjInfo* p = _src_obj_table.get(regen_src_obj);
 485   assert(p != nullptr, "regenerated object should always be dumped");
 486   SourceObjInfo orig_src_info(orig_src_obj, p);
 487   bool created;
 488   _src_obj_table.put_if_absent(orig_src_obj, orig_src_info, &created);
 489   assert(created, "We shouldn't have archived the original copy of a regenerated object");
 490 }
 491 
 492 // Remember that we have a pointer inside ref->enclosing_obj() that points to ref->obj()
 493 void ArchiveBuilder::remember_embedded_pointer_in_enclosing_obj(MetaspaceClosure::Ref* ref) {
 494   assert(ref->obj() != nullptr, "should have checked");
 495 
 496   address enclosing_obj = ref->enclosing_obj();
 497   if (enclosing_obj == nullptr) {
 498     return;
 499   }
 500 
 501   // We are dealing with 3 addresses:
 502   // address o    = ref->obj(): We have found an object whose address is o.
 503   // address* mpp = ref->mpp(): The object o is pointed to by a pointer whose address is mpp.
 504   //                            I.e., (*mpp == o)
 505   // enclosing_obj            : If non-null, it is the object which has a field that points to o.
 506   //                            mpp is the address if that field.
 507   //
 508   // Example: We have an array whose first element points to a Method:
 509   //     Method* o                     = 0x0000abcd;
 510   //     Array<Method*>* enclosing_obj = 0x00001000;
 511   //     enclosing_obj->at_put(0, o);
 512   //
 513   // We the MetaspaceClosure iterates on the very first element of this array, we have
 514   //     ref->obj()           == 0x0000abcd   (the Method)
 515   //     ref->mpp()           == 0x00001008   (the location of the first element in the array)
 516   //     ref->enclosing_obj() == 0x00001000   (the Array that contains the Method)
 517   //
 518   // We use the above information to mark the bitmap to indicate that there's a pointer on address 0x00001008.
 519   SourceObjInfo* src_info = _src_obj_table.get(enclosing_obj);
 520   if (src_info == nullptr || !src_info->should_copy()) {
 521     // source objects of point_to_it/set_to_null types are not copied
 522     // so we don't need to remember their pointers.
 523   } else {
 524     if (src_info->read_only()) {
 525       _ro_src_objs.remember_embedded_pointer(src_info, ref);
 526     } else {
 527       _rw_src_objs.remember_embedded_pointer(src_info, ref);
 528     }
 529   }
 530 }
 531 
 532 void ArchiveBuilder::gather_source_objs() {
 533   ResourceMark rm;
 534   aot_log_info(aot)("Gathering all archivable objects ... ");
 535   gather_klasses_and_symbols();
 536   GatherSortedSourceObjs doit(this);
 537   iterate_sorted_roots(&doit);
 538   doit.finish();
 539 }
 540 
 541 bool ArchiveBuilder::is_excluded(Klass* klass) {
 542   if (klass->is_instance_klass()) {
 543     InstanceKlass* ik = InstanceKlass::cast(klass);
 544     return SystemDictionaryShared::is_excluded_class(ik);
 545   } else if (klass->is_objArray_klass()) {
 546     Klass* bottom = ObjArrayKlass::cast(klass)->bottom_klass();
 547     if (CDSConfig::is_dumping_dynamic_archive() && MetaspaceShared::is_shared_static(bottom)) {
 548       // The bottom class is in the static archive so it's clearly not excluded.
 549       return false;
 550     } else if (bottom->is_instance_klass()) {
 551       return SystemDictionaryShared::is_excluded_class(InstanceKlass::cast(bottom));
 552     }
 553   }
 554 
 555   return false;
 556 }
 557 
 558 ArchiveBuilder::FollowMode ArchiveBuilder::get_follow_mode(MetaspaceClosure::Ref *ref) {
 559   address obj = ref->obj();
 560   if (CDSConfig::is_dumping_dynamic_archive() && MetaspaceShared::is_in_shared_metaspace(obj)) {
 561     // Don't dump existing shared metadata again.
 562     return point_to_it;
 563   } else if (ref->msotype() == MetaspaceObj::MethodDataType ||
 564              ref->msotype() == MetaspaceObj::MethodCountersType ||
 565              ref->msotype() == MetaspaceObj::KlassTrainingDataType ||
 566              ref->msotype() == MetaspaceObj::MethodTrainingDataType ||
 567              ref->msotype() == MetaspaceObj::CompileTrainingDataType) {
 568     return (TrainingData::need_data() || TrainingData::assembling_data()) ? make_a_copy : set_to_null;
 569   } else if (ref->msotype() == MetaspaceObj::AdapterHandlerEntryType) {
 570     if (CDSConfig::is_dumping_adapters()) {
 571       AdapterHandlerEntry* entry = (AdapterHandlerEntry*)ref->obj();
 572       return AdapterHandlerLibrary::is_abstract_method_adapter(entry) ? set_to_null : make_a_copy;
 573     } else {
 574       return set_to_null;
 575     }
 576   } else {
 577     if (ref->msotype() == MetaspaceObj::ClassType) {
 578       Klass* klass = (Klass*)ref->obj();
 579       assert(klass->is_klass(), "must be");
 580       if (is_excluded(klass)) {
 581         ResourceMark rm;
 582         log_debug(cds, dynamic)("Skipping class (excluded): %s", klass->external_name());
 583         return set_to_null;
 584       }
 585     }
 586 
 587     return make_a_copy;
 588   }
 589 }
 590 
 591 void ArchiveBuilder::start_dump_region(DumpRegion* next) {
 592   current_dump_region()->pack(next);
 593   _current_dump_region = next;
 594 }
 595 
 596 char* ArchiveBuilder::ro_strdup(const char* s) {
 597   char* archived_str = ro_region_alloc((int)strlen(s) + 1);
 598   strcpy(archived_str, s);
 599   return archived_str;
 600 }
 601 
 602 // The objects that have embedded pointers will sink
 603 // towards the end of the list. This ensures we have a maximum
 604 // number of leading zero bits in the relocation bitmap.
 605 int ArchiveBuilder::compare_src_objs(SourceObjInfo** a, SourceObjInfo** b) {
 606   if ((*a)->has_embedded_pointer() && !(*b)->has_embedded_pointer()) {
 607     return 1;
 608   } else if (!(*a)->has_embedded_pointer() && (*b)->has_embedded_pointer()) {
 609     return -1;
 610   } else {
 611     // This is necessary to keep the sorting order stable. Otherwise the
 612     // archive's contents may not be deterministic.
 613     return (*a)->id() - (*b)->id();
 614   }
 615 }
 616 
 617 void ArchiveBuilder::sort_metadata_objs() {
 618   _rw_src_objs.objs()->sort(compare_src_objs);
 619   _ro_src_objs.objs()->sort(compare_src_objs);
 620 }
 621 
 622 void ArchiveBuilder::dump_rw_metadata() {
 623   ResourceMark rm;
 624   aot_log_info(aot)("Allocating RW objects ... ");
 625   make_shallow_copies(&_rw_region, &_rw_src_objs);
 626 
 627 #if INCLUDE_CDS_JAVA_HEAP
 628   if (CDSConfig::is_dumping_full_module_graph()) {
 629     // Archive the ModuleEntry's and PackageEntry's of the 3 built-in loaders
 630     char* start = rw_region()->top();
 631     ClassLoaderDataShared::allocate_archived_tables();
 632     alloc_stats()->record_modules(rw_region()->top() - start, /*read_only*/false);
 633   }
 634 #endif
 635 }
 636 
 637 void ArchiveBuilder::dump_ro_metadata() {
 638   ResourceMark rm;
 639   aot_log_info(aot)("Allocating RO objects ... ");
 640 
 641   start_dump_region(&_ro_region);
 642   make_shallow_copies(&_ro_region, &_ro_src_objs);
 643 
 644 #if INCLUDE_CDS_JAVA_HEAP
 645   if (CDSConfig::is_dumping_full_module_graph()) {
 646     char* start = ro_region()->top();
 647     ClassLoaderDataShared::init_archived_tables();
 648     alloc_stats()->record_modules(ro_region()->top() - start, /*read_only*/true);
 649   }
 650 #endif
 651 
 652   RegeneratedClasses::record_regenerated_objects();
 653 }
 654 
 655 void ArchiveBuilder::make_shallow_copies(DumpRegion *dump_region,
 656                                          const ArchiveBuilder::SourceObjList* src_objs) {
 657   for (int i = 0; i < src_objs->objs()->length(); i++) {
 658     make_shallow_copy(dump_region, src_objs->objs()->at(i));
 659   }
 660   aot_log_info(aot)("done (%d objects)", src_objs->objs()->length());
 661 }
 662 
 663 void ArchiveBuilder::make_shallow_copy(DumpRegion *dump_region, SourceObjInfo* src_info) {
 664   address src = src_info->source_addr();
 665   int bytes = src_info->size_in_bytes();
 666   char* dest;
 667   char* oldtop;
 668   char* newtop;
 669 
 670   oldtop = dump_region->top();
 671   if (src_info->msotype() == MetaspaceObj::ClassType) {
 672     // Allocate space for a pointer directly in front of the future InstanceKlass, so
 673     // we can do a quick lookup from InstanceKlass* -> RunTimeClassInfo*
 674     // without building another hashtable. See RunTimeClassInfo::get_for()
 675     // in systemDictionaryShared.cpp.
 676     Klass* klass = (Klass*)src;
 677     if (klass->is_instance_klass()) {
 678       SystemDictionaryShared::validate_before_archiving(InstanceKlass::cast(klass));
 679       dump_region->allocate(sizeof(address));
 680     }
 681     // Allocate space for the future InstanceKlass with proper alignment
 682     const size_t alignment =
 683 #ifdef _LP64
 684       UseCompressedClassPointers ?
 685         nth_bit(ArchiveBuilder::precomputed_narrow_klass_shift()) :
 686         SharedSpaceObjectAlignment;
 687 #else
 688       SharedSpaceObjectAlignment;
 689 #endif
 690     dest = dump_region->allocate(bytes, alignment);
 691   } else {
 692     dest = dump_region->allocate(bytes);
 693   }
 694   newtop = dump_region->top();
 695 
 696   memcpy(dest, src, bytes);
 697 
 698   // Update the hash of buffered sorted symbols for static dump so that the symbols have deterministic contents
 699   if (CDSConfig::is_dumping_static_archive() && (src_info->msotype() == MetaspaceObj::SymbolType)) {
 700     Symbol* buffered_symbol = (Symbol*)dest;
 701     assert(((Symbol*)src)->is_permanent(), "archived symbols must be permanent");
 702     buffered_symbol->update_identity_hash();
 703   }
 704 
 705   {
 706     bool created;
 707     _buffered_to_src_table.put_if_absent((address)dest, src, &created);
 708     assert(created, "must be");
 709     if (_buffered_to_src_table.maybe_grow()) {
 710       log_info(aot, hashtables)("Expanded _buffered_to_src_table table to %d", _buffered_to_src_table.table_size());
 711     }
 712   }
 713 
 714   intptr_t* archived_vtable = CppVtables::get_archived_vtable(src_info->msotype(), (address)dest);
 715   if (archived_vtable != nullptr) {
 716     *(address*)dest = (address)archived_vtable;
 717     ArchivePtrMarker::mark_pointer((address*)dest);
 718   }
 719 
 720   log_trace(aot)("Copy: " PTR_FORMAT " ==> " PTR_FORMAT " %d", p2i(src), p2i(dest), bytes);
 721   src_info->set_buffered_addr((address)dest);
 722 
 723   _alloc_stats.record(src_info->msotype(), int(newtop - oldtop), src_info->read_only());
 724 
 725   DEBUG_ONLY(_alloc_stats.verify((int)dump_region->used(), src_info->read_only()));
 726 }
 727 
 728 // This is used by code that hand-assembles data structures, such as the LambdaProxyClassKey, that are
 729 // not handled by MetaspaceClosure.
 730 void ArchiveBuilder::write_pointer_in_buffer(address* ptr_location, address src_addr) {
 731   assert(is_in_buffer_space(ptr_location), "must be");
 732   if (src_addr == nullptr) {
 733     *ptr_location = nullptr;
 734     ArchivePtrMarker::clear_pointer(ptr_location);
 735   } else {
 736     *ptr_location = get_buffered_addr(src_addr);
 737     ArchivePtrMarker::mark_pointer(ptr_location);
 738   }
 739 }
 740 
 741 void ArchiveBuilder::mark_and_relocate_to_buffered_addr(address* ptr_location) {
 742   assert(*ptr_location != nullptr, "sanity");
 743   if (!is_in_mapped_static_archive(*ptr_location)) {
 744     *ptr_location = get_buffered_addr(*ptr_location);
 745   }
 746   ArchivePtrMarker::mark_pointer(ptr_location);
 747 }
 748 
 749 bool ArchiveBuilder::has_been_archived(address src_addr) const {
 750   SourceObjInfo* p = _src_obj_table.get(src_addr);
 751   return (p != nullptr);
 752 }
 753 
 754 bool ArchiveBuilder::has_been_buffered(address src_addr) const {
 755   if (RegeneratedClasses::has_been_regenerated(src_addr) ||
 756       _src_obj_table.get(src_addr) == nullptr ||
 757       get_buffered_addr(src_addr) == nullptr) {
 758     return false;
 759   } else {
 760     return true;
 761   }
 762 }
 763 
 764 address ArchiveBuilder::get_buffered_addr(address src_addr) const {
 765   SourceObjInfo* p = _src_obj_table.get(src_addr);
 766   assert(p != nullptr, "src_addr " INTPTR_FORMAT " is used but has not been archived",
 767          p2i(src_addr));
 768 
 769   return p->buffered_addr();
 770 }
 771 
 772 address ArchiveBuilder::get_source_addr(address buffered_addr) const {
 773   assert(is_in_buffer_space(buffered_addr), "must be");
 774   address* src_p = _buffered_to_src_table.get(buffered_addr);
 775   assert(src_p != nullptr && *src_p != nullptr, "must be");
 776   return *src_p;
 777 }
 778 
 779 void ArchiveBuilder::relocate_embedded_pointers(ArchiveBuilder::SourceObjList* src_objs) {
 780   for (int i = 0; i < src_objs->objs()->length(); i++) {
 781     src_objs->relocate(i, this);
 782   }
 783 }
 784 
 785 void ArchiveBuilder::relocate_metaspaceobj_embedded_pointers() {
 786   aot_log_info(aot)("Relocating embedded pointers in core regions ... ");
 787   relocate_embedded_pointers(&_rw_src_objs);
 788   relocate_embedded_pointers(&_ro_src_objs);
 789   log_info(cds)("Relocating %zu pointers, %zu tagged, %zu nulled",
 790                 _relocated_ptr_info._num_ptrs,
 791                 _relocated_ptr_info._num_tagged_ptrs,
 792                 _relocated_ptr_info._num_nulled_ptrs);
 793 }
 794 
 795 #define ADD_COUNT(x) \
 796   x += 1; \
 797   x ## _a += aotlinked ? 1 : 0; \
 798   x ## _i += inited ? 1 : 0;
 799 
 800 #define DECLARE_INSTANCE_KLASS_COUNTER(x) \
 801   int x = 0; \
 802   int x ## _a = 0; \
 803   int x ## _i = 0;
 804 
 805 void ArchiveBuilder::make_klasses_shareable() {
 806   DECLARE_INSTANCE_KLASS_COUNTER(num_instance_klasses);
 807   DECLARE_INSTANCE_KLASS_COUNTER(num_boot_klasses);
 808   DECLARE_INSTANCE_KLASS_COUNTER(num_vm_klasses);
 809   DECLARE_INSTANCE_KLASS_COUNTER(num_platform_klasses);
 810   DECLARE_INSTANCE_KLASS_COUNTER(num_app_klasses);
 811   DECLARE_INSTANCE_KLASS_COUNTER(num_old_klasses);
 812   DECLARE_INSTANCE_KLASS_COUNTER(num_hidden_klasses);
 813   DECLARE_INSTANCE_KLASS_COUNTER(num_enum_klasses);
 814   DECLARE_INSTANCE_KLASS_COUNTER(num_unregistered_klasses);
 815   int num_unlinked_klasses = 0;
 816   int num_obj_array_klasses = 0;
 817   int num_type_array_klasses = 0;
 818 
 819   int boot_unlinked = 0;
 820   int platform_unlinked = 0;
 821   int app_unlinked = 0;
 822   int unreg_unlinked = 0;
 823 
 824   for (int i = 0; i < klasses()->length(); i++) {
 825     // Some of the code in ConstantPool::remove_unshareable_info() requires the classes
 826     // to be in linked state, so it must be call here before the next loop, which returns
 827     // all classes to unlinked state.
 828     Klass* k = get_buffered_addr(klasses()->at(i));
 829     if (k->is_instance_klass()) {
 830       InstanceKlass::cast(k)->constants()->remove_unshareable_info();
 831     }
 832   }
 833 
 834   for (int i = 0; i < klasses()->length(); i++) {
 835     const char* type;
 836     const char* unlinked = "";
 837     const char* kind = "";
 838     const char* hidden = "";
 839     const char* old = "";
 840     const char* generated = "";
 841     const char* aotlinked_msg = "";
 842     const char* inited_msg = "";
 843     Klass* k = get_buffered_addr(klasses()->at(i));
 844     bool inited = false;
 845     k->remove_java_mirror();
 846 #ifdef _LP64
 847     if (UseCompactObjectHeaders) {
 848       Klass* requested_k = to_requested(k);
 849       address narrow_klass_base = _requested_static_archive_bottom; // runtime encoding base == runtime mapping start
 850       const int narrow_klass_shift = precomputed_narrow_klass_shift();
 851       narrowKlass nk = CompressedKlassPointers::encode_not_null_without_asserts(requested_k, narrow_klass_base, narrow_klass_shift);
 852       k->set_prototype_header(markWord::prototype().set_narrow_klass(nk));
 853     }
 854 #endif //_LP64
 855     if (k->is_objArray_klass()) {
 856       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
 857       // on their array classes.
 858       num_obj_array_klasses ++;
 859       type = "array";
 860     } else if (k->is_typeArray_klass()) {
 861       num_type_array_klasses ++;
 862       type = "array";
 863       k->remove_unshareable_info();
 864     } else {
 865       assert(k->is_instance_klass(), " must be");
 866       InstanceKlass* ik = InstanceKlass::cast(k);
 867       InstanceKlass* src_ik = get_source_addr(ik);
 868       bool aotlinked = AOTClassLinker::is_candidate(src_ik);
 869       inited = ik->has_aot_initialized_mirror();
 870       ADD_COUNT(num_instance_klasses);
 871       if (ik->is_hidden()) {
 872         ADD_COUNT(num_hidden_klasses);
 873         hidden = " hidden";
 874         oop loader = k->class_loader();
 875         if (loader == nullptr) {
 876           type = "boot";
 877           ADD_COUNT(num_boot_klasses);
 878         } else if (loader == SystemDictionary::java_platform_loader()) {
 879           type = "plat";
 880           ADD_COUNT(num_platform_klasses);
 881         } else if (loader == SystemDictionary::java_system_loader()) {
 882           type = "app";
 883           ADD_COUNT(num_app_klasses);
 884         } else {
 885           type = "bad";
 886           assert(0, "shouldn't happen");
 887         }
 888         if (CDSConfig::is_dumping_method_handles()) {
 889           assert(HeapShared::is_archivable_hidden_klass(ik), "sanity");
 890         } else {
 891           // Legacy CDS support for lambda proxies
 892           CDS_JAVA_HEAP_ONLY(assert(HeapShared::is_lambda_proxy_klass(ik), "sanity");)
 893         }
 894       } else if (ik->defined_by_boot_loader()) {
 895         type = "boot";
 896         ADD_COUNT(num_boot_klasses);
 897       } else if (ik->defined_by_platform_loader()) {
 898         type = "plat";
 899         ADD_COUNT(num_platform_klasses);
 900       } else if (ik->defined_by_app_loader()) {
 901         type = "app";
 902         ADD_COUNT(num_app_klasses);
 903       } else {
 904         assert(ik->defined_by_other_loaders(), "must be");
 905         type = "unreg";
 906         ADD_COUNT(num_unregistered_klasses);
 907       }
 908 
 909       if (AOTClassLinker::is_vm_class(src_ik)) {
 910         ADD_COUNT(num_vm_klasses);
 911       }
 912 
 913       if (!ik->is_linked()) {
 914         num_unlinked_klasses ++;
 915         unlinked = " unlinked";
 916         if (ik->defined_by_boot_loader()) {
 917           boot_unlinked ++;
 918         } else if (ik->defined_by_platform_loader()) {
 919           platform_unlinked ++;
 920         } else if (ik->defined_by_app_loader()) {
 921           app_unlinked ++;
 922         } else {
 923           unreg_unlinked ++;
 924         }
 925       }
 926 
 927       if (ik->is_interface()) {
 928         kind = " interface";
 929       } else if (src_ik->is_enum_subclass()) {
 930         kind = " enum";
 931         ADD_COUNT(num_enum_klasses);
 932       }
 933 
 934       if (!ik->can_be_verified_at_dumptime()) {
 935         ADD_COUNT(num_old_klasses);
 936         old = " old";
 937       }
 938 
 939       if (ik->is_generated_shared_class()) {
 940         generated = " generated";
 941       }
 942       if (aotlinked) {
 943         aotlinked_msg = " aot-linked";
 944       }
 945       if (inited) {
 946         if (InstanceKlass::cast(k)->static_field_size() == 0) {
 947           inited_msg = " inited (no static fields)";
 948         } else {
 949           inited_msg = " inited";
 950         }
 951       }
 952 
 953       MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread::current(), ik);
 954       ik->remove_unshareable_info();
 955     }
 956 
 957     if (aot_log_is_enabled(Debug, aot, class)) {
 958       ResourceMark rm;
 959       aot_log_debug(aot, class)("klasses[%5d] = " PTR_FORMAT " %-5s %s%s%s%s%s%s%s%s", i,
 960                             p2i(to_requested(k)), type, k->external_name(),
 961                             kind, hidden, old, unlinked, generated, aotlinked_msg, inited_msg);
 962     }
 963   }
 964 
 965 #define STATS_FORMAT    "= %5d, aot-linked = %5d, inited = %5d"
 966 #define STATS_PARAMS(x) num_ ## x, num_ ## x ## _a, num_ ## x ## _i
 967 
 968   aot_log_info(aot)("Number of classes %d", num_instance_klasses + num_obj_array_klasses + num_type_array_klasses);
 969   aot_log_info(aot)("    instance classes   " STATS_FORMAT, STATS_PARAMS(instance_klasses));
 970   aot_log_info(aot)("      boot             " STATS_FORMAT, STATS_PARAMS(boot_klasses));
 971   aot_log_info(aot)("        vm             " STATS_FORMAT, STATS_PARAMS(vm_klasses));
 972   aot_log_info(aot)("      platform         " STATS_FORMAT, STATS_PARAMS(platform_klasses));
 973   aot_log_info(aot)("      app              " STATS_FORMAT, STATS_PARAMS(app_klasses));
 974   aot_log_info(aot)("      unregistered     " STATS_FORMAT, STATS_PARAMS(unregistered_klasses));
 975   aot_log_info(aot)("      (enum)           " STATS_FORMAT, STATS_PARAMS(enum_klasses));
 976   aot_log_info(aot)("      (hidden)         " STATS_FORMAT, STATS_PARAMS(hidden_klasses));
 977   aot_log_info(aot)("      (old)            " STATS_FORMAT, STATS_PARAMS(old_klasses));
 978   aot_log_info(aot)("      (unlinked)       = %5d, boot = %d, plat = %d, app = %d, unreg = %d",
 979                 num_unlinked_klasses, boot_unlinked, platform_unlinked, app_unlinked, unreg_unlinked);
 980   aot_log_info(aot)("    obj array classes  = %5d", num_obj_array_klasses);
 981   aot_log_info(aot)("    type array classes = %5d", num_type_array_klasses);
 982   aot_log_info(aot)("               symbols = %5d", _symbols->length());
 983 
 984 #undef STATS_FORMAT
 985 #undef STATS_PARAMS
 986 
 987   DynamicArchive::make_array_klasses_shareable();
 988 }
 989 
 990 void ArchiveBuilder::make_training_data_shareable() {
 991   auto clean_td = [&] (address& src_obj,  SourceObjInfo& info) {
 992     if (!is_in_buffer_space(info.buffered_addr())) {
 993       return;
 994     }
 995 
 996     if (info.msotype() == MetaspaceObj::KlassTrainingDataType ||
 997         info.msotype() == MetaspaceObj::MethodTrainingDataType ||
 998         info.msotype() == MetaspaceObj::CompileTrainingDataType) {
 999       TrainingData* buffered_td = (TrainingData*)info.buffered_addr();
1000       buffered_td->remove_unshareable_info();
1001     } else if (info.msotype() == MetaspaceObj::MethodDataType) {
1002       MethodData* buffered_mdo = (MethodData*)info.buffered_addr();
1003       buffered_mdo->remove_unshareable_info();
1004     } else if (info.msotype() == MetaspaceObj::MethodCountersType) {
1005       MethodCounters* buffered_mc = (MethodCounters*)info.buffered_addr();
1006       buffered_mc->remove_unshareable_info();
1007     }
1008   };
1009   _src_obj_table.iterate_all(clean_td);
1010 }
1011 
1012 void ArchiveBuilder::serialize_dynamic_archivable_items(SerializeClosure* soc) {
1013   SymbolTable::serialize_shared_table_header(soc, false);
1014   SystemDictionaryShared::serialize_dictionary_headers(soc, false);
1015   DynamicArchive::serialize_array_klasses(soc);
1016   AOTLinkedClassBulkLoader::serialize(soc, false);
1017 }
1018 
1019 uintx ArchiveBuilder::buffer_to_offset(address p) const {
1020   address requested_p = to_requested(p);
1021   assert(requested_p >= _requested_static_archive_bottom, "must be");
1022   return requested_p - _requested_static_archive_bottom;
1023 }
1024 
1025 uintx ArchiveBuilder::any_to_offset(address p) const {
1026   if (is_in_mapped_static_archive(p)) {
1027     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1028     return p - _mapped_static_archive_bottom;
1029   }
1030   if (!is_in_buffer_space(p)) {
1031     // p must be a "source" address
1032     p = get_buffered_addr(p);
1033   }
1034   return buffer_to_offset(p);
1035 }
1036 
1037 address ArchiveBuilder::offset_to_buffered_address(u4 offset) const {
1038   address requested_addr = _requested_static_archive_bottom + offset;
1039   address buffered_addr = requested_addr - _buffer_to_requested_delta;
1040   assert(is_in_buffer_space(buffered_addr), "bad offset");
1041   return buffered_addr;
1042 }
1043 
1044 void ArchiveBuilder::start_ac_region() {
1045   ro_region()->pack();
1046   start_dump_region(&_ac_region);
1047 }
1048 
1049 void ArchiveBuilder::end_ac_region() {
1050   _ac_region.pack();
1051 }
1052 
1053 #if INCLUDE_CDS_JAVA_HEAP
1054 narrowKlass ArchiveBuilder::get_requested_narrow_klass(Klass* k) {
1055   assert(CDSConfig::is_dumping_heap(), "sanity");
1056   k = get_buffered_klass(k);
1057   Klass* requested_k = to_requested(k);
1058   const int narrow_klass_shift = ArchiveBuilder::precomputed_narrow_klass_shift();
1059 #ifdef ASSERT
1060   const size_t klass_alignment = MAX2(SharedSpaceObjectAlignment, (size_t)nth_bit(narrow_klass_shift));
1061   assert(is_aligned(k, klass_alignment), "Klass " PTR_FORMAT " misaligned.", p2i(k));
1062 #endif
1063   address narrow_klass_base = _requested_static_archive_bottom; // runtime encoding base == runtime mapping start
1064   // Note: use the "raw" version of encode that takes explicit narrow klass base and shift. Don't use any
1065   // of the variants that do sanity checks, nor any of those that use the current - dump - JVM's encoding setting.
1066   return CompressedKlassPointers::encode_not_null_without_asserts(requested_k, narrow_klass_base, narrow_klass_shift);
1067 }
1068 #endif // INCLUDE_CDS_JAVA_HEAP
1069 
1070 // RelocateBufferToRequested --- Relocate all the pointers in rw/ro,
1071 // so that the archive can be mapped to the "requested" location without runtime relocation.
1072 //
1073 // - See ArchiveBuilder header for the definition of "buffer", "mapped" and "requested"
1074 // - ArchivePtrMarker::ptrmap() marks all the pointers in the rw/ro regions
1075 // - Every pointer must have one of the following values:
1076 //   [a] nullptr:
1077 //       No relocation is needed. Remove this pointer from ptrmap so we don't need to
1078 //       consider it at runtime.
1079 //   [b] Points into an object X which is inside the buffer:
1080 //       Adjust this pointer by _buffer_to_requested_delta, so it points to X
1081 //       when the archive is mapped at the requested location.
1082 //   [c] Points into an object Y which is inside mapped static archive:
1083 //       - This happens only during dynamic dump
1084 //       - Adjust this pointer by _mapped_to_requested_static_archive_delta,
1085 //         so it points to Y when the static archive is mapped at the requested location.
1086 template <bool STATIC_DUMP>
1087 class RelocateBufferToRequested : public BitMapClosure {
1088   ArchiveBuilder* _builder;
1089   address _buffer_bottom;
1090   intx _buffer_to_requested_delta;
1091   intx _mapped_to_requested_static_archive_delta;
1092   size_t _max_non_null_offset;
1093 
1094  public:
1095   RelocateBufferToRequested(ArchiveBuilder* builder) {
1096     _builder = builder;
1097     _buffer_bottom = _builder->buffer_bottom();
1098     _buffer_to_requested_delta = builder->buffer_to_requested_delta();
1099     _mapped_to_requested_static_archive_delta = builder->requested_static_archive_bottom() - builder->mapped_static_archive_bottom();
1100     _max_non_null_offset = 0;
1101 
1102     address bottom = _builder->buffer_bottom();
1103     address top = _builder->buffer_top();
1104     address new_bottom = bottom + _buffer_to_requested_delta;
1105     address new_top = top + _buffer_to_requested_delta;
1106     aot_log_debug(aot)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT "] to "
1107                    "[" INTPTR_FORMAT " - " INTPTR_FORMAT "]",
1108                    p2i(bottom), p2i(top),
1109                    p2i(new_bottom), p2i(new_top));
1110   }
1111 
1112   bool do_bit(size_t offset) {
1113     address* p = (address*)_buffer_bottom + offset;
1114     assert(_builder->is_in_buffer_space(p), "pointer must live in buffer space");
1115 
1116     if (*p == nullptr) {
1117       // todo -- clear bit, etc
1118       ArchivePtrMarker::ptrmap()->clear_bit(offset);
1119     } else {
1120       if (STATIC_DUMP) {
1121         assert(_builder->is_in_buffer_space(*p), "old pointer must point inside buffer space");
1122         *p += _buffer_to_requested_delta;
1123         assert(_builder->is_in_requested_static_archive(*p), "new pointer must point inside requested archive");
1124       } else {
1125         if (_builder->is_in_buffer_space(*p)) {
1126           *p += _buffer_to_requested_delta;
1127           // assert is in requested dynamic archive
1128         } else {
1129           assert(_builder->is_in_mapped_static_archive(*p), "old pointer must point inside buffer space or mapped static archive");
1130           *p += _mapped_to_requested_static_archive_delta;
1131           assert(_builder->is_in_requested_static_archive(*p), "new pointer must point inside requested archive");
1132         }
1133       }
1134       _max_non_null_offset = offset;
1135     }
1136 
1137     return true; // keep iterating
1138   }
1139 
1140   void doit() {
1141     ArchivePtrMarker::ptrmap()->iterate(this);
1142     ArchivePtrMarker::compact(_max_non_null_offset);
1143   }
1144 };
1145 
1146 #ifdef _LP64
1147 int ArchiveBuilder::precomputed_narrow_klass_shift() {
1148   // Legacy Mode:
1149   //    We use 32 bits for narrowKlass, which should cover the full 4G Klass range. Shift can be 0.
1150   // CompactObjectHeader Mode:
1151   //    narrowKlass is much smaller, and we use the highest possible shift value to later get the maximum
1152   //    Klass encoding range.
1153   //
1154   // Note that all of this may change in the future, if we decide to correct the pre-calculated
1155   // narrow Klass IDs at archive load time.
1156   assert(UseCompressedClassPointers, "Only needed for compressed class pointers");
1157   return UseCompactObjectHeaders ?  CompressedKlassPointers::max_shift() : 0;
1158 }
1159 #endif // _LP64
1160 
1161 void ArchiveBuilder::relocate_to_requested() {
1162   if (!ro_region()->is_packed()) {
1163     ro_region()->pack();
1164   }
1165   size_t my_archive_size = buffer_top() - buffer_bottom();
1166 
1167   if (CDSConfig::is_dumping_static_archive()) {
1168     _requested_static_archive_top = _requested_static_archive_bottom + my_archive_size;
1169     RelocateBufferToRequested<true> patcher(this);
1170     patcher.doit();
1171   } else {
1172     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1173     _requested_dynamic_archive_top = _requested_dynamic_archive_bottom + my_archive_size;
1174     RelocateBufferToRequested<false> patcher(this);
1175     patcher.doit();
1176   }
1177 }
1178 
1179 // Write detailed info to a mapfile to analyze contents of the archive.
1180 // static dump:
1181 //   java -Xshare:dump -Xlog:cds+map=trace:file=cds.map:none:filesize=0
1182 // dynamic dump:
1183 //   java -cp MyApp.jar -XX:ArchiveClassesAtExit=MyApp.jsa \
1184 //        -Xlog:cds+map=trace:file=cds.map:none:filesize=0 MyApp
1185 //
1186 // We need to do some address translation because the buffers used at dump time may be mapped to
1187 // a different location at runtime. At dump time, the buffers may be at arbitrary locations
1188 // picked by the OS. At runtime, we try to map at a fixed location (SharedBaseAddress). For
1189 // consistency, we log everything using runtime addresses.
1190 class ArchiveBuilder::CDSMapLogger : AllStatic {
1191   static intx buffer_to_runtime_delta() {
1192     // Translate the buffers used by the RW/RO regions to their eventual (requested) locations
1193     // at runtime.
1194     return ArchiveBuilder::current()->buffer_to_requested_delta();
1195   }
1196 
1197   // rw/ro regions only
1198   static void log_metaspace_region(const char* name, DumpRegion* region,
1199                                    const ArchiveBuilder::SourceObjList* src_objs) {
1200     address region_base = address(region->base());
1201     address region_top  = address(region->top());
1202     log_region(name, region_base, region_top, region_base + buffer_to_runtime_delta());
1203     log_metaspace_objects(region, src_objs);
1204   }
1205 
1206 #define _LOG_PREFIX PTR_FORMAT ": @@ %-17s %d"
1207 
1208   static void log_klass(Klass* k, address runtime_dest, const char* type_name, int bytes, Thread* current) {
1209     ResourceMark rm(current);
1210     log_debug(aot, map)(_LOG_PREFIX " %s",
1211                         p2i(runtime_dest), type_name, bytes, k->external_name());
1212   }
1213   static void log_method(Method* m, address runtime_dest, const char* type_name, int bytes, Thread* current) {
1214     ResourceMark rm(current);
1215     log_debug(aot, map)(_LOG_PREFIX " %s",
1216                         p2i(runtime_dest), type_name, bytes,  m->external_name());
1217   }
1218 
1219   // rw/ro regions only
1220   static void log_metaspace_objects(DumpRegion* region, const ArchiveBuilder::SourceObjList* src_objs) {
1221     address last_obj_base = address(region->base());
1222     address last_obj_end  = address(region->base());
1223     address region_end    = address(region->end());
1224     Thread* current = Thread::current();
1225     for (int i = 0; i < src_objs->objs()->length(); i++) {
1226       SourceObjInfo* src_info = src_objs->at(i);
1227       address src = src_info->source_addr();
1228       address dest = src_info->buffered_addr();
1229       log_as_hex(last_obj_base, dest, last_obj_base + buffer_to_runtime_delta());
1230       address runtime_dest = dest + buffer_to_runtime_delta();
1231       int bytes = src_info->size_in_bytes();
1232 
1233       MetaspaceObj::Type type = src_info->msotype();
1234       const char* type_name = MetaspaceObj::type_name(type);
1235 
1236       switch (type) {
1237       case MetaspaceObj::ClassType:
1238         log_klass((Klass*)src, runtime_dest, type_name, bytes, current);
1239         break;
1240       case MetaspaceObj::ConstantPoolType:
1241         log_klass(((ConstantPool*)src)->pool_holder(),
1242                     runtime_dest, type_name, bytes, current);
1243         break;
1244       case MetaspaceObj::ConstantPoolCacheType:
1245         log_klass(((ConstantPoolCache*)src)->constant_pool()->pool_holder(),
1246                     runtime_dest, type_name, bytes, current);
1247         break;
1248       case MetaspaceObj::MethodType:
1249         log_method((Method*)src, runtime_dest, type_name, bytes, current);
1250         break;
1251       case MetaspaceObj::ConstMethodType:
1252         log_method(((ConstMethod*)src)->method(), runtime_dest, type_name, bytes, current);
1253         break;
1254       case MetaspaceObj::SymbolType:
1255         {
1256           ResourceMark rm(current);
1257           Symbol* s = (Symbol*)src;
1258           log_debug(aot, map)(_LOG_PREFIX " %s", p2i(runtime_dest), type_name, bytes,
1259                               s->as_quoted_ascii());
1260         }
1261         break;
1262       default:
1263         log_debug(aot, map)(_LOG_PREFIX, p2i(runtime_dest), type_name, bytes);
1264         break;
1265       }
1266 
1267       last_obj_base = dest;
1268       last_obj_end  = dest + bytes;
1269     }
1270 
1271     log_as_hex(last_obj_base, last_obj_end, last_obj_base + buffer_to_runtime_delta());
1272     if (last_obj_end < region_end) {
1273       log_debug(aot, map)(PTR_FORMAT ": @@ Misc data %zu bytes",
1274                           p2i(last_obj_end + buffer_to_runtime_delta()),
1275                           size_t(region_end - last_obj_end));
1276       log_as_hex(last_obj_end, region_end, last_obj_end + buffer_to_runtime_delta());
1277     }
1278   }
1279 
1280 #undef _LOG_PREFIX
1281 
1282   // Log information about a region, whose address at dump time is [base .. top). At
1283   // runtime, this region will be mapped to requested_base. requested_base is nullptr if this
1284   // region will be mapped at os-selected addresses (such as the bitmap region), or will
1285   // be accessed with os::read (the header).
1286   //
1287   // Note: across -Xshare:dump runs, base may be different, but requested_base should
1288   // be the same as the archive contents should be deterministic.
1289   static void log_region(const char* name, address base, address top, address requested_base) {
1290     size_t size = top - base;
1291     base = requested_base;
1292     if (requested_base == nullptr) {
1293       top = (address)size;
1294     } else {
1295       top = requested_base + size;
1296     }
1297     log_info(aot, map)("[%-18s " PTR_FORMAT " - " PTR_FORMAT " %9zu bytes]",
1298                        name, p2i(base), p2i(top), size);
1299   }
1300 
1301 #if INCLUDE_CDS_JAVA_HEAP
1302   static void log_heap_region(ArchiveHeapInfo* heap_info) {
1303     MemRegion r = heap_info->buffer_region();
1304     address start = address(r.start()); // start of the current oop inside the buffer
1305     address end = address(r.end());
1306     log_region("heap", start, end, ArchiveHeapWriter::buffered_addr_to_requested_addr(start));
1307 
1308     LogStreamHandle(Info, aot, map) st;
1309 
1310     HeapRootSegments segments = heap_info->heap_root_segments();
1311     assert(segments.base_offset() == 0, "Sanity");
1312 
1313     for (size_t seg_idx = 0; seg_idx < segments.count(); seg_idx++) {
1314       address requested_start = ArchiveHeapWriter::buffered_addr_to_requested_addr(start);
1315       st.print_cr(PTR_FORMAT ": Heap roots segment [%d]",
1316                   p2i(requested_start), segments.size_in_elems(seg_idx));
1317       start += segments.size_in_bytes(seg_idx);
1318     }
1319     log_heap_roots();
1320 
1321     while (start < end) {
1322       size_t byte_size;
1323       oop source_oop = ArchiveHeapWriter::buffered_addr_to_source_obj(start);
1324       address requested_start = ArchiveHeapWriter::buffered_addr_to_requested_addr(start);
1325       st.print(PTR_FORMAT ": @@ Object ", p2i(requested_start));
1326 
1327       if (source_oop != nullptr) {
1328         // This is a regular oop that got archived.
1329         // Don't print the requested addr again as we have just printed it at the beginning of the line.
1330         // Example:
1331         // 0x00000007ffd27938: @@ Object (0xfffa4f27) java.util.HashMap
1332         print_oop_info_cr(&st, source_oop, /*print_requested_addr=*/false);
1333         byte_size = source_oop->size() * BytesPerWord;
1334       } else if ((byte_size = ArchiveHeapWriter::get_filler_size_at(start)) > 0) {
1335         // We have a filler oop, which also does not exist in BufferOffsetToSourceObjectTable.
1336         // Example:
1337         // 0x00000007ffc3ffd8: @@ Object filler 40 bytes
1338         st.print_cr("filler %zu bytes", byte_size);
1339       } else {
1340         ShouldNotReachHere();
1341       }
1342 
1343       address oop_end = start + byte_size;
1344       log_as_hex(start, oop_end, requested_start, /*is_heap=*/true);
1345 
1346       if (source_oop != nullptr) {
1347         log_oop_details(heap_info, source_oop, /*buffered_addr=*/start);
1348       }
1349       start = oop_end;
1350     }
1351   }
1352 
1353   // ArchivedFieldPrinter is used to print the fields of archived objects. We can't
1354   // use _source_obj->print_on(), because we want to print the oop fields
1355   // in _source_obj with their requested addresses using print_oop_info_cr().
1356   class ArchivedFieldPrinter : public FieldClosure {
1357     ArchiveHeapInfo* _heap_info;
1358     outputStream* _st;
1359     oop _source_obj;
1360     address _buffered_addr;
1361   public:
1362     ArchivedFieldPrinter(ArchiveHeapInfo* heap_info, outputStream* st, oop src_obj, address buffered_addr) :
1363       _heap_info(heap_info), _st(st), _source_obj(src_obj), _buffered_addr(buffered_addr) {}
1364 
1365     void do_field(fieldDescriptor* fd) {
1366       _st->print(" - ");
1367       BasicType ft = fd->field_type();
1368       switch (ft) {
1369       case T_ARRAY:
1370       case T_OBJECT:
1371         {
1372           fd->print_on(_st); // print just the name and offset
1373           oop obj = _source_obj->obj_field(fd->offset());
1374           if (java_lang_Class::is_instance(obj)) {
1375             obj = HeapShared::scratch_java_mirror(obj);
1376           }
1377           print_oop_info_cr(_st, obj);
1378         }
1379         break;
1380       default:
1381         if (ArchiveHeapWriter::is_marked_as_native_pointer(_heap_info, _source_obj, fd->offset())) {
1382           print_as_native_pointer(fd);
1383         } else {
1384           fd->print_on_for(_st, cast_to_oop(_buffered_addr)); // name, offset, value
1385           _st->cr();
1386         }
1387       }
1388     }
1389 
1390     void print_as_native_pointer(fieldDescriptor* fd) {
1391       LP64_ONLY(assert(fd->field_type() == T_LONG, "must be"));
1392       NOT_LP64 (assert(fd->field_type() == T_INT,  "must be"));
1393 
1394       // We have a field that looks like an integer, but it's actually a pointer to a MetaspaceObj.
1395       address source_native_ptr = (address)
1396           LP64_ONLY(_source_obj->long_field(fd->offset()))
1397           NOT_LP64( _source_obj->int_field (fd->offset()));
1398       ArchiveBuilder* builder = ArchiveBuilder::current();
1399 
1400       // The value of the native pointer at runtime.
1401       address requested_native_ptr = builder->to_requested(builder->get_buffered_addr(source_native_ptr));
1402 
1403       // The address of _source_obj at runtime
1404       oop requested_obj = ArchiveHeapWriter::source_obj_to_requested_obj(_source_obj);
1405       // The address of this field in the requested space
1406       assert(requested_obj != nullptr, "Attempting to load field from null oop");
1407       address requested_field_addr = cast_from_oop<address>(requested_obj) + fd->offset();
1408 
1409       fd->print_on(_st);
1410       _st->print_cr(PTR_FORMAT " (marked metadata pointer @" PTR_FORMAT " )",
1411                     p2i(requested_native_ptr), p2i(requested_field_addr));
1412     }
1413   };
1414 
1415   // Print the fields of instanceOops, or the elements of arrayOops
1416   static void log_oop_details(ArchiveHeapInfo* heap_info, oop source_oop, address buffered_addr) {
1417     LogStreamHandle(Trace, aot, map, oops) st;
1418     if (st.is_enabled()) {
1419       Klass* source_klass = source_oop->klass();
1420       ArchiveBuilder* builder = ArchiveBuilder::current();
1421       Klass* requested_klass = builder->to_requested(builder->get_buffered_addr(source_klass));
1422 
1423       st.print(" - klass: ");
1424       source_klass->print_value_on(&st);
1425       st.print(" " PTR_FORMAT, p2i(requested_klass));
1426       st.cr();
1427 
1428       if (source_oop->is_typeArray()) {
1429         TypeArrayKlass::cast(source_klass)->oop_print_elements_on(typeArrayOop(source_oop), &st);
1430       } else if (source_oop->is_objArray()) {
1431         objArrayOop source_obj_array = objArrayOop(source_oop);
1432         for (int i = 0; i < source_obj_array->length(); i++) {
1433           st.print(" -%4d: ", i);
1434           oop obj = source_obj_array->obj_at(i);
1435           if (java_lang_Class::is_instance(obj)) {
1436             obj = HeapShared::scratch_java_mirror(obj);
1437           }
1438           print_oop_info_cr(&st, obj);
1439         }
1440       } else {
1441         st.print_cr(" - fields (%zu words):", source_oop->size());
1442         ArchivedFieldPrinter print_field(heap_info, &st, source_oop, buffered_addr);
1443         InstanceKlass::cast(source_klass)->print_nonstatic_fields(&print_field);
1444 
1445         if (java_lang_Class::is_instance(source_oop)) {
1446           oop scratch_mirror = source_oop;
1447           st.print(" - signature: ");
1448           print_class_signature_for_mirror(&st, scratch_mirror);
1449           st.cr();
1450 
1451           Klass* src_klass = java_lang_Class::as_Klass(scratch_mirror);
1452           if (src_klass != nullptr && src_klass->is_instance_klass()) {
1453             oop rr = HeapShared::scratch_resolved_references(InstanceKlass::cast(src_klass)->constants());
1454             st.print(" - archived_resolved_references: ");
1455             print_oop_info_cr(&st, rr);
1456 
1457             // We need to print the fields in the scratch_mirror, not the original mirror.
1458             // (if a class is not aot-initialized, static fields in its scratch mirror will be cleared).
1459             assert(scratch_mirror == HeapShared::scratch_java_mirror(src_klass->java_mirror()), "sanity");
1460             st.print_cr("- ---- static fields (%d):", java_lang_Class::static_oop_field_count(scratch_mirror));
1461             InstanceKlass::cast(src_klass)->do_local_static_fields(&print_field);
1462           }
1463         }
1464       }
1465     }
1466   }
1467 
1468   static void print_class_signature_for_mirror(outputStream* st, oop scratch_mirror) {
1469     assert(java_lang_Class::is_instance(scratch_mirror), "sanity");
1470     if (java_lang_Class::is_primitive(scratch_mirror)) {
1471       for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
1472         BasicType bt = (BasicType)i;
1473         if (!is_reference_type(bt) && scratch_mirror == HeapShared::scratch_java_mirror(bt)) {
1474           oop orig_mirror = Universe::java_mirror(bt);
1475           java_lang_Class::print_signature(orig_mirror, st);
1476           return;
1477         }
1478       }
1479       ShouldNotReachHere();
1480     }
1481     java_lang_Class::print_signature(scratch_mirror, st);
1482   }
1483 
1484   static void log_heap_roots() {
1485     LogStreamHandle(Trace, aot, map, oops) st;
1486     if (st.is_enabled()) {
1487       for (int i = 0; i < HeapShared::pending_roots()->length(); i++) {
1488         st.print("roots[%4d]: ", i);
1489         print_oop_info_cr(&st, HeapShared::pending_roots()->at(i).resolve());
1490       }
1491     }
1492   }
1493 
1494   // Example output:
1495   // - The first number is the requested address (if print_requested_addr == true)
1496   // - The second number is the narrowOop version of the requested address (if UseCompressedOops == true)
1497   //     0x00000007ffc7e840 (0xfff8fd08) java.lang.Class Ljava/util/Array;
1498   //     0x00000007ffc000f8 (0xfff8001f) [B length: 11
1499   static void print_oop_info_cr(outputStream* st, oop source_oop, bool print_requested_addr = true) {
1500     if (source_oop == nullptr) {
1501       st->print_cr("null");
1502     } else {
1503       ResourceMark rm;
1504       oop requested_obj = ArchiveHeapWriter::source_obj_to_requested_obj(source_oop);
1505       if (print_requested_addr) {
1506         st->print(PTR_FORMAT " ", p2i(requested_obj));
1507       }
1508       if (UseCompressedOops) {
1509         st->print("(0x%08x) ", CompressedOops::narrow_oop_value(requested_obj));
1510       }
1511       if (source_oop->is_array()) {
1512         int array_len = arrayOop(source_oop)->length();
1513         st->print_cr("%s length: %d", source_oop->klass()->external_name(), array_len);
1514       } else {
1515         st->print("%s", source_oop->klass()->external_name());
1516 
1517         if (java_lang_String::is_instance(source_oop)) {
1518           st->print(" ");
1519           java_lang_String::print(source_oop, st);
1520         } else if (java_lang_invoke_MethodType::is_instance(source_oop)) {
1521           st->print(" ");
1522           java_lang_invoke_MethodType::print_signature(source_oop, st);
1523         } else if (java_lang_Class::is_instance(source_oop)) {
1524           oop scratch_mirror = source_oop;
1525 
1526           st->print(" ");
1527           print_class_signature_for_mirror(st, scratch_mirror);
1528 
1529           Klass* src_klass = java_lang_Class::as_Klass(scratch_mirror);
1530           if (src_klass != nullptr && src_klass->is_instance_klass()) {
1531             InstanceKlass* buffered_klass =
1532               ArchiveBuilder::current()->get_buffered_addr(InstanceKlass::cast(src_klass));
1533             if (buffered_klass->has_aot_initialized_mirror()) {
1534               st->print(" (aot-inited)");
1535             }
1536           }
1537         }
1538         st->cr();
1539       }
1540     }
1541   }
1542 #endif // INCLUDE_CDS_JAVA_HEAP
1543 
1544   // Log all the data [base...top). Pretend that the base address
1545   // will be mapped to requested_base at run-time.
1546   static void log_as_hex(address base, address top, address requested_base, bool is_heap = false) {
1547     assert(top >= base, "must be");
1548 
1549     LogStreamHandle(Trace, aot, map) lsh;
1550     if (lsh.is_enabled()) {
1551       int unitsize = sizeof(address);
1552       if (is_heap && UseCompressedOops) {
1553         // This makes the compressed oop pointers easier to read, but
1554         // longs and doubles will be split into two words.
1555         unitsize = sizeof(narrowOop);
1556       }
1557       os::print_hex_dump(&lsh, base, top, unitsize, /* print_ascii=*/true, /* bytes_per_line=*/32, requested_base);
1558     }
1559   }
1560 
1561   static void log_header(FileMapInfo* mapinfo) {
1562     LogStreamHandle(Info, aot, map) lsh;
1563     if (lsh.is_enabled()) {
1564       mapinfo->print(&lsh);
1565     }
1566   }
1567 
1568 public:
1569   static void log(ArchiveBuilder* builder, FileMapInfo* mapinfo,
1570                   ArchiveHeapInfo* heap_info,
1571                   char* bitmap, size_t bitmap_size_in_bytes) {
1572     log_info(aot, map)("%s CDS archive map for %s", CDSConfig::is_dumping_static_archive() ? "Static" : "Dynamic", mapinfo->full_path());
1573 
1574     address header = address(mapinfo->header());
1575     address header_end = header + mapinfo->header()->header_size();
1576     log_region("header", header, header_end, nullptr);
1577     log_header(mapinfo);
1578     log_as_hex(header, header_end, nullptr);
1579 
1580     DumpRegion* rw_region = &builder->_rw_region;
1581     DumpRegion* ro_region = &builder->_ro_region;
1582 
1583     log_metaspace_region("rw region", rw_region, &builder->_rw_src_objs);
1584     log_metaspace_region("ro region", ro_region, &builder->_ro_src_objs);
1585 
1586     address bitmap_end = address(bitmap + bitmap_size_in_bytes);
1587     log_region("bitmap", address(bitmap), bitmap_end, nullptr);
1588     log_as_hex((address)bitmap, bitmap_end, nullptr);
1589 
1590 #if INCLUDE_CDS_JAVA_HEAP
1591     if (heap_info->is_used()) {
1592       log_heap_region(heap_info);
1593     }
1594 #endif
1595 
1596     log_info(aot, map)("[End of CDS archive map]");
1597   }
1598 }; // end ArchiveBuilder::CDSMapLogger
1599 
1600 void ArchiveBuilder::print_stats() {
1601   _alloc_stats.print_stats(int(_ro_region.used()), int(_rw_region.used()));
1602 }
1603 
1604 void ArchiveBuilder::write_archive(FileMapInfo* mapinfo, ArchiveHeapInfo* heap_info) {
1605   // Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with
1606   // MetaspaceShared::n_regions (internal to hotspot).
1607   assert(NUM_CDS_REGIONS == MetaspaceShared::n_regions, "sanity");
1608 
1609   write_region(mapinfo, MetaspaceShared::rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);
1610   write_region(mapinfo, MetaspaceShared::ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);
1611   write_region(mapinfo, MetaspaceShared::ac, &_ac_region, /*read_only=*/false,/*allow_exec=*/false);
1612 
1613   // Split pointer map into read-write and read-only bitmaps
1614   ArchivePtrMarker::initialize_rw_ro_ac_maps(&_rw_ptrmap, &_ro_ptrmap, &_ac_ptrmap);
1615 
1616   size_t bitmap_size_in_bytes;
1617   char* bitmap = mapinfo->write_bitmap_region(ArchivePtrMarker::rw_ptrmap(),
1618                                               ArchivePtrMarker::ro_ptrmap(),
1619                                               ArchivePtrMarker::ac_ptrmap(),
1620                                               heap_info,
1621                                               bitmap_size_in_bytes);
1622 
1623   if (heap_info->is_used()) {
1624     _total_heap_region_size = mapinfo->write_heap_region(heap_info);
1625   }
1626 
1627   print_region_stats(mapinfo, heap_info);
1628 
1629   mapinfo->set_requested_base((char*)MetaspaceShared::requested_base_address());
1630   mapinfo->set_header_crc(mapinfo->compute_header_crc());
1631   // After this point, we should not write any data into mapinfo->header() since this
1632   // would corrupt its checksum we have calculated before.
1633   mapinfo->write_header();
1634   mapinfo->close();
1635 
1636   aot_log_info(aot)("Full module graph = %s", CDSConfig::is_dumping_full_module_graph() ? "enabled" : "disabled");
1637   if (log_is_enabled(Info, aot)) {
1638     print_stats();
1639   }
1640 
1641   if (log_is_enabled(Info, aot, map)) {
1642     CDSMapLogger::log(this, mapinfo, heap_info,
1643                       bitmap, bitmap_size_in_bytes);
1644   }
1645   CDS_JAVA_HEAP_ONLY(HeapShared::destroy_archived_object_cache());
1646   FREE_C_HEAP_ARRAY(char, bitmap);
1647 }
1648 
1649 void ArchiveBuilder::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only,  bool allow_exec) {
1650   mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);
1651 }
1652 
1653 void ArchiveBuilder::count_relocated_pointer(bool tagged, bool nulled) {
1654   _relocated_ptr_info._num_ptrs ++;
1655   _relocated_ptr_info._num_tagged_ptrs += tagged ? 1 : 0;
1656   _relocated_ptr_info._num_nulled_ptrs += nulled ? 1 : 0;
1657 }
1658 
1659 void ArchiveBuilder::print_region_stats(FileMapInfo *mapinfo, ArchiveHeapInfo* heap_info) {
1660   // Print statistics of all the regions
1661   const size_t bitmap_used = mapinfo->region_at(MetaspaceShared::bm)->used();
1662   const size_t bitmap_reserved = mapinfo->region_at(MetaspaceShared::bm)->used_aligned();
1663   const size_t total_reserved = _ro_region.reserved()  + _rw_region.reserved() +
1664                                 bitmap_reserved +
1665                                 _total_heap_region_size;
1666   const size_t total_bytes = _ro_region.used()  + _rw_region.used() +
1667                              bitmap_used +
1668                              _total_heap_region_size;
1669   const double total_u_perc = percent_of(total_bytes, total_reserved);
1670 
1671   _rw_region.print(total_reserved);
1672   _ro_region.print(total_reserved);
1673   _ac_region.print(total_reserved);
1674 
1675   print_bitmap_region_stats(bitmap_used, total_reserved);
1676 
1677   if (heap_info->is_used()) {
1678     print_heap_region_stats(heap_info, total_reserved);
1679   }
1680 
1681   aot_log_debug(aot)("total   : %9zu [100.0%% of total] out of %9zu bytes [%5.1f%% used]",
1682                  total_bytes, total_reserved, total_u_perc);
1683 }
1684 
1685 void ArchiveBuilder::print_bitmap_region_stats(size_t size, size_t total_size) {
1686   aot_log_debug(aot)("bm space: %9zu [ %4.1f%% of total] out of %9zu bytes [100.0%% used]",
1687                  size, size/double(total_size)*100.0, size);
1688 }
1689 
1690 void ArchiveBuilder::print_heap_region_stats(ArchiveHeapInfo *info, size_t total_size) {
1691   char* start = info->buffer_start();
1692   size_t size = info->buffer_byte_size();
1693   char* top = start + size;
1694   aot_log_debug(aot)("hp space: %9zu [ %4.1f%% of total] out of %9zu bytes [100.0%% used] at " INTPTR_FORMAT,
1695                      size, size/double(total_size)*100.0, size, p2i(start));
1696 }
1697 
1698 void ArchiveBuilder::report_out_of_space(const char* name, size_t needed_bytes) {
1699   // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space.
1700   // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes
1701   // or so.
1702   _rw_region.print_out_of_space_msg(name, needed_bytes);
1703   _ro_region.print_out_of_space_msg(name, needed_bytes);
1704 
1705   log_error(aot)("Unable to allocate from '%s' region: Please reduce the number of shared classes.", name);
1706   MetaspaceShared::unrecoverable_writing_error();
1707 }