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