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/heapShared.hpp"
  37 #include "cds/metaspaceShared.hpp"
  38 #include "cds/regeneratedClasses.hpp"
  39 #include "classfile/classLoader.hpp"
  40 #include "classfile/classLoaderDataShared.hpp"
  41 #include "classfile/classLoaderExt.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 "logging/logStream.hpp"
  51 #include "memory/allStatic.hpp"
  52 #include "memory/memoryReserver.hpp"
  53 #include "memory/memRegion.hpp"
  54 #include "memory/resourceArea.hpp"
  55 #include "oops/compressedKlass.inline.hpp"
  56 #include "oops/instanceKlass.hpp"
  57 #include "oops/methodCounters.hpp"
  58 #include "oops/methodData.hpp"
  59 #include "oops/objArrayKlass.hpp"
  60 #include "oops/objArrayOop.inline.hpp"
  61 #include "oops/oopHandle.inline.hpp"
  62 #include "oops/trainingData.hpp"
  63 #include "runtime/arguments.hpp"
  64 #include "runtime/fieldDescriptor.inline.hpp"
  65 #include "runtime/globals_extension.hpp"
  66 #include "runtime/javaThread.hpp"
  67 #include "runtime/sharedRuntime.hpp"
  68 #include "utilities/align.hpp"
  69 #include "utilities/bitMap.inline.hpp"
  70 #include "utilities/formatBuffer.hpp"
  71 
  72 ArchiveBuilder* ArchiveBuilder::_current = nullptr;
  73 
  74 ArchiveBuilder::OtherROAllocMark::~OtherROAllocMark() {
  75   char* newtop = ArchiveBuilder::current()->_ro_region.top();
  76   ArchiveBuilder::alloc_stats()->record_other_type(int(newtop - _oldtop), true);
  77 }
  78 
  79 ArchiveBuilder::SourceObjList::SourceObjList() : _ptrmap(16 * K, mtClassShared) {
  80   _total_bytes = 0;
  81   _objs = new (mtClassShared) GrowableArray<SourceObjInfo*>(128 * K, mtClassShared);
  82 }
  83 
  84 ArchiveBuilder::SourceObjList::~SourceObjList() {
  85   delete _objs;
  86 }
  87 
  88 void ArchiveBuilder::SourceObjList::append(SourceObjInfo* src_info) {
  89   // Save this source object for copying
  90   src_info->set_id(_objs->length());
  91   _objs->append(src_info);
  92 
  93   // Prepare for marking the pointers in this source object
  94   assert(is_aligned(_total_bytes, sizeof(address)), "must be");
  95   src_info->set_ptrmap_start(_total_bytes / sizeof(address));
  96   _total_bytes = align_up(_total_bytes + (uintx)src_info->size_in_bytes(), sizeof(address));
  97   src_info->set_ptrmap_end(_total_bytes / sizeof(address));
  98 
  99   BitMap::idx_t bitmap_size_needed = BitMap::idx_t(src_info->ptrmap_end());
 100   if (_ptrmap.size() <= bitmap_size_needed) {
 101     _ptrmap.resize((bitmap_size_needed + 1) * 2);
 102   }
 103 }
 104 
 105 void ArchiveBuilder::SourceObjList::remember_embedded_pointer(SourceObjInfo* src_info, MetaspaceClosure::Ref* ref) {
 106   // src_obj contains a pointer. Remember the location of this pointer in _ptrmap,
 107   // so that we can copy/relocate it later.
 108   src_info->set_has_embedded_pointer();
 109   address src_obj = src_info->source_addr();
 110   address* field_addr = ref->addr();
 111   assert(src_info->ptrmap_start() < _total_bytes, "sanity");
 112   assert(src_info->ptrmap_end() <= _total_bytes, "sanity");
 113   assert(*field_addr != nullptr, "should have checked");
 114 
 115   intx field_offset_in_bytes = ((address)field_addr) - src_obj;
 116   DEBUG_ONLY(int src_obj_size = src_info->size_in_bytes();)
 117   assert(field_offset_in_bytes >= 0, "must be");
 118   assert(field_offset_in_bytes + intx(sizeof(intptr_t)) <= intx(src_obj_size), "must be");
 119   assert(is_aligned(field_offset_in_bytes, sizeof(address)), "must be");
 120 
 121   BitMap::idx_t idx = BitMap::idx_t(src_info->ptrmap_start() + (uintx)(field_offset_in_bytes / sizeof(address)));
 122   _ptrmap.set_bit(BitMap::idx_t(idx));
 123 }
 124 
 125 class RelocateEmbeddedPointers : public BitMapClosure {
 126   ArchiveBuilder* _builder;
 127   address _buffered_obj;
 128   BitMap::idx_t _start_idx;
 129 public:
 130   RelocateEmbeddedPointers(ArchiveBuilder* builder, address buffered_obj, BitMap::idx_t start_idx) :
 131     _builder(builder), _buffered_obj(buffered_obj), _start_idx(start_idx) {}
 132 
 133   bool do_bit(BitMap::idx_t bit_offset) {
 134     size_t field_offset = size_t(bit_offset - _start_idx) * sizeof(address);
 135     address* ptr_loc = (address*)(_buffered_obj + field_offset);
 136 
 137     address old_p_with_tags = *ptr_loc;
 138     assert(old_p_with_tags != nullptr, "null ptrs shouldn't have been marked");
 139 
 140     address old_p = MetaspaceClosure::strip_tags(old_p_with_tags);
 141     uintx tags = MetaspaceClosure::decode_tags(old_p_with_tags);
 142     address new_p = _builder->get_buffered_addr(old_p);
 143 
 144     bool nulled;
 145     if (new_p == nullptr) {
 146       // old_p had a FollowMode of set_to_null
 147       nulled = true;
 148     } else {
 149       new_p = MetaspaceClosure::add_tags(new_p, tags);
 150       nulled = false;
 151     }
 152 
 153     log_trace(aot)("Ref: [" PTR_FORMAT "] -> " PTR_FORMAT " => " PTR_FORMAT " %zu",
 154                    p2i(ptr_loc), p2i(old_p) + tags, p2i(new_p), tags);
 155 
 156     ArchivePtrMarker::set_and_mark_pointer(ptr_loc, new_p);
 157     ArchiveBuilder::current()->count_relocated_pointer(tags != 0, nulled);
 158     return true; // keep iterating the bitmap
 159   }
 160 };
 161 
 162 void ArchiveBuilder::SourceObjList::relocate(int i, ArchiveBuilder* builder) {
 163   SourceObjInfo* src_info = objs()->at(i);
 164   assert(src_info->should_copy(), "must be");
 165   BitMap::idx_t start = BitMap::idx_t(src_info->ptrmap_start()); // inclusive
 166   BitMap::idx_t end = BitMap::idx_t(src_info->ptrmap_end());     // exclusive
 167 
 168   RelocateEmbeddedPointers relocator(builder, src_info->buffered_addr(), start);
 169   _ptrmap.iterate(&relocator, start, end);
 170 }
 171 
 172 ArchiveBuilder::ArchiveBuilder() :
 173   _current_dump_region(nullptr),
 174   _buffer_bottom(nullptr),
 175   _requested_static_archive_bottom(nullptr),
 176   _requested_static_archive_top(nullptr),
 177   _requested_dynamic_archive_bottom(nullptr),
 178   _requested_dynamic_archive_top(nullptr),
 179   _mapped_static_archive_bottom(nullptr),
 180   _mapped_static_archive_top(nullptr),
 181   _buffer_to_requested_delta(0),
 182   _pz_region("pz", MAX_SHARED_DELTA), // protection zone -- used only during dumping; does NOT exist in cds archive.
 183   _rw_region("rw", MAX_SHARED_DELTA),
 184   _ro_region("ro", MAX_SHARED_DELTA),
 185   _ac_region("ac", MAX_SHARED_DELTA),
 186   _ptrmap(mtClassShared),
 187   _rw_ptrmap(mtClassShared),
 188   _ro_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                                              MetaspaceShared::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     MetaspaceShared::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)MetaspaceShared::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::shared_metaspace_base();
 371     _mapped_static_archive_top  = (address)MetaspaceObj::shared_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, MetaspaceShared::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     MetaspaceShared::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(MetaspaceShared::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() && MetaspaceShared::is_shared_static(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() && MetaspaceShared::is_in_shared_metaspace(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     if (CDSConfig::is_dumping_adapters()) {
 569       AdapterHandlerEntry* entry = (AdapterHandlerEntry*)ref->obj();
 570       return AdapterHandlerLibrary::is_abstract_method_adapter(entry) ? set_to_null : make_a_copy;
 571     } else {
 572       return set_to_null;
 573     }
 574   } else {
 575     if (ref->msotype() == MetaspaceObj::ClassType) {
 576       Klass* klass = (Klass*)ref->obj();
 577       assert(klass->is_klass(), "must be");
 578       if (is_excluded(klass)) {
 579         ResourceMark rm;
 580         log_debug(cds, dynamic)("Skipping class (excluded): %s", klass->external_name());
 581         return set_to_null;
 582       }
 583     }
 584 
 585     return make_a_copy;
 586   }
 587 }
 588 
 589 void ArchiveBuilder::start_dump_region(DumpRegion* next) {
 590   current_dump_region()->pack(next);
 591   _current_dump_region = next;
 592 }
 593 
 594 char* ArchiveBuilder::ro_strdup(const char* s) {
 595   char* archived_str = ro_region_alloc((int)strlen(s) + 1);
 596   strcpy(archived_str, s);
 597   return archived_str;
 598 }
 599 
 600 // The objects that have embedded pointers will sink
 601 // towards the end of the list. This ensures we have a maximum
 602 // number of leading zero bits in the relocation bitmap.
 603 int ArchiveBuilder::compare_src_objs(SourceObjInfo** a, SourceObjInfo** b) {
 604   if ((*a)->has_embedded_pointer() && !(*b)->has_embedded_pointer()) {
 605     return 1;
 606   } else if (!(*a)->has_embedded_pointer() && (*b)->has_embedded_pointer()) {
 607     return -1;
 608   } else {
 609     // This is necessary to keep the sorting order stable. Otherwise the
 610     // archive's contents may not be deterministic.
 611     return (*a)->id() - (*b)->id();
 612   }
 613 }
 614 
 615 void ArchiveBuilder::sort_metadata_objs() {
 616   _rw_src_objs.objs()->sort(compare_src_objs);
 617   _ro_src_objs.objs()->sort(compare_src_objs);
 618 }
 619 
 620 void ArchiveBuilder::dump_rw_metadata() {
 621   ResourceMark rm;
 622   aot_log_info(aot)("Allocating RW objects ... ");
 623   make_shallow_copies(&_rw_region, &_rw_src_objs);
 624 
 625 #if INCLUDE_CDS_JAVA_HEAP
 626   if (CDSConfig::is_dumping_full_module_graph()) {
 627     // Archive the ModuleEntry's and PackageEntry's of the 3 built-in loaders
 628     char* start = rw_region()->top();
 629     ClassLoaderDataShared::allocate_archived_tables();
 630     alloc_stats()->record_modules(rw_region()->top() - start, /*read_only*/false);
 631   }
 632 #endif
 633 }
 634 
 635 void ArchiveBuilder::dump_ro_metadata() {
 636   ResourceMark rm;
 637   aot_log_info(aot)("Allocating RO objects ... ");
 638 
 639   start_dump_region(&_ro_region);
 640   make_shallow_copies(&_ro_region, &_ro_src_objs);
 641 
 642 #if INCLUDE_CDS_JAVA_HEAP
 643   if (CDSConfig::is_dumping_full_module_graph()) {
 644     char* start = ro_region()->top();
 645     ClassLoaderDataShared::init_archived_tables();
 646     alloc_stats()->record_modules(ro_region()->top() - start, /*read_only*/true);
 647   }
 648 #endif
 649 
 650   RegeneratedClasses::record_regenerated_objects();
 651 }
 652 
 653 void ArchiveBuilder::make_shallow_copies(DumpRegion *dump_region,
 654                                          const ArchiveBuilder::SourceObjList* src_objs) {
 655   for (int i = 0; i < src_objs->objs()->length(); i++) {
 656     make_shallow_copy(dump_region, src_objs->objs()->at(i));
 657   }
 658   aot_log_info(aot)("done (%d objects)", src_objs->objs()->length());
 659 }
 660 
 661 void ArchiveBuilder::make_shallow_copy(DumpRegion *dump_region, SourceObjInfo* src_info) {
 662   address src = src_info->source_addr();
 663   int bytes = src_info->size_in_bytes();
 664   char* dest;
 665   char* oldtop;
 666   char* newtop;
 667 
 668   oldtop = dump_region->top();
 669   if (src_info->msotype() == MetaspaceObj::ClassType) {
 670     // Allocate space for a pointer directly in front of the future InstanceKlass, so
 671     // we can do a quick lookup from InstanceKlass* -> RunTimeClassInfo*
 672     // without building another hashtable. See RunTimeClassInfo::get_for()
 673     // in systemDictionaryShared.cpp.
 674     Klass* klass = (Klass*)src;
 675     if (klass->is_instance_klass()) {
 676       SystemDictionaryShared::validate_before_archiving(InstanceKlass::cast(klass));
 677       dump_region->allocate(sizeof(address));
 678     }
 679     // Allocate space for the future InstanceKlass with proper alignment
 680     const size_t alignment =
 681 #ifdef _LP64
 682       UseCompressedClassPointers ?
 683         nth_bit(ArchiveBuilder::precomputed_narrow_klass_shift()) :
 684         SharedSpaceObjectAlignment;
 685 #else
 686       SharedSpaceObjectAlignment;
 687 #endif
 688     dest = dump_region->allocate(bytes, alignment);
 689   } else {
 690     dest = dump_region->allocate(bytes);
 691   }
 692   newtop = dump_region->top();
 693 
 694   memcpy(dest, src, bytes);
 695 
 696   // Update the hash of buffered sorted symbols for static dump so that the symbols have deterministic contents
 697   if (CDSConfig::is_dumping_static_archive() && (src_info->msotype() == MetaspaceObj::SymbolType)) {
 698     Symbol* buffered_symbol = (Symbol*)dest;
 699     assert(((Symbol*)src)->is_permanent(), "archived symbols must be permanent");
 700     buffered_symbol->update_identity_hash();
 701   }
 702 
 703   {
 704     bool created;
 705     _buffered_to_src_table.put_if_absent((address)dest, src, &created);
 706     assert(created, "must be");
 707     if (_buffered_to_src_table.maybe_grow()) {
 708       log_info(aot, hashtables)("Expanded _buffered_to_src_table table to %d", _buffered_to_src_table.table_size());
 709     }
 710   }
 711 
 712   intptr_t* archived_vtable = CppVtables::get_archived_vtable(src_info->msotype(), (address)dest);
 713   if (archived_vtable != nullptr) {
 714     *(address*)dest = (address)archived_vtable;
 715     ArchivePtrMarker::mark_pointer((address*)dest);
 716   }
 717 
 718   log_trace(aot)("Copy: " PTR_FORMAT " ==> " PTR_FORMAT " %d", p2i(src), p2i(dest), bytes);
 719   src_info->set_buffered_addr((address)dest);
 720 
 721   _alloc_stats.record(src_info->msotype(), int(newtop - oldtop), src_info->read_only());
 722 
 723   DEBUG_ONLY(_alloc_stats.verify((int)dump_region->used(), src_info->read_only()));
 724 }
 725 
 726 // This is used by code that hand-assembles data structures, such as the LambdaProxyClassKey, that are
 727 // not handled by MetaspaceClosure.
 728 void ArchiveBuilder::write_pointer_in_buffer(address* ptr_location, address src_addr) {
 729   assert(is_in_buffer_space(ptr_location), "must be");
 730   if (src_addr == nullptr) {
 731     *ptr_location = nullptr;
 732     ArchivePtrMarker::clear_pointer(ptr_location);
 733   } else {
 734     *ptr_location = get_buffered_addr(src_addr);
 735     ArchivePtrMarker::mark_pointer(ptr_location);
 736   }
 737 }
 738 
 739 void ArchiveBuilder::mark_and_relocate_to_buffered_addr(address* ptr_location) {
 740   assert(*ptr_location != nullptr, "sanity");
 741   if (!is_in_mapped_static_archive(*ptr_location)) {
 742     *ptr_location = get_buffered_addr(*ptr_location);
 743   }
 744   ArchivePtrMarker::mark_pointer(ptr_location);
 745 }
 746 
 747 bool ArchiveBuilder::has_been_archived(address src_addr) const {
 748   SourceObjInfo* p = _src_obj_table.get(src_addr);
 749   return (p != nullptr);
 750 }
 751 
 752 bool ArchiveBuilder::has_been_buffered(address src_addr) const {
 753   if (RegeneratedClasses::has_been_regenerated(src_addr) ||
 754       _src_obj_table.get(src_addr) == nullptr ||
 755       get_buffered_addr(src_addr) == nullptr) {
 756     return false;
 757   } else {
 758     return true;
 759   }
 760 }
 761 
 762 address ArchiveBuilder::get_buffered_addr(address src_addr) const {
 763   SourceObjInfo* p = _src_obj_table.get(src_addr);
 764   assert(p != nullptr, "src_addr " INTPTR_FORMAT " is used but has not been archived",
 765          p2i(src_addr));
 766 
 767   return p->buffered_addr();
 768 }
 769 
 770 address ArchiveBuilder::get_source_addr(address buffered_addr) const {
 771   assert(is_in_buffer_space(buffered_addr), "must be");
 772   address* src_p = _buffered_to_src_table.get(buffered_addr);
 773   assert(src_p != nullptr && *src_p != nullptr, "must be");
 774   return *src_p;
 775 }
 776 
 777 void ArchiveBuilder::relocate_embedded_pointers(ArchiveBuilder::SourceObjList* src_objs) {
 778   for (int i = 0; i < src_objs->objs()->length(); i++) {
 779     src_objs->relocate(i, this);
 780   }
 781 }
 782 
 783 void ArchiveBuilder::relocate_metaspaceobj_embedded_pointers() {
 784   aot_log_info(aot)("Relocating embedded pointers in core regions ... ");
 785   relocate_embedded_pointers(&_rw_src_objs);
 786   relocate_embedded_pointers(&_ro_src_objs);
 787   log_info(cds)("Relocating %zu pointers, %zu tagged, %zu nulled",
 788                 _relocated_ptr_info._num_ptrs,
 789                 _relocated_ptr_info._num_tagged_ptrs,
 790                 _relocated_ptr_info._num_nulled_ptrs);
 791 }
 792 
 793 #define ADD_COUNT(x) \
 794   x += 1; \
 795   x ## _a += aotlinked ? 1 : 0; \
 796   x ## _i += inited ? 1 : 0;
 797 
 798 #define DECLARE_INSTANCE_KLASS_COUNTER(x) \
 799   int x = 0; \
 800   int x ## _a = 0; \
 801   int x ## _i = 0;
 802 
 803 void ArchiveBuilder::make_klasses_shareable() {
 804   DECLARE_INSTANCE_KLASS_COUNTER(num_instance_klasses);
 805   DECLARE_INSTANCE_KLASS_COUNTER(num_boot_klasses);
 806   DECLARE_INSTANCE_KLASS_COUNTER(num_vm_klasses);
 807   DECLARE_INSTANCE_KLASS_COUNTER(num_platform_klasses);
 808   DECLARE_INSTANCE_KLASS_COUNTER(num_app_klasses);
 809   DECLARE_INSTANCE_KLASS_COUNTER(num_old_klasses);
 810   DECLARE_INSTANCE_KLASS_COUNTER(num_hidden_klasses);
 811   DECLARE_INSTANCE_KLASS_COUNTER(num_enum_klasses);
 812   DECLARE_INSTANCE_KLASS_COUNTER(num_unregistered_klasses);
 813   int num_unlinked_klasses = 0;
 814   int num_obj_array_klasses = 0;
 815   int num_type_array_klasses = 0;
 816 
 817   int boot_unlinked = 0;
 818   int platform_unlinked = 0;
 819   int app_unlinked = 0;
 820   int unreg_unlinked = 0;
 821 
 822   for (int i = 0; i < klasses()->length(); i++) {
 823     // Some of the code in ConstantPool::remove_unshareable_info() requires the classes
 824     // to be in linked state, so it must be call here before the next loop, which returns
 825     // all classes to unlinked state.
 826     Klass* k = get_buffered_addr(klasses()->at(i));
 827     if (k->is_instance_klass()) {
 828       InstanceKlass::cast(k)->constants()->remove_unshareable_info();
 829     }
 830   }
 831 
 832   for (int i = 0; i < klasses()->length(); i++) {
 833     const char* type;
 834     const char* unlinked = "";
 835     const char* kind = "";
 836     const char* hidden = "";
 837     const char* old = "";
 838     const char* generated = "";
 839     const char* aotlinked_msg = "";
 840     const char* inited_msg = "";
 841     Klass* k = get_buffered_addr(klasses()->at(i));
 842     bool inited = false;
 843     k->remove_java_mirror();
 844 #ifdef _LP64
 845     if (UseCompactObjectHeaders) {
 846       Klass* requested_k = to_requested(k);
 847       address narrow_klass_base = _requested_static_archive_bottom; // runtime encoding base == runtime mapping start
 848       const int narrow_klass_shift = precomputed_narrow_klass_shift();
 849       narrowKlass nk = CompressedKlassPointers::encode_not_null_without_asserts(requested_k, narrow_klass_base, narrow_klass_shift);
 850       k->set_prototype_header(markWord::prototype().set_narrow_klass(nk));
 851     }
 852 #endif //_LP64
 853     if (k->is_objArray_klass()) {
 854       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
 855       // on their array classes.
 856       num_obj_array_klasses ++;
 857       type = "array";
 858     } else if (k->is_typeArray_klass()) {
 859       num_type_array_klasses ++;
 860       type = "array";
 861       k->remove_unshareable_info();
 862     } else {
 863       assert(k->is_instance_klass(), " must be");
 864       InstanceKlass* ik = InstanceKlass::cast(k);
 865       InstanceKlass* src_ik = get_source_addr(ik);
 866       bool aotlinked = AOTClassLinker::is_candidate(src_ik);
 867       inited = ik->has_aot_initialized_mirror();
 868       ADD_COUNT(num_instance_klasses);
 869       if (ik->is_hidden()) {
 870         ADD_COUNT(num_hidden_klasses);
 871         hidden = " hidden";
 872         oop loader = k->class_loader();
 873         if (loader == nullptr) {
 874           type = "boot";
 875           ADD_COUNT(num_boot_klasses);
 876         } else if (loader == SystemDictionary::java_platform_loader()) {
 877           type = "plat";
 878           ADD_COUNT(num_platform_klasses);
 879         } else if (loader == SystemDictionary::java_system_loader()) {
 880           type = "app";
 881           ADD_COUNT(num_app_klasses);
 882         } else {
 883           type = "bad";
 884           assert(0, "shouldn't happen");
 885         }
 886         if (CDSConfig::is_dumping_method_handles()) {
 887           assert(HeapShared::is_archivable_hidden_klass(ik), "sanity");
 888         } else {
 889           // Legacy CDS support for lambda proxies
 890           CDS_JAVA_HEAP_ONLY(assert(HeapShared::is_lambda_proxy_klass(ik), "sanity");)
 891         }
 892       } else if (ik->defined_by_boot_loader()) {
 893         type = "boot";
 894         ADD_COUNT(num_boot_klasses);
 895       } else if (ik->defined_by_platform_loader()) {
 896         type = "plat";
 897         ADD_COUNT(num_platform_klasses);
 898       } else if (ik->defined_by_app_loader()) {
 899         type = "app";
 900         ADD_COUNT(num_app_klasses);
 901       } else {
 902         assert(ik->defined_by_other_loaders(), "must be");
 903         type = "unreg";
 904         ADD_COUNT(num_unregistered_klasses);
 905       }
 906 
 907       if (AOTClassLinker::is_vm_class(src_ik)) {
 908         ADD_COUNT(num_vm_klasses);
 909       }
 910 
 911       if (!ik->is_linked()) {
 912         num_unlinked_klasses ++;
 913         unlinked = " unlinked";
 914         if (ik->defined_by_boot_loader()) {
 915           boot_unlinked ++;
 916         } else if (ik->defined_by_platform_loader()) {
 917           platform_unlinked ++;
 918         } else if (ik->defined_by_app_loader()) {
 919           app_unlinked ++;
 920         } else {
 921           unreg_unlinked ++;
 922         }
 923       }
 924 
 925       if (ik->is_interface()) {
 926         kind = " interface";
 927       } else if (src_ik->is_enum_subclass()) {
 928         kind = " enum";
 929         ADD_COUNT(num_enum_klasses);
 930       }
 931 
 932       if (!ik->can_be_verified_at_dumptime()) {
 933         ADD_COUNT(num_old_klasses);
 934         old = " old";
 935       }
 936 
 937       if (ik->is_generated_shared_class()) {
 938         generated = " generated";
 939       }
 940       if (aotlinked) {
 941         aotlinked_msg = " aot-linked";
 942       }
 943       if (inited) {
 944         if (InstanceKlass::cast(k)->static_field_size() == 0) {
 945           inited_msg = " inited (no static fields)";
 946         } else {
 947           inited_msg = " inited";
 948         }
 949       }
 950 
 951       MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread::current(), ik);
 952       ik->remove_unshareable_info();
 953     }
 954 
 955     if (aot_log_is_enabled(Debug, aot, class)) {
 956       ResourceMark rm;
 957       aot_log_debug(aot, class)("klasses[%5d] = " PTR_FORMAT " %-5s %s%s%s%s%s%s%s%s", i,
 958                             p2i(to_requested(k)), type, k->external_name(),
 959                             kind, hidden, old, unlinked, generated, aotlinked_msg, inited_msg);
 960     }
 961   }
 962 
 963 #define STATS_FORMAT    "= %5d, aot-linked = %5d, inited = %5d"
 964 #define STATS_PARAMS(x) num_ ## x, num_ ## x ## _a, num_ ## x ## _i
 965 
 966   aot_log_info(aot)("Number of classes %d", num_instance_klasses + num_obj_array_klasses + num_type_array_klasses);
 967   aot_log_info(aot)("    instance classes   " STATS_FORMAT, STATS_PARAMS(instance_klasses));
 968   aot_log_info(aot)("      boot             " STATS_FORMAT, STATS_PARAMS(boot_klasses));
 969   aot_log_info(aot)("        vm             " STATS_FORMAT, STATS_PARAMS(vm_klasses));
 970   aot_log_info(aot)("      platform         " STATS_FORMAT, STATS_PARAMS(platform_klasses));
 971   aot_log_info(aot)("      app              " STATS_FORMAT, STATS_PARAMS(app_klasses));
 972   aot_log_info(aot)("      unregistered     " STATS_FORMAT, STATS_PARAMS(unregistered_klasses));
 973   aot_log_info(aot)("      (enum)           " STATS_FORMAT, STATS_PARAMS(enum_klasses));
 974   aot_log_info(aot)("      (hidden)         " STATS_FORMAT, STATS_PARAMS(hidden_klasses));
 975   aot_log_info(aot)("      (old)            " STATS_FORMAT, STATS_PARAMS(old_klasses));
 976   aot_log_info(aot)("      (unlinked)       = %5d, boot = %d, plat = %d, app = %d, unreg = %d",
 977                 num_unlinked_klasses, boot_unlinked, platform_unlinked, app_unlinked, unreg_unlinked);
 978   aot_log_info(aot)("    obj array classes  = %5d", num_obj_array_klasses);
 979   aot_log_info(aot)("    type array classes = %5d", num_type_array_klasses);
 980   aot_log_info(aot)("               symbols = %5d", _symbols->length());
 981 
 982 #undef STATS_FORMAT
 983 #undef STATS_PARAMS
 984 
 985   DynamicArchive::make_array_klasses_shareable();
 986 }
 987 
 988 void ArchiveBuilder::make_training_data_shareable() {
 989   auto clean_td = [&] (address& src_obj,  SourceObjInfo& info) {
 990     if (!is_in_buffer_space(info.buffered_addr())) {
 991       return;
 992     }
 993 
 994     if (info.msotype() == MetaspaceObj::KlassTrainingDataType ||
 995         info.msotype() == MetaspaceObj::MethodTrainingDataType ||
 996         info.msotype() == MetaspaceObj::CompileTrainingDataType) {
 997       TrainingData* buffered_td = (TrainingData*)info.buffered_addr();
 998       buffered_td->remove_unshareable_info();
 999     } else if (info.msotype() == MetaspaceObj::MethodDataType) {
1000       MethodData* buffered_mdo = (MethodData*)info.buffered_addr();
1001       buffered_mdo->remove_unshareable_info();
1002     } else if (info.msotype() == MetaspaceObj::MethodCountersType) {
1003       MethodCounters* buffered_mc = (MethodCounters*)info.buffered_addr();
1004       buffered_mc->remove_unshareable_info();
1005     }
1006   };
1007   _src_obj_table.iterate_all(clean_td);
1008 }
1009 
1010 void ArchiveBuilder::serialize_dynamic_archivable_items(SerializeClosure* soc) {
1011   SymbolTable::serialize_shared_table_header(soc, false);
1012   SystemDictionaryShared::serialize_dictionary_headers(soc, false);
1013   DynamicArchive::serialize_array_klasses(soc);
1014   AOTLinkedClassBulkLoader::serialize(soc, false);
1015 }
1016 
1017 uintx ArchiveBuilder::buffer_to_offset(address p) const {
1018   address requested_p = to_requested(p);
1019   assert(requested_p >= _requested_static_archive_bottom, "must be");
1020   return requested_p - _requested_static_archive_bottom;
1021 }
1022 
1023 uintx ArchiveBuilder::any_to_offset(address p) const {
1024   if (is_in_mapped_static_archive(p)) {
1025     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1026     return p - _mapped_static_archive_bottom;
1027   }
1028   if (!is_in_buffer_space(p)) {
1029     // p must be a "source" address
1030     p = get_buffered_addr(p);
1031   }
1032   return buffer_to_offset(p);
1033 }
1034 
1035 address ArchiveBuilder::offset_to_buffered_address(u4 offset) const {
1036   address requested_addr = _requested_static_archive_bottom + offset;
1037   address buffered_addr = requested_addr - _buffer_to_requested_delta;
1038   assert(is_in_buffer_space(buffered_addr), "bad offset");
1039   return buffered_addr;
1040 }
1041 
1042 void ArchiveBuilder::start_ac_region() {
1043   ro_region()->pack();
1044   start_dump_region(&_ac_region);
1045 }
1046 
1047 void ArchiveBuilder::end_ac_region() {
1048   _ac_region.pack();
1049 }
1050 
1051 #if INCLUDE_CDS_JAVA_HEAP
1052 narrowKlass ArchiveBuilder::get_requested_narrow_klass(Klass* k) {
1053   assert(CDSConfig::is_dumping_heap(), "sanity");
1054   k = get_buffered_klass(k);
1055   Klass* requested_k = to_requested(k);
1056   const int narrow_klass_shift = ArchiveBuilder::precomputed_narrow_klass_shift();
1057 #ifdef ASSERT
1058   const size_t klass_alignment = MAX2(SharedSpaceObjectAlignment, (size_t)nth_bit(narrow_klass_shift));
1059   assert(is_aligned(k, klass_alignment), "Klass " PTR_FORMAT " misaligned.", p2i(k));
1060 #endif
1061   address narrow_klass_base = _requested_static_archive_bottom; // runtime encoding base == runtime mapping start
1062   // Note: use the "raw" version of encode that takes explicit narrow klass base and shift. Don't use any
1063   // of the variants that do sanity checks, nor any of those that use the current - dump - JVM's encoding setting.
1064   return CompressedKlassPointers::encode_not_null_without_asserts(requested_k, narrow_klass_base, narrow_klass_shift);
1065 }
1066 #endif // INCLUDE_CDS_JAVA_HEAP
1067 
1068 // RelocateBufferToRequested --- Relocate all the pointers in rw/ro,
1069 // so that the archive can be mapped to the "requested" location without runtime relocation.
1070 //
1071 // - See ArchiveBuilder header for the definition of "buffer", "mapped" and "requested"
1072 // - ArchivePtrMarker::ptrmap() marks all the pointers in the rw/ro regions
1073 // - Every pointer must have one of the following values:
1074 //   [a] nullptr:
1075 //       No relocation is needed. Remove this pointer from ptrmap so we don't need to
1076 //       consider it at runtime.
1077 //   [b] Points into an object X which is inside the buffer:
1078 //       Adjust this pointer by _buffer_to_requested_delta, so it points to X
1079 //       when the archive is mapped at the requested location.
1080 //   [c] Points into an object Y which is inside mapped static archive:
1081 //       - This happens only during dynamic dump
1082 //       - Adjust this pointer by _mapped_to_requested_static_archive_delta,
1083 //         so it points to Y when the static archive is mapped at the requested location.
1084 template <bool STATIC_DUMP>
1085 class RelocateBufferToRequested : public BitMapClosure {
1086   ArchiveBuilder* _builder;
1087   address _buffer_bottom;
1088   intx _buffer_to_requested_delta;
1089   intx _mapped_to_requested_static_archive_delta;
1090   size_t _max_non_null_offset;
1091 
1092  public:
1093   RelocateBufferToRequested(ArchiveBuilder* builder) {
1094     _builder = builder;
1095     _buffer_bottom = _builder->buffer_bottom();
1096     _buffer_to_requested_delta = builder->buffer_to_requested_delta();
1097     _mapped_to_requested_static_archive_delta = builder->requested_static_archive_bottom() - builder->mapped_static_archive_bottom();
1098     _max_non_null_offset = 0;
1099 
1100     address bottom = _builder->buffer_bottom();
1101     address top = _builder->buffer_top();
1102     address new_bottom = bottom + _buffer_to_requested_delta;
1103     address new_top = top + _buffer_to_requested_delta;
1104     aot_log_debug(aot)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT "] to "
1105                    "[" INTPTR_FORMAT " - " INTPTR_FORMAT "]",
1106                    p2i(bottom), p2i(top),
1107                    p2i(new_bottom), p2i(new_top));
1108   }
1109 
1110   bool do_bit(size_t offset) {
1111     address* p = (address*)_buffer_bottom + offset;
1112     assert(_builder->is_in_buffer_space(p), "pointer must live in buffer space");
1113 
1114     if (*p == nullptr) {
1115       // todo -- clear bit, etc
1116       ArchivePtrMarker::ptrmap()->clear_bit(offset);
1117     } else {
1118       if (STATIC_DUMP) {
1119         assert(_builder->is_in_buffer_space(*p), "old pointer must point inside buffer space");
1120         *p += _buffer_to_requested_delta;
1121         assert(_builder->is_in_requested_static_archive(*p), "new pointer must point inside requested archive");
1122       } else {
1123         if (_builder->is_in_buffer_space(*p)) {
1124           *p += _buffer_to_requested_delta;
1125           // assert is in requested dynamic archive
1126         } else {
1127           assert(_builder->is_in_mapped_static_archive(*p), "old pointer must point inside buffer space or mapped static archive");
1128           *p += _mapped_to_requested_static_archive_delta;
1129           assert(_builder->is_in_requested_static_archive(*p), "new pointer must point inside requested archive");
1130         }
1131       }
1132       _max_non_null_offset = offset;
1133     }
1134 
1135     return true; // keep iterating
1136   }
1137 
1138   void doit() {
1139     ArchivePtrMarker::ptrmap()->iterate(this);
1140     ArchivePtrMarker::compact(_max_non_null_offset);
1141   }
1142 };
1143 
1144 #ifdef _LP64
1145 int ArchiveBuilder::precomputed_narrow_klass_shift() {
1146   // Legacy Mode:
1147   //    We use 32 bits for narrowKlass, which should cover the full 4G Klass range. Shift can be 0.
1148   // CompactObjectHeader Mode:
1149   //    narrowKlass is much smaller, and we use the highest possible shift value to later get the maximum
1150   //    Klass encoding range.
1151   //
1152   // Note that all of this may change in the future, if we decide to correct the pre-calculated
1153   // narrow Klass IDs at archive load time.
1154   assert(UseCompressedClassPointers, "Only needed for compressed class pointers");
1155   return UseCompactObjectHeaders ?  CompressedKlassPointers::max_shift() : 0;
1156 }
1157 #endif // _LP64
1158 
1159 void ArchiveBuilder::relocate_to_requested() {
1160   if (!ro_region()->is_packed()) {
1161     ro_region()->pack();
1162   }
1163   size_t my_archive_size = buffer_top() - buffer_bottom();
1164 
1165   if (CDSConfig::is_dumping_static_archive()) {
1166     _requested_static_archive_top = _requested_static_archive_bottom + my_archive_size;
1167     RelocateBufferToRequested<true> patcher(this);
1168     patcher.doit();
1169   } else {
1170     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1171     _requested_dynamic_archive_top = _requested_dynamic_archive_bottom + my_archive_size;
1172     RelocateBufferToRequested<false> patcher(this);
1173     patcher.doit();
1174   }
1175 }
1176 
1177 // Write detailed info to a mapfile to analyze contents of the archive.
1178 // static dump:
1179 //   java -Xshare:dump -Xlog:cds+map=trace:file=cds.map:none:filesize=0
1180 // dynamic dump:
1181 //   java -cp MyApp.jar -XX:ArchiveClassesAtExit=MyApp.jsa \
1182 //        -Xlog:cds+map=trace:file=cds.map:none:filesize=0 MyApp
1183 //
1184 // We need to do some address translation because the buffers used at dump time may be mapped to
1185 // a different location at runtime. At dump time, the buffers may be at arbitrary locations
1186 // picked by the OS. At runtime, we try to map at a fixed location (SharedBaseAddress). For
1187 // consistency, we log everything using runtime addresses.
1188 class ArchiveBuilder::CDSMapLogger : AllStatic {
1189   static intx buffer_to_runtime_delta() {
1190     // Translate the buffers used by the RW/RO regions to their eventual (requested) locations
1191     // at runtime.
1192     return ArchiveBuilder::current()->buffer_to_requested_delta();
1193   }
1194 
1195   // rw/ro regions only
1196   static void log_metaspace_region(const char* name, DumpRegion* region,
1197                                    const ArchiveBuilder::SourceObjList* src_objs) {
1198     address region_base = address(region->base());
1199     address region_top  = address(region->top());
1200     log_region(name, region_base, region_top, region_base + buffer_to_runtime_delta());
1201     log_metaspace_objects(region, src_objs);
1202   }
1203 
1204 #define _LOG_PREFIX PTR_FORMAT ": @@ %-17s %d"
1205 
1206   static void log_klass(Klass* k, address runtime_dest, const char* type_name, int bytes, Thread* current) {
1207     ResourceMark rm(current);
1208     log_debug(aot, map)(_LOG_PREFIX " %s",
1209                         p2i(runtime_dest), type_name, bytes, k->external_name());
1210   }
1211   static void log_method(Method* m, address runtime_dest, const char* type_name, int bytes, Thread* current) {
1212     ResourceMark rm(current);
1213     log_debug(aot, map)(_LOG_PREFIX " %s",
1214                         p2i(runtime_dest), type_name, bytes,  m->external_name());
1215   }
1216 
1217   // rw/ro regions only
1218   static void log_metaspace_objects(DumpRegion* region, const ArchiveBuilder::SourceObjList* src_objs) {
1219     address last_obj_base = address(region->base());
1220     address last_obj_end  = address(region->base());
1221     address region_end    = address(region->end());
1222     Thread* current = Thread::current();
1223     for (int i = 0; i < src_objs->objs()->length(); i++) {
1224       SourceObjInfo* src_info = src_objs->at(i);
1225       address src = src_info->source_addr();
1226       address dest = src_info->buffered_addr();
1227       log_as_hex(last_obj_base, dest, last_obj_base + buffer_to_runtime_delta());
1228       address runtime_dest = dest + buffer_to_runtime_delta();
1229       int bytes = src_info->size_in_bytes();
1230 
1231       MetaspaceObj::Type type = src_info->msotype();
1232       const char* type_name = MetaspaceObj::type_name(type);
1233 
1234       switch (type) {
1235       case MetaspaceObj::ClassType:
1236         log_klass((Klass*)src, runtime_dest, type_name, bytes, current);
1237         break;
1238       case MetaspaceObj::ConstantPoolType:
1239         log_klass(((ConstantPool*)src)->pool_holder(),
1240                     runtime_dest, type_name, bytes, current);
1241         break;
1242       case MetaspaceObj::ConstantPoolCacheType:
1243         log_klass(((ConstantPoolCache*)src)->constant_pool()->pool_holder(),
1244                     runtime_dest, type_name, bytes, current);
1245         break;
1246       case MetaspaceObj::MethodType:
1247         log_method((Method*)src, runtime_dest, type_name, bytes, current);
1248         break;
1249       case MetaspaceObj::ConstMethodType:
1250         log_method(((ConstMethod*)src)->method(), runtime_dest, type_name, bytes, current);
1251         break;
1252       case MetaspaceObj::SymbolType:
1253         {
1254           ResourceMark rm(current);
1255           Symbol* s = (Symbol*)src;
1256           log_debug(aot, map)(_LOG_PREFIX " %s", p2i(runtime_dest), type_name, bytes,
1257                               s->as_quoted_ascii());
1258         }
1259         break;
1260       default:
1261         log_debug(aot, map)(_LOG_PREFIX, p2i(runtime_dest), type_name, bytes);
1262         break;
1263       }
1264 
1265       last_obj_base = dest;
1266       last_obj_end  = dest + bytes;
1267     }
1268 
1269     log_as_hex(last_obj_base, last_obj_end, last_obj_base + buffer_to_runtime_delta());
1270     if (last_obj_end < region_end) {
1271       log_debug(aot, map)(PTR_FORMAT ": @@ Misc data %zu bytes",
1272                           p2i(last_obj_end + buffer_to_runtime_delta()),
1273                           size_t(region_end - last_obj_end));
1274       log_as_hex(last_obj_end, region_end, last_obj_end + buffer_to_runtime_delta());
1275     }
1276   }
1277 
1278 #undef _LOG_PREFIX
1279 
1280   // Log information about a region, whose address at dump time is [base .. top). At
1281   // runtime, this region will be mapped to requested_base. requested_base is nullptr if this
1282   // region will be mapped at os-selected addresses (such as the bitmap region), or will
1283   // be accessed with os::read (the header).
1284   //
1285   // Note: across -Xshare:dump runs, base may be different, but requested_base should
1286   // be the same as the archive contents should be deterministic.
1287   static void log_region(const char* name, address base, address top, address requested_base) {
1288     size_t size = top - base;
1289     base = requested_base;
1290     if (requested_base == nullptr) {
1291       top = (address)size;
1292     } else {
1293       top = requested_base + size;
1294     }
1295     log_info(aot, map)("[%-18s " PTR_FORMAT " - " PTR_FORMAT " %9zu bytes]",
1296                        name, p2i(base), p2i(top), size);
1297   }
1298 
1299 #if INCLUDE_CDS_JAVA_HEAP
1300   static void log_heap_region(ArchiveHeapInfo* heap_info) {
1301     MemRegion r = heap_info->buffer_region();
1302     address start = address(r.start()); // start of the current oop inside the buffer
1303     address end = address(r.end());
1304     log_region("heap", start, end, ArchiveHeapWriter::buffered_addr_to_requested_addr(start));
1305 
1306     LogStreamHandle(Info, aot, map) st;
1307 
1308     HeapRootSegments segments = heap_info->heap_root_segments();
1309     assert(segments.base_offset() == 0, "Sanity");
1310 
1311     for (size_t seg_idx = 0; seg_idx < segments.count(); seg_idx++) {
1312       address requested_start = ArchiveHeapWriter::buffered_addr_to_requested_addr(start);
1313       st.print_cr(PTR_FORMAT ": Heap roots segment [%d]",
1314                   p2i(requested_start), segments.size_in_elems(seg_idx));
1315       start += segments.size_in_bytes(seg_idx);
1316     }
1317     log_heap_roots();
1318 
1319     while (start < end) {
1320       size_t byte_size;
1321       oop source_oop = ArchiveHeapWriter::buffered_addr_to_source_obj(start);
1322       address requested_start = ArchiveHeapWriter::buffered_addr_to_requested_addr(start);
1323       st.print(PTR_FORMAT ": @@ Object ", p2i(requested_start));
1324 
1325       if (source_oop != nullptr) {
1326         // This is a regular oop that got archived.
1327         // Don't print the requested addr again as we have just printed it at the beginning of the line.
1328         // Example:
1329         // 0x00000007ffd27938: @@ Object (0xfffa4f27) java.util.HashMap
1330         print_oop_info_cr(&st, source_oop, /*print_requested_addr=*/false);
1331         byte_size = source_oop->size() * BytesPerWord;
1332       } else if ((byte_size = ArchiveHeapWriter::get_filler_size_at(start)) > 0) {
1333         // We have a filler oop, which also does not exist in BufferOffsetToSourceObjectTable.
1334         // Example:
1335         // 0x00000007ffc3ffd8: @@ Object filler 40 bytes
1336         st.print_cr("filler %zu bytes", byte_size);
1337       } else {
1338         ShouldNotReachHere();
1339       }
1340 
1341       address oop_end = start + byte_size;
1342       log_as_hex(start, oop_end, requested_start, /*is_heap=*/true);
1343 
1344       if (source_oop != nullptr) {
1345         log_oop_details(heap_info, source_oop, /*buffered_addr=*/start);
1346       }
1347       start = oop_end;
1348     }
1349   }
1350 
1351   // ArchivedFieldPrinter is used to print the fields of archived objects. We can't
1352   // use _source_obj->print_on(), because we want to print the oop fields
1353   // in _source_obj with their requested addresses using print_oop_info_cr().
1354   class ArchivedFieldPrinter : public FieldClosure {
1355     ArchiveHeapInfo* _heap_info;
1356     outputStream* _st;
1357     oop _source_obj;
1358     address _buffered_addr;
1359   public:
1360     ArchivedFieldPrinter(ArchiveHeapInfo* heap_info, outputStream* st, oop src_obj, address buffered_addr) :
1361       _heap_info(heap_info), _st(st), _source_obj(src_obj), _buffered_addr(buffered_addr) {}
1362 
1363     void do_field(fieldDescriptor* fd) {
1364       _st->print(" - ");
1365       BasicType ft = fd->field_type();
1366       switch (ft) {
1367       case T_ARRAY:
1368       case T_OBJECT:
1369         {
1370           fd->print_on(_st); // print just the name and offset
1371           oop obj = _source_obj->obj_field(fd->offset());
1372           if (java_lang_Class::is_instance(obj)) {
1373             obj = HeapShared::scratch_java_mirror(obj);
1374           }
1375           print_oop_info_cr(_st, obj);
1376         }
1377         break;
1378       default:
1379         if (ArchiveHeapWriter::is_marked_as_native_pointer(_heap_info, _source_obj, fd->offset())) {
1380           print_as_native_pointer(fd);
1381         } else {
1382           fd->print_on_for(_st, cast_to_oop(_buffered_addr)); // name, offset, value
1383           _st->cr();
1384         }
1385       }
1386     }
1387 
1388     void print_as_native_pointer(fieldDescriptor* fd) {
1389       LP64_ONLY(assert(fd->field_type() == T_LONG, "must be"));
1390       NOT_LP64 (assert(fd->field_type() == T_INT,  "must be"));
1391 
1392       // We have a field that looks like an integer, but it's actually a pointer to a MetaspaceObj.
1393       address source_native_ptr = (address)
1394           LP64_ONLY(_source_obj->long_field(fd->offset()))
1395           NOT_LP64( _source_obj->int_field (fd->offset()));
1396       ArchiveBuilder* builder = ArchiveBuilder::current();
1397 
1398       // The value of the native pointer at runtime.
1399       address requested_native_ptr = builder->to_requested(builder->get_buffered_addr(source_native_ptr));
1400 
1401       // The address of _source_obj at runtime
1402       oop requested_obj = ArchiveHeapWriter::source_obj_to_requested_obj(_source_obj);
1403       // The address of this field in the requested space
1404       assert(requested_obj != nullptr, "Attempting to load field from null oop");
1405       address requested_field_addr = cast_from_oop<address>(requested_obj) + fd->offset();
1406 
1407       fd->print_on(_st);
1408       _st->print_cr(PTR_FORMAT " (marked metadata pointer @" PTR_FORMAT " )",
1409                     p2i(requested_native_ptr), p2i(requested_field_addr));
1410     }
1411   };
1412 
1413   // Print the fields of instanceOops, or the elements of arrayOops
1414   static void log_oop_details(ArchiveHeapInfo* heap_info, oop source_oop, address buffered_addr) {
1415     LogStreamHandle(Trace, aot, map, oops) st;
1416     if (st.is_enabled()) {
1417       Klass* source_klass = source_oop->klass();
1418       ArchiveBuilder* builder = ArchiveBuilder::current();
1419       Klass* requested_klass = builder->to_requested(builder->get_buffered_addr(source_klass));
1420 
1421       st.print(" - klass: ");
1422       source_klass->print_value_on(&st);
1423       st.print(" " PTR_FORMAT, p2i(requested_klass));
1424       st.cr();
1425 
1426       if (source_oop->is_typeArray()) {
1427         TypeArrayKlass::cast(source_klass)->oop_print_elements_on(typeArrayOop(source_oop), &st);
1428       } else if (source_oop->is_objArray()) {
1429         objArrayOop source_obj_array = objArrayOop(source_oop);
1430         for (int i = 0; i < source_obj_array->length(); i++) {
1431           st.print(" -%4d: ", i);
1432           oop obj = source_obj_array->obj_at(i);
1433           if (java_lang_Class::is_instance(obj)) {
1434             obj = HeapShared::scratch_java_mirror(obj);
1435           }
1436           print_oop_info_cr(&st, obj);
1437         }
1438       } else {
1439         st.print_cr(" - fields (%zu words):", source_oop->size());
1440         ArchivedFieldPrinter print_field(heap_info, &st, source_oop, buffered_addr);
1441         InstanceKlass::cast(source_klass)->print_nonstatic_fields(&print_field);
1442 
1443         if (java_lang_Class::is_instance(source_oop)) {
1444           oop scratch_mirror = source_oop;
1445           st.print(" - signature: ");
1446           print_class_signature_for_mirror(&st, scratch_mirror);
1447           st.cr();
1448 
1449           Klass* src_klass = java_lang_Class::as_Klass(scratch_mirror);
1450           if (src_klass != nullptr && src_klass->is_instance_klass()) {
1451             oop rr = HeapShared::scratch_resolved_references(InstanceKlass::cast(src_klass)->constants());
1452             st.print(" - archived_resolved_references: ");
1453             print_oop_info_cr(&st, rr);
1454 
1455             // We need to print the fields in the scratch_mirror, not the original mirror.
1456             // (if a class is not aot-initialized, static fields in its scratch mirror will be cleared).
1457             assert(scratch_mirror == HeapShared::scratch_java_mirror(src_klass->java_mirror()), "sanity");
1458             st.print_cr("- ---- static fields (%d):", java_lang_Class::static_oop_field_count(scratch_mirror));
1459             InstanceKlass::cast(src_klass)->do_local_static_fields(&print_field);
1460           }
1461         }
1462       }
1463     }
1464   }
1465 
1466   static void print_class_signature_for_mirror(outputStream* st, oop scratch_mirror) {
1467     assert(java_lang_Class::is_instance(scratch_mirror), "sanity");
1468     if (java_lang_Class::is_primitive(scratch_mirror)) {
1469       for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
1470         BasicType bt = (BasicType)i;
1471         if (!is_reference_type(bt) && scratch_mirror == HeapShared::scratch_java_mirror(bt)) {
1472           oop orig_mirror = Universe::java_mirror(bt);
1473           java_lang_Class::print_signature(orig_mirror, st);
1474           return;
1475         }
1476       }
1477       ShouldNotReachHere();
1478     }
1479     java_lang_Class::print_signature(scratch_mirror, st);
1480   }
1481 
1482   static void log_heap_roots() {
1483     LogStreamHandle(Trace, aot, map, oops) st;
1484     if (st.is_enabled()) {
1485       for (int i = 0; i < HeapShared::pending_roots()->length(); i++) {
1486         st.print("roots[%4d]: ", i);
1487         print_oop_info_cr(&st, HeapShared::pending_roots()->at(i));
1488       }
1489     }
1490   }
1491 
1492   // Example output:
1493   // - The first number is the requested address (if print_requested_addr == true)
1494   // - The second number is the narrowOop version of the requested address (if UseCompressedOops == true)
1495   //     0x00000007ffc7e840 (0xfff8fd08) java.lang.Class Ljava/util/Array;
1496   //     0x00000007ffc000f8 (0xfff8001f) [B length: 11
1497   static void print_oop_info_cr(outputStream* st, oop source_oop, bool print_requested_addr = true) {
1498     if (source_oop == nullptr) {
1499       st->print_cr("null");
1500     } else {
1501       ResourceMark rm;
1502       oop requested_obj = ArchiveHeapWriter::source_obj_to_requested_obj(source_oop);
1503       if (print_requested_addr) {
1504         st->print(PTR_FORMAT " ", p2i(requested_obj));
1505       }
1506       if (UseCompressedOops) {
1507         st->print("(0x%08x) ", CompressedOops::narrow_oop_value(requested_obj));
1508       }
1509       if (source_oop->is_array()) {
1510         int array_len = arrayOop(source_oop)->length();
1511         st->print_cr("%s length: %d", source_oop->klass()->external_name(), array_len);
1512       } else {
1513         st->print("%s", source_oop->klass()->external_name());
1514 
1515         if (java_lang_String::is_instance(source_oop)) {
1516           st->print(" ");
1517           java_lang_String::print(source_oop, st);
1518         } else if (java_lang_Class::is_instance(source_oop)) {
1519           oop scratch_mirror = source_oop;
1520 
1521           st->print(" ");
1522           print_class_signature_for_mirror(st, scratch_mirror);
1523 
1524           Klass* src_klass = java_lang_Class::as_Klass(scratch_mirror);
1525           if (src_klass != nullptr && src_klass->is_instance_klass()) {
1526             InstanceKlass* buffered_klass =
1527               ArchiveBuilder::current()->get_buffered_addr(InstanceKlass::cast(src_klass));
1528             if (buffered_klass->has_aot_initialized_mirror()) {
1529               st->print(" (aot-inited)");
1530             }
1531           }
1532         }
1533         st->cr();
1534       }
1535     }
1536   }
1537 #endif // INCLUDE_CDS_JAVA_HEAP
1538 
1539   // Log all the data [base...top). Pretend that the base address
1540   // will be mapped to requested_base at run-time.
1541   static void log_as_hex(address base, address top, address requested_base, bool is_heap = false) {
1542     assert(top >= base, "must be");
1543 
1544     LogStreamHandle(Trace, aot, map) lsh;
1545     if (lsh.is_enabled()) {
1546       int unitsize = sizeof(address);
1547       if (is_heap && UseCompressedOops) {
1548         // This makes the compressed oop pointers easier to read, but
1549         // longs and doubles will be split into two words.
1550         unitsize = sizeof(narrowOop);
1551       }
1552       os::print_hex_dump(&lsh, base, top, unitsize, /* print_ascii=*/true, /* bytes_per_line=*/32, requested_base);
1553     }
1554   }
1555 
1556   static void log_header(FileMapInfo* mapinfo) {
1557     LogStreamHandle(Info, aot, map) lsh;
1558     if (lsh.is_enabled()) {
1559       mapinfo->print(&lsh);
1560     }
1561   }
1562 
1563 public:
1564   static void log(ArchiveBuilder* builder, FileMapInfo* mapinfo,
1565                   ArchiveHeapInfo* heap_info,
1566                   char* bitmap, size_t bitmap_size_in_bytes) {
1567     log_info(aot, map)("%s CDS archive map for %s", CDSConfig::is_dumping_static_archive() ? "Static" : "Dynamic", mapinfo->full_path());
1568 
1569     address header = address(mapinfo->header());
1570     address header_end = header + mapinfo->header()->header_size();
1571     log_region("header", header, header_end, nullptr);
1572     log_header(mapinfo);
1573     log_as_hex(header, header_end, nullptr);
1574 
1575     DumpRegion* rw_region = &builder->_rw_region;
1576     DumpRegion* ro_region = &builder->_ro_region;
1577 
1578     log_metaspace_region("rw region", rw_region, &builder->_rw_src_objs);
1579     log_metaspace_region("ro region", ro_region, &builder->_ro_src_objs);
1580 
1581     address bitmap_end = address(bitmap + bitmap_size_in_bytes);
1582     log_region("bitmap", address(bitmap), bitmap_end, nullptr);
1583     log_as_hex((address)bitmap, bitmap_end, nullptr);
1584 
1585 #if INCLUDE_CDS_JAVA_HEAP
1586     if (heap_info->is_used()) {
1587       log_heap_region(heap_info);
1588     }
1589 #endif
1590 
1591     log_info(aot, map)("[End of CDS archive map]");
1592   }
1593 }; // end ArchiveBuilder::CDSMapLogger
1594 
1595 void ArchiveBuilder::print_stats() {
1596   _alloc_stats.print_stats(int(_ro_region.used()), int(_rw_region.used()));
1597 }
1598 
1599 void ArchiveBuilder::write_archive(FileMapInfo* mapinfo, ArchiveHeapInfo* heap_info) {
1600   // Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with
1601   // MetaspaceShared::n_regions (internal to hotspot).
1602   assert(NUM_CDS_REGIONS == MetaspaceShared::n_regions, "sanity");
1603 
1604   write_region(mapinfo, MetaspaceShared::rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);
1605   write_region(mapinfo, MetaspaceShared::ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);
1606   write_region(mapinfo, MetaspaceShared::ac, &_ac_region, /*read_only=*/false,/*allow_exec=*/false);
1607 
1608   // Split pointer map into read-write and read-only bitmaps
1609   ArchivePtrMarker::initialize_rw_ro_maps(&_rw_ptrmap, &_ro_ptrmap);
1610 
1611   size_t bitmap_size_in_bytes;
1612   char* bitmap = mapinfo->write_bitmap_region(ArchivePtrMarker::rw_ptrmap(), ArchivePtrMarker::ro_ptrmap(), heap_info,
1613                                               bitmap_size_in_bytes);
1614 
1615   if (heap_info->is_used()) {
1616     _total_heap_region_size = mapinfo->write_heap_region(heap_info);
1617   }
1618 
1619   print_region_stats(mapinfo, heap_info);
1620 
1621   mapinfo->set_requested_base((char*)MetaspaceShared::requested_base_address());
1622   mapinfo->set_header_crc(mapinfo->compute_header_crc());
1623   // After this point, we should not write any data into mapinfo->header() since this
1624   // would corrupt its checksum we have calculated before.
1625   mapinfo->write_header();
1626   mapinfo->close();
1627 
1628   if (log_is_enabled(Info, aot)) {
1629     log_info(aot)("Full module graph = %s", CDSConfig::is_dumping_full_module_graph() ? "enabled" : "disabled");
1630     print_stats();
1631   }
1632 
1633   if (log_is_enabled(Info, aot, map)) {
1634     CDSMapLogger::log(this, mapinfo, heap_info,
1635                       bitmap, bitmap_size_in_bytes);
1636   }
1637   CDS_JAVA_HEAP_ONLY(HeapShared::destroy_archived_object_cache());
1638   FREE_C_HEAP_ARRAY(char, bitmap);
1639 }
1640 
1641 void ArchiveBuilder::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only,  bool allow_exec) {
1642   mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);
1643 }
1644 
1645 void ArchiveBuilder::count_relocated_pointer(bool tagged, bool nulled) {
1646   _relocated_ptr_info._num_ptrs ++;
1647   _relocated_ptr_info._num_tagged_ptrs += tagged ? 1 : 0;
1648   _relocated_ptr_info._num_nulled_ptrs += nulled ? 1 : 0;
1649 }
1650 
1651 void ArchiveBuilder::print_region_stats(FileMapInfo *mapinfo, ArchiveHeapInfo* heap_info) {
1652   // Print statistics of all the regions
1653   const size_t bitmap_used = mapinfo->region_at(MetaspaceShared::bm)->used();
1654   const size_t bitmap_reserved = mapinfo->region_at(MetaspaceShared::bm)->used_aligned();
1655   const size_t total_reserved = _ro_region.reserved()  + _rw_region.reserved() +
1656                                 bitmap_reserved +
1657                                 _total_heap_region_size;
1658   const size_t total_bytes = _ro_region.used()  + _rw_region.used() +
1659                              bitmap_used +
1660                              _total_heap_region_size;
1661   const double total_u_perc = percent_of(total_bytes, total_reserved);
1662 
1663   _rw_region.print(total_reserved);
1664   _ro_region.print(total_reserved);
1665   _ac_region.print(total_reserved);
1666 
1667   print_bitmap_region_stats(bitmap_used, total_reserved);
1668 
1669   if (heap_info->is_used()) {
1670     print_heap_region_stats(heap_info, total_reserved);
1671   }
1672 
1673   aot_log_debug(aot)("total   : %9zu [100.0%% of total] out of %9zu bytes [%5.1f%% used]",
1674                  total_bytes, total_reserved, total_u_perc);
1675 }
1676 
1677 void ArchiveBuilder::print_bitmap_region_stats(size_t size, size_t total_size) {
1678   aot_log_debug(aot)("bm space: %9zu [ %4.1f%% of total] out of %9zu bytes [100.0%% used]",
1679                  size, size/double(total_size)*100.0, size);
1680 }
1681 
1682 void ArchiveBuilder::print_heap_region_stats(ArchiveHeapInfo *info, size_t total_size) {
1683   char* start = info->buffer_start();
1684   size_t size = info->buffer_byte_size();
1685   char* top = start + size;
1686   aot_log_debug(aot)("hp space: %9zu [ %4.1f%% of total] out of %9zu bytes [100.0%% used] at " INTPTR_FORMAT,
1687                      size, size/double(total_size)*100.0, size, p2i(start));
1688 }
1689 
1690 void ArchiveBuilder::report_out_of_space(const char* name, size_t needed_bytes) {
1691   // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space.
1692   // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes
1693   // or so.
1694   _rw_region.print_out_of_space_msg(name, needed_bytes);
1695   _ro_region.print_out_of_space_msg(name, needed_bytes);
1696 
1697   log_error(aot)("Unable to allocate from '%s' region: Please reduce the number of shared classes.", name);
1698   MetaspaceShared::unrecoverable_writing_error();
1699 }