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