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