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