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/archiveBuilder.hpp"
  27 #include "cds/archiveHeapWriter.hpp"
  28 #include "cds/archiveUtils.hpp"
  29 #include "cds/cdsConfig.hpp"
  30 #include "cds/classPrelinker.hpp"
  31 #include "cds/classPreloader.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/javaClasses.hpp"
  42 #include "classfile/symbolTable.hpp"
  43 #include "classfile/systemDictionaryShared.hpp"
  44 #include "classfile/vmClasses.hpp"
  45 #include "interpreter/abstractInterpreter.hpp"
  46 #include "logging/log.hpp"
  47 #include "logging/logStream.hpp"
  48 #include "memory/allStatic.hpp"
  49 #include "memory/memRegion.hpp"
  50 #include "memory/resourceArea.hpp"
  51 #include "oops/compressedKlass.inline.hpp"
  52 #include "oops/instanceKlass.hpp"
  53 #include "oops/objArrayKlass.hpp"
  54 #include "oops/objArrayOop.inline.hpp"
  55 #include "oops/oopHandle.inline.hpp"
  56 #include "oops/trainingData.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   _objs->append(src_info);
  85 
  86   // Prepare for marking the pointers in this source object
  87   assert(is_aligned(_total_bytes, sizeof(address)), "must be");
  88   src_info->set_ptrmap_start(_total_bytes / sizeof(address));
  89   _total_bytes = align_up(_total_bytes + (uintx)src_info->size_in_bytes(), sizeof(address));
  90   src_info->set_ptrmap_end(_total_bytes / sizeof(address));
  91 
  92   BitMap::idx_t bitmap_size_needed = BitMap::idx_t(src_info->ptrmap_end());
  93   if (_ptrmap.size() <= bitmap_size_needed) {
  94     _ptrmap.resize((bitmap_size_needed + 1) * 2);
  95   }
  96 }
  97 
  98 void ArchiveBuilder::SourceObjList::remember_embedded_pointer(SourceObjInfo* src_info, MetaspaceClosure::Ref* ref) {
  99   // src_obj contains a pointer. Remember the location of this pointer in _ptrmap,
 100   // so that we can copy/relocate it later.
 101   address src_obj = src_info->source_addr();
 102   address* field_addr = ref->addr();
 103   assert(src_info->ptrmap_start() < _total_bytes, "sanity");
 104   assert(src_info->ptrmap_end() <= _total_bytes, "sanity");
 105   assert(*field_addr != nullptr, "should have checked");
 106 
 107   intx field_offset_in_bytes = ((address)field_addr) - src_obj;
 108   DEBUG_ONLY(int src_obj_size = src_info->size_in_bytes();)
 109   assert(field_offset_in_bytes >= 0, "must be");
 110   assert(field_offset_in_bytes + intx(sizeof(intptr_t)) <= intx(src_obj_size), "must be");
 111   assert(is_aligned(field_offset_in_bytes, sizeof(address)), "must be");
 112 
 113   BitMap::idx_t idx = BitMap::idx_t(src_info->ptrmap_start() + (uintx)(field_offset_in_bytes / sizeof(address)));
 114   _ptrmap.set_bit(BitMap::idx_t(idx));
 115 }
 116 
 117 class RelocateEmbeddedPointers : public BitMapClosure {
 118   ArchiveBuilder* _builder;
 119   address _buffered_obj;
 120   BitMap::idx_t _start_idx;
 121 public:
 122   RelocateEmbeddedPointers(ArchiveBuilder* builder, address buffered_obj, BitMap::idx_t start_idx) :
 123     _builder(builder), _buffered_obj(buffered_obj), _start_idx(start_idx) {}
 124 
 125   bool do_bit(BitMap::idx_t bit_offset) {
 126     size_t field_offset = size_t(bit_offset - _start_idx) * sizeof(address);
 127     address* ptr_loc = (address*)(_buffered_obj + field_offset);
 128 
 129     address old_p = *ptr_loc;
 130     address new_p = _builder->get_buffered_addr(old_p);
 131 
 132     log_trace(cds)("Ref: [" PTR_FORMAT "] -> " PTR_FORMAT " => " PTR_FORMAT,
 133                    p2i(ptr_loc), p2i(old_p), p2i(new_p));
 134 
 135     ArchivePtrMarker::set_and_mark_pointer(ptr_loc, new_p);
 136     return true; // keep iterating the bitmap
 137   }
 138 };
 139 
 140 void ArchiveBuilder::SourceObjList::relocate(int i, ArchiveBuilder* builder) {
 141   SourceObjInfo* src_info = objs()->at(i);
 142   assert(src_info->should_copy(), "must be");
 143   BitMap::idx_t start = BitMap::idx_t(src_info->ptrmap_start()); // inclusive
 144   BitMap::idx_t end = BitMap::idx_t(src_info->ptrmap_end());     // exclusive
 145 
 146   RelocateEmbeddedPointers relocator(builder, src_info->buffered_addr(), start);
 147   _ptrmap.iterate(&relocator, start, end);
 148 }
 149 
 150 ArchiveBuilder::ArchiveBuilder() :
 151   _current_dump_space(nullptr),
 152   _buffer_bottom(nullptr),
 153   _last_verified_top(nullptr),
 154   _num_dump_regions_used(0),
 155   _other_region_used_bytes(0),
 156   _requested_static_archive_bottom(nullptr),
 157   _requested_static_archive_top(nullptr),
 158   _requested_dynamic_archive_bottom(nullptr),
 159   _requested_dynamic_archive_top(nullptr),
 160   _mapped_static_archive_bottom(nullptr),
 161   _mapped_static_archive_top(nullptr),
 162   _buffer_to_requested_delta(0),
 163   _rw_region("rw", MAX_SHARED_DELTA),
 164   _ro_region("ro", MAX_SHARED_DELTA),
 165   _cc_region("cc", MAX_SHARED_DELTA),
 166   _ptrmap(mtClassShared),
 167   _rw_ptrmap(mtClassShared),
 168   _ro_ptrmap(mtClassShared),
 169   _cc_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 
 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 class GatherKlassesAndSymbols : public UniqueMetaspaceClosure {
 201   ArchiveBuilder* _builder;
 202 
 203 public:
 204   GatherKlassesAndSymbols(ArchiveBuilder* builder) : _builder(builder) {}
 205 
 206   virtual bool do_unique_ref(Ref* ref, bool read_only) {
 207     return _builder->gather_klass_and_symbol(ref, read_only);
 208   }
 209 };
 210 
 211 bool ArchiveBuilder::gather_klass_and_symbol(MetaspaceClosure::Ref* ref, bool read_only) {
 212   if (ref->obj() == nullptr) {
 213     return false;
 214   }
 215   if (get_follow_mode(ref) != make_a_copy) {
 216     return false;
 217   }
 218   if (ref->msotype() == MetaspaceObj::ClassType) {
 219     Klass* klass = (Klass*)ref->obj();
 220     assert(klass->is_klass(), "must be");
 221     if (!is_excluded(klass)) {
 222       _klasses->append(klass);
 223       if (klass->is_hidden() && klass->is_instance_klass()) {
 224         update_hidden_class_loader_type(InstanceKlass::cast(klass));
 225       }
 226     }
 227     // See RunTimeClassInfo::get_for()
 228     _estimated_metaspaceobj_bytes += align_up(BytesPerWord, SharedSpaceObjectAlignment);
 229   } else if (ref->msotype() == MetaspaceObj::SymbolType) {
 230     // Make sure the symbol won't be GC'ed while we are dumping the archive.
 231     Symbol* sym = (Symbol*)ref->obj();
 232     sym->increment_refcount();
 233     _symbols->append(sym);
 234   }
 235 
 236   int bytes = ref->size() * BytesPerWord;
 237   _estimated_metaspaceobj_bytes += align_up(bytes, SharedSpaceObjectAlignment);
 238 
 239   return true; // recurse
 240 }
 241 
 242 void ArchiveBuilder::gather_klasses_and_symbols() {
 243   ResourceMark rm;
 244   log_info(cds)("Gathering classes and symbols ... ");
 245   GatherKlassesAndSymbols doit(this);
 246   iterate_roots(&doit);
 247 #if INCLUDE_CDS_JAVA_HEAP
 248   if (CDSConfig::is_dumping_full_module_graph()) {
 249     ClassLoaderDataShared::iterate_symbols(&doit);
 250   }
 251 #endif
 252   doit.finish();
 253 
 254   if (CDSConfig::is_dumping_static_archive()) {
 255     // To ensure deterministic contents in the static archive, we need to ensure that
 256     // we iterate the MetaspaceObjs in a deterministic order. It doesn't matter where
 257     // the MetaspaceObjs are located originally, as they are copied sequentially into
 258     // the archive during the iteration.
 259     //
 260     // The only issue here is that the symbol table and the system directories may be
 261     // randomly ordered, so we copy the symbols and klasses into two arrays and sort
 262     // them deterministically.
 263     //
 264     // During -Xshare:dump, the order of Symbol creation is strictly determined by
 265     // the SharedClassListFile (class loading is done in a single thread and the JIT
 266     // is disabled). Also, Symbols are allocated in monotonically increasing addresses
 267     // (see Symbol::operator new(size_t, int)). So if we iterate the Symbols by
 268     // ascending address order, we ensure that all Symbols are copied into deterministic
 269     // locations in the archive.
 270     //
 271     // TODO: in the future, if we want to produce deterministic contents in the
 272     // dynamic archive, we might need to sort the symbols alphabetically (also see
 273     // DynamicArchiveBuilder::sort_methods()).
 274     log_info(cds)("Sorting symbols ... ");
 275     _symbols->sort(compare_symbols_by_address);
 276     sort_klasses();
 277 
 278     // TODO -- we need a proper estimate for the archived modules, etc,
 279     // but this should be enough for now
 280     _estimated_metaspaceobj_bytes += 200 * 1024 * 1024;
 281   }
 282 }
 283 
 284 #if INCLUDE_CDS_JAVA_HEAP
 285 
 286 void ArchiveBuilder::update_hidden_class_loader_type(InstanceKlass* ik) {
 287   s2 classloader_type;
 288   if (HeapShared::is_lambda_form_klass(ik)) {
 289     assert(CDSConfig::is_dumping_invokedynamic(), "lambda form classes are archived only if ArchiveInvokeDynamic is true");
 290     classloader_type = ClassLoader::BOOT_LOADER;
 291   } else if (HeapShared::is_lambda_proxy_klass(ik)) {
 292     oop loader = ik->class_loader();
 293 
 294     if (loader == nullptr) {
 295       classloader_type = ClassLoader::BOOT_LOADER;
 296     } else if (SystemDictionary::is_platform_class_loader(loader)) {
 297       classloader_type = ClassLoader::PLATFORM_LOADER;
 298     } else if (SystemDictionary::is_system_class_loader(loader)) {
 299       classloader_type = ClassLoader::APP_LOADER;
 300     } else {
 301       ShouldNotReachHere();
 302     }
 303   } else {
 304     ShouldNotReachHere();
 305   }
 306 
 307   ik->set_shared_class_loader_type(classloader_type);
 308   if (HeapShared::is_lambda_proxy_klass(ik)) {
 309     InstanceKlass* nest_host = ik->nest_host_not_null();
 310     ik->set_shared_classpath_index(nest_host->shared_classpath_index());
 311   }
 312 }
 313 
 314 #endif //INCLUDE_CDS_JAVA_HEAP
 315 
 316 int ArchiveBuilder::compare_symbols_by_address(Symbol** a, Symbol** b) {
 317   if (a[0] < b[0]) {
 318     return -1;
 319   } else {
 320     assert(a[0] > b[0], "Duplicated symbol %s unexpected", (*a)->as_C_string());
 321     return 1;
 322   }
 323 }
 324 
 325 int ArchiveBuilder::compare_klass_by_name(Klass** a, Klass** b) {
 326   return a[0]->name()->fast_compare(b[0]->name());
 327 }
 328 
 329 void ArchiveBuilder::sort_klasses() {
 330   log_info(cds)("Sorting classes ... ");
 331   _klasses->sort(compare_klass_by_name);
 332 }
 333 
 334 size_t ArchiveBuilder::estimate_archive_size() {
 335   // size of the symbol table and two dictionaries, plus the RunTimeClassInfo's
 336   size_t symbol_table_est = SymbolTable::estimate_size_for_archive();
 337   size_t dictionary_est = SystemDictionaryShared::estimate_size_for_archive();
 338   size_t training_data_est = TrainingData::estimate_size_for_archive();
 339   _estimated_hashtable_bytes = symbol_table_est + dictionary_est + training_data_est;
 340 
 341   if (CDSConfig::is_dumping_final_static_archive()) {
 342     _estimated_hashtable_bytes += 200 * 1024 * 1024; // FIXME -- need to iterate archived symbols??
 343   }
 344 
 345   if (CDSConfig::is_dumping_dynamic_archive()) {
 346     // Some extra space for traning data. Be generous. Unused areas will be trimmed from the archive file.
 347     _estimated_hashtable_bytes += 200 * 1024 * 1024;
 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(buffer_size, MetaspaceShared::core_region_alignment(), os::vm_page_size());
 368   if (!rs.is_reserved()) {
 369     log_error(cds)("Failed to reserve " SIZE_FORMAT " bytes of output buffer.", buffer_size);
 370     MetaspaceShared::unrecoverable_writing_error();
 371   }
 372 
 373   // buffer_bottom is the lowest address of the 2 core regions (rw, ro) when
 374   // we are copying the class metadata into the buffer.
 375   address buffer_bottom = (address)rs.base();
 376   log_info(cds)("Reserved output buffer space at " PTR_FORMAT " [" SIZE_FORMAT " bytes]",
 377                 p2i(buffer_bottom), buffer_size);
 378   _shared_rs = rs;
 379 
 380   _buffer_bottom = buffer_bottom;
 381   _last_verified_top = buffer_bottom;
 382   _current_dump_space = &_rw_region;
 383   _num_dump_regions_used = 1;
 384   _other_region_used_bytes = 0;
 385   _current_dump_space->init(&_shared_rs, &_shared_vs);
 386 
 387   ArchivePtrMarker::initialize(&_ptrmap, &_shared_vs);
 388 
 389   // The bottom of the static archive should be mapped at this address by default.
 390   _requested_static_archive_bottom = (address)MetaspaceShared::requested_base_address();
 391 
 392   // The bottom of the archive (that I am writing now) should be mapped at this address by default.
 393   address my_archive_requested_bottom;
 394 
 395   if (CDSConfig::is_dumping_static_archive()) {
 396     my_archive_requested_bottom = _requested_static_archive_bottom;
 397   } else {
 398     _mapped_static_archive_bottom = (address)MetaspaceObj::shared_metaspace_base();
 399     _mapped_static_archive_top  = (address)MetaspaceObj::shared_metaspace_top();
 400     assert(_mapped_static_archive_top >= _mapped_static_archive_bottom, "must be");
 401     size_t static_archive_size = _mapped_static_archive_top - _mapped_static_archive_bottom;
 402 
 403     // At run time, we will mmap the dynamic archive at my_archive_requested_bottom
 404     _requested_static_archive_top = _requested_static_archive_bottom + static_archive_size;
 405     my_archive_requested_bottom = align_up(_requested_static_archive_top, MetaspaceShared::core_region_alignment());
 406 
 407     _requested_dynamic_archive_bottom = my_archive_requested_bottom;
 408   }
 409 
 410   _buffer_to_requested_delta = my_archive_requested_bottom - _buffer_bottom;
 411 
 412   address my_archive_requested_top = my_archive_requested_bottom + buffer_size;
 413   if (my_archive_requested_bottom <  _requested_static_archive_bottom ||
 414       my_archive_requested_top    <= _requested_static_archive_bottom) {
 415     // Size overflow.
 416     log_error(cds)("my_archive_requested_bottom = " INTPTR_FORMAT, p2i(my_archive_requested_bottom));
 417     log_error(cds)("my_archive_requested_top    = " INTPTR_FORMAT, p2i(my_archive_requested_top));
 418     log_error(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is too high. "
 419                    "Please rerun java -Xshare:dump with a lower value", p2i(_requested_static_archive_bottom));
 420     MetaspaceShared::unrecoverable_writing_error();
 421   }
 422 
 423   if (CDSConfig::is_dumping_static_archive()) {
 424     // We don't want any valid object to be at the very bottom of the archive.
 425     // See ArchivePtrMarker::mark_pointer().
 426     rw_region()->allocate(16);
 427   }
 428 
 429   return buffer_bottom;
 430 }
 431 
 432 void ArchiveBuilder::iterate_sorted_roots(MetaspaceClosure* it) {
 433   int num_symbols = _symbols->length();
 434   for (int i = 0; i < num_symbols; i++) {
 435     it->push(_symbols->adr_at(i));
 436   }
 437 
 438   int num_klasses = _klasses->length();
 439   for (int i = 0; i < num_klasses; i++) {
 440     it->push(_klasses->adr_at(i));
 441   }
 442 
 443   iterate_roots(it);
 444 }
 445 
 446 class GatherSortedSourceObjs : public MetaspaceClosure {
 447   ArchiveBuilder* _builder;
 448 
 449 public:
 450   GatherSortedSourceObjs(ArchiveBuilder* builder) : _builder(builder) {}
 451 
 452   virtual bool do_ref(Ref* ref, bool read_only) {
 453     return _builder->gather_one_source_obj(ref, read_only);
 454   }
 455 };
 456 
 457 bool ArchiveBuilder::gather_one_source_obj(MetaspaceClosure::Ref* ref, bool read_only) {
 458   address src_obj = ref->obj();
 459   if (src_obj == nullptr) {
 460     return false;
 461   }
 462 
 463   remember_embedded_pointer_in_enclosing_obj(ref);
 464   if (RegeneratedClasses::has_been_regenerated(src_obj)) {
 465     // No need to copy it. We will later relocate it to point to the regenerated klass/method.
 466     return false;
 467   }

 468 
 469   FollowMode follow_mode = get_follow_mode(ref);
 470   SourceObjInfo src_info(ref, read_only, follow_mode);
 471   bool created;
 472   SourceObjInfo* p = _src_obj_table.put_if_absent(src_obj, src_info, &created);
 473   if (created) {
 474     if (_src_obj_table.maybe_grow()) {
 475       log_info(cds, hashtables)("Expanded _src_obj_table table to %d", _src_obj_table.table_size());
 476     }
 477   }
 478 
 479 #ifdef ASSERT
 480   if (ref->msotype() == MetaspaceObj::MethodType) {
 481     Method* m = (Method*)ref->obj();
 482     assert(!RegeneratedClasses::has_been_regenerated((address)m->method_holder()),
 483            "Should not archive methods in a class that has been regenerated");
 484   }
 485 #endif
 486 
 487   assert(p->read_only() == src_info.read_only(), "must be");
 488 
 489   if (created && src_info.should_copy()) {
 490     if (read_only) {
 491       _ro_src_objs.append(p);
 492     } else {
 493       _rw_src_objs.append(p);
 494     }
 495     return true; // Need to recurse into this ref only if we are copying it
 496   } else {
 497     return false;
 498   }
 499 }
 500 
 501 void ArchiveBuilder::record_regenerated_object(address orig_src_obj, address regen_src_obj) {
 502   // Record the fact that orig_src_obj has been replaced by regen_src_obj. All calls to get_buffered_addr(orig_src_obj)
 503   // should return the same value as get_buffered_addr(regen_src_obj).
 504   SourceObjInfo* p = _src_obj_table.get(regen_src_obj);
 505   assert(p != nullptr, "regenerated object should always be dumped");
 506   SourceObjInfo orig_src_info(orig_src_obj, p);
 507   bool created;
 508   _src_obj_table.put_if_absent(orig_src_obj, orig_src_info, &created);
 509   assert(created, "We shouldn't have archived the original copy of a regenerated object");
 510 }
 511 
 512 // Remember that we have a pointer inside ref->enclosing_obj() that points to ref->obj()
 513 void ArchiveBuilder::remember_embedded_pointer_in_enclosing_obj(MetaspaceClosure::Ref* ref) {
 514   assert(ref->obj() != nullptr, "should have checked");
 515 
 516   address enclosing_obj = ref->enclosing_obj();
 517   if (enclosing_obj == nullptr) {
 518     return;
 519   }
 520 
 521   // We are dealing with 3 addresses:
 522   // address o    = ref->obj(): We have found an object whose address is o.
 523   // address* mpp = ref->mpp(): The object o is pointed to by a pointer whose address is mpp.
 524   //                            I.e., (*mpp == o)
 525   // enclosing_obj            : If non-null, it is the object which has a field that points to o.
 526   //                            mpp is the address if that field.
 527   //
 528   // Example: We have an array whose first element points to a Method:
 529   //     Method* o                     = 0x0000abcd;
 530   //     Array<Method*>* enclosing_obj = 0x00001000;
 531   //     enclosing_obj->at_put(0, o);
 532   //
 533   // We the MetaspaceClosure iterates on the very first element of this array, we have
 534   //     ref->obj()           == 0x0000abcd   (the Method)
 535   //     ref->mpp()           == 0x00001008   (the location of the first element in the array)
 536   //     ref->enclosing_obj() == 0x00001000   (the Array that contains the Method)
 537   //
 538   // We use the above information to mark the bitmap to indicate that there's a pointer on address 0x00001008.
 539   SourceObjInfo* src_info = _src_obj_table.get(enclosing_obj);
 540   if (src_info == nullptr || !src_info->should_copy()) {
 541     // source objects of point_to_it/set_to_null types are not copied
 542     // so we don't need to remember their pointers.
 543   } else {
 544     if (src_info->read_only()) {
 545       _ro_src_objs.remember_embedded_pointer(src_info, ref);
 546     } else {
 547       _rw_src_objs.remember_embedded_pointer(src_info, ref);
 548     }
 549   }
 550 }
 551 
 552 void ArchiveBuilder::gather_source_objs() {
 553   ResourceMark rm;
 554   log_info(cds)("Gathering all archivable objects ... ");
 555   gather_klasses_and_symbols();
 556   GatherSortedSourceObjs doit(this);
 557   iterate_sorted_roots(&doit);
 558   doit.finish();
 559 }
 560 
 561 bool ArchiveBuilder::is_excluded(Klass* klass) {
 562   if (klass->is_instance_klass()) {
 563     InstanceKlass* ik = InstanceKlass::cast(klass);
 564     return SystemDictionaryShared::is_excluded_class(ik);
 565   } else if (klass->is_objArray_klass()) {
 566     Klass* bottom = ObjArrayKlass::cast(klass)->bottom_klass();
 567     if (CDSConfig::is_dumping_dynamic_archive() && MetaspaceShared::is_shared_static(bottom)) {
 568       // The bottom class is in the static archive so it's clearly not excluded.
 569       assert(CDSConfig::is_dumping_dynamic_archive(), "sanity");
 570       return false;
 571     } else if (bottom->is_instance_klass()) {
 572       return SystemDictionaryShared::is_excluded_class(InstanceKlass::cast(bottom));
 573     }
 574   }
 575 
 576   return false;
 577 }
 578 
 579 ArchiveBuilder::FollowMode ArchiveBuilder::get_follow_mode(MetaspaceClosure::Ref *ref) {
 580   address obj = ref->obj();
 581   if (CDSConfig::is_dumping_dynamic_archive() && MetaspaceShared::is_in_shared_metaspace(obj)) {
 582     // Don't dump existing shared metadata again.
 583     return point_to_it;
 584   } else if (ref->msotype() == MetaspaceObj::MethodDataType ||
 585              ref->msotype() == MetaspaceObj::MethodCountersType ||
 586              ref->msotype() == MetaspaceObj::KlassTrainingDataType ||
 587              ref->msotype() == MetaspaceObj::MethodTrainingDataType ||
 588              ref->msotype() == MetaspaceObj::CompileTrainingDataType) {
 589       return TrainingData::need_data() ? make_a_copy : set_to_null;
 590   } else {
 591     if (ref->msotype() == MetaspaceObj::ClassType) {
 592       Klass* klass = (Klass*)ref->obj();
 593       assert(klass->is_klass(), "must be");
 594       if (is_excluded(klass)) {
 595         ResourceMark rm;
 596         log_debug(cds, dynamic)("Skipping class (excluded): %s", klass->external_name());
 597         return set_to_null;
 598       }
 599     }
 600 
 601     return make_a_copy;
 602   }
 603 }
 604 
 605 void ArchiveBuilder::start_dump_space(DumpRegion* next) {
 606   address bottom = _last_verified_top;
 607   address top = (address)(current_dump_space()->top());
 608   _other_region_used_bytes += size_t(top - bottom);
 609 
 610   current_dump_space()->pack(next);
 611   _current_dump_space = next;
 612   _num_dump_regions_used ++;
 613 
 614   _last_verified_top = (address)(current_dump_space()->top());
 615 }
 616 
 617 void ArchiveBuilder::verify_estimate_size(size_t estimate, const char* which) {
 618   address bottom = _last_verified_top;
 619   address top = (address)(current_dump_space()->top());
 620   size_t used = size_t(top - bottom) + _other_region_used_bytes;
 621   int diff = int(estimate) - int(used);
 622 
 623   log_info(cds)("%s estimate = " SIZE_FORMAT " used = " SIZE_FORMAT "; diff = %d bytes", which, estimate, used, diff);
 624   assert(diff >= 0, "Estimate is too small");
 625 
 626   _last_verified_top = top;
 627   _other_region_used_bytes = 0;
 628 }
 629 
 630 char* ArchiveBuilder::ro_strdup(const char* s) {
 631   char* archived_str = ro_region_alloc((int)strlen(s) + 1);
 632   strcpy(archived_str, s);
 633   return archived_str;
 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_space(&_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     // Save a pointer immediate in front of an 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   }
 696   dest = dump_region->allocate(bytes);
 697   newtop = dump_region->top();
 698 
 699   memcpy(dest, src, bytes);
 700 
 701   // Update the hash of buffered sorted symbols for static dump so that the symbols have deterministic contents
 702   if (CDSConfig::is_dumping_static_archive() && (src_info->msotype() == MetaspaceObj::SymbolType)) {
 703     Symbol* buffered_symbol = (Symbol*)dest;
 704     assert(((Symbol*)src)->is_permanent(), "archived symbols must be permanent");
 705     buffered_symbol->update_identity_hash();
 706   }
 707 
 708   {
 709     bool created;
 710     _buffered_to_src_table.put_if_absent((address)dest, src, &created);
 711     assert(created, "must be");
 712     if (_buffered_to_src_table.maybe_grow()) {
 713       log_info(cds, hashtables)("Expanded _buffered_to_src_table table to %d", _buffered_to_src_table.table_size());
 714     }
 715   }
 716 
 717   intptr_t* archived_vtable = CppVtables::get_archived_vtable(src_info->msotype(), (address)dest);
 718   if (archived_vtable != nullptr) {
 719     *(address*)dest = (address)archived_vtable;
 720     ArchivePtrMarker::mark_pointer((address*)dest);
 721   }
 722 
 723   log_trace(cds)("Copy: " PTR_FORMAT " ==> " PTR_FORMAT " %d", p2i(src), p2i(dest), bytes);
 724   src_info->set_buffered_addr((address)dest);
 725 
 726   _alloc_stats.record(src_info->msotype(), int(newtop - oldtop), src_info->read_only());
 727 }
 728 
 729 // This is used by code that hand-assembles data structures, such as the LambdaProxyClassKey, that are
 730 // not handled by MetaspaceClosure.
 731 void ArchiveBuilder::write_pointer_in_buffer(address* ptr_location, address src_addr) {
 732   assert(is_in_buffer_space(ptr_location), "must be");
 733   if (src_addr == nullptr) {
 734     *ptr_location = nullptr;
 735     ArchivePtrMarker::clear_pointer(ptr_location);
 736   } else {
 737     *ptr_location = get_buffered_addr(src_addr);
 738     ArchivePtrMarker::mark_pointer(ptr_location);
 739   }
 740 }
 741 
 742 void ArchiveBuilder::mark_and_relocate_to_buffered_addr(address* ptr_location) {
 743   assert(*ptr_location != nullptr, "sanity");
 744   if (!is_in_mapped_static_archive(*ptr_location)) {
 745     *ptr_location = get_buffered_addr(*ptr_location);
 746   }
 747   ArchivePtrMarker::mark_pointer(ptr_location);
 748 }
 749 
 750 address ArchiveBuilder::get_buffered_addr(address src_addr) const {
 751   SourceObjInfo* p = _src_obj_table.get(src_addr);
 752   assert(p != nullptr, "src_addr " INTPTR_FORMAT " is used but has not been archived",
 753          p2i(src_addr));
 754 
 755   return p->buffered_addr();
 756 }
 757 
 758 bool ArchiveBuilder::has_been_archived(address src_addr) const {
 759   SourceObjInfo* p = _src_obj_table.get(src_addr);
 760   return (p != nullptr);
 761 }
 762 
 763 address ArchiveBuilder::get_source_addr(address buffered_addr) const {
 764   assert(is_in_buffer_space(buffered_addr), "must be");
 765   address* src_p = _buffered_to_src_table.get(buffered_addr);
 766   assert(src_p != nullptr && *src_p != nullptr, "must be");
 767   return *src_p;
 768 }
 769 
 770 void ArchiveBuilder::relocate_embedded_pointers(ArchiveBuilder::SourceObjList* src_objs) {
 771   for (int i = 0; i < src_objs->objs()->length(); i++) {
 772     src_objs->relocate(i, this);
 773   }
 774 }
 775 
 776 void ArchiveBuilder::relocate_metaspaceobj_embedded_pointers() {
 777   log_info(cds)("Relocating embedded pointers in core regions ... ");
 778   relocate_embedded_pointers(&_rw_src_objs);
 779   relocate_embedded_pointers(&_ro_src_objs);
 780 }
 781 
 782 #define ADD_COUNT(x) \
 783   x += 1; \
 784   x ## _p += preloaded; \
 785   x ## _i += inited;
 786 
 787 #define DECLARE_INSTANCE_KLASS_COUNTER(x) \
 788   int x = 0; \
 789   int x ## _p = 0; \
 790   int x ## _i = 0; \
 791 
 792 void ArchiveBuilder::make_klasses_shareable() {
 793   DECLARE_INSTANCE_KLASS_COUNTER(num_instance_klasses);
 794   DECLARE_INSTANCE_KLASS_COUNTER(num_boot_klasses);
 795   DECLARE_INSTANCE_KLASS_COUNTER(num_vm_klasses);
 796   DECLARE_INSTANCE_KLASS_COUNTER(num_platform_klasses);
 797   DECLARE_INSTANCE_KLASS_COUNTER(num_app_klasses);
 798   DECLARE_INSTANCE_KLASS_COUNTER(num_hidden_klasses);
 799   DECLARE_INSTANCE_KLASS_COUNTER(num_unlinked_klasses);
 800   DECLARE_INSTANCE_KLASS_COUNTER(num_unregistered_klasses);
 801   int num_obj_array_klasses = 0;
 802   int num_type_array_klasses = 0;
 803 
 804   int boot_unlinked = 0;
 805   int platform_unlinked = 0;
 806   int app_unlinked = 0;
 807   int unreg_unlinked = 0;
 808 
 809   for (int i = 0; i < klasses()->length(); i++) {
 810     // Some of the code in ConstantPool::remove_unshareable_info() requires the classes
 811     // to be in linked state, so it must be call here before the next loop, which returns
 812     // all classes to unlinked state.
 813     Klass* k = get_buffered_addr(klasses()->at(i));
 814     if (k->is_instance_klass()) {
 815       InstanceKlass::cast(k)->constants()->remove_unshareable_info();
 816     }
 817   }
 818 
 819   for (int i = 0; i < klasses()->length(); i++) {
 820     const char* type;
 821     const char* unlinked = "";
 822     const char* hidden = "";
 823     const char* generated = "";
 824     const char* preloaded_msg = "";
 825     const char* inited_msg = "";
 826     Klass* k = get_buffered_addr(klasses()->at(i));
 827     k->remove_java_mirror();
 828     if (k->is_objArray_klass()) {
 829       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
 830       // on their array classes.
 831       num_obj_array_klasses ++;
 832       type = "array";
 833     } else if (k->is_typeArray_klass()) {
 834       num_type_array_klasses ++;
 835       type = "array";
 836       k->remove_unshareable_info();
 837     } else {
 838       assert(k->is_instance_klass(), " must be");

 839       InstanceKlass* ik = InstanceKlass::cast(k);
 840       InstanceKlass* src_ik = get_source_addr(ik);
 841       int preloaded = ClassPreloader::is_preloaded_class(src_ik);
 842       int inited = ik->has_preinitialized_mirror();
 843       ADD_COUNT(num_instance_klasses);
 844       if (CDSConfig::is_dumping_dynamic_archive()) {
 845         // For static dump, class loader type are already set.
 846         ik->assign_class_loader_type();
 847       }
 848       if (ik->is_hidden()) {
 849         oop loader = k->class_loader();
 850         if (loader == nullptr) {
 851           type = "boot";
 852           ADD_COUNT(num_boot_klasses);
 853         } else if (loader == SystemDictionary::java_platform_loader()) {
 854           type = "plat";
 855           ADD_COUNT(num_platform_klasses);
 856         } else if (loader == SystemDictionary::java_system_loader()) {
 857           type = "app";
 858           ADD_COUNT(num_app_klasses);
 859         } else {
 860           type = "bad";
 861           assert(0, "shouldn't happen");
 862         }
 863       } else if (ik->is_shared_boot_class()) {
 864         type = "boot";
 865         ADD_COUNT(num_boot_klasses);
 866       } else if (ik->is_shared_platform_class()) {
 867         type = "plat";
 868         ADD_COUNT(num_platform_klasses);
 869       } else if (ik->is_shared_app_class()) {
 870         type = "app";
 871         ADD_COUNT(num_app_klasses);
 872       } else {
 873         assert(ik->is_shared_unregistered_class(), "must be");
 874         type = "unreg";
 875         ADD_COUNT(num_unregistered_klasses);
 876       }
 877 
 878       if (ClassPreloader::is_vm_class(src_ik)) {
 879         ADD_COUNT(num_vm_klasses);
 880       }
 881 
 882       if (!ik->is_linked()) {
 883         ADD_COUNT(num_unlinked_klasses);
 884         unlinked = " unlinked";
 885         if (ik->is_shared_boot_class()) {
 886           boot_unlinked ++;
 887         } else if (ik->is_shared_platform_class()) {
 888           platform_unlinked ++;
 889         } else if (ik->is_shared_app_class()) {
 890           app_unlinked ++;
 891         } else {
 892           unreg_unlinked ++;
 893         }
 894       }
 895 
 896       if (ik->is_hidden()) {
 897         ADD_COUNT(num_hidden_klasses);
 898         hidden = " hidden";
 899       }
 900 
 901       if (ik->is_generated_shared_class()) {
 902         generated = " generated";
 903       }
 904       if (preloaded) {
 905         preloaded_msg = " preloaded";
 906       }
 907       if (inited) {
 908         inited_msg = " inited";
 909       }
 910 
 911       MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread::current(), ik);
 912       ik->remove_unshareable_info();
 913     }
 914 
 915     if (log_is_enabled(Debug, cds, class)) {
 916       ResourceMark rm;
 917       log_debug(cds, class)("klasses[%5d] = " PTR_FORMAT " %-5s %s%s%s%s%s%s", i,
 918                             p2i(to_requested(k)), type, k->external_name(),
 919                             hidden, unlinked, generated, preloaded_msg, inited_msg);
 920     }
 921   }
 922 
 923 #define STATS_FORMAT    "= %5d, preloaded = %5d, inited = %5d"
 924 #define STATS_PARAMS(x) num_ ## x, num_ ## x ## _p, num_ ## x ## _i
 925 
 926   log_info(cds)("Number of classes %d", num_instance_klasses + num_obj_array_klasses + num_type_array_klasses);
 927   log_info(cds)("    instance classes   " STATS_FORMAT, STATS_PARAMS(instance_klasses));
 928   log_info(cds)("      boot             " STATS_FORMAT, STATS_PARAMS(boot_klasses));
 929   log_info(cds)("       vm              " STATS_FORMAT, STATS_PARAMS(vm_klasses));
 930   log_info(cds)("      platform         " STATS_FORMAT, STATS_PARAMS(platform_klasses));
 931   log_info(cds)("      app              " STATS_FORMAT, STATS_PARAMS(app_klasses));
 932   log_info(cds)("      unregistered     " STATS_FORMAT, STATS_PARAMS(unregistered_klasses));
 933   log_info(cds)("      (hidden)         " STATS_FORMAT, STATS_PARAMS(hidden_klasses));
 934   log_info(cds)("      (unlinked)       " STATS_FORMAT ", boot = %d, plat = %d, app = %d, unreg = %d",
 935                                                               STATS_PARAMS(unlinked_klasses),
 936                                                               boot_unlinked, platform_unlinked,
 937                                                               app_unlinked, unreg_unlinked);
 938   log_info(cds)("    obj array classes  = %5d", num_obj_array_klasses);
 939   log_info(cds)("    type array classes = %5d", num_type_array_klasses);
 940   log_info(cds)("               symbols = %5d", _symbols->length());
 941 
 942 #undef STATS_FORMAT
 943 #undef STATS_PARAMS
 944 
 945   DynamicArchive::make_array_klasses_shareable();
 946 }
 947 
 948 void ArchiveBuilder::serialize_dynamic_archivable_items(SerializeClosure* soc) {
 949   SymbolTable::serialize_shared_table_header(soc, false);
 950   SystemDictionaryShared::serialize_dictionary_headers(soc, false);
 951   DynamicArchive::serialize_array_klasses(soc);
 952   ClassPreloader::serialize(soc, false);
 953   FinalImageRecipes::serialize(soc, false);
 954   TrainingData::serialize_training_data(soc);
 955 }
 956 
 957 uintx ArchiveBuilder::buffer_to_offset(address p) const {
 958   address requested_p = to_requested(p);
 959   assert(requested_p >= _requested_static_archive_bottom, "must be");
 960   return requested_p - _requested_static_archive_bottom;
 961 }
 962 
 963 uintx ArchiveBuilder::any_to_offset(address p) const {
 964   if (is_in_mapped_static_archive(p)) {
 965     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
 966     return p - _mapped_static_archive_bottom;
 967   }
 968   if (!is_in_buffer_space(p)) {
 969     // p must be a "source" address
 970     p = get_buffered_addr(p);
 971   }
 972   return buffer_to_offset(p);
 973 }
 974 
 975 void ArchiveBuilder::start_cc_region() {
 976   ro_region()->pack();
 977   start_dump_space(&_cc_region);
 978 }
 979 
 980 void ArchiveBuilder::end_cc_region() {
 981   _cc_region.pack();
 982 }
 983 
 984 #if INCLUDE_CDS_JAVA_HEAP
 985 narrowKlass ArchiveBuilder::get_requested_narrow_klass(Klass* k) {
 986   assert(CDSConfig::is_dumping_heap(), "sanity");
 987   k = get_buffered_klass(k);
 988   Klass* requested_k = to_requested(k);
 989   address narrow_klass_base = _requested_static_archive_bottom; // runtime encoding base == runtime mapping start
 990   const int narrow_klass_shift = ArchiveHeapWriter::precomputed_narrow_klass_shift;
 991   return CompressedKlassPointers::encode_not_null(requested_k, narrow_klass_base, narrow_klass_shift);
 992 }
 993 #endif // INCLUDE_CDS_JAVA_HEAP
 994 
 995 // RelocateBufferToRequested --- Relocate all the pointers in rw/ro,
 996 // so that the archive can be mapped to the "requested" location without runtime relocation.
 997 //
 998 // - See ArchiveBuilder header for the definition of "buffer", "mapped" and "requested"
 999 // - ArchivePtrMarker::ptrmap() marks all the pointers in the rw/ro regions
1000 // - Every pointer must have one of the following values:
1001 //   [a] nullptr:
1002 //       No relocation is needed. Remove this pointer from ptrmap so we don't need to
1003 //       consider it at runtime.
1004 //   [b] Points into an object X which is inside the buffer:
1005 //       Adjust this pointer by _buffer_to_requested_delta, so it points to X
1006 //       when the archive is mapped at the requested location.
1007 //   [c] Points into an object Y which is inside mapped static archive:
1008 //       - This happens only during dynamic dump
1009 //       - Adjust this pointer by _mapped_to_requested_static_archive_delta,
1010 //         so it points to Y when the static archive is mapped at the requested location.
1011 template <bool STATIC_DUMP>
1012 class RelocateBufferToRequested : public BitMapClosure {
1013   ArchiveBuilder* _builder;
1014   address _buffer_bottom;
1015   intx _buffer_to_requested_delta;
1016   intx _mapped_to_requested_static_archive_delta;
1017   size_t _max_non_null_offset;
1018 
1019  public:
1020   RelocateBufferToRequested(ArchiveBuilder* builder) {
1021     _builder = builder;
1022     _buffer_bottom = _builder->buffer_bottom();
1023     _buffer_to_requested_delta = builder->buffer_to_requested_delta();
1024     _mapped_to_requested_static_archive_delta = builder->requested_static_archive_bottom() - builder->mapped_static_archive_bottom();
1025     _max_non_null_offset = 0;
1026 
1027     address bottom = _builder->buffer_bottom();
1028     address top = _builder->buffer_top();
1029     address new_bottom = bottom + _buffer_to_requested_delta;
1030     address new_top = top + _buffer_to_requested_delta;
1031     log_debug(cds)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT "] to "
1032                    "[" INTPTR_FORMAT " - " INTPTR_FORMAT "]",
1033                    p2i(bottom), p2i(top),
1034                    p2i(new_bottom), p2i(new_top));
1035   }
1036 
1037   bool do_bit(size_t offset) {
1038     address* p = (address*)_buffer_bottom + offset;
1039     assert(_builder->is_in_buffer_space(p), "pointer must live in buffer space");
1040 
1041     if (*p == nullptr) {
1042       // todo -- clear bit, etc
1043       ArchivePtrMarker::ptrmap()->clear_bit(offset);
1044     } else {
1045       if (STATIC_DUMP) {
1046         assert(_builder->is_in_buffer_space(*p), "old pointer must point inside buffer space");
1047         *p += _buffer_to_requested_delta;
1048         assert(_builder->is_in_requested_static_archive(*p), "new pointer must point inside requested archive");
1049       } else {
1050         if (_builder->is_in_buffer_space(*p)) {
1051           *p += _buffer_to_requested_delta;
1052           // assert is in requested dynamic archive
1053         } else {
1054           assert(_builder->is_in_mapped_static_archive(*p), "old pointer must point inside buffer space or mapped static archive");
1055           *p += _mapped_to_requested_static_archive_delta;
1056           assert(_builder->is_in_requested_static_archive(*p), "new pointer must point inside requested archive");
1057         }
1058       }
1059       _max_non_null_offset = offset;
1060     }
1061 
1062     return true; // keep iterating
1063   }
1064 
1065   void doit() {
1066     ArchivePtrMarker::ptrmap()->iterate(this);
1067     ArchivePtrMarker::compact(_max_non_null_offset);
1068   }
1069 };
1070 
1071 
1072 void ArchiveBuilder::relocate_to_requested() {
1073   if (!ro_region()->is_packed()) {
1074     ro_region()->pack();
1075   }
1076 
1077   size_t my_archive_size = buffer_top() - buffer_bottom();
1078 
1079   if (CDSConfig::is_dumping_static_archive()) {
1080     _requested_static_archive_top = _requested_static_archive_bottom + my_archive_size;
1081     RelocateBufferToRequested<true> patcher(this);
1082     patcher.doit();
1083   } else {
1084     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1085     _requested_dynamic_archive_top = _requested_dynamic_archive_bottom + my_archive_size;
1086     RelocateBufferToRequested<false> patcher(this);
1087     patcher.doit();
1088   }
1089 }
1090 
1091 // Write detailed info to a mapfile to analyze contents of the archive.
1092 // static dump:
1093 //   java -Xshare:dump -Xlog:cds+map=trace:file=cds.map:none:filesize=0
1094 // dynamic dump:
1095 //   java -cp MyApp.jar -XX:ArchiveClassesAtExit=MyApp.jsa \
1096 //        -Xlog:cds+map=trace:file=cds.map:none:filesize=0 MyApp
1097 //
1098 // We need to do some address translation because the buffers used at dump time may be mapped to
1099 // a different location at runtime. At dump time, the buffers may be at arbitrary locations
1100 // picked by the OS. At runtime, we try to map at a fixed location (SharedBaseAddress). For
1101 // consistency, we log everything using runtime addresses.
1102 class ArchiveBuilder::CDSMapLogger : AllStatic {
1103   static intx buffer_to_runtime_delta() {
1104     // Translate the buffers used by the RW/RO regions to their eventual (requested) locations
1105     // at runtime.
1106     return ArchiveBuilder::current()->buffer_to_requested_delta();
1107   }
1108 
1109   // rw/ro regions only
1110   static void log_metaspace_region(const char* name, DumpRegion* region,
1111                                    const ArchiveBuilder::SourceObjList* src_objs) {
1112     address region_base = address(region->base());
1113     address region_top  = address(region->top());
1114     log_region(name, region_base, region_top, region_base + buffer_to_runtime_delta());
1115     log_metaspace_objects(region, src_objs);
1116   }
1117 
1118 #define _LOG_PREFIX PTR_FORMAT ": @@ %-17s %d"
1119 
1120   static void log_klass(Klass* k, address runtime_dest, const char* type_name, int bytes, Thread* current) {
1121     ResourceMark rm(current);
1122     log_debug(cds, map)(_LOG_PREFIX " %s",
1123                         p2i(runtime_dest), type_name, bytes, k->external_name());
1124   }
1125   static void log_method(Method* m, address runtime_dest, const char* type_name, int bytes, Thread* current) {
1126     ResourceMark rm(current);
1127     log_debug(cds, map)(_LOG_PREFIX " %s",
1128                         p2i(runtime_dest), type_name, bytes,  m->external_name());
1129   }
1130 
1131   // rw/ro regions only
1132   static void log_metaspace_objects(DumpRegion* region, const ArchiveBuilder::SourceObjList* src_objs) {
1133     address last_obj_base = address(region->base());
1134     address last_obj_end  = address(region->base());
1135     address region_end    = address(region->end());
1136     Thread* current = Thread::current();
1137     for (int i = 0; i < src_objs->objs()->length(); i++) {
1138       SourceObjInfo* src_info = src_objs->at(i);
1139       address src = src_info->source_addr();
1140       address dest = src_info->buffered_addr();
1141       log_as_hex(last_obj_base, dest, last_obj_base + buffer_to_runtime_delta());
1142       address runtime_dest = dest + buffer_to_runtime_delta();
1143       int bytes = src_info->size_in_bytes();
1144 
1145       MetaspaceObj::Type type = src_info->msotype();
1146       const char* type_name = MetaspaceObj::type_name(type);
1147 
1148       switch (type) {
1149       case MetaspaceObj::ClassType:
1150         log_klass((Klass*)src, runtime_dest, type_name, bytes, current);
1151         break;
1152       case MetaspaceObj::ConstantPoolType:
1153         log_klass(((ConstantPool*)src)->pool_holder(),
1154                     runtime_dest, type_name, bytes, current);
1155         break;
1156       case MetaspaceObj::ConstantPoolCacheType:
1157         log_klass(((ConstantPoolCache*)src)->constant_pool()->pool_holder(),
1158                     runtime_dest, type_name, bytes, current);
1159         break;
1160       case MetaspaceObj::MethodType:
1161         log_method((Method*)src, runtime_dest, type_name, bytes, current);
1162         break;
1163       case MetaspaceObj::ConstMethodType:
1164         log_method(((ConstMethod*)src)->method(), runtime_dest, type_name, bytes, current);
1165         break;
1166       case MetaspaceObj::SymbolType:
1167         {
1168           ResourceMark rm(current);
1169           Symbol* s = (Symbol*)src;
1170           log_debug(cds, map)(_LOG_PREFIX " %s", p2i(runtime_dest), type_name, bytes,
1171                               s->as_quoted_ascii());
1172         }
1173         break;
1174       default:
1175         log_debug(cds, map)(_LOG_PREFIX, p2i(runtime_dest), type_name, bytes);
1176         break;
1177       }
1178 
1179       last_obj_base = dest;
1180       last_obj_end  = dest + bytes;
1181     }
1182 
1183     log_as_hex(last_obj_base, last_obj_end, last_obj_base + buffer_to_runtime_delta());
1184     if (last_obj_end < region_end) {
1185       log_debug(cds, map)(PTR_FORMAT ": @@ Misc data " SIZE_FORMAT " bytes",
1186                           p2i(last_obj_end + buffer_to_runtime_delta()),
1187                           size_t(region_end - last_obj_end));
1188       log_as_hex(last_obj_end, region_end, last_obj_end + buffer_to_runtime_delta());
1189     }
1190   }
1191 
1192 #undef _LOG_PREFIX
1193 
1194   // Log information about a region, whose address at dump time is [base .. top). At
1195   // runtime, this region will be mapped to requested_base. requested_base is 0 if this
1196   // region will be mapped at os-selected addresses (such as the bitmap region), or will
1197   // be accessed with os::read (the header).
1198   //
1199   // Note: across -Xshare:dump runs, base may be different, but requested_base should
1200   // be the same as the archive contents should be deterministic.
1201   static void log_region(const char* name, address base, address top, address requested_base) {
1202     size_t size = top - base;
1203     base = requested_base;
1204     top = requested_base + size;
1205     log_info(cds, map)("[%-18s " PTR_FORMAT " - " PTR_FORMAT " " SIZE_FORMAT_W(9) " bytes]",
1206                        name, p2i(base), p2i(top), size);
1207   }
1208 
1209 #if INCLUDE_CDS_JAVA_HEAP
1210   static void log_heap_region(ArchiveHeapInfo* heap_info) {
1211     MemRegion r = heap_info->buffer_region();
1212     address start = address(r.start()); // start of the current oop inside the buffer
1213     address end = address(r.end());
1214     log_region("heap", start, end, ArchiveHeapWriter::buffered_addr_to_requested_addr(start));
1215 
1216     LogStreamHandle(Info, cds, map) st;
1217 
1218     while (start < end) {
1219       size_t byte_size;
1220       oop source_oop = ArchiveHeapWriter::buffered_addr_to_source_obj(start);
1221       address requested_start = ArchiveHeapWriter::buffered_addr_to_requested_addr(start);
1222       st.print(PTR_FORMAT ": @@ Object ", p2i(requested_start));
1223       int permobj_segment = -1;
1224       int permobj_segment_length = -1;
1225 
1226       if (source_oop != nullptr) {
1227         // This is a regular oop that got archived.
1228         print_oop_with_requested_addr_cr(&st, source_oop, false);
1229         byte_size = source_oop->size() * BytesPerWord;
1230       } else if (start == ArchiveHeapWriter::buffered_heap_roots_addr()) {
1231         // HeapShared::roots() is copied specially, so it doesn't exist in
1232         // ArchiveHeapWriter::BufferOffsetToSourceObjectTable.
1233         // See ArchiveHeapWriter::copy_roots_to_buffer().
1234         st.print_cr("HeapShared::roots[%d]", HeapShared::pending_roots()->length());
1235         byte_size = ArchiveHeapWriter::heap_roots_word_size() * BytesPerWord;
1236       } else if ((byte_size = ArchiveHeapWriter::get_filler_size_at(start)) > 0) {
1237         // We have a filler oop, which also does not exist in BufferOffsetToSourceObjectTable.
1238         st.print_cr("filler " SIZE_FORMAT " bytes", byte_size);
1239       } else if ((permobj_segment = ArchiveHeapWriter::get_permobj_segment_at(start, &byte_size, &permobj_segment_length)) >= 0) {
1240         st.print_cr("permobj_%d[%d] %zu bytes", permobj_segment, permobj_segment_length, byte_size);
1241       } else {
1242         ShouldNotReachHere();
1243       }
1244 
1245       address oop_end = start + byte_size;
1246       log_as_hex(start, oop_end, requested_start, /*is_heap=*/true);
1247 
1248       if (source_oop != nullptr) {
1249         log_oop_details(heap_info, source_oop, /*buffered_addr=*/start);
1250       } else if (start == ArchiveHeapWriter::buffered_heap_roots_addr()) {
1251         log_heap_roots();
1252       } else if (permobj_segment >= 0) {
1253         log_permobj_segment(permobj_segment, permobj_segment_length);
1254       }
1255       start = oop_end;
1256     }
1257   }
1258 
1259   // ArchivedFieldPrinter is used to print the fields of archived objects. We can't
1260   // use _source_obj->print_on(), because we want to print the oop fields
1261   // in _source_obj with their requested addresses using print_oop_with_requested_addr_cr().
1262   class ArchivedFieldPrinter : public FieldClosure {
1263     ArchiveHeapInfo* _heap_info;
1264     outputStream* _st;
1265     oop _source_obj;
1266     address _buffered_addr;
1267   public:
1268     ArchivedFieldPrinter(ArchiveHeapInfo* heap_info, outputStream* st, oop src_obj, address buffered_addr) :
1269       _heap_info(heap_info), _st(st), _source_obj(src_obj), _buffered_addr(buffered_addr) {}
1270 
1271     void do_field(fieldDescriptor* fd) {
1272       _st->print(" - ");
1273       BasicType ft = fd->field_type();
1274       switch (ft) {
1275       case T_ARRAY:
1276       case T_OBJECT:
1277         fd->print_on(_st); // print just the name and offset
1278         print_oop_with_requested_addr_cr(_st, _source_obj->obj_field(fd->offset()));
1279         break;
1280       default:
1281         if (ArchiveHeapWriter::is_marked_as_native_pointer(_heap_info, _source_obj, fd->offset())) {
1282           print_as_native_pointer(fd);
1283         } else {
1284           fd->print_on_for(_st, cast_to_oop(_buffered_addr)); // name, offset, value
1285           _st->cr();
1286         }
1287       }
1288     }
1289 
1290     void print_as_native_pointer(fieldDescriptor* fd) {
1291       LP64_ONLY(assert(fd->field_type() == T_LONG, "must be"));
1292       NOT_LP64 (assert(fd->field_type() == T_INT,  "must be"));
1293 
1294       // We have a field that looks like an integer, but it's actually a pointer to a MetaspaceObj.
1295       address source_native_ptr = (address)
1296           LP64_ONLY(_source_obj->long_field(fd->offset()))
1297           NOT_LP64( _source_obj->int_field (fd->offset()));
1298       ArchiveBuilder* builder = ArchiveBuilder::current();
1299 
1300       // The value of the native pointer at runtime.
1301       address requested_native_ptr = builder->to_requested(builder->get_buffered_addr(source_native_ptr));
1302 
1303       // The address of _source_obj at runtime
1304       oop requested_obj = ArchiveHeapWriter::source_obj_to_requested_obj(_source_obj);
1305       // The address of this field in the requested space
1306       assert(requested_obj != nullptr, "Attempting to load field from null oop");
1307       address requested_field_addr = cast_from_oop<address>(requested_obj) + fd->offset();
1308 
1309       fd->print_on(_st);
1310       _st->print_cr(PTR_FORMAT " (marked metadata pointer @" PTR_FORMAT " )",
1311                     p2i(requested_native_ptr), p2i(requested_field_addr));
1312     }
1313   };
1314 
1315   // Print the fields of instanceOops, or the elements of arrayOops
1316   static void log_oop_details(ArchiveHeapInfo* heap_info, oop source_oop, address buffered_addr) {
1317     LogStreamHandle(Trace, cds, map, oops) st;
1318     if (st.is_enabled()) {
1319       Klass* source_klass = source_oop->klass();
1320       ArchiveBuilder* builder = ArchiveBuilder::current();
1321       Klass* requested_klass = builder->to_requested(builder->get_buffered_addr(source_klass));
1322 
1323       st.print(" - klass: ");
1324       source_klass->print_value_on(&st);
1325       st.print(" " PTR_FORMAT, p2i(requested_klass));
1326       st.cr();
1327 
1328       if (source_oop->is_typeArray()) {
1329         TypeArrayKlass::cast(source_klass)->oop_print_elements_on(typeArrayOop(source_oop), &st);
1330       } else if (source_oop->is_objArray()) {
1331         objArrayOop source_obj_array = objArrayOop(source_oop);
1332         for (int i = 0; i < source_obj_array->length(); i++) {
1333           st.print(" -%4d: ", i);
1334           print_oop_with_requested_addr_cr(&st, source_obj_array->obj_at(i));
1335         }
1336       } else {
1337         st.print_cr(" - fields (" SIZE_FORMAT " words):", source_oop->size());
1338         ArchivedFieldPrinter print_field(heap_info, &st, source_oop, buffered_addr);
1339         InstanceKlass::cast(source_klass)->print_nonstatic_fields(&print_field);
1340       }
1341     }
1342   }
1343 
1344   static void log_heap_roots() {
1345     LogStreamHandle(Trace, cds, map, oops) st;
1346     if (st.is_enabled()) {
1347       for (int i = 0; i < HeapShared::pending_roots()->length(); i++) {
1348         st.print("roots[%4d]: ", i);
1349         print_oop_with_requested_addr_cr(&st, HeapShared::pending_roots()->at(i));
1350       }
1351     }
1352   }
1353 
1354   static void log_permobj_segment(int permobj_segment, int permobj_segment_length) {
1355     LogStreamHandle(Trace, cds, map, oops) st;
1356     if (st.is_enabled()) {
1357       for (int i = 0; i < permobj_segment_length; i++) {
1358         st.print("permobj_%d[%4d]: ", permobj_segment, i);
1359         print_oop_with_requested_addr_cr(&st, ArchiveHeapWriter::get_permobj_source_addr(permobj_segment, i));
1360       }
1361     }
1362   }
1363 
1364 
1365   // The output looks like this. The first number is the requested address. The second number is
1366   // the narrowOop version of the requested address.
1367   //     0x00000007ffc7e840 (0xfff8fd08) java.lang.Class
1368   //     0x00000007ffc000f8 (0xfff8001f) [B length: 11
1369   static void print_oop_with_requested_addr_cr(outputStream* st, oop source_oop, bool print_addr = true) {
1370     if (source_oop == nullptr) {
1371       st->print_cr("null");
1372     } else {
1373       ResourceMark rm;
1374       oop requested_obj = ArchiveHeapWriter::source_obj_to_requested_obj(source_oop);
1375       if (print_addr) {
1376         st->print(PTR_FORMAT " ", p2i(requested_obj));
1377       }
1378       if (UseCompressedOops) {
1379         st->print("(0x%08x) ", CompressedOops::narrow_oop_value(requested_obj));
1380       }
1381       if (source_oop->is_array()) {
1382         int array_len = arrayOop(source_oop)->length();
1383         st->print_cr("%s length: %d", source_oop->klass()->external_name(), array_len);
1384       } else {
1385         st->print("%s", source_oop->klass()->external_name());
1386         if (java_lang_invoke_MethodType::is_instance(source_oop)) {
1387           st->print(" ");
1388           java_lang_invoke_MethodType::print_signature(source_oop, st);
1389         }
1390         st->cr();
1391       }
1392     }
1393   }
1394 #endif // INCLUDE_CDS_JAVA_HEAP
1395 
1396   // Log all the data [base...top). Pretend that the base address
1397   // will be mapped to requested_base at run-time.
1398   static void log_as_hex(address base, address top, address requested_base, bool is_heap = false) {
1399     assert(top >= base, "must be");
1400 
1401     LogStreamHandle(Trace, cds, map) lsh;
1402     if (lsh.is_enabled()) {
1403       int unitsize = sizeof(address);
1404       if (is_heap && UseCompressedOops) {
1405         // This makes the compressed oop pointers easier to read, but
1406         // longs and doubles will be split into two words.
1407         unitsize = sizeof(narrowOop);
1408       }
1409       os::print_hex_dump(&lsh, base, top, unitsize, 32, requested_base);
1410     }
1411   }
1412 
1413   static void log_header(FileMapInfo* mapinfo) {
1414     LogStreamHandle(Info, cds, map) lsh;
1415     if (lsh.is_enabled()) {
1416       mapinfo->print(&lsh);
1417     }
1418   }
1419 
1420 public:
1421   static void log(ArchiveBuilder* builder, FileMapInfo* mapinfo,
1422                   ArchiveHeapInfo* heap_info,
1423                   char* bitmap, size_t bitmap_size_in_bytes) {
1424     log_info(cds, map)("%s CDS archive map for %s", CDSConfig::is_dumping_static_archive() ? "Static" : "Dynamic", mapinfo->full_path());
1425 
1426     address header = address(mapinfo->header());
1427     address header_end = header + mapinfo->header()->header_size();
1428     log_region("header", header, header_end, 0);
1429     log_header(mapinfo);
1430     log_as_hex(header, header_end, 0);
1431 
1432     DumpRegion* rw_region = &builder->_rw_region;
1433     DumpRegion* ro_region = &builder->_ro_region;
1434 
1435     log_metaspace_region("rw region", rw_region, &builder->_rw_src_objs);
1436     log_metaspace_region("ro region", ro_region, &builder->_ro_src_objs);
1437 
1438     address bitmap_end = address(bitmap + bitmap_size_in_bytes);
1439     log_region("bitmap", address(bitmap), bitmap_end, 0);
1440     log_as_hex((address)bitmap, bitmap_end, 0);
1441 
1442 #if INCLUDE_CDS_JAVA_HEAP
1443     if (heap_info->is_used()) {
1444       log_heap_region(heap_info);
1445     }
1446 #endif
1447 
1448     log_info(cds, map)("[End of CDS archive map]");
1449   }
1450 }; // end ArchiveBuilder::CDSMapLogger
1451 
1452 void ArchiveBuilder::print_stats() {
1453   _alloc_stats.print_stats(int(_ro_region.used()), int(_rw_region.used()));
1454 }
1455 
1456 void ArchiveBuilder::write_archive(FileMapInfo* mapinfo, ArchiveHeapInfo* heap_info) {
1457   // Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with
1458   // MetaspaceShared::n_regions (internal to hotspot).
1459   assert(NUM_CDS_REGIONS == MetaspaceShared::n_regions, "sanity");
1460 
1461   write_region(mapinfo, MetaspaceShared::rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);
1462   write_region(mapinfo, MetaspaceShared::ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);
1463   write_region(mapinfo, MetaspaceShared::cc, &_cc_region, /*read_only=*/false,/*allow_exec=*/true);
1464 
1465   // Split pointer map into read-write and read-only bitmaps
1466   ArchivePtrMarker::initialize_rw_ro_cc_maps(&_rw_ptrmap, &_ro_ptrmap, &_cc_ptrmap);
1467 
1468   size_t bitmap_size_in_bytes;
1469   char* bitmap = mapinfo->write_bitmap_region(ArchivePtrMarker::rw_ptrmap(),
1470                                               ArchivePtrMarker::ro_ptrmap(),
1471                                               ArchivePtrMarker::cc_ptrmap(),
1472                                               heap_info,
1473                                               bitmap_size_in_bytes);
1474 
1475   if (heap_info->is_used()) {
1476     _total_heap_region_size = mapinfo->write_heap_region(heap_info);
1477   }
1478 
1479   print_region_stats(mapinfo, heap_info);
1480 
1481   mapinfo->set_requested_base((char*)MetaspaceShared::requested_base_address());
1482   mapinfo->set_header_crc(mapinfo->compute_header_crc());
1483   // After this point, we should not write any data into mapinfo->header() since this
1484   // would corrupt its checksum we have calculated before.
1485   mapinfo->write_header();
1486   mapinfo->close();
1487 
1488   if (log_is_enabled(Info, cds)) {
1489     print_stats();
1490   }
1491 
1492   if (log_is_enabled(Info, cds, map)) {
1493     CDSMapLogger::log(this, mapinfo, heap_info,
1494                       bitmap, bitmap_size_in_bytes);
1495   }
1496   CDS_JAVA_HEAP_ONLY(HeapShared::destroy_archived_object_cache());
1497   FREE_C_HEAP_ARRAY(char, bitmap);
1498 }
1499 
1500 void ArchiveBuilder::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only,  bool allow_exec) {
1501   mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);
1502 }
1503 
1504 void ArchiveBuilder::print_region_stats(FileMapInfo *mapinfo, ArchiveHeapInfo* heap_info) {
1505   // Print statistics of all the regions
1506   const size_t bitmap_used = mapinfo->region_at(MetaspaceShared::bm)->used();
1507   const size_t bitmap_reserved = mapinfo->region_at(MetaspaceShared::bm)->used_aligned();
1508   const size_t total_reserved = _ro_region.reserved()  + _rw_region.reserved() +
1509                                 bitmap_reserved +
1510                                 _total_heap_region_size;
1511   const size_t total_bytes = _ro_region.used()  + _rw_region.used() +
1512                              bitmap_used +
1513                              _total_heap_region_size;
1514   const double total_u_perc = percent_of(total_bytes, total_reserved);
1515 
1516   _rw_region.print(total_reserved);
1517   _ro_region.print(total_reserved);
1518   _cc_region.print(total_reserved);
1519 
1520   print_bitmap_region_stats(bitmap_used, total_reserved);
1521 
1522   if (heap_info->is_used()) {
1523     print_heap_region_stats(heap_info, total_reserved);
1524   }
1525 
1526   log_debug(cds)("total   : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]",
1527                  total_bytes, total_reserved, total_u_perc);
1528 }
1529 
1530 void ArchiveBuilder::print_bitmap_region_stats(size_t size, size_t total_size) {
1531   log_debug(cds)("bm space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used]",
1532                  size, size/double(total_size)*100.0, size);
1533 }
1534 
1535 void ArchiveBuilder::print_heap_region_stats(ArchiveHeapInfo *info, size_t total_size) {
1536   char* start = info->buffer_start();
1537   size_t size = info->buffer_byte_size();
1538   char* top = start + size;
1539   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,
1540                      size, size/double(total_size)*100.0, size, p2i(start));
1541 }
1542 
1543 void ArchiveBuilder::report_out_of_space(const char* name, size_t needed_bytes) {
1544   // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space.
1545   // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes
1546   // or so.
1547   _rw_region.print_out_of_space_msg(name, needed_bytes);
1548   _ro_region.print_out_of_space_msg(name, needed_bytes);
1549 
1550   log_error(cds)("Unable to allocate from '%s' region: Please reduce the number of shared classes.", name);
1551   MetaspaceShared::unrecoverable_writing_error();
1552 }







--- EOF ---