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