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