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