1 /*
   2  * Copyright (c) 2020, 2023, 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/cppVtables.hpp"
  30 #include "cds/dumpAllocStats.hpp"
  31 #include "cds/heapShared.hpp"
  32 #include "cds/metaspaceShared.hpp"
  33 #include "classfile/classLoaderDataShared.hpp"
  34 #include "classfile/symbolTable.hpp"
  35 #include "classfile/systemDictionaryShared.hpp"
  36 #include "classfile/vmClasses.hpp"
  37 #include "interpreter/abstractInterpreter.hpp"
  38 #include "logging/log.hpp"
  39 #include "logging/logStream.hpp"
  40 #include "memory/allStatic.hpp"
  41 #include "memory/memRegion.hpp"
  42 #include "memory/resourceArea.hpp"
  43 #include "oops/instanceKlass.hpp"
  44 #include "oops/objArrayKlass.hpp"
  45 #include "oops/objArrayOop.inline.hpp"
  46 #include "oops/oopHandle.inline.hpp"
  47 #include "runtime/arguments.hpp"
  48 #include "runtime/globals_extension.hpp"
  49 #include "runtime/javaThread.hpp"
  50 #include "runtime/sharedRuntime.hpp"
  51 #include "utilities/align.hpp"
  52 #include "utilities/bitMap.inline.hpp"
  53 #include "utilities/formatBuffer.hpp"
  54 
  55 ArchiveBuilder* ArchiveBuilder::_current = nullptr;
  56 
  57 ArchiveBuilder::OtherROAllocMark::~OtherROAllocMark() {
  58   char* newtop = ArchiveBuilder::current()->_ro_region.top();
  59   ArchiveBuilder::alloc_stats()->record_other_type(int(newtop - _oldtop), true);
  60 }
  61 
  62 ArchiveBuilder::SourceObjList::SourceObjList() : _ptrmap(16 * K, mtClassShared) {
  63   _total_bytes = 0;
  64   _objs = new (mtClassShared) GrowableArray<SourceObjInfo*>(128 * K, mtClassShared);
  65 }
  66 
  67 ArchiveBuilder::SourceObjList::~SourceObjList() {
  68   delete _objs;
  69 }
  70 
  71 void ArchiveBuilder::SourceObjList::append(MetaspaceClosure::Ref* enclosing_ref, SourceObjInfo* src_info) {
  72   // Save this source object for copying
  73   _objs->append(src_info);
  74 
  75   // Prepare for marking the pointers in this source object
  76   assert(is_aligned(_total_bytes, sizeof(address)), "must be");
  77   src_info->set_ptrmap_start(_total_bytes / sizeof(address));
  78   _total_bytes = align_up(_total_bytes + (uintx)src_info->size_in_bytes(), sizeof(address));
  79   src_info->set_ptrmap_end(_total_bytes / sizeof(address));
  80 
  81   BitMap::idx_t bitmap_size_needed = BitMap::idx_t(src_info->ptrmap_end());
  82   if (_ptrmap.size() <= bitmap_size_needed) {
  83     _ptrmap.resize((bitmap_size_needed + 1) * 2);
  84   }
  85 }
  86 
  87 void ArchiveBuilder::SourceObjList::remember_embedded_pointer(SourceObjInfo* src_info, MetaspaceClosure::Ref* ref) {
  88   // src_obj contains a pointer. Remember the location of this pointer in _ptrmap,
  89   // so that we can copy/relocate it later. E.g., if we have
  90   //    class Foo { intx scala; Bar* ptr; }
  91   //    Foo *f = 0x100;
  92   // To mark the f->ptr pointer on 64-bit platform, this function is called with
  93   //    src_info()->obj() == 0x100
  94   //    ref->addr() == 0x108
  95   address src_obj = src_info->obj();
  96   address* field_addr = ref->addr();
  97   assert(src_info->ptrmap_start() < _total_bytes, "sanity");
  98   assert(src_info->ptrmap_end() <= _total_bytes, "sanity");
  99   assert(*field_addr != nullptr, "should have checked");
 100 
 101   intx field_offset_in_bytes = ((address)field_addr) - src_obj;
 102   DEBUG_ONLY(int src_obj_size = src_info->size_in_bytes();)
 103   assert(field_offset_in_bytes >= 0, "must be");
 104   assert(field_offset_in_bytes + intx(sizeof(intptr_t)) <= intx(src_obj_size), "must be");
 105   assert(is_aligned(field_offset_in_bytes, sizeof(address)), "must be");
 106 
 107   BitMap::idx_t idx = BitMap::idx_t(src_info->ptrmap_start() + (uintx)(field_offset_in_bytes / sizeof(address)));
 108   _ptrmap.set_bit(BitMap::idx_t(idx));
 109 }
 110 
 111 class RelocateEmbeddedPointers : public BitMapClosure {
 112   ArchiveBuilder* _builder;
 113   address _buffered_obj;
 114   BitMap::idx_t _start_idx;
 115 public:
 116   RelocateEmbeddedPointers(ArchiveBuilder* builder, address buffered_obj, BitMap::idx_t start_idx) :
 117     _builder(builder), _buffered_obj(buffered_obj), _start_idx(start_idx) {}
 118 
 119   bool do_bit(BitMap::idx_t bit_offset) {
 120     size_t field_offset = size_t(bit_offset - _start_idx) * sizeof(address);
 121     address* ptr_loc = (address*)(_buffered_obj + field_offset);
 122 
 123     address old_p = *ptr_loc;
 124     address new_p = _builder->get_buffered_addr(old_p);
 125 
 126     log_trace(cds)("Ref: [" PTR_FORMAT "] -> " PTR_FORMAT " => " PTR_FORMAT,
 127                    p2i(ptr_loc), p2i(old_p), p2i(new_p));
 128 
 129     ArchivePtrMarker::set_and_mark_pointer(ptr_loc, new_p);
 130     return true; // keep iterating the bitmap
 131   }
 132 };
 133 
 134 void ArchiveBuilder::SourceObjList::relocate(int i, ArchiveBuilder* builder) {
 135   SourceObjInfo* src_info = objs()->at(i);
 136   assert(src_info->should_copy(), "must be");
 137   BitMap::idx_t start = BitMap::idx_t(src_info->ptrmap_start()); // inclusive
 138   BitMap::idx_t end = BitMap::idx_t(src_info->ptrmap_end());     // exclusive
 139 
 140   RelocateEmbeddedPointers relocator(builder, src_info->buffered_addr(), start);
 141   _ptrmap.iterate(&relocator, start, end);
 142 }
 143 
 144 ArchiveBuilder::ArchiveBuilder() :
 145   _current_dump_space(nullptr),
 146   _buffer_bottom(nullptr),
 147   _last_verified_top(nullptr),
 148   _num_dump_regions_used(0),
 149   _other_region_used_bytes(0),
 150   _requested_static_archive_bottom(nullptr),
 151   _requested_static_archive_top(nullptr),
 152   _requested_dynamic_archive_bottom(nullptr),
 153   _requested_dynamic_archive_top(nullptr),
 154   _mapped_static_archive_bottom(nullptr),
 155   _mapped_static_archive_top(nullptr),
 156   _buffer_to_requested_delta(0),
 157   _rw_region("rw", MAX_SHARED_DELTA),
 158   _ro_region("ro", MAX_SHARED_DELTA),
 159   _ptrmap(mtClassShared),
 160   _rw_src_objs(),
 161   _ro_src_objs(),
 162   _src_obj_table(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE),
 163   _buffered_to_src_table(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE),
 164   _total_closed_heap_region_size(0),
 165   _total_open_heap_region_size(0),
 166   _estimated_metaspaceobj_bytes(0),
 167   _estimated_hashtable_bytes(0)
 168 {
 169   _klasses = new (mtClassShared) GrowableArray<Klass*>(4 * K, mtClassShared);
 170   _symbols = new (mtClassShared) GrowableArray<Symbol*>(256 * K, mtClassShared);
 171   _special_refs = new (mtClassShared) GrowableArray<SpecialRefInfo>(24 * K, mtClassShared);
 172 
 173   assert(_current == nullptr, "must be");
 174   _current = this;
 175 }
 176 
 177 ArchiveBuilder::~ArchiveBuilder() {
 178   assert(_current == this, "must be");
 179   _current = nullptr;
 180 
 181   clean_up_src_obj_table();
 182 
 183   for (int i = 0; i < _symbols->length(); i++) {
 184     _symbols->at(i)->decrement_refcount();
 185   }
 186 
 187   delete _klasses;
 188   delete _symbols;
 189   delete _special_refs;
 190   if (_shared_rs.is_reserved()) {
 191     _shared_rs.release();
 192   }
 193 }
 194 
 195 bool ArchiveBuilder::is_dumping_full_module_graph() {
 196   return DumpSharedSpaces && MetaspaceShared::use_full_module_graph();
 197 }
 198 
 199 class GatherKlassesAndSymbols : public UniqueMetaspaceClosure {
 200   ArchiveBuilder* _builder;
 201 
 202 public:
 203   GatherKlassesAndSymbols(ArchiveBuilder* builder) : _builder(builder) {}
 204 
 205   virtual bool do_unique_ref(Ref* ref, bool read_only) {
 206     return _builder->gather_klass_and_symbol(ref, read_only);
 207   }
 208 };
 209 
 210 bool ArchiveBuilder::gather_klass_and_symbol(MetaspaceClosure::Ref* ref, bool read_only) {
 211   if (ref->obj() == nullptr) {
 212     return false;
 213   }
 214   if (get_follow_mode(ref) != make_a_copy) {
 215     return false;
 216   }
 217   if (ref->msotype() == MetaspaceObj::ClassType) {
 218     Klass* klass = (Klass*)ref->obj();
 219     assert(klass->is_klass(), "must be");
 220     if (!is_excluded(klass)) {
 221       _klasses->append(klass);
 222     }
 223     // See RunTimeClassInfo::get_for()
 224     _estimated_metaspaceobj_bytes += align_up(BytesPerWord, SharedSpaceObjectAlignment);
 225   } else if (ref->msotype() == MetaspaceObj::SymbolType) {
 226     // Make sure the symbol won't be GC'ed while we are dumping the archive.
 227     Symbol* sym = (Symbol*)ref->obj();
 228     sym->increment_refcount();
 229     _symbols->append(sym);
 230   }
 231 
 232   int bytes = ref->size() * BytesPerWord;
 233   _estimated_metaspaceobj_bytes += align_up(bytes, SharedSpaceObjectAlignment);
 234 
 235   return true; // recurse
 236 }
 237 
 238 void ArchiveBuilder::gather_klasses_and_symbols() {
 239   ResourceMark rm;
 240   log_info(cds)("Gathering classes and symbols ... ");
 241   GatherKlassesAndSymbols doit(this);
 242   iterate_roots(&doit, /*is_relocating_pointers=*/false);
 243 #if INCLUDE_CDS_JAVA_HEAP
 244   if (is_dumping_full_module_graph()) {
 245     ClassLoaderDataShared::iterate_symbols(&doit);
 246   }
 247 #endif
 248   doit.finish();
 249 
 250   if (DumpSharedSpaces) {
 251     // To ensure deterministic contents in the static archive, we need to ensure that
 252     // we iterate the MetaspaceObjs in a deterministic order. It doesn't matter where
 253     // the MetaspaceObjs are located originally, as they are copied sequentially into
 254     // the archive during the iteration.
 255     //
 256     // The only issue here is that the symbol table and the system directories may be
 257     // randomly ordered, so we copy the symbols and klasses into two arrays and sort
 258     // them deterministically.
 259     //
 260     // During -Xshare:dump, the order of Symbol creation is strictly determined by
 261     // the SharedClassListFile (class loading is done in a single thread and the JIT
 262     // is disabled). Also, Symbols are allocated in monotonically increasing addresses
 263     // (see Symbol::operator new(size_t, int)). So if we iterate the Symbols by
 264     // ascending address order, we ensure that all Symbols are copied into deterministic
 265     // locations in the archive.
 266     //
 267     // TODO: in the future, if we want to produce deterministic contents in the
 268     // dynamic archive, we might need to sort the symbols alphabetically (also see
 269     // DynamicArchiveBuilder::sort_methods()).
 270     sort_symbols_and_fix_hash();
 271     sort_klasses();
 272 
 273     // TODO -- we need a proper estimate for the archived modules, etc,
 274     // but this should be enough for now
 275     _estimated_metaspaceobj_bytes += 200 * 1024 * 1024;
 276   }
 277 }
 278 
 279 int ArchiveBuilder::compare_symbols_by_address(Symbol** a, Symbol** b) {
 280   if (a[0] < b[0]) {
 281     return -1;
 282   } else {
 283     assert(a[0] > b[0], "Duplicated symbol %s unexpected", (*a)->as_C_string());
 284     return 1;
 285   }
 286 }
 287 
 288 void ArchiveBuilder::sort_symbols_and_fix_hash() {
 289   log_info(cds)("Sorting symbols and fixing identity hash ... ");
 290   os::init_random(0x12345678);
 291   _symbols->sort(compare_symbols_by_address);
 292   for (int i = 0; i < _symbols->length(); i++) {
 293     assert(_symbols->at(i)->is_permanent(), "archived symbols must be permanent");
 294     _symbols->at(i)->update_identity_hash();
 295   }
 296 }
 297 
 298 int ArchiveBuilder::compare_klass_by_name(Klass** a, Klass** b) {
 299   return a[0]->name()->fast_compare(b[0]->name());
 300 }
 301 
 302 void ArchiveBuilder::sort_klasses() {
 303   log_info(cds)("Sorting classes ... ");
 304   _klasses->sort(compare_klass_by_name);
 305 }
 306 
 307 size_t ArchiveBuilder::estimate_archive_size() {
 308   // size of the symbol table and two dictionaries, plus the RunTimeClassInfo's
 309   size_t symbol_table_est = SymbolTable::estimate_size_for_archive();
 310   size_t dictionary_est = SystemDictionaryShared::estimate_size_for_archive();
 311   _estimated_hashtable_bytes = symbol_table_est + dictionary_est;
 312 
 313   size_t total = 0;
 314 
 315   total += _estimated_metaspaceobj_bytes;
 316   total += _estimated_hashtable_bytes;
 317 
 318   // allow fragmentation at the end of each dump region
 319   total += _total_dump_regions * MetaspaceShared::core_region_alignment();
 320 
 321   log_info(cds)("_estimated_hashtable_bytes = " SIZE_FORMAT " + " SIZE_FORMAT " = " SIZE_FORMAT,
 322                 symbol_table_est, dictionary_est, _estimated_hashtable_bytes);
 323   log_info(cds)("_estimated_metaspaceobj_bytes = " SIZE_FORMAT, _estimated_metaspaceobj_bytes);
 324   log_info(cds)("total estimate bytes = " SIZE_FORMAT, total);
 325 
 326   return align_up(total, MetaspaceShared::core_region_alignment());
 327 }
 328 
 329 address ArchiveBuilder::reserve_buffer() {
 330   size_t buffer_size = estimate_archive_size();
 331   ReservedSpace rs(buffer_size, MetaspaceShared::core_region_alignment(), os::vm_page_size());
 332   if (!rs.is_reserved()) {
 333     log_error(cds)("Failed to reserve " SIZE_FORMAT " bytes of output buffer.", buffer_size);
 334     os::_exit(0);
 335   }
 336 
 337   // buffer_bottom is the lowest address of the 2 core regions (rw, ro) when
 338   // we are copying the class metadata into the buffer.
 339   address buffer_bottom = (address)rs.base();
 340   log_info(cds)("Reserved output buffer space at " PTR_FORMAT " [" SIZE_FORMAT " bytes]",
 341                 p2i(buffer_bottom), buffer_size);
 342   _shared_rs = rs;
 343 
 344   _buffer_bottom = buffer_bottom;
 345   _last_verified_top = buffer_bottom;
 346   _current_dump_space = &_rw_region;
 347   _num_dump_regions_used = 1;
 348   _other_region_used_bytes = 0;
 349   _current_dump_space->init(&_shared_rs, &_shared_vs);
 350 
 351   ArchivePtrMarker::initialize(&_ptrmap, &_shared_vs);
 352 
 353   // The bottom of the static archive should be mapped at this address by default.
 354   _requested_static_archive_bottom = (address)MetaspaceShared::requested_base_address();
 355 
 356   // The bottom of the archive (that I am writing now) should be mapped at this address by default.
 357   address my_archive_requested_bottom;
 358 
 359   if (DumpSharedSpaces) {
 360     my_archive_requested_bottom = _requested_static_archive_bottom;
 361   } else {
 362     _mapped_static_archive_bottom = (address)MetaspaceObj::shared_metaspace_base();
 363     _mapped_static_archive_top  = (address)MetaspaceObj::shared_metaspace_top();
 364     assert(_mapped_static_archive_top >= _mapped_static_archive_bottom, "must be");
 365     size_t static_archive_size = _mapped_static_archive_top - _mapped_static_archive_bottom;
 366 
 367     // At run time, we will mmap the dynamic archive at my_archive_requested_bottom
 368     _requested_static_archive_top = _requested_static_archive_bottom + static_archive_size;
 369     my_archive_requested_bottom = align_up(_requested_static_archive_top, MetaspaceShared::core_region_alignment());
 370 
 371     _requested_dynamic_archive_bottom = my_archive_requested_bottom;
 372   }
 373 
 374   _buffer_to_requested_delta = my_archive_requested_bottom - _buffer_bottom;
 375 
 376   address my_archive_requested_top = my_archive_requested_bottom + buffer_size;
 377   if (my_archive_requested_bottom <  _requested_static_archive_bottom ||
 378       my_archive_requested_top    <= _requested_static_archive_bottom) {
 379     // Size overflow.
 380     log_error(cds)("my_archive_requested_bottom = " INTPTR_FORMAT, p2i(my_archive_requested_bottom));
 381     log_error(cds)("my_archive_requested_top    = " INTPTR_FORMAT, p2i(my_archive_requested_top));
 382     log_error(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is too high. "
 383                    "Please rerun java -Xshare:dump with a lower value", p2i(_requested_static_archive_bottom));
 384     os::_exit(0);
 385   }
 386 
 387   if (DumpSharedSpaces) {
 388     // We don't want any valid object to be at the very bottom of the archive.
 389     // See ArchivePtrMarker::mark_pointer().
 390     rw_region()->allocate(16);
 391   }
 392 
 393   return buffer_bottom;
 394 }
 395 
 396 void ArchiveBuilder::iterate_sorted_roots(MetaspaceClosure* it, bool is_relocating_pointers) {
 397   int i;
 398 
 399   if (!is_relocating_pointers) {
 400     // Don't relocate _symbol, so we can safely call decrement_refcount on the
 401     // original symbols.
 402     int num_symbols = _symbols->length();
 403     for (i = 0; i < num_symbols; i++) {
 404       it->push(_symbols->adr_at(i));
 405     }
 406   }
 407 
 408   int num_klasses = _klasses->length();
 409   for (i = 0; i < num_klasses; i++) {
 410     it->push(_klasses->adr_at(i));
 411   }
 412 
 413   iterate_roots(it, is_relocating_pointers);
 414 }
 415 
 416 class GatherSortedSourceObjs : public MetaspaceClosure {
 417   ArchiveBuilder* _builder;
 418 
 419 public:
 420   GatherSortedSourceObjs(ArchiveBuilder* builder) : _builder(builder) {}
 421 
 422   virtual bool do_ref(Ref* ref, bool read_only) {
 423     return _builder->gather_one_source_obj(enclosing_ref(), ref, read_only);
 424   }
 425 
 426   virtual void push_special(SpecialRef type, Ref* ref, intptr_t* p) {
 427     assert(type == _method_entry_ref, "only special type allowed for now");
 428     address src_obj = ref->obj();
 429     size_t field_offset = pointer_delta(p, src_obj,  sizeof(u1));
 430     _builder->add_special_ref(type, src_obj, field_offset);
 431   };
 432 
 433   virtual void do_pending_ref(Ref* ref) {
 434     if (ref->obj() != nullptr) {
 435       _builder->remember_embedded_pointer_in_copied_obj(enclosing_ref(), ref);
 436     }
 437   }
 438 };
 439 
 440 bool ArchiveBuilder::gather_one_source_obj(MetaspaceClosure::Ref* enclosing_ref,
 441                                            MetaspaceClosure::Ref* ref, bool read_only) {
 442   address src_obj = ref->obj();
 443   if (src_obj == nullptr) {
 444     return false;
 445   }
 446   ref->set_keep_after_pushing();
 447   remember_embedded_pointer_in_copied_obj(enclosing_ref, ref);
 448 
 449   FollowMode follow_mode = get_follow_mode(ref);
 450   SourceObjInfo src_info(ref, read_only, follow_mode);
 451   bool created;
 452   SourceObjInfo* p = _src_obj_table.put_if_absent(src_obj, src_info, &created);
 453   if (created) {
 454     if (_src_obj_table.maybe_grow()) {
 455       log_info(cds, hashtables)("Expanded _src_obj_table table to %d", _src_obj_table.table_size());
 456     }
 457   }
 458 
 459   assert(p->read_only() == src_info.read_only(), "must be");
 460 
 461   if (created && src_info.should_copy()) {
 462     ref->set_user_data((void*)p);
 463     if (read_only) {
 464       _ro_src_objs.append(enclosing_ref, p);
 465     } else {
 466       _rw_src_objs.append(enclosing_ref, p);
 467     }
 468     return true; // Need to recurse into this ref only if we are copying it
 469   } else {
 470     return false;
 471   }
 472 }
 473 
 474 void ArchiveBuilder::add_special_ref(MetaspaceClosure::SpecialRef type, address src_obj, size_t field_offset) {
 475   _special_refs->append(SpecialRefInfo(type, src_obj, field_offset));
 476 }
 477 
 478 void ArchiveBuilder::remember_embedded_pointer_in_copied_obj(MetaspaceClosure::Ref* enclosing_ref,
 479                                                              MetaspaceClosure::Ref* ref) {
 480   assert(ref->obj() != nullptr, "should have checked");
 481 
 482   if (enclosing_ref != nullptr) {
 483     SourceObjInfo* src_info = (SourceObjInfo*)enclosing_ref->user_data();
 484     if (src_info == nullptr) {
 485       // source objects of point_to_it/set_to_null types are not copied
 486       // so we don't need to remember their pointers.
 487     } else {
 488       if (src_info->read_only()) {
 489         _ro_src_objs.remember_embedded_pointer(src_info, ref);
 490       } else {
 491         _rw_src_objs.remember_embedded_pointer(src_info, ref);
 492       }
 493     }
 494   }
 495 }
 496 
 497 void ArchiveBuilder::gather_source_objs() {
 498   ResourceMark rm;
 499   log_info(cds)("Gathering all archivable objects ... ");
 500   gather_klasses_and_symbols();
 501   GatherSortedSourceObjs doit(this);
 502   iterate_sorted_roots(&doit, /*is_relocating_pointers=*/false);
 503   doit.finish();
 504 }
 505 
 506 bool ArchiveBuilder::is_excluded(Klass* klass) {
 507   if (klass->is_instance_klass()) {
 508     InstanceKlass* ik = InstanceKlass::cast(klass);
 509     return SystemDictionaryShared::is_excluded_class(ik);
 510   } else if (klass->is_objArray_klass()) {
 511     if (DynamicDumpSharedSpaces) {
 512       // Don't support archiving of array klasses for now (WHY???)
 513       return true;
 514     }
 515     Klass* bottom = ObjArrayKlass::cast(klass)->bottom_klass();
 516     if (bottom->is_instance_klass()) {
 517       return SystemDictionaryShared::is_excluded_class(InstanceKlass::cast(bottom));
 518     }
 519   }
 520 
 521   return false;
 522 }
 523 
 524 ArchiveBuilder::FollowMode ArchiveBuilder::get_follow_mode(MetaspaceClosure::Ref *ref) {
 525   address obj = ref->obj();
 526   if (MetaspaceShared::is_in_shared_metaspace(obj)) {
 527     // Don't dump existing shared metadata again.
 528     return point_to_it;
 529   } else if (ref->msotype() == MetaspaceObj::MethodDataType ||
 530              ref->msotype() == MetaspaceObj::MethodCountersType) {
 531     return set_to_null;
 532   } else {
 533     if (ref->msotype() == MetaspaceObj::ClassType) {
 534       Klass* klass = (Klass*)ref->obj();
 535       assert(klass->is_klass(), "must be");
 536       if (is_excluded(klass)) {
 537         ResourceMark rm;
 538         log_debug(cds, dynamic)("Skipping class (excluded): %s", klass->external_name());
 539         return set_to_null;
 540       }
 541     }
 542 
 543     return make_a_copy;
 544   }
 545 }
 546 
 547 void ArchiveBuilder::start_dump_space(DumpRegion* next) {
 548   address bottom = _last_verified_top;
 549   address top = (address)(current_dump_space()->top());
 550   _other_region_used_bytes += size_t(top - bottom);
 551 
 552   current_dump_space()->pack(next);
 553   _current_dump_space = next;
 554   _num_dump_regions_used ++;
 555 
 556   _last_verified_top = (address)(current_dump_space()->top());
 557 }
 558 
 559 void ArchiveBuilder::verify_estimate_size(size_t estimate, const char* which) {
 560   address bottom = _last_verified_top;
 561   address top = (address)(current_dump_space()->top());
 562   size_t used = size_t(top - bottom) + _other_region_used_bytes;
 563   int diff = int(estimate) - int(used);
 564 
 565   log_info(cds)("%s estimate = " SIZE_FORMAT " used = " SIZE_FORMAT "; diff = %d bytes", which, estimate, used, diff);
 566   assert(diff >= 0, "Estimate is too small");
 567 
 568   _last_verified_top = top;
 569   _other_region_used_bytes = 0;
 570 }
 571 
 572 void ArchiveBuilder::dump_rw_metadata() {
 573   ResourceMark rm;
 574   log_info(cds)("Allocating RW objects ... ");
 575   make_shallow_copies(&_rw_region, &_rw_src_objs);
 576 
 577 #if INCLUDE_CDS_JAVA_HEAP
 578   if (is_dumping_full_module_graph()) {
 579     // Archive the ModuleEntry's and PackageEntry's of the 3 built-in loaders
 580     char* start = rw_region()->top();
 581     ClassLoaderDataShared::allocate_archived_tables();
 582     alloc_stats()->record_modules(rw_region()->top() - start, /*read_only*/false);
 583   }
 584 #endif
 585 }
 586 
 587 void ArchiveBuilder::dump_ro_metadata() {
 588   ResourceMark rm;
 589   log_info(cds)("Allocating RO objects ... ");
 590 
 591   start_dump_space(&_ro_region);
 592   make_shallow_copies(&_ro_region, &_ro_src_objs);
 593 
 594 #if INCLUDE_CDS_JAVA_HEAP
 595   if (is_dumping_full_module_graph()) {
 596     char* start = ro_region()->top();
 597     ClassLoaderDataShared::init_archived_tables();
 598     alloc_stats()->record_modules(ro_region()->top() - start, /*read_only*/true);
 599   }
 600 #endif
 601 }
 602 
 603 void ArchiveBuilder::make_shallow_copies(DumpRegion *dump_region,
 604                                          const ArchiveBuilder::SourceObjList* src_objs) {
 605   for (int i = 0; i < src_objs->objs()->length(); i++) {
 606     make_shallow_copy(dump_region, src_objs->objs()->at(i));
 607   }
 608   log_info(cds)("done (%d objects)", src_objs->objs()->length());
 609 }
 610 
 611 void ArchiveBuilder::make_shallow_copy(DumpRegion *dump_region, SourceObjInfo* src_info) {
 612   MetaspaceClosure::Ref* ref = src_info->ref();
 613   address src = ref->obj();
 614   int bytes = src_info->size_in_bytes();
 615   char* dest;
 616   char* oldtop;
 617   char* newtop;
 618 
 619   oldtop = dump_region->top();
 620   if (ref->msotype() == MetaspaceObj::ClassType) {
 621     // Save a pointer immediate in front of an InstanceKlass, so
 622     // we can do a quick lookup from InstanceKlass* -> RunTimeClassInfo*
 623     // without building another hashtable. See RunTimeClassInfo::get_for()
 624     // in systemDictionaryShared.cpp.
 625     Klass* klass = (Klass*)src;
 626     if (klass->is_instance_klass()) {
 627       SystemDictionaryShared::validate_before_archiving(InstanceKlass::cast(klass));
 628       dump_region->allocate(sizeof(address));
 629     }
 630   }
 631   dest = dump_region->allocate(bytes);
 632   newtop = dump_region->top();
 633 
 634   memcpy(dest, src, bytes);
 635   {
 636     bool created;
 637     _buffered_to_src_table.put_if_absent((address)dest, src, &created);
 638     assert(created, "must be");
 639     if (_buffered_to_src_table.maybe_grow()) {
 640       log_info(cds, hashtables)("Expanded _buffered_to_src_table table to %d", _buffered_to_src_table.table_size());
 641     }
 642   }
 643 
 644   intptr_t* archived_vtable = CppVtables::get_archived_vtable(ref->msotype(), (address)dest);
 645   if (archived_vtable != nullptr) {
 646     *(address*)dest = (address)archived_vtable;
 647     ArchivePtrMarker::mark_pointer((address*)dest);
 648   }
 649 
 650   log_trace(cds)("Copy: " PTR_FORMAT " ==> " PTR_FORMAT " %d", p2i(src), p2i(dest), bytes);
 651   src_info->set_buffered_addr((address)dest);
 652 
 653   _alloc_stats.record(ref->msotype(), int(newtop - oldtop), src_info->read_only());
 654 }
 655 
 656 address ArchiveBuilder::get_buffered_addr(address src_addr) const {
 657   SourceObjInfo* p = _src_obj_table.get(src_addr);
 658   assert(p != nullptr, "must be");
 659 
 660   return p->buffered_addr();
 661 }
 662 
 663 address ArchiveBuilder::get_source_addr(address buffered_addr) const {
 664   assert(is_in_buffer_space(buffered_addr), "must be");
 665   address* src_p = _buffered_to_src_table.get(buffered_addr);
 666   assert(src_p != nullptr && *src_p != nullptr, "must be");
 667   return *src_p;
 668 }
 669 
 670 void ArchiveBuilder::relocate_embedded_pointers(ArchiveBuilder::SourceObjList* src_objs) {
 671   for (int i = 0; i < src_objs->objs()->length(); i++) {
 672     src_objs->relocate(i, this);
 673   }
 674 }
 675 
 676 void ArchiveBuilder::update_special_refs() {
 677   for (int i = 0; i < _special_refs->length(); i++) {
 678     SpecialRefInfo s = _special_refs->at(i);
 679     size_t field_offset = s.field_offset();
 680     address src_obj = s.src_obj();
 681     address dst_obj = get_buffered_addr(src_obj);
 682     intptr_t* src_p = (intptr_t*)(src_obj + field_offset);
 683     intptr_t* dst_p = (intptr_t*)(dst_obj + field_offset);
 684     assert(s.type() == MetaspaceClosure::_method_entry_ref, "only special type allowed for now");
 685 
 686     assert(*src_p == *dst_p, "must be a copy");
 687     ArchivePtrMarker::mark_pointer((address*)dst_p);
 688   }
 689 }
 690 
 691 class RefRelocator: public MetaspaceClosure {
 692   ArchiveBuilder* _builder;
 693 
 694 public:
 695   RefRelocator(ArchiveBuilder* builder) : _builder(builder) {}
 696 
 697   virtual bool do_ref(Ref* ref, bool read_only) {
 698     if (ref->not_null()) {
 699       ref->update(_builder->get_buffered_addr(ref->obj()));
 700       ArchivePtrMarker::mark_pointer(ref->addr());
 701     }
 702     return false; // Do not recurse.
 703   }
 704 };
 705 
 706 void ArchiveBuilder::relocate_roots() {
 707   log_info(cds)("Relocating external roots ... ");
 708   ResourceMark rm;
 709   RefRelocator doit(this);
 710   iterate_sorted_roots(&doit, /*is_relocating_pointers=*/true);
 711   doit.finish();
 712   log_info(cds)("done");
 713 }
 714 
 715 void ArchiveBuilder::relocate_metaspaceobj_embedded_pointers() {
 716   log_info(cds)("Relocating embedded pointers in core regions ... ");
 717   relocate_embedded_pointers(&_rw_src_objs);
 718   relocate_embedded_pointers(&_ro_src_objs);
 719   update_special_refs();
 720 }
 721 
 722 // We must relocate vmClasses::_klasses[] only after we have copied the
 723 // java objects in during dump_java_heap_objects(): during the object copy, we operate on
 724 // old objects which assert that their klass is the original klass.
 725 void ArchiveBuilder::relocate_vm_classes() {
 726   log_info(cds)("Relocating vmClasses::_klasses[] ... ");
 727   ResourceMark rm;
 728   RefRelocator doit(this);
 729   vmClasses::metaspace_pointers_do(&doit);
 730 }
 731 
 732 void ArchiveBuilder::make_klasses_shareable() {
 733   int num_instance_klasses = 0;
 734   int num_boot_klasses = 0;
 735   int num_platform_klasses = 0;
 736   int num_app_klasses = 0;
 737   int num_hidden_klasses = 0;
 738   int num_unlinked_klasses = 0;
 739   int num_unregistered_klasses = 0;
 740   int num_obj_array_klasses = 0;
 741   int num_type_array_klasses = 0;
 742 
 743   for (int i = 0; i < klasses()->length(); i++) {
 744     const char* type;
 745     const char* unlinked = "";
 746     const char* hidden = "";
 747     const char* generated = "";
 748     Klass* k = klasses()->at(i);
 749     k->remove_java_mirror();
 750     if (k->is_objArray_klass()) {
 751       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
 752       // on their array classes.
 753       num_obj_array_klasses ++;
 754       type = "array";
 755     } else if (k->is_typeArray_klass()) {
 756       num_type_array_klasses ++;
 757       type = "array";
 758       k->remove_unshareable_info();
 759     } else {
 760       assert(k->is_instance_klass(), " must be");
 761       num_instance_klasses ++;
 762       InstanceKlass* ik = InstanceKlass::cast(k);
 763       if (DynamicDumpSharedSpaces) {
 764         // For static dump, class loader type are already set.
 765         ik->assign_class_loader_type();
 766       }
 767       if (ik->is_shared_boot_class()) {
 768         type = "boot";
 769         num_boot_klasses ++;
 770       } else if (ik->is_shared_platform_class()) {
 771         type = "plat";
 772         num_platform_klasses ++;
 773       } else if (ik->is_shared_app_class()) {
 774         type = "app";
 775         num_app_klasses ++;
 776       } else {
 777         assert(ik->is_shared_unregistered_class(), "must be");
 778         type = "unreg";
 779         num_unregistered_klasses ++;
 780       }
 781 
 782       if (!ik->is_linked()) {
 783         num_unlinked_klasses ++;
 784         unlinked = " ** unlinked";
 785       }
 786 
 787       if (ik->is_hidden()) {
 788         num_hidden_klasses ++;
 789         hidden = " ** hidden";
 790       }
 791 
 792       if (ik->is_generated_shared_class()) {
 793         generated = " ** generated";
 794       }
 795       MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread::current(), ik);
 796       ik->remove_unshareable_info();
 797     }
 798 
 799     if (log_is_enabled(Debug, cds, class)) {
 800       ResourceMark rm;
 801       log_debug(cds, class)("klasses[%5d] = " PTR_FORMAT " %-5s %s%s%s%s", i,
 802                             p2i(to_requested(k)), type, k->external_name(),
 803                             hidden, unlinked, generated);
 804     }
 805   }
 806 
 807   log_info(cds)("Number of classes %d", num_instance_klasses + num_obj_array_klasses + num_type_array_klasses);
 808   log_info(cds)("    instance classes   = %5d", num_instance_klasses);
 809   log_info(cds)("      boot             = %5d", num_boot_klasses);
 810   log_info(cds)("      app              = %5d", num_app_klasses);
 811   log_info(cds)("      platform         = %5d", num_platform_klasses);
 812   log_info(cds)("      unregistered     = %5d", num_unregistered_klasses);
 813   log_info(cds)("      (hidden)         = %5d", num_hidden_klasses);
 814   log_info(cds)("      (unlinked)       = %5d", num_unlinked_klasses);
 815   log_info(cds)("    obj array classes  = %5d", num_obj_array_klasses);
 816   log_info(cds)("    type array classes = %5d", num_type_array_klasses);
 817   log_info(cds)("               symbols = %5d", _symbols->length());
 818 }
 819 
 820 uintx ArchiveBuilder::buffer_to_offset(address p) const {
 821   address requested_p = to_requested(p);
 822   assert(requested_p >= _requested_static_archive_bottom, "must be");
 823   return requested_p - _requested_static_archive_bottom;
 824 }
 825 
 826 uintx ArchiveBuilder::any_to_offset(address p) const {
 827   if (is_in_mapped_static_archive(p)) {
 828     assert(DynamicDumpSharedSpaces, "must be");
 829     return p - _mapped_static_archive_bottom;
 830   }
 831   return buffer_to_offset(p);
 832 }
 833 
 834 narrowKlass ArchiveBuilder::get_requested_narrow_klass(Klass* k) {
 835   assert(DumpSharedSpaces, "sanity");
 836   k = get_buffered_klass(k);
 837   Klass* requested_k = to_requested(k);
 838   return CompressedKlassPointers::encode_not_null(requested_k, _requested_static_archive_bottom);
 839 }
 840 
 841 // RelocateBufferToRequested --- Relocate all the pointers in rw/ro,
 842 // so that the archive can be mapped to the "requested" location without runtime relocation.
 843 //
 844 // - See ArchiveBuilder header for the definition of "buffer", "mapped" and "requested"
 845 // - ArchivePtrMarker::ptrmap() marks all the pointers in the rw/ro regions
 846 // - Every pointer must have one of the following values:
 847 //   [a] nullptr:
 848 //       No relocation is needed. Remove this pointer from ptrmap so we don't need to
 849 //       consider it at runtime.
 850 //   [b] Points into an object X which is inside the buffer:
 851 //       Adjust this pointer by _buffer_to_requested_delta, so it points to X
 852 //       when the archive is mapped at the requested location.
 853 //   [c] Points into an object Y which is inside mapped static archive:
 854 //       - This happens only during dynamic dump
 855 //       - Adjust this pointer by _mapped_to_requested_static_archive_delta,
 856 //         so it points to Y when the static archive is mapped at the requested location.
 857 template <bool STATIC_DUMP>
 858 class RelocateBufferToRequested : public BitMapClosure {
 859   ArchiveBuilder* _builder;
 860   address _buffer_bottom;
 861   intx _buffer_to_requested_delta;
 862   intx _mapped_to_requested_static_archive_delta;
 863   size_t _max_non_null_offset;
 864 
 865  public:
 866   RelocateBufferToRequested(ArchiveBuilder* builder) {
 867     _builder = builder;
 868     _buffer_bottom = _builder->buffer_bottom();
 869     _buffer_to_requested_delta = builder->buffer_to_requested_delta();
 870     _mapped_to_requested_static_archive_delta = builder->requested_static_archive_bottom() - builder->mapped_static_archive_bottom();
 871     _max_non_null_offset = 0;
 872 
 873     address bottom = _builder->buffer_bottom();
 874     address top = _builder->buffer_top();
 875     address new_bottom = bottom + _buffer_to_requested_delta;
 876     address new_top = top + _buffer_to_requested_delta;
 877     log_debug(cds)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT "] to "
 878                    "[" INTPTR_FORMAT " - " INTPTR_FORMAT "]",
 879                    p2i(bottom), p2i(top),
 880                    p2i(new_bottom), p2i(new_top));
 881   }
 882 
 883   bool do_bit(size_t offset) {
 884     address* p = (address*)_buffer_bottom + offset;
 885     assert(_builder->is_in_buffer_space(p), "pointer must live in buffer space");
 886 
 887     if (*p == nullptr) {
 888       // todo -- clear bit, etc
 889       ArchivePtrMarker::ptrmap()->clear_bit(offset);
 890     } else {
 891       if (STATIC_DUMP) {
 892         assert(_builder->is_in_buffer_space(*p), "old pointer must point inside buffer space");
 893         *p += _buffer_to_requested_delta;
 894         assert(_builder->is_in_requested_static_archive(*p), "new pointer must point inside requested archive");
 895       } else {
 896         if (_builder->is_in_buffer_space(*p)) {
 897           *p += _buffer_to_requested_delta;
 898           // assert is in requested dynamic archive
 899         } else {
 900           assert(_builder->is_in_mapped_static_archive(*p), "old pointer must point inside buffer space or mapped static archive");
 901           *p += _mapped_to_requested_static_archive_delta;
 902           assert(_builder->is_in_requested_static_archive(*p), "new pointer must point inside requested archive");
 903         }
 904       }
 905       _max_non_null_offset = offset;
 906     }
 907 
 908     return true; // keep iterating
 909   }
 910 
 911   void doit() {
 912     ArchivePtrMarker::ptrmap()->iterate(this);
 913     ArchivePtrMarker::compact(_max_non_null_offset);
 914   }
 915 };
 916 
 917 
 918 void ArchiveBuilder::relocate_to_requested() {
 919   ro_region()->pack();
 920 
 921   size_t my_archive_size = buffer_top() - buffer_bottom();
 922 
 923   if (DumpSharedSpaces) {
 924     _requested_static_archive_top = _requested_static_archive_bottom + my_archive_size;
 925     RelocateBufferToRequested<true> patcher(this);
 926     patcher.doit();
 927   } else {
 928     assert(DynamicDumpSharedSpaces, "must be");
 929     _requested_dynamic_archive_top = _requested_dynamic_archive_bottom + my_archive_size;
 930     RelocateBufferToRequested<false> patcher(this);
 931     patcher.doit();
 932   }
 933 }
 934 
 935 // Write detailed info to a mapfile to analyze contents of the archive.
 936 // static dump:
 937 //   java -Xshare:dump -Xlog:cds+map=trace:file=cds.map:none:filesize=0
 938 // dynamic dump:
 939 //   java -cp MyApp.jar -XX:ArchiveClassesAtExit=MyApp.jsa \
 940 //        -Xlog:cds+map=trace:file=cds.map:none:filesize=0 MyApp
 941 //
 942 // We need to do some address translation because the buffers used at dump time may be mapped to
 943 // a different location at runtime. At dump time, the buffers may be at arbitrary locations
 944 // picked by the OS. At runtime, we try to map at a fixed location (SharedBaseAddress). For
 945 // consistency, we log everything using runtime addresses.
 946 class ArchiveBuilder::CDSMapLogger : AllStatic {
 947   static intx buffer_to_runtime_delta() {
 948     // Translate the buffers used by the RW/RO regions to their eventual (requested) locations
 949     // at runtime.
 950     return ArchiveBuilder::current()->buffer_to_requested_delta();
 951   }
 952 
 953   // rw/ro regions only
 954   static void log_metaspace_region(const char* name, DumpRegion* region,
 955                                    const ArchiveBuilder::SourceObjList* src_objs) {
 956     address region_base = address(region->base());
 957     address region_top  = address(region->top());
 958     log_region(name, region_base, region_top, region_base + buffer_to_runtime_delta());
 959     log_metaspace_objects(region, src_objs);
 960   }
 961 
 962 #define _LOG_PREFIX PTR_FORMAT ": @@ %-17s %d"
 963 
 964   static void log_klass(Klass* k, address runtime_dest, const char* type_name, int bytes, Thread* current) {
 965     ResourceMark rm(current);
 966     log_debug(cds, map)(_LOG_PREFIX " %s",
 967                         p2i(runtime_dest), type_name, bytes, k->external_name());
 968   }
 969   static void log_method(Method* m, address runtime_dest, const char* type_name, int bytes, Thread* current) {
 970     ResourceMark rm(current);
 971     log_debug(cds, map)(_LOG_PREFIX " %s",
 972                         p2i(runtime_dest), type_name, bytes,  m->external_name());
 973   }
 974 
 975   // rw/ro regions only
 976   static void log_metaspace_objects(DumpRegion* region, const ArchiveBuilder::SourceObjList* src_objs) {
 977     address last_obj_base = address(region->base());
 978     address last_obj_end  = address(region->base());
 979     address region_end    = address(region->end());
 980     Thread* current = Thread::current();
 981     for (int i = 0; i < src_objs->objs()->length(); i++) {
 982       SourceObjInfo* src_info = src_objs->at(i);
 983       address src = src_info->source_addr();
 984       address dest = src_info->buffered_addr();
 985       log_data(last_obj_base, dest, last_obj_base + buffer_to_runtime_delta());
 986       address runtime_dest = dest + buffer_to_runtime_delta();
 987       int bytes = src_info->size_in_bytes();
 988 
 989       MetaspaceObj::Type type = src_info->msotype();
 990       const char* type_name = MetaspaceObj::type_name(type);
 991 
 992       switch (type) {
 993       case MetaspaceObj::ClassType:
 994         log_klass((Klass*)src, runtime_dest, type_name, bytes, current);
 995         break;
 996       case MetaspaceObj::ConstantPoolType:
 997         log_klass(((ConstantPool*)src)->pool_holder(),
 998                     runtime_dest, type_name, bytes, current);
 999         break;
1000       case MetaspaceObj::ConstantPoolCacheType:
1001         log_klass(((ConstantPoolCache*)src)->constant_pool()->pool_holder(),
1002                     runtime_dest, type_name, bytes, current);
1003         break;
1004       case MetaspaceObj::MethodType:
1005         log_method((Method*)src, runtime_dest, type_name, bytes, current);
1006         break;
1007       case MetaspaceObj::ConstMethodType:
1008         log_method(((ConstMethod*)src)->method(), runtime_dest, type_name, bytes, current);
1009         break;
1010       case MetaspaceObj::SymbolType:
1011         {
1012           ResourceMark rm(current);
1013           Symbol* s = (Symbol*)src;
1014           log_debug(cds, map)(_LOG_PREFIX " %s", p2i(runtime_dest), type_name, bytes,
1015                               s->as_quoted_ascii());
1016         }
1017         break;
1018       default:
1019         log_debug(cds, map)(_LOG_PREFIX, p2i(runtime_dest), type_name, bytes);
1020         break;
1021       }
1022 
1023       last_obj_base = dest;
1024       last_obj_end  = dest + bytes;
1025     }
1026 
1027     log_data(last_obj_base, last_obj_end, last_obj_base + buffer_to_runtime_delta());
1028     if (last_obj_end < region_end) {
1029       log_debug(cds, map)(PTR_FORMAT ": @@ Misc data " SIZE_FORMAT " bytes",
1030                           p2i(last_obj_end + buffer_to_runtime_delta()),
1031                           size_t(region_end - last_obj_end));
1032       log_data(last_obj_end, region_end, last_obj_end + buffer_to_runtime_delta());
1033     }
1034   }
1035 
1036 #undef _LOG_PREFIX
1037 
1038   // Log information about a region, whose address at dump time is [base .. top). At
1039   // runtime, this region will be mapped to requested_base. requested_base is 0 if this
1040   // region will be mapped at os-selected addresses (such as the bitmap region), or will
1041   // be accessed with os::read (the header).
1042   //
1043   // Note: across -Xshare:dump runs, base may be different, but requested_base should
1044   // be the same as the archive contents should be deterministic.
1045   static void log_region(const char* name, address base, address top, address requested_base) {
1046     size_t size = top - base;
1047     base = requested_base;
1048     top = requested_base + size;
1049     log_info(cds, map)("[%-18s " PTR_FORMAT " - " PTR_FORMAT " " SIZE_FORMAT_W(9) " bytes]",
1050                        name, p2i(base), p2i(top), size);
1051   }
1052 
1053 #if INCLUDE_CDS_JAVA_HEAP
1054   // open and closed archive regions
1055   static void log_heap_regions(const char* which, GrowableArray<MemRegion> *regions) {
1056     for (int i = 0; i < regions->length(); i++) {
1057       address start = address(regions->at(i).start());
1058       address end = address(regions->at(i).end());
1059       log_region(which, start, end, to_requested(start));
1060 
1061       while (start < end) {
1062         size_t byte_size;
1063         oop original_oop = ArchiveHeapWriter::buffered_addr_to_source_obj(start);
1064         if (original_oop != nullptr) {
1065           ResourceMark rm;
1066           log_info(cds, map)(PTR_FORMAT ": @@ Object %s",
1067                              p2i(to_requested(start)), original_oop->klass()->external_name());
1068           byte_size = original_oop->size() * BytesPerWord;
1069         } else if (start == ArchiveHeapWriter::buffered_heap_roots_addr()) {
1070           // HeapShared::roots() is copied specially so it doesn't exist in
1071           // HeapShared::OriginalObjectTable. See HeapShared::copy_roots().
1072           log_info(cds, map)(PTR_FORMAT ": @@ Object HeapShared::roots (ObjArray)",
1073                              p2i(to_requested(start)));
1074           byte_size = ArchiveHeapWriter::heap_roots_word_size() * BytesPerWord;
1075         } else {
1076           // We have reached the end of the region
1077           break;
1078         }
1079         address oop_end = start + byte_size;
1080         log_data(start, oop_end, to_requested(start), /*is_heap=*/true);
1081         start = oop_end;
1082       }
1083       if (start < end) {
1084         log_info(cds, map)(PTR_FORMAT ": @@ Unused heap space " SIZE_FORMAT " bytes",
1085                            p2i(to_requested(start)), size_t(end - start));
1086         log_data(start, end, to_requested(start), /*is_heap=*/true);
1087       }
1088     }
1089   }
1090   static address to_requested(address p) {
1091     return ArchiveHeapWriter::buffered_addr_to_requested_addr(p);
1092   }
1093 #endif
1094 
1095   // Log all the data [base...top). Pretend that the base address
1096   // will be mapped to requested_base at run-time.
1097   static void log_data(address base, address top, address requested_base, bool is_heap = false) {
1098     assert(top >= base, "must be");
1099 
1100     LogStreamHandle(Trace, cds, map) lsh;
1101     if (lsh.is_enabled()) {
1102       int unitsize = sizeof(address);
1103       if (is_heap && UseCompressedOops) {
1104         // This makes the compressed oop pointers easier to read, but
1105         // longs and doubles will be split into two words.
1106         unitsize = sizeof(narrowOop);
1107       }
1108       os::print_hex_dump(&lsh, base, top, unitsize, 32, requested_base);
1109     }
1110   }
1111 
1112   static void log_header(FileMapInfo* mapinfo) {
1113     LogStreamHandle(Info, cds, map) lsh;
1114     if (lsh.is_enabled()) {
1115       mapinfo->print(&lsh);
1116     }
1117   }
1118 
1119 public:
1120   static void log(ArchiveBuilder* builder, FileMapInfo* mapinfo,
1121                   GrowableArray<MemRegion> *closed_heap_regions,
1122                   GrowableArray<MemRegion> *open_heap_regions,
1123                   char* bitmap, size_t bitmap_size_in_bytes) {
1124     log_info(cds, map)("%s CDS archive map for %s", DumpSharedSpaces ? "Static" : "Dynamic", mapinfo->full_path());
1125 
1126     address header = address(mapinfo->header());
1127     address header_end = header + mapinfo->header()->header_size();
1128     log_region("header", header, header_end, 0);
1129     log_header(mapinfo);
1130     log_data(header, header_end, 0);
1131 
1132     DumpRegion* rw_region = &builder->_rw_region;
1133     DumpRegion* ro_region = &builder->_ro_region;
1134 
1135     log_metaspace_region("rw region", rw_region, &builder->_rw_src_objs);
1136     log_metaspace_region("ro region", ro_region, &builder->_ro_src_objs);
1137 
1138     address bitmap_end = address(bitmap + bitmap_size_in_bytes);
1139     log_region("bitmap", address(bitmap), bitmap_end, 0);
1140     log_data((address)bitmap, bitmap_end, 0);
1141 
1142 #if INCLUDE_CDS_JAVA_HEAP
1143     if (closed_heap_regions != nullptr) {
1144       log_heap_regions("closed heap region", closed_heap_regions);
1145     }
1146     if (open_heap_regions != nullptr) {
1147       log_heap_regions("open heap region", open_heap_regions);
1148     }
1149 #endif
1150 
1151     log_info(cds, map)("[End of CDS archive map]");
1152   }
1153 }; // end ArchiveBuilder::CDSMapLogger
1154 
1155 void ArchiveBuilder::print_stats() {
1156   _alloc_stats.print_stats(int(_ro_region.used()), int(_rw_region.used()));
1157 }
1158 
1159 void ArchiveBuilder::clean_up_src_obj_table() {
1160   SrcObjTableCleaner cleaner;
1161   _src_obj_table.iterate(&cleaner);
1162 }
1163 
1164 void ArchiveBuilder::write_archive(FileMapInfo* mapinfo,
1165                                    GrowableArray<MemRegion>* closed_heap_regions,
1166                                    GrowableArray<MemRegion>* open_heap_regions,
1167                                    GrowableArray<ArchiveHeapBitmapInfo>* closed_heap_bitmaps,
1168                                    GrowableArray<ArchiveHeapBitmapInfo>* open_heap_bitmaps) {
1169   // Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with
1170   // MetaspaceShared::n_regions (internal to hotspot).
1171   assert(NUM_CDS_REGIONS == MetaspaceShared::n_regions, "sanity");
1172 
1173   write_region(mapinfo, MetaspaceShared::rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);
1174   write_region(mapinfo, MetaspaceShared::ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);
1175 
1176   size_t bitmap_size_in_bytes;
1177   char* bitmap = mapinfo->write_bitmap_region(ArchivePtrMarker::ptrmap(), closed_heap_bitmaps, open_heap_bitmaps,
1178                                               bitmap_size_in_bytes);
1179 
1180   if (closed_heap_regions != nullptr) {
1181     _total_closed_heap_region_size = mapinfo->write_heap_regions(
1182                                         closed_heap_regions,
1183                                         closed_heap_bitmaps,
1184                                         MetaspaceShared::first_closed_heap_region,
1185                                         MetaspaceShared::max_num_closed_heap_regions);
1186     _total_open_heap_region_size = mapinfo->write_heap_regions(
1187                                         open_heap_regions,
1188                                         open_heap_bitmaps,
1189                                         MetaspaceShared::first_open_heap_region,
1190                                         MetaspaceShared::max_num_open_heap_regions);
1191   }
1192 
1193   print_region_stats(mapinfo, closed_heap_regions, open_heap_regions);
1194 
1195   mapinfo->set_requested_base((char*)MetaspaceShared::requested_base_address());
1196   mapinfo->set_header_crc(mapinfo->compute_header_crc());
1197   // After this point, we should not write any data into mapinfo->header() since this
1198   // would corrupt its checksum we have calculated before.
1199   mapinfo->write_header();
1200   mapinfo->close();
1201 
1202   if (log_is_enabled(Info, cds)) {
1203     print_stats();
1204   }
1205 
1206   if (log_is_enabled(Info, cds, map)) {
1207     CDSMapLogger::log(this, mapinfo, closed_heap_regions, open_heap_regions,
1208                       bitmap, bitmap_size_in_bytes);
1209   }
1210   CDS_JAVA_HEAP_ONLY(HeapShared::destroy_archived_object_cache());
1211   FREE_C_HEAP_ARRAY(char, bitmap);
1212 }
1213 
1214 void ArchiveBuilder::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only,  bool allow_exec) {
1215   mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);
1216 }
1217 
1218 void ArchiveBuilder::print_region_stats(FileMapInfo *mapinfo,
1219                                         GrowableArray<MemRegion>* closed_heap_regions,
1220                                         GrowableArray<MemRegion>* open_heap_regions) {
1221   // Print statistics of all the regions
1222   const size_t bitmap_used = mapinfo->region_at(MetaspaceShared::bm)->used();
1223   const size_t bitmap_reserved = mapinfo->region_at(MetaspaceShared::bm)->used_aligned();
1224   const size_t total_reserved = _ro_region.reserved()  + _rw_region.reserved() +
1225                                 bitmap_reserved +
1226                                 _total_closed_heap_region_size +
1227                                 _total_open_heap_region_size;
1228   const size_t total_bytes = _ro_region.used()  + _rw_region.used() +
1229                              bitmap_used +
1230                              _total_closed_heap_region_size +
1231                              _total_open_heap_region_size;
1232   const double total_u_perc = percent_of(total_bytes, total_reserved);
1233 
1234   _rw_region.print(total_reserved);
1235   _ro_region.print(total_reserved);
1236 
1237   print_bitmap_region_stats(bitmap_used, total_reserved);
1238 
1239   if (closed_heap_regions != nullptr) {
1240     print_heap_region_stats(closed_heap_regions, "ca", total_reserved);
1241     print_heap_region_stats(open_heap_regions, "oa", total_reserved);
1242   }
1243 
1244   log_debug(cds)("total    : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]",
1245                  total_bytes, total_reserved, total_u_perc);
1246 }
1247 
1248 void ArchiveBuilder::print_bitmap_region_stats(size_t size, size_t total_size) {
1249   log_debug(cds)("bm  space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used]",
1250                  size, size/double(total_size)*100.0, size);
1251 }
1252 
1253 void ArchiveBuilder::print_heap_region_stats(GrowableArray<MemRegion>* regions,
1254                                              const char *name, size_t total_size) {
1255   int arr_len = regions == nullptr ? 0 : regions->length();
1256   for (int i = 0; i < arr_len; i++) {
1257       char* start = (char*)regions->at(i).start();
1258       size_t size = regions->at(i).byte_size();
1259       char* top = start + size;
1260       log_debug(cds)("%s%d space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used] at " INTPTR_FORMAT,
1261                      name, i, size, size/double(total_size)*100.0, size, p2i(start));
1262   }
1263 }
1264 
1265 void ArchiveBuilder::report_out_of_space(const char* name, size_t needed_bytes) {
1266   // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space.
1267   // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes
1268   // or so.
1269   _rw_region.print_out_of_space_msg(name, needed_bytes);
1270   _ro_region.print_out_of_space_msg(name, needed_bytes);
1271 
1272   vm_exit_during_initialization(err_msg("Unable to allocate from '%s' region", name),
1273                                 "Please reduce the number of shared classes.");
1274 }
1275 
1276 
1277 #ifndef PRODUCT
1278 void ArchiveBuilder::assert_is_vm_thread() {
1279   assert(Thread::current()->is_VM_thread(), "ArchiveBuilder should be used only inside the VMThread");
1280 }
1281 #endif