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