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