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