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