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/compressedKlass.inline.hpp"
  42 #include "oops/instanceKlass.hpp"
  43 #include "oops/klass.inline.hpp"
  44 #include "oops/objArrayKlass.hpp"
  45 #include "oops/oopHandle.inline.hpp"
  46 #include "runtime/arguments.hpp"
  47 #include "runtime/globals_extension.hpp"
  48 #include "runtime/sharedRuntime.hpp"
  49 #include "runtime/thread.hpp"
  50 #include "utilities/align.hpp"
  51 #include "utilities/bitMap.inline.hpp"
  52 #include "utilities/formatBuffer.hpp"
  53 #include "utilities/hashtable.inline.hpp"
  54 
  55 ArchiveBuilder* ArchiveBuilder::_current = NULL;
  56 
  57 ArchiveBuilder::OtherROAllocMark::~OtherROAllocMark() {
  58   char* newtop = ArchiveBuilder::current()->_ro_region.top();
  59   ArchiveBuilder::alloc_stats()->record_other_type(int(newtop - _oldtop), true);
  60 }
  61 
  62 ArchiveBuilder::SourceObjList::SourceObjList() : _ptrmap(16 * K) {
  63   _total_bytes = 0;
  64   _objs = new (ResourceObj::C_HEAP, mtClassShared) GrowableArray<SourceObjInfo*>(128 * K, mtClassShared);
  65 }
  66 
  67 ArchiveBuilder::SourceObjList::~SourceObjList() {
  68   delete _objs;
  69 }
  70 
  71 void ArchiveBuilder::SourceObjList::append(MetaspaceClosure::Ref* enclosing_ref, SourceObjInfo* src_info) {
  72   // Save this source object for copying
  73   _objs->append(src_info);
  74 
  75   // Prepare for marking the pointers in this source object
  76   assert(is_aligned(_total_bytes, sizeof(address)), "must be");
  77   src_info->set_ptrmap_start(_total_bytes / sizeof(address));
  78   _total_bytes = align_up(_total_bytes + (uintx)src_info->size_in_bytes(), sizeof(address));
  79   src_info->set_ptrmap_end(_total_bytes / sizeof(address));
  80 
  81   BitMap::idx_t bitmap_size_needed = BitMap::idx_t(src_info->ptrmap_end());
  82   if (_ptrmap.size() <= bitmap_size_needed) {
  83     _ptrmap.resize((bitmap_size_needed + 1) * 2);
  84   }
  85 }
  86 
  87 void ArchiveBuilder::SourceObjList::remember_embedded_pointer(SourceObjInfo* src_info, MetaspaceClosure::Ref* ref) {
  88   // src_obj contains a pointer. Remember the location of this pointer in _ptrmap,
  89   // so that we can copy/relocate it later. E.g., if we have
  90   //    class Foo { intx scala; Bar* ptr; }
  91   //    Foo *f = 0x100;
  92   // To mark the f->ptr pointer on 64-bit platform, this function is called with
  93   //    src_info()->obj() == 0x100
  94   //    ref->addr() == 0x108
  95   address src_obj = src_info->obj();
  96   address* field_addr = ref->addr();
  97   assert(src_info->ptrmap_start() < _total_bytes, "sanity");
  98   assert(src_info->ptrmap_end() <= _total_bytes, "sanity");
  99   assert(*field_addr != NULL, "should have checked");
 100 
 101   intx field_offset_in_bytes = ((address)field_addr) - src_obj;
 102   DEBUG_ONLY(int src_obj_size = src_info->size_in_bytes();)
 103   assert(field_offset_in_bytes >= 0, "must be");
 104   assert(field_offset_in_bytes + intx(sizeof(intptr_t)) <= intx(src_obj_size), "must be");
 105   assert(is_aligned(field_offset_in_bytes, sizeof(address)), "must be");
 106 
 107   BitMap::idx_t idx = BitMap::idx_t(src_info->ptrmap_start() + (uintx)(field_offset_in_bytes / sizeof(address)));
 108   _ptrmap.set_bit(BitMap::idx_t(idx));
 109 }
 110 
 111 class RelocateEmbeddedPointers : public BitMapClosure {
 112   ArchiveBuilder* _builder;
 113   address _dumped_obj;
 114   BitMap::idx_t _start_idx;
 115 public:
 116   RelocateEmbeddedPointers(ArchiveBuilder* builder, address dumped_obj, BitMap::idx_t start_idx) :
 117     _builder(builder), _dumped_obj(dumped_obj), _start_idx(start_idx) {}
 118 
 119   bool do_bit(BitMap::idx_t bit_offset) {
 120     size_t field_offset = size_t(bit_offset - _start_idx) * sizeof(address);
 121     address* ptr_loc = (address*)(_dumped_obj + field_offset);
 122 
 123     address old_p = *ptr_loc;
 124     address new_p = _builder->get_dumped_addr(old_p);
 125 
 126     log_trace(cds)("Ref: [" PTR_FORMAT "] -> " PTR_FORMAT " => " PTR_FORMAT,
 127                    p2i(ptr_loc), p2i(old_p), p2i(new_p));
 128 
 129     ArchivePtrMarker::set_and_mark_pointer(ptr_loc, new_p);
 130     return true; // keep iterating the bitmap
 131   }
 132 };
 133 
 134 void ArchiveBuilder::SourceObjList::relocate(int i, ArchiveBuilder* builder) {
 135   SourceObjInfo* src_info = objs()->at(i);
 136   assert(src_info->should_copy(), "must be");
 137   BitMap::idx_t start = BitMap::idx_t(src_info->ptrmap_start()); // inclusive
 138   BitMap::idx_t end = BitMap::idx_t(src_info->ptrmap_end());     // exclusive
 139 
 140   RelocateEmbeddedPointers relocator(builder, src_info->dumped_addr(), start);
 141   _ptrmap.iterate(&relocator, start, end);
 142 }
 143 
 144 ArchiveBuilder::ArchiveBuilder() :
 145   _current_dump_space(NULL),
 146   _buffer_bottom(NULL),
 147   _last_verified_top(NULL),
 148   _num_dump_regions_used(0),
 149   _other_region_used_bytes(0),
 150   _requested_static_archive_bottom(NULL),
 151   _requested_static_archive_top(NULL),
 152   _requested_dynamic_archive_bottom(NULL),
 153   _requested_dynamic_archive_top(NULL),
 154   _mapped_static_archive_bottom(NULL),
 155   _mapped_static_archive_top(NULL),
 156   _buffer_to_requested_delta(0),
 157   _rw_region("rw", MAX_SHARED_DELTA),
 158   _ro_region("ro", MAX_SHARED_DELTA),
 159   _rw_src_objs(),
 160   _ro_src_objs(),
 161   _src_obj_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 ArchiveBuilder::make_shallow_copies: make sure we have enough space for both maximum
 222     // Klass alignment as well as the RuntimeInfo* pointer we will embed in front of a Klass.
 223     _estimated_metaspaceobj_bytes += align_up(BytesPerWord, KlassAlignmentInBytes) +
 224         align_up(sizeof(void*), SharedSpaceObjectAlignment);
 225   } else if (ref->msotype() == MetaspaceObj::SymbolType) {
 226     // Make sure the symbol won't be GC'ed while we are dumping the archive.
 227     Symbol* sym = (Symbol*)ref->obj();
 228     sym->increment_refcount();
 229     _symbols->append(sym);
 230   }
 231 
 232   int bytes = ref->size() * BytesPerWord;
 233   _estimated_metaspaceobj_bytes += align_up(bytes, SharedSpaceObjectAlignment);
 234 
 235   return true; // recurse
 236 }
 237 
 238 void ArchiveBuilder::gather_klasses_and_symbols() {
 239   ResourceMark rm;
 240   log_info(cds)("Gathering classes and symbols ... ");
 241   GatherKlassesAndSymbols doit(this);
 242   iterate_roots(&doit, /*is_relocating_pointers=*/false);
 243 #if INCLUDE_CDS_JAVA_HEAP
 244   if (is_dumping_full_module_graph()) {
 245     ClassLoaderDataShared::iterate_symbols(&doit);
 246   }
 247 #endif
 248   doit.finish();
 249 
 250   if (DumpSharedSpaces) {
 251     // To ensure deterministic contents in the static archive, we need to ensure that
 252     // we iterate the MetaspaceObjs in a deterministic order. It doesn't matter where
 253     // the MetaspaceObjs are located originally, as they are copied sequentially into
 254     // the archive during the iteration.
 255     //
 256     // The only issue here is that the symbol table and the system directories may be
 257     // randomly ordered, so we copy the symbols and klasses into two arrays and sort
 258     // them deterministically.
 259     //
 260     // During -Xshare:dump, the order of Symbol creation is strictly determined by
 261     // the SharedClassListFile (class loading is done in a single thread and the JIT
 262     // is disabled). Also, Symbols are allocated in monotonically increasing addresses
 263     // (see Symbol::operator new(size_t, int)). So if we iterate the Symbols by
 264     // ascending address order, we ensure that all Symbols are copied into deterministic
 265     // locations in the archive.
 266     //
 267     // TODO: in the future, if we want to produce deterministic contents in the
 268     // dynamic archive, we might need to sort the symbols alphabetically (also see
 269     // DynamicArchiveBuilder::sort_methods()).
 270     sort_symbols_and_fix_hash();
 271     sort_klasses();
 272 
 273     // TODO -- we need a proper estimate for the archived modules, etc,
 274     // but this should be enough for now
 275     _estimated_metaspaceobj_bytes += 200 * 1024 * 1024;
 276   }
 277 }
 278 
 279 int ArchiveBuilder::compare_symbols_by_address(Symbol** a, Symbol** b) {
 280   if (a[0] < b[0]) {
 281     return -1;
 282   } else {
 283     assert(a[0] > b[0], "Duplicated symbol %s unexpected", (*a)->as_C_string());
 284     return 1;
 285   }
 286 }
 287 
 288 void ArchiveBuilder::sort_symbols_and_fix_hash() {
 289   log_info(cds)("Sorting symbols and fixing identity hash ... ");
 290   os::init_random(0x12345678);
 291   _symbols->sort(compare_symbols_by_address);
 292   for (int i = 0; i < _symbols->length(); i++) {
 293     assert(_symbols->at(i)->is_permanent(), "archived symbols must be permanent");
 294     _symbols->at(i)->update_identity_hash();
 295   }
 296 }
 297 
 298 int ArchiveBuilder::compare_klass_by_name(Klass** a, Klass** b) {
 299   return a[0]->name()->fast_compare(b[0]->name());
 300 }
 301 
 302 void ArchiveBuilder::sort_klasses() {
 303   log_info(cds)("Sorting classes ... ");
 304   _klasses->sort(compare_klass_by_name);
 305 }
 306 
 307 size_t ArchiveBuilder::estimate_archive_size() {
 308   // size of the symbol table and two dictionaries, plus the RunTimeClassInfo's
 309   size_t symbol_table_est = SymbolTable::estimate_size_for_archive();
 310   size_t dictionary_est = SystemDictionaryShared::estimate_size_for_archive();
 311   _estimated_hashtable_bytes = symbol_table_est + dictionary_est;
 312 
 313   size_t total = 0;
 314 
 315   total += _estimated_metaspaceobj_bytes;
 316   total += _estimated_hashtable_bytes;
 317 
 318   // allow fragmentation at the end of each dump region
 319   total += _total_dump_regions * MetaspaceShared::core_region_alignment();
 320 
 321   log_info(cds)("_estimated_hashtable_bytes = " SIZE_FORMAT " + " SIZE_FORMAT " = " SIZE_FORMAT,
 322                 symbol_table_est, dictionary_est, _estimated_hashtable_bytes);
 323   log_info(cds)("_estimated_metaspaceobj_bytes = " SIZE_FORMAT, _estimated_metaspaceobj_bytes);
 324   log_info(cds)("total estimate bytes = " SIZE_FORMAT, total);
 325 
 326   return align_up(total, MetaspaceShared::core_region_alignment());
 327 }
 328 
 329 address ArchiveBuilder::reserve_buffer() {
 330   size_t buffer_size = estimate_archive_size();
 331   ReservedSpace rs(buffer_size, MetaspaceShared::core_region_alignment(), os::vm_page_size());
 332   if (!rs.is_reserved()) {
 333     log_error(cds)("Failed to reserve " SIZE_FORMAT " bytes of output buffer.", buffer_size);
 334     vm_direct_exit(0);
 335   }
 336 
 337   // buffer_bottom is the lowest address of the 2 core regions (rw, ro) when
 338   // we are copying the class metadata into the buffer.
 339   address buffer_bottom = (address)rs.base();
 340   log_info(cds)("Reserved output buffer space at " PTR_FORMAT " [" SIZE_FORMAT " bytes]",
 341                 p2i(buffer_bottom), buffer_size);
 342   _shared_rs = rs;
 343 
 344   _buffer_bottom = buffer_bottom;
 345   _last_verified_top = buffer_bottom;
 346   _current_dump_space = &_rw_region;
 347   _num_dump_regions_used = 1;
 348   _other_region_used_bytes = 0;
 349   _current_dump_space->init(&_shared_rs, &_shared_vs);
 350 
 351   ArchivePtrMarker::initialize(&_ptrmap, &_shared_vs);
 352 
 353   // The bottom of the static archive should be mapped at this address by default.
 354   _requested_static_archive_bottom = (address)MetaspaceShared::requested_base_address();
 355 
 356   // The bottom of the archive (that I am writing now) should be mapped at this address by default.
 357   address my_archive_requested_bottom;
 358 
 359   if (DumpSharedSpaces) {
 360     my_archive_requested_bottom = _requested_static_archive_bottom;
 361   } else {
 362     _mapped_static_archive_bottom = (address)MetaspaceObj::shared_metaspace_base();
 363     _mapped_static_archive_top  = (address)MetaspaceObj::shared_metaspace_top();
 364     assert(_mapped_static_archive_top >= _mapped_static_archive_bottom, "must be");
 365     size_t static_archive_size = _mapped_static_archive_top - _mapped_static_archive_bottom;
 366 
 367     // At run time, we will mmap the dynamic archive at my_archive_requested_bottom
 368     _requested_static_archive_top = _requested_static_archive_bottom + static_archive_size;
 369     my_archive_requested_bottom = align_up(_requested_static_archive_top, MetaspaceShared::core_region_alignment());
 370 
 371     _requested_dynamic_archive_bottom = my_archive_requested_bottom;
 372   }
 373 
 374   _buffer_to_requested_delta = my_archive_requested_bottom - _buffer_bottom;
 375 
 376   address my_archive_requested_top = my_archive_requested_bottom + buffer_size;
 377   if (my_archive_requested_bottom <  _requested_static_archive_bottom ||
 378       my_archive_requested_top    <= _requested_static_archive_bottom) {
 379     // Size overflow.
 380     log_error(cds)("my_archive_requested_bottom = " INTPTR_FORMAT, p2i(my_archive_requested_bottom));
 381     log_error(cds)("my_archive_requested_top    = " INTPTR_FORMAT, p2i(my_archive_requested_top));
 382     log_error(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is too high. "
 383                    "Please rerun java -Xshare:dump with a lower value", p2i(_requested_static_archive_bottom));
 384     vm_direct_exit(0);
 385   }
 386 
 387   if (DumpSharedSpaces) {
 388     // We don't want any valid object to be at the very bottom of the archive.
 389     // See ArchivePtrMarker::mark_pointer().
 390     rw_region()->allocate(16);
 391   }
 392 
 393   return buffer_bottom;
 394 }
 395 
 396 void ArchiveBuilder::iterate_sorted_roots(MetaspaceClosure* it, bool is_relocating_pointers) {
 397   int i;
 398 
 399   if (!is_relocating_pointers) {
 400     // Don't relocate _symbol, so we can safely call decrement_refcount on the
 401     // original symbols.
 402     int num_symbols = _symbols->length();
 403     for (i = 0; i < num_symbols; i++) {
 404       it->push(_symbols->adr_at(i));
 405     }
 406   }
 407 
 408   int num_klasses = _klasses->length();
 409   for (i = 0; i < num_klasses; i++) {
 410     it->push(_klasses->adr_at(i));
 411   }
 412 
 413   iterate_roots(it, is_relocating_pointers);
 414 }
 415 
 416 class GatherSortedSourceObjs : public MetaspaceClosure {
 417   ArchiveBuilder* _builder;
 418 
 419 public:
 420   GatherSortedSourceObjs(ArchiveBuilder* builder) : _builder(builder) {}
 421 
 422   virtual bool do_ref(Ref* ref, bool read_only) {
 423     return _builder->gather_one_source_obj(enclosing_ref(), ref, read_only);
 424   }
 425 
 426   virtual void push_special(SpecialRef type, Ref* ref, intptr_t* p) {
 427     assert(type == _method_entry_ref, "only special type allowed for now");
 428     address src_obj = ref->obj();
 429     size_t field_offset = pointer_delta(p, src_obj,  sizeof(u1));
 430     _builder->add_special_ref(type, src_obj, field_offset);
 431   };
 432 
 433   virtual void do_pending_ref(Ref* ref) {
 434     if (ref->obj() != NULL) {
 435       _builder->remember_embedded_pointer_in_copied_obj(enclosing_ref(), ref);
 436     }
 437   }
 438 };
 439 
 440 bool ArchiveBuilder::gather_one_source_obj(MetaspaceClosure::Ref* enclosing_ref,
 441                                            MetaspaceClosure::Ref* ref, bool read_only) {
 442   address src_obj = ref->obj();
 443   if (src_obj == NULL) {
 444     return false;
 445   }
 446   ref->set_keep_after_pushing();
 447   remember_embedded_pointer_in_copied_obj(enclosing_ref, ref);
 448 
 449   FollowMode follow_mode = get_follow_mode(ref);
 450   SourceObjInfo src_info(ref, read_only, follow_mode);
 451   bool created;
 452   SourceObjInfo* p = _src_obj_table.put_if_absent(src_obj, src_info, &created);
 453   if (created) {
 454     if (_src_obj_table.maybe_grow()) {
 455       log_info(cds, hashtables)("Expanded _src_obj_table table to %d", _src_obj_table.table_size());
 456     }
 457   }
 458 
 459   assert(p->read_only() == src_info.read_only(), "must be");
 460 
 461   if (created && src_info.should_copy()) {
 462     ref->set_user_data((void*)p);
 463     if (read_only) {
 464       _ro_src_objs.append(enclosing_ref, p);
 465     } else {
 466       _rw_src_objs.append(enclosing_ref, p);
 467     }
 468     return true; // Need to recurse into this ref only if we are copying it
 469   } else {
 470     return false;
 471   }
 472 }
 473 
 474 void ArchiveBuilder::add_special_ref(MetaspaceClosure::SpecialRef type, address src_obj, size_t field_offset) {
 475   _special_refs->append(SpecialRefInfo(type, src_obj, field_offset));
 476 }
 477 
 478 void ArchiveBuilder::remember_embedded_pointer_in_copied_obj(MetaspaceClosure::Ref* enclosing_ref,
 479                                                              MetaspaceClosure::Ref* ref) {
 480   assert(ref->obj() != NULL, "should have checked");
 481 
 482   if (enclosing_ref != NULL) {
 483     SourceObjInfo* src_info = (SourceObjInfo*)enclosing_ref->user_data();
 484     if (src_info == NULL) {
 485       // source objects of point_to_it/set_to_null types are not copied
 486       // so we don't need to remember their pointers.
 487     } else {
 488       if (src_info->read_only()) {
 489         _ro_src_objs.remember_embedded_pointer(src_info, ref);
 490       } else {
 491         _rw_src_objs.remember_embedded_pointer(src_info, ref);
 492       }
 493     }
 494   }
 495 }
 496 
 497 void ArchiveBuilder::gather_source_objs() {
 498   ResourceMark rm;
 499   log_info(cds)("Gathering all archivable objects ... ");
 500   gather_klasses_and_symbols();
 501   GatherSortedSourceObjs doit(this);
 502   iterate_sorted_roots(&doit, /*is_relocating_pointers=*/false);
 503   doit.finish();
 504 }
 505 
 506 bool ArchiveBuilder::is_excluded(Klass* klass) {
 507   if (klass->is_instance_klass()) {
 508     InstanceKlass* ik = InstanceKlass::cast(klass);
 509     return SystemDictionaryShared::is_excluded_class(ik);
 510   } else if (klass->is_objArray_klass()) {
 511     if (DynamicDumpSharedSpaces) {
 512       // Don't support archiving of array klasses for now (WHY???)
 513       return true;
 514     }
 515     Klass* bottom = ObjArrayKlass::cast(klass)->bottom_klass();
 516     if (bottom->is_instance_klass()) {
 517       return SystemDictionaryShared::is_excluded_class(InstanceKlass::cast(bottom));
 518     }
 519   }
 520 
 521   return false;
 522 }
 523 
 524 ArchiveBuilder::FollowMode ArchiveBuilder::get_follow_mode(MetaspaceClosure::Ref *ref) {
 525   address obj = ref->obj();
 526   if (MetaspaceShared::is_in_shared_metaspace(obj)) {
 527     // Don't dump existing shared metadata again.
 528     return point_to_it;
 529   } else if (ref->msotype() == MetaspaceObj::MethodDataType) {
 530     return set_to_null;
 531   } else {
 532     if (ref->msotype() == MetaspaceObj::ClassType) {
 533       Klass* klass = (Klass*)ref->obj();
 534       assert(klass->is_klass(), "must be");
 535       if (is_excluded(klass)) {
 536         ResourceMark rm;
 537         log_debug(cds, dynamic)("Skipping class (excluded): %s", klass->external_name());
 538         return set_to_null;
 539       }
 540     }
 541 
 542     return make_a_copy;
 543   }
 544 }
 545 
 546 void ArchiveBuilder::start_dump_space(DumpRegion* next) {
 547   address bottom = _last_verified_top;
 548   address top = (address)(current_dump_space()->top());
 549   _other_region_used_bytes += size_t(top - bottom);
 550 
 551   current_dump_space()->pack(next);
 552   _current_dump_space = next;
 553   _num_dump_regions_used ++;
 554 
 555   _last_verified_top = (address)(current_dump_space()->top());
 556 }
 557 
 558 void ArchiveBuilder::verify_estimate_size(size_t estimate, const char* which) {
 559   address bottom = _last_verified_top;
 560   address top = (address)(current_dump_space()->top());
 561   size_t used = size_t(top - bottom) + _other_region_used_bytes;
 562   int diff = int(estimate) - int(used);
 563 
 564   log_info(cds)("%s estimate = " SIZE_FORMAT " used = " SIZE_FORMAT "; diff = %d bytes", which, estimate, used, diff);
 565   assert(diff >= 0, "Estimate is too small");
 566 
 567   _last_verified_top = top;
 568   _other_region_used_bytes = 0;
 569 }
 570 
 571 void ArchiveBuilder::dump_rw_metadata() {
 572   ResourceMark rm;
 573   log_info(cds)("Allocating RW objects ... ");
 574   make_shallow_copies(&_rw_region, &_rw_src_objs);
 575 
 576 #if INCLUDE_CDS_JAVA_HEAP
 577   if (is_dumping_full_module_graph()) {
 578     // Archive the ModuleEntry's and PackageEntry's of the 3 built-in loaders
 579     char* start = rw_region()->top();
 580     ClassLoaderDataShared::allocate_archived_tables();
 581     alloc_stats()->record_modules(rw_region()->top() - start, /*read_only*/false);
 582   }
 583 #endif
 584 }
 585 
 586 void ArchiveBuilder::dump_ro_metadata() {
 587   ResourceMark rm;
 588   log_info(cds)("Allocating RO objects ... ");
 589 
 590   start_dump_space(&_ro_region);
 591   make_shallow_copies(&_ro_region, &_ro_src_objs);
 592 
 593 #if INCLUDE_CDS_JAVA_HEAP
 594   if (is_dumping_full_module_graph()) {
 595     char* start = ro_region()->top();
 596     ClassLoaderDataShared::init_archived_tables();
 597     alloc_stats()->record_modules(ro_region()->top() - start, /*read_only*/true);
 598   }
 599 #endif
 600 }
 601 
 602 void ArchiveBuilder::make_shallow_copies(DumpRegion *dump_region,
 603                                          const ArchiveBuilder::SourceObjList* src_objs) {
 604   for (int i = 0; i < src_objs->objs()->length(); i++) {
 605     make_shallow_copy(dump_region, src_objs->objs()->at(i));
 606   }
 607   log_info(cds)("done (%d objects)", src_objs->objs()->length());
 608 }
 609 
 610 void ArchiveBuilder::make_shallow_copy(DumpRegion *dump_region, SourceObjInfo* src_info) {
 611   MetaspaceClosure::Ref* ref = src_info->ref();
 612   address src = ref->obj();
 613   int bytes = src_info->size_in_bytes();
 614   char* dest;
 615   char* oldtop;
 616   char* newtop;
 617 
 618   oldtop = dump_region->top();
 619   if (ref->msotype() == MetaspaceObj::ClassType) {
 620     // Reserve space for a pointer immediately in front of an InstanceKlass. That space will
 621     // later be used to store the RuntimeClassInfo* pointer directly in front of the archived
 622     // InstanceKlass, in order to have a quick lookup InstanceKlass* -> RunTimeClassInfo*
 623     // without building another hashtable. See RunTimeClassInfo::get_for()/::set_for() for
 624     // details.
 625     Klass* klass = (Klass*)src;
 626     if (klass->is_instance_klass()) {
 627       SystemDictionaryShared::validate_before_archiving(InstanceKlass::cast(klass));
 628       dump_region->allocate(sizeof(address));
 629     }
 630     dest = dump_region->allocate(bytes, KlassAlignmentInBytes);
 631   } else {
 632     dest = dump_region->allocate(bytes);
 633   }

 634   newtop = dump_region->top();
 635 
 636   memcpy(dest, src, bytes);
 637 
 638   intptr_t* archived_vtable = CppVtables::get_archived_vtable(ref->msotype(), (address)dest);
 639   if (archived_vtable != NULL) {
 640     *(address*)dest = (address)archived_vtable;
 641     ArchivePtrMarker::mark_pointer((address*)dest);
 642   }
 643 
 644   log_trace(cds)("Copy: " PTR_FORMAT " ==> " PTR_FORMAT " %d (%s)", p2i(src), p2i(dest), bytes,
 645                  MetaspaceObj::type_name(ref->msotype()));
 646   src_info->set_dumped_addr((address)dest);
 647 
 648   _alloc_stats.record(ref->msotype(), int(newtop - oldtop), src_info->read_only());
 649 
 650   DEBUG_ONLY(_alloc_stats.verify((int)dump_region->used(), src_info->read_only()));
 651 }
 652 
 653 address ArchiveBuilder::get_dumped_addr(address src_obj) const {
 654   SourceObjInfo* p = _src_obj_table.get(src_obj);
 655   assert(p != NULL, "must be");
 656 
 657   return p->dumped_addr();
 658 }
 659 
 660 void ArchiveBuilder::relocate_embedded_pointers(ArchiveBuilder::SourceObjList* src_objs) {
 661   for (int i = 0; i < src_objs->objs()->length(); i++) {
 662     src_objs->relocate(i, this);
 663   }
 664 }
 665 
 666 void ArchiveBuilder::update_special_refs() {
 667   for (int i = 0; i < _special_refs->length(); i++) {
 668     SpecialRefInfo s = _special_refs->at(i);
 669     size_t field_offset = s.field_offset();
 670     address src_obj = s.src_obj();
 671     address dst_obj = get_dumped_addr(src_obj);
 672     intptr_t* src_p = (intptr_t*)(src_obj + field_offset);
 673     intptr_t* dst_p = (intptr_t*)(dst_obj + field_offset);
 674     assert(s.type() == MetaspaceClosure::_method_entry_ref, "only special type allowed for now");
 675 
 676     assert(*src_p == *dst_p, "must be a copy");
 677     ArchivePtrMarker::mark_pointer((address*)dst_p);
 678   }
 679 }
 680 
 681 class RefRelocator: public MetaspaceClosure {
 682   ArchiveBuilder* _builder;
 683 
 684 public:
 685   RefRelocator(ArchiveBuilder* builder) : _builder(builder) {}
 686 
 687   virtual bool do_ref(Ref* ref, bool read_only) {
 688     if (ref->not_null()) {
 689       ref->update(_builder->get_dumped_addr(ref->obj()));
 690       ArchivePtrMarker::mark_pointer(ref->addr());
 691     }
 692     return false; // Do not recurse.
 693   }
 694 };
 695 
 696 void ArchiveBuilder::relocate_roots() {
 697   log_info(cds)("Relocating external roots ... ");
 698   ResourceMark rm;
 699   RefRelocator doit(this);
 700   iterate_sorted_roots(&doit, /*is_relocating_pointers=*/true);
 701   doit.finish();
 702   log_info(cds)("done");
 703 }
 704 
 705 void ArchiveBuilder::relocate_metaspaceobj_embedded_pointers() {
 706   log_info(cds)("Relocating embedded pointers in core regions ... ");
 707   relocate_embedded_pointers(&_rw_src_objs);
 708   relocate_embedded_pointers(&_ro_src_objs);
 709   update_special_refs();
 710 }
 711 
 712 // We must relocate vmClasses::_klasses[] only after we have copied the
 713 // java objects in during dump_java_heap_objects(): during the object copy, we operate on
 714 // old objects which assert that their klass is the original klass.
 715 void ArchiveBuilder::relocate_vm_classes() {
 716   log_info(cds)("Relocating vmClasses::_klasses[] ... ");
 717   ResourceMark rm;
 718   RefRelocator doit(this);
 719   vmClasses::metaspace_pointers_do(&doit);
 720 }
 721 
 722 void ArchiveBuilder::make_klasses_shareable() {
 723   int num_instance_klasses = 0;
 724   int num_boot_klasses = 0;
 725   int num_platform_klasses = 0;
 726   int num_app_klasses = 0;
 727   int num_hidden_klasses = 0;
 728   int num_unlinked_klasses = 0;
 729   int num_unregistered_klasses = 0;
 730   int num_obj_array_klasses = 0;
 731   int num_type_array_klasses = 0;
 732 
 733   for (int i = 0; i < klasses()->length(); i++) {
 734     const char* type;
 735     const char* unlinked = "";
 736     const char* hidden = "";
 737     Klass* k = klasses()->at(i);
 738     k->remove_java_mirror();
 739     Klass* requested_k = to_requested(k);
 740     narrowKlass nk = CompressedKlassPointers::encode_not_null(requested_k, _requested_static_archive_bottom);
 741     k->set_prototype_header(markWord::prototype() LP64_ONLY(.set_narrow_klass(nk)));
 742     if (k->is_objArray_klass()) {
 743       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
 744       // on their array classes.
 745       num_obj_array_klasses ++;
 746       type = "array";
 747     } else if (k->is_typeArray_klass()) {
 748       num_type_array_klasses ++;
 749       type = "array";
 750       k->remove_unshareable_info();
 751     } else {
 752       assert(k->is_instance_klass(), " must be");
 753       num_instance_klasses ++;
 754       InstanceKlass* ik = InstanceKlass::cast(k);
 755       if (DynamicDumpSharedSpaces) {
 756         // For static dump, class loader type are already set.
 757         ik->assign_class_loader_type();
 758       }
 759       if (ik->is_shared_boot_class()) {
 760         type = "boot";
 761         num_boot_klasses ++;
 762       } else if (ik->is_shared_platform_class()) {
 763         type = "plat";
 764         num_platform_klasses ++;
 765       } else if (ik->is_shared_app_class()) {
 766         type = "app";
 767         num_app_klasses ++;
 768       } else {
 769         assert(ik->is_shared_unregistered_class(), "must be");
 770         type = "unreg";
 771         num_unregistered_klasses ++;
 772       }
 773 
 774       if (!ik->is_linked()) {
 775         num_unlinked_klasses ++;
 776         unlinked = " ** unlinked";
 777       }
 778 
 779       if (ik->is_hidden()) {
 780         num_hidden_klasses ++;
 781         hidden = " ** hidden";
 782       }
 783 
 784       MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread::current(), ik);
 785       ik->remove_unshareable_info();
 786     }
 787 
 788     if (log_is_enabled(Debug, cds, class)) {
 789       ResourceMark rm;
 790       log_debug(cds, class)("klasses[%5d] = " PTR_FORMAT " %-5s %s%s%s", i, p2i(to_requested(k)), type, k->external_name(), hidden, unlinked);
 791     }
 792   }
 793 
 794   log_info(cds)("Number of classes %d", num_instance_klasses + num_obj_array_klasses + num_type_array_klasses);
 795   log_info(cds)("    instance classes   = %5d", num_instance_klasses);
 796   log_info(cds)("      boot             = %5d", num_boot_klasses);
 797   log_info(cds)("      app              = %5d", num_app_klasses);
 798   log_info(cds)("      platform         = %5d", num_platform_klasses);
 799   log_info(cds)("      unregistered     = %5d", num_unregistered_klasses);
 800   log_info(cds)("      (hidden)         = %5d", num_hidden_klasses);
 801   log_info(cds)("      (unlinked)       = %5d", num_unlinked_klasses);
 802   log_info(cds)("    obj array classes  = %5d", num_obj_array_klasses);
 803   log_info(cds)("    type array classes = %5d", num_type_array_klasses);
 804   log_info(cds)("               symbols = %5d", _symbols->length());
 805 }
 806 
 807 uintx ArchiveBuilder::buffer_to_offset(address p) const {
 808   address requested_p = to_requested(p);
 809   assert(requested_p >= _requested_static_archive_bottom, "must be");
 810   return requested_p - _requested_static_archive_bottom;
 811 }
 812 
 813 uintx ArchiveBuilder::any_to_offset(address p) const {
 814   if (is_in_mapped_static_archive(p)) {
 815     assert(DynamicDumpSharedSpaces, "must be");
 816     return p - _mapped_static_archive_bottom;
 817   }
 818   return buffer_to_offset(p);
 819 }
 820 
 821 // Update a Java object to point its Klass* to the new location after
 822 // shared archive has been compacted.
 823 void ArchiveBuilder::relocate_klass_ptr(oop o) {
 824   assert(DumpSharedSpaces, "sanity");
 825   Klass* k = get_relocated_klass(o->klass());
 826   Klass* requested_k = to_requested(k);
 827   narrowKlass nk = CompressedKlassPointers::encode_not_null(requested_k, _requested_static_archive_bottom);
 828 #ifdef _LP64
 829   o->set_mark(o->mark().set_narrow_klass(nk));
 830 #endif
 831   o->set_narrow_klass(nk);
 832 }
 833 
 834 // RelocateBufferToRequested --- Relocate all the pointers in rw/ro,
 835 // so that the archive can be mapped to the "requested" location without runtime relocation.
 836 //
 837 // - See ArchiveBuilder header for the definition of "buffer", "mapped" and "requested"
 838 // - ArchivePtrMarker::ptrmap() marks all the pointers in the rw/ro regions
 839 // - Every pointer must have one of the following values:
 840 //   [a] NULL:
 841 //       No relocation is needed. Remove this pointer from ptrmap so we don't need to
 842 //       consider it at runtime.
 843 //   [b] Points into an object X which is inside the buffer:
 844 //       Adjust this pointer by _buffer_to_requested_delta, so it points to X
 845 //       when the archive is mapped at the requested location.
 846 //   [c] Points into an object Y which is inside mapped static archive:
 847 //       - This happens only during dynamic dump
 848 //       - Adjust this pointer by _mapped_to_requested_static_archive_delta,
 849 //         so it points to Y when the static archive is mapped at the requested location.
 850 template <bool STATIC_DUMP>
 851 class RelocateBufferToRequested : public BitMapClosure {
 852   ArchiveBuilder* _builder;
 853   address _buffer_bottom;
 854   intx _buffer_to_requested_delta;
 855   intx _mapped_to_requested_static_archive_delta;
 856   size_t _max_non_null_offset;
 857 
 858  public:
 859   RelocateBufferToRequested(ArchiveBuilder* builder) {
 860     _builder = builder;
 861     _buffer_bottom = _builder->buffer_bottom();
 862     _buffer_to_requested_delta = builder->buffer_to_requested_delta();
 863     _mapped_to_requested_static_archive_delta = builder->requested_static_archive_bottom() - builder->mapped_static_archive_bottom();
 864     _max_non_null_offset = 0;
 865 
 866     address bottom = _builder->buffer_bottom();
 867     address top = _builder->buffer_top();
 868     address new_bottom = bottom + _buffer_to_requested_delta;
 869     address new_top = top + _buffer_to_requested_delta;
 870     log_debug(cds)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT "] to "
 871                    "[" INTPTR_FORMAT " - " INTPTR_FORMAT "]",
 872                    p2i(bottom), p2i(top),
 873                    p2i(new_bottom), p2i(new_top));
 874   }
 875 
 876   bool do_bit(size_t offset) {
 877     address* p = (address*)_buffer_bottom + offset;
 878     assert(_builder->is_in_buffer_space(p), "pointer must live in buffer space");
 879 
 880     if (*p == NULL) {
 881       // todo -- clear bit, etc
 882       ArchivePtrMarker::ptrmap()->clear_bit(offset);
 883     } else {
 884       if (STATIC_DUMP) {
 885         assert(_builder->is_in_buffer_space(*p), "old pointer must point inside buffer space");
 886         *p += _buffer_to_requested_delta;
 887         assert(_builder->is_in_requested_static_archive(*p), "new pointer must point inside requested archive");
 888       } else {
 889         if (_builder->is_in_buffer_space(*p)) {
 890           *p += _buffer_to_requested_delta;
 891           // assert is in requested dynamic archive
 892         } else {
 893           assert(_builder->is_in_mapped_static_archive(*p), "old pointer must point inside buffer space or mapped static archive");
 894           *p += _mapped_to_requested_static_archive_delta;
 895           assert(_builder->is_in_requested_static_archive(*p), "new pointer must point inside requested archive");
 896         }
 897       }
 898       _max_non_null_offset = offset;
 899     }
 900 
 901     return true; // keep iterating
 902   }
 903 
 904   void doit() {
 905     ArchivePtrMarker::ptrmap()->iterate(this);
 906     ArchivePtrMarker::compact(_max_non_null_offset);
 907   }
 908 };
 909 
 910 
 911 void ArchiveBuilder::relocate_to_requested() {
 912   ro_region()->pack();
 913 
 914   size_t my_archive_size = buffer_top() - buffer_bottom();
 915 
 916   if (DumpSharedSpaces) {
 917     _requested_static_archive_top = _requested_static_archive_bottom + my_archive_size;
 918     RelocateBufferToRequested<true> patcher(this);
 919     patcher.doit();
 920   } else {
 921     assert(DynamicDumpSharedSpaces, "must be");
 922     _requested_dynamic_archive_top = _requested_dynamic_archive_bottom + my_archive_size;
 923     RelocateBufferToRequested<false> patcher(this);
 924     patcher.doit();
 925   }
 926 }
 927 
 928 // Write detailed info to a mapfile to analyze contents of the archive.
 929 // static dump:
 930 //   java -Xshare:dump -Xlog:cds+map=trace:file=cds.map:none:filesize=0
 931 // dynamic dump:
 932 //   java -cp MyApp.jar -XX:ArchiveClassesAtExit=MyApp.jsa \
 933 //        -Xlog:cds+map=trace:file=cds.map:none:filesize=0 MyApp
 934 //
 935 // We need to do some address translation because the buffers used at dump time may be mapped to
 936 // a different location at runtime. At dump time, the buffers may be at arbitrary locations
 937 // picked by the OS. At runtime, we try to map at a fixed location (SharedBaseAddress). For
 938 // consistency, we log everything using runtime addresses.
 939 class ArchiveBuilder::CDSMapLogger : AllStatic {
 940   static intx buffer_to_runtime_delta() {
 941     // Translate the buffers used by the RW/RO regions to their eventual (requested) locations
 942     // at runtime.
 943     return ArchiveBuilder::current()->buffer_to_requested_delta();
 944   }
 945 
 946   // rw/ro regions only
 947   static void write_dump_region(const char* name, DumpRegion* region) {
 948     address region_base = address(region->base());
 949     address region_top  = address(region->top());
 950     write_region(name, region_base, region_top, region_base + buffer_to_runtime_delta());
 951   }
 952 
 953 #define _LOG_PREFIX PTR_FORMAT ": @@ %-17s %d"
 954 
 955   static void write_klass(Klass* k, address runtime_dest, const char* type_name, int bytes, Thread* current) {
 956     ResourceMark rm(current);
 957     log_debug(cds, map)(_LOG_PREFIX " %s",
 958                         p2i(runtime_dest), type_name, bytes, k->external_name());
 959   }
 960   static void write_method(Method* m, address runtime_dest, const char* type_name, int bytes, Thread* current) {
 961     ResourceMark rm(current);
 962     log_debug(cds, map)(_LOG_PREFIX " %s",
 963                         p2i(runtime_dest), type_name, bytes,  m->external_name());
 964   }
 965 
 966   // rw/ro regions only
 967   static void write_objects(DumpRegion* region, const ArchiveBuilder::SourceObjList* src_objs) {
 968     address last_obj_base = address(region->base());
 969     address last_obj_end  = address(region->base());
 970     address region_end    = address(region->end());
 971     Thread* current = Thread::current();
 972     for (int i = 0; i < src_objs->objs()->length(); i++) {
 973       SourceObjInfo* src_info = src_objs->at(i);
 974       address src = src_info->orig_obj();
 975       address dest = src_info->dumped_addr();
 976       write_data(last_obj_base, dest, last_obj_base + buffer_to_runtime_delta());
 977       address runtime_dest = dest + buffer_to_runtime_delta();
 978       int bytes = src_info->size_in_bytes();
 979 
 980       MetaspaceObj::Type type = src_info->msotype();
 981       const char* type_name = MetaspaceObj::type_name(type);
 982 
 983       switch (type) {
 984       case MetaspaceObj::ClassType:
 985         write_klass((Klass*)src, runtime_dest, type_name, bytes, current);
 986         break;
 987       case MetaspaceObj::ConstantPoolType:
 988         write_klass(((ConstantPool*)src)->pool_holder(),
 989                     runtime_dest, type_name, bytes, current);
 990         break;
 991       case MetaspaceObj::ConstantPoolCacheType:
 992         write_klass(((ConstantPoolCache*)src)->constant_pool()->pool_holder(),
 993                     runtime_dest, type_name, bytes, current);
 994         break;
 995       case MetaspaceObj::MethodType:
 996         write_method((Method*)src, runtime_dest, type_name, bytes, current);
 997         break;
 998       case MetaspaceObj::ConstMethodType:
 999         write_method(((ConstMethod*)src)->method(), runtime_dest, type_name, bytes, current);
1000         break;
1001       case MetaspaceObj::SymbolType:
1002         {
1003           ResourceMark rm(current);
1004           Symbol* s = (Symbol*)src;
1005           log_debug(cds, map)(_LOG_PREFIX " %s", p2i(runtime_dest), type_name, bytes,
1006                               s->as_quoted_ascii());
1007         }
1008         break;
1009       default:
1010         log_debug(cds, map)(_LOG_PREFIX, p2i(runtime_dest), type_name, bytes);
1011         break;
1012       }
1013 
1014       last_obj_base = dest;
1015       last_obj_end  = dest + bytes;
1016     }
1017 
1018     write_data(last_obj_base, last_obj_end, last_obj_base + buffer_to_runtime_delta());
1019     if (last_obj_end < region_end) {
1020       log_debug(cds, map)(PTR_FORMAT ": @@ Misc data " SIZE_FORMAT " bytes",
1021                           p2i(last_obj_end + buffer_to_runtime_delta()),
1022                           size_t(region_end - last_obj_end));
1023       write_data(last_obj_end, region_end, last_obj_end + buffer_to_runtime_delta());
1024     }
1025   }
1026 
1027 #undef _LOG_PREFIX
1028 
1029   // Write information about a region, whose address at dump time is [base .. top). At
1030   // runtime, this region will be mapped to runtime_base.  runtime_base is 0 if this
1031   // region will be mapped at os-selected addresses (such as the bitmap region), or will
1032   // be accessed with os::read (the header).
1033   static void write_region(const char* name, address base, address top, address runtime_base) {
1034     size_t size = top - base;
1035     base = runtime_base;
1036     top = runtime_base + size;
1037     log_info(cds, map)("[%-18s " PTR_FORMAT " - " PTR_FORMAT " " SIZE_FORMAT_W(9) " bytes]",
1038                        name, p2i(base), p2i(top), size);
1039   }
1040 
1041   // open and closed archive regions
1042   static void write_heap_region(const char* which, GrowableArray<MemRegion> *regions) {
1043     for (int i = 0; i < regions->length(); i++) {
1044       address start = address(regions->at(i).start());
1045       address end = address(regions->at(i).end());
1046       write_region(which, start, end, start);
1047       write_data(start, end, start);
1048     }
1049   }
1050 
1051   // Dump all the data [base...top). Pretend that the base address
1052   // will be mapped to runtime_base at run-time.
1053   static void write_data(address base, address top, address runtime_base) {
1054     assert(top >= base, "must be");
1055 
1056     LogStreamHandle(Trace, cds, map) lsh;
1057     if (lsh.is_enabled()) {
1058       os::print_hex_dump(&lsh, base, top, sizeof(address), 32, runtime_base);
1059     }
1060   }
1061 
1062   static void write_header(FileMapInfo* mapinfo) {
1063     LogStreamHandle(Info, cds, map) lsh;
1064     if (lsh.is_enabled()) {
1065       mapinfo->print(&lsh);
1066     }
1067   }
1068 
1069 public:
1070   static void write(ArchiveBuilder* builder, FileMapInfo* mapinfo,
1071              GrowableArray<MemRegion> *closed_heap_regions,
1072              GrowableArray<MemRegion> *open_heap_regions,
1073              char* bitmap, size_t bitmap_size_in_bytes) {
1074     log_info(cds, map)("%s CDS archive map for %s", DumpSharedSpaces ? "Static" : "Dynamic", mapinfo->full_path());
1075 
1076     address header = address(mapinfo->header());
1077     address header_end = header + mapinfo->header()->header_size();
1078     write_region("header", header, header_end, 0);
1079     write_header(mapinfo);
1080     write_data(header, header_end, 0);
1081 
1082     DumpRegion* rw_region = &builder->_rw_region;
1083     DumpRegion* ro_region = &builder->_ro_region;
1084 
1085     write_dump_region("rw region", rw_region);
1086     write_objects(rw_region, &builder->_rw_src_objs);
1087 
1088     write_dump_region("ro region", ro_region);
1089     write_objects(ro_region, &builder->_ro_src_objs);
1090 
1091     address bitmap_end = address(bitmap + bitmap_size_in_bytes);
1092     write_region("bitmap", address(bitmap), bitmap_end, 0);
1093     write_data(header, header_end, 0);
1094 
1095     if (closed_heap_regions != NULL) {
1096       write_heap_region("closed heap region", closed_heap_regions);
1097     }
1098     if (open_heap_regions != NULL) {
1099       write_heap_region("open heap region", open_heap_regions);
1100     }
1101 
1102     log_info(cds, map)("[End of CDS archive map]");
1103   }
1104 };
1105 
1106 void ArchiveBuilder::print_stats() {
1107   _alloc_stats.print_stats(int(_ro_region.used()), int(_rw_region.used()));
1108 }
1109 
1110 void ArchiveBuilder::clean_up_src_obj_table() {
1111   SrcObjTableCleaner cleaner;
1112   _src_obj_table.iterate(&cleaner);
1113 }
1114 
1115 void ArchiveBuilder::write_archive(FileMapInfo* mapinfo,
1116                                    GrowableArray<MemRegion>* closed_heap_regions,
1117                                    GrowableArray<MemRegion>* open_heap_regions,
1118                                    GrowableArray<ArchiveHeapOopmapInfo>* closed_heap_oopmaps,
1119                                    GrowableArray<ArchiveHeapOopmapInfo>* open_heap_oopmaps) {
1120   // Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with
1121   // MetaspaceShared::n_regions (internal to hotspot).
1122   assert(NUM_CDS_REGIONS == MetaspaceShared::n_regions, "sanity");
1123 
1124   write_region(mapinfo, MetaspaceShared::rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);
1125   write_region(mapinfo, MetaspaceShared::ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);
1126 
1127   size_t bitmap_size_in_bytes;
1128   char* bitmap = mapinfo->write_bitmap_region(ArchivePtrMarker::ptrmap(), closed_heap_oopmaps, open_heap_oopmaps,
1129                                               bitmap_size_in_bytes);
1130 
1131   if (closed_heap_regions != NULL) {
1132     _total_closed_heap_region_size = mapinfo->write_heap_regions(
1133                                         closed_heap_regions,
1134                                         closed_heap_oopmaps,
1135                                         MetaspaceShared::first_closed_heap_region,
1136                                         MetaspaceShared::max_num_closed_heap_regions);
1137     _total_open_heap_region_size = mapinfo->write_heap_regions(
1138                                         open_heap_regions,
1139                                         open_heap_oopmaps,
1140                                         MetaspaceShared::first_open_heap_region,
1141                                         MetaspaceShared::max_num_open_heap_regions);
1142   }
1143 
1144   print_region_stats(mapinfo, closed_heap_regions, open_heap_regions);
1145 
1146   mapinfo->set_requested_base((char*)MetaspaceShared::requested_base_address());
1147   mapinfo->set_header_crc(mapinfo->compute_header_crc());
1148   // After this point, we should not write any data into mapinfo->header() since this
1149   // would corrupt its checksum we have calculated before.
1150   mapinfo->write_header();
1151   mapinfo->close();
1152 
1153   if (log_is_enabled(Info, cds)) {
1154     print_stats();
1155   }
1156 
1157   if (log_is_enabled(Info, cds, map)) {
1158     CDSMapLogger::write(this, mapinfo, closed_heap_regions, open_heap_regions,
1159                         bitmap, bitmap_size_in_bytes);
1160   }
1161   FREE_C_HEAP_ARRAY(char, bitmap);
1162 }
1163 
1164 void ArchiveBuilder::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only,  bool allow_exec) {
1165   mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);
1166 }
1167 
1168 void ArchiveBuilder::print_region_stats(FileMapInfo *mapinfo,
1169                                         GrowableArray<MemRegion>* closed_heap_regions,
1170                                         GrowableArray<MemRegion>* open_heap_regions) {
1171   // Print statistics of all the regions
1172   const size_t bitmap_used = mapinfo->space_at(MetaspaceShared::bm)->used();
1173   const size_t bitmap_reserved = mapinfo->space_at(MetaspaceShared::bm)->used_aligned();
1174   const size_t total_reserved = _ro_region.reserved()  + _rw_region.reserved() +
1175                                 bitmap_reserved +
1176                                 _total_closed_heap_region_size +
1177                                 _total_open_heap_region_size;
1178   const size_t total_bytes = _ro_region.used()  + _rw_region.used() +
1179                              bitmap_used +
1180                              _total_closed_heap_region_size +
1181                              _total_open_heap_region_size;
1182   const double total_u_perc = percent_of(total_bytes, total_reserved);
1183 
1184   _rw_region.print(total_reserved);
1185   _ro_region.print(total_reserved);
1186 
1187   print_bitmap_region_stats(bitmap_used, total_reserved);
1188 
1189   if (closed_heap_regions != NULL) {
1190     print_heap_region_stats(closed_heap_regions, "ca", total_reserved);
1191     print_heap_region_stats(open_heap_regions, "oa", total_reserved);
1192   }
1193 
1194   log_debug(cds)("total    : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]",
1195                  total_bytes, total_reserved, total_u_perc);
1196 }
1197 
1198 void ArchiveBuilder::print_bitmap_region_stats(size_t size, size_t total_size) {
1199   log_debug(cds)("bm  space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used]",
1200                  size, size/double(total_size)*100.0, size);
1201 }
1202 
1203 void ArchiveBuilder::print_heap_region_stats(GrowableArray<MemRegion>* regions,
1204                                              const char *name, size_t total_size) {
1205   int arr_len = regions == NULL ? 0 : regions->length();
1206   for (int i = 0; i < arr_len; i++) {
1207       char* start = (char*)regions->at(i).start();
1208       size_t size = regions->at(i).byte_size();
1209       char* top = start + size;
1210       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,
1211                      name, i, size, size/double(total_size)*100.0, size, p2i(start));
1212   }
1213 }
1214 
1215 void ArchiveBuilder::report_out_of_space(const char* name, size_t needed_bytes) {
1216   // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space.
1217   // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes
1218   // or so.
1219   _rw_region.print_out_of_space_msg(name, needed_bytes);
1220   _ro_region.print_out_of_space_msg(name, needed_bytes);
1221 
1222   vm_exit_during_initialization(err_msg("Unable to allocate from '%s' region", name),
1223                                 "Please reduce the number of shared classes.");
1224 }
1225 
1226 
1227 #ifndef PRODUCT
1228 void ArchiveBuilder::assert_is_vm_thread() {
1229   assert(Thread::current()->is_VM_thread(), "ArchiveBuilder should be used only inside the VMThread");
1230 }
1231 #endif
--- EOF ---