1 /*
   2  * Copyright (c) 2012, 2020, 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 "classfile/classLoaderDataGraph.hpp"
  27 #include "classfile/classLoaderDataShared.hpp"
  28 #include "classfile/classListParser.hpp"
  29 #include "classfile/classLoaderExt.hpp"
  30 #include "classfile/loaderConstraints.hpp"
  31 #include "classfile/javaClasses.inline.hpp"
  32 #include "classfile/placeholders.hpp"
  33 #include "classfile/symbolTable.hpp"
  34 #include "classfile/stringTable.hpp"
  35 #include "classfile/systemDictionary.hpp"
  36 #include "classfile/systemDictionaryShared.hpp"
  37 #include "code/codeCache.hpp"
  38 #include "interpreter/bytecodeStream.hpp"
  39 #include "interpreter/bytecodes.hpp"
  40 #include "logging/log.hpp"
  41 #include "logging/logMessage.hpp"
  42 #include "memory/archiveBuilder.hpp"
  43 #include "memory/archiveUtils.inline.hpp"
  44 #include "memory/dumpAllocStats.hpp"
  45 #include "memory/dynamicArchive.hpp"
  46 #include "memory/filemap.hpp"
  47 #include "memory/heapShared.inline.hpp"
  48 #include "memory/metaspace.hpp"
  49 #include "memory/metaspaceClosure.hpp"
  50 #include "memory/metaspaceShared.hpp"
  51 #include "memory/resourceArea.hpp"
  52 #include "memory/universe.hpp"
  53 #include "oops/compressedOops.inline.hpp"
  54 #include "oops/instanceClassLoaderKlass.hpp"
  55 #include "oops/instanceMirrorKlass.hpp"
  56 #include "oops/instanceRefKlass.hpp"
  57 #include "oops/methodData.hpp"
  58 #include "oops/objArrayKlass.hpp"
  59 #include "oops/objArrayOop.hpp"
  60 #include "oops/oop.inline.hpp"
  61 #include "oops/typeArrayKlass.hpp"
  62 #include "runtime/handles.inline.hpp"
  63 #include "runtime/os.hpp"
  64 #include "runtime/safepointVerifiers.hpp"
  65 #include "runtime/timerTrace.hpp"
  66 #include "runtime/vmThread.hpp"
  67 #include "runtime/vmOperations.hpp"
  68 #include "utilities/align.hpp"
  69 #include "utilities/bitMap.inline.hpp"
  70 #include "utilities/ostream.hpp"
  71 #include "utilities/defaultStream.hpp"
  72 #include "utilities/hashtable.inline.hpp"
  73 #if INCLUDE_G1GC
  74 #include "gc/g1/g1CollectedHeap.hpp"
  75 #endif
  76 
  77 ReservedSpace MetaspaceShared::_shared_rs;
  78 VirtualSpace MetaspaceShared::_shared_vs;
  79 ReservedSpace MetaspaceShared::_symbol_rs;
  80 VirtualSpace MetaspaceShared::_symbol_vs;
  81 MetaspaceSharedStats MetaspaceShared::_stats;
  82 bool MetaspaceShared::_has_error_classes;
  83 bool MetaspaceShared::_archive_loading_failed = false;
  84 bool MetaspaceShared::_remapped_readwrite = false;
  85 address MetaspaceShared::_i2i_entry_code_buffers = NULL;
  86 size_t MetaspaceShared::_i2i_entry_code_buffers_size = 0;
  87 void* MetaspaceShared::_shared_metaspace_static_top = NULL;
  88 intx MetaspaceShared::_relocation_delta;
  89 char* MetaspaceShared::_requested_base_address;
  90 bool MetaspaceShared::_use_optimized_module_handling = true;
  91 bool MetaspaceShared::_use_full_module_graph = true;
  92 
  93 // The CDS archive is divided into the following regions:
  94 //     mc  - misc code (the method entry trampolines, c++ vtables)
  95 //     rw  - read-write metadata
  96 //     ro  - read-only metadata and read-only tables
  97 //
  98 //     ca0 - closed archive heap space #0
  99 //     ca1 - closed archive heap space #1 (may be empty)
 100 //     oa0 - open archive heap space #0
 101 //     oa1 - open archive heap space #1 (may be empty)
 102 //
 103 // The mc, rw, and ro regions are linearly allocated, starting from
 104 // SharedBaseAddress, in the order of mc->rw->ro. The size of these 3 regions
 105 // are page-aligned, and there's no gap between any consecutive regions.
 106 //
 107 // These 3 regions are populated in the following steps:
 108 // [1] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
 109 //     temporarily allocated outside of the shared regions. Only the method entry
 110 //     trampolines are written into the mc region.
 111 // [2] C++ vtables are copied into the mc region.
 112 // [3] ArchiveBuilder copies RW metadata into the rw region.
 113 // [4] ArchiveBuilder copies RO metadata into the ro region.
 114 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
 115 //     are copied into the ro region as read-only tables.
 116 //
 117 // The s0/s1 and oa0/oa1 regions are populated inside HeapShared::archive_java_heap_objects.
 118 // Their layout is independent of the other 4 regions.
 119 
 120 static DumpRegion _mc_region("mc"), _ro_region("ro"), _rw_region("rw"), _symbol_region("symbols");
 121 static size_t _total_closed_archive_region_size = 0, _total_open_archive_region_size = 0;
 122 
 123 void MetaspaceShared::init_shared_dump_space(DumpRegion* first_space) {
 124   first_space->init(&_shared_rs, &_shared_vs);
 125 }
 126 
 127 DumpRegion* MetaspaceShared::misc_code_dump_space() {
 128   return &_mc_region;
 129 }
 130 
 131 DumpRegion* MetaspaceShared::read_write_dump_space() {
 132   return &_rw_region;
 133 }
 134 
 135 DumpRegion* MetaspaceShared::read_only_dump_space() {
 136   return &_ro_region;
 137 }
 138 
 139 void MetaspaceShared::pack_dump_space(DumpRegion* current, DumpRegion* next,
 140                                       ReservedSpace* rs) {
 141   current->pack(next);
 142 }
 143 
 144 char* MetaspaceShared::symbol_space_alloc(size_t num_bytes) {
 145   return _symbol_region.allocate(num_bytes);
 146 }
 147 
 148 char* MetaspaceShared::misc_code_space_alloc(size_t num_bytes) {
 149   return _mc_region.allocate(num_bytes);
 150 }
 151 
 152 char* MetaspaceShared::read_only_space_alloc(size_t num_bytes) {
 153   return _ro_region.allocate(num_bytes);
 154 }
 155 
 156 char* MetaspaceShared::read_write_space_alloc(size_t num_bytes) {
 157   return _rw_region.allocate(num_bytes);
 158 }
 159 
 160 size_t MetaspaceShared::reserved_space_alignment() { return os::vm_allocation_granularity(); }
 161 
 162 static bool shared_base_valid(char* shared_base) {
 163 #ifdef _LP64
 164   return CompressedKlassPointers::is_valid_base((address)shared_base);
 165 #else
 166   return true;
 167 #endif
 168 }
 169 
 170 static bool shared_base_too_high(char* shared_base, size_t cds_total) {
 171   if (SharedBaseAddress != 0 && shared_base < (char*)SharedBaseAddress) {
 172     // SharedBaseAddress is very high (e.g., 0xffffffffffffff00) so
 173     // align_up(SharedBaseAddress, MetaspaceShared::reserved_space_alignment()) has wrapped around.
 174     return true;
 175   }
 176   if (max_uintx - uintx(shared_base) < uintx(cds_total)) {
 177     // The end of the archive will wrap around
 178     return true;
 179   }
 180 
 181   return false;
 182 }
 183 
 184 static char* compute_shared_base(size_t cds_total) {
 185   char* shared_base = (char*)align_up((char*)SharedBaseAddress, MetaspaceShared::reserved_space_alignment());
 186   const char* err = NULL;
 187   if (shared_base_too_high(shared_base, cds_total)) {
 188     err = "too high";
 189   } else if (!shared_base_valid(shared_base)) {
 190     err = "invalid for this platform";
 191   }
 192   if (err) {
 193     log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
 194                      p2i((void*)SharedBaseAddress), err,
 195                      p2i((void*)Arguments::default_SharedBaseAddress()));
 196     SharedBaseAddress = Arguments::default_SharedBaseAddress();
 197     shared_base = (char*)align_up((char*)SharedBaseAddress, MetaspaceShared::reserved_space_alignment());
 198   }
 199   assert(!shared_base_too_high(shared_base, cds_total) && shared_base_valid(shared_base), "Sanity");
 200   return shared_base;
 201 }
 202 
 203 void MetaspaceShared::initialize_dumptime_shared_and_meta_spaces() {
 204   assert(DumpSharedSpaces, "should be called for dump time only");
 205 
 206   const size_t reserve_alignment = MetaspaceShared::reserved_space_alignment();
 207 
 208 #ifdef _LP64
 209   // On 64-bit VM we reserve a 4G range and, if UseCompressedClassPointers=1,
 210   //  will use that to house both the archives and the ccs. See below for
 211   //  details.
 212   const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
 213   const size_t cds_total = align_down(UnscaledClassSpaceMax, reserve_alignment);
 214 #else
 215   // We don't support archives larger than 256MB on 32-bit due to limited
 216   //  virtual address space.
 217   size_t cds_total = align_down(256*M, reserve_alignment);
 218 #endif
 219 
 220   char* shared_base = compute_shared_base(cds_total);
 221   _requested_base_address = shared_base;
 222 
 223   // Whether to use SharedBaseAddress as attach address.
 224   bool use_requested_base = true;
 225 
 226   if (shared_base == NULL) {
 227     use_requested_base = false;
 228   }
 229 
 230   if (ArchiveRelocationMode == 1) {
 231     log_info(cds)("ArchiveRelocationMode == 1: always allocate class space at an alternative address");
 232     use_requested_base = false;
 233   }
 234 
 235   // First try to reserve the space at the specified SharedBaseAddress.
 236   assert(!_shared_rs.is_reserved(), "must be");
 237   if (use_requested_base) {
 238     _shared_rs = ReservedSpace(cds_total, reserve_alignment,
 239                                false /* large */, (char*)shared_base);
 240     if (_shared_rs.is_reserved()) {
 241       assert(_shared_rs.base() == shared_base, "should match");
 242     } else {
 243       log_info(cds)("dumptime space reservation: failed to map at "
 244                     "SharedBaseAddress " PTR_FORMAT, p2i(shared_base));
 245     }
 246   }
 247   if (!_shared_rs.is_reserved()) {
 248     // Get a reserved space anywhere if attaching at the SharedBaseAddress
 249     //  fails:
 250     if (UseCompressedClassPointers) {
 251       // If we need to reserve class space as well, let the platform handle
 252       //  the reservation.
 253       LP64_ONLY(_shared_rs =
 254                 Metaspace::reserve_address_space_for_compressed_classes(cds_total);)
 255       NOT_LP64(ShouldNotReachHere();)
 256     } else {
 257       // anywhere is fine.
 258       _shared_rs = ReservedSpace(cds_total, reserve_alignment,
 259                                  false /* large */, (char*)NULL);
 260     }
 261   }
 262 
 263   if (!_shared_rs.is_reserved()) {
 264     vm_exit_during_initialization("Unable to reserve memory for shared space",
 265                                   err_msg(SIZE_FORMAT " bytes.", cds_total));
 266   }
 267 
 268 #ifdef _LP64
 269 
 270   if (UseCompressedClassPointers) {
 271 
 272     assert(CompressedKlassPointers::is_valid_base((address)_shared_rs.base()), "Sanity");
 273 
 274     // On 64-bit VM, if UseCompressedClassPointers=1, the compressed class space
 275     //  must be allocated near the cds such as that the compressed Klass pointer
 276     //  encoding can be used to en/decode pointers from both cds and ccs. Since
 277     //  Metaspace cannot do this (it knows nothing about cds), we do it for
 278     //  Metaspace here and pass it the space to use for ccs.
 279     //
 280     // We do this by reserving space for the ccs behind the archives. Note
 281     //  however that ccs follows a different alignment
 282     //  (Metaspace::reserve_alignment), so there may be a gap between ccs and
 283     //  cds.
 284     // We use a similar layout at runtime, see reserve_address_space_for_archives().
 285     //
 286     //                              +-- SharedBaseAddress (default = 0x800000000)
 287     //                              v
 288     // +-..---------+---------+ ... +----+----+----+--------+-----------------+
 289     // |    Heap    | Archive |     | MC | RW | RO | [gap]  |    class space  |
 290     // +-..---------+---------+ ... +----+----+----+--------+-----------------+
 291     // |<--   MaxHeapSize  -->|     |<-- UnscaledClassSpaceMax = 4GB -->|
 292     //
 293     // Note: ccs must follow the archives, and the archives must start at the
 294     //  encoding base. However, the exact placement of ccs does not matter as
 295     //  long as it it resides in the encoding range of CompressedKlassPointers
 296     //  and comes after the archive.
 297     //
 298     // We do this by splitting up the allocated 4G into 3G of archive space,
 299     //  followed by 1G for the ccs:
 300     // + The upper 1 GB is used as the "temporary compressed class space"
 301     //   -- preload_classes() will store Klasses into this space.
 302     // + The lower 3 GB is used for the archive -- when preload_classes()
 303     //   is done, ArchiveBuilder will copy the class metadata into this
 304     //   space, first the RW parts, then the RO parts.
 305 
 306     // Starting address of ccs must be aligned to Metaspace::reserve_alignment()...
 307     size_t class_space_size = align_down(_shared_rs.size() / 4, Metaspace::reserve_alignment());
 308     address class_space_start = (address)align_down(_shared_rs.end() - class_space_size, Metaspace::reserve_alignment());
 309     size_t archive_size = class_space_start - (address)_shared_rs.base();
 310 
 311     ReservedSpace tmp_class_space = _shared_rs.last_part(archive_size);
 312     _shared_rs = _shared_rs.first_part(archive_size);
 313 
 314     // ... as does the size of ccs.
 315     tmp_class_space = tmp_class_space.first_part(class_space_size);
 316     CompressedClassSpaceSize = class_space_size;
 317 
 318     // Let Metaspace initialize ccs
 319     Metaspace::initialize_class_space(tmp_class_space);
 320 
 321     // and set up CompressedKlassPointers encoding.
 322     CompressedKlassPointers::initialize((address)_shared_rs.base(), cds_total);
 323 
 324     log_info(cds)("narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
 325                   p2i(CompressedKlassPointers::base()), CompressedKlassPointers::shift());
 326 
 327     log_info(cds)("Allocated temporary class space: " SIZE_FORMAT " bytes at " PTR_FORMAT,
 328                   CompressedClassSpaceSize, p2i(tmp_class_space.base()));
 329 
 330     assert(_shared_rs.end() == tmp_class_space.base() &&
 331            is_aligned(_shared_rs.base(), MetaspaceShared::reserved_space_alignment()) &&
 332            is_aligned(tmp_class_space.base(), Metaspace::reserve_alignment()) &&
 333            is_aligned(tmp_class_space.size(), Metaspace::reserve_alignment()), "Sanity");
 334   }
 335 
 336 #endif
 337 
 338   init_shared_dump_space(&_mc_region);
 339   SharedBaseAddress = (size_t)_shared_rs.base();
 340   log_info(cds)("Allocated shared space: " SIZE_FORMAT " bytes at " PTR_FORMAT,
 341                 _shared_rs.size(), p2i(_shared_rs.base()));
 342 
 343   // We don't want any valid object to be at the very bottom of the archive.
 344   // See ArchivePtrMarker::mark_pointer().
 345   MetaspaceShared::misc_code_space_alloc(16);
 346 
 347   size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
 348   _symbol_rs = ReservedSpace(symbol_rs_size);
 349   if (!_symbol_rs.is_reserved()) {
 350     vm_exit_during_initialization("Unable to reserve memory for symbols",
 351                                   err_msg(SIZE_FORMAT " bytes.", symbol_rs_size));
 352   }
 353   _symbol_region.init(&_symbol_rs, &_symbol_vs);
 354 }
 355 
 356 // Called by universe_post_init()
 357 void MetaspaceShared::post_initialize(TRAPS) {
 358   if (UseSharedSpaces) {
 359     int size = FileMapInfo::get_number_of_shared_paths();
 360     if (size > 0) {
 361       SystemDictionaryShared::allocate_shared_data_arrays(size, THREAD);
 362       if (!DynamicDumpSharedSpaces) {
 363         FileMapInfo* info;
 364         if (FileMapInfo::dynamic_info() == NULL) {
 365           info = FileMapInfo::current_info();
 366         } else {
 367           info = FileMapInfo::dynamic_info();
 368         }
 369         ClassLoaderExt::init_paths_start_index(info->app_class_paths_start_index());
 370         ClassLoaderExt::init_app_module_paths_start_index(info->app_module_paths_start_index());
 371       }
 372     }
 373   }
 374 }
 375 
 376 static GrowableArrayCHeap<Handle, mtClassShared>* _extra_interned_strings = NULL;
 377 
 378 void MetaspaceShared::read_extra_data(const char* filename, TRAPS) {
 379   _extra_interned_strings = new GrowableArrayCHeap<Handle, mtClassShared>(10000);
 380 
 381   HashtableTextDump reader(filename);
 382   reader.check_version("VERSION: 1.0");
 383 
 384   while (reader.remain() > 0) {
 385     int utf8_length;
 386     int prefix_type = reader.scan_prefix(&utf8_length);
 387     ResourceMark rm(THREAD);
 388     if (utf8_length == 0x7fffffff) {
 389       // buf_len will overflown 32-bit value.
 390       vm_exit_during_initialization(err_msg("string length too large: %d", utf8_length));
 391     }
 392     int buf_len = utf8_length+1;
 393     char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len);
 394     reader.get_utf8(utf8_buffer, utf8_length);
 395     utf8_buffer[utf8_length] = '\0';
 396 
 397     if (prefix_type == HashtableTextDump::SymbolPrefix) {
 398       SymbolTable::new_permanent_symbol(utf8_buffer);
 399     } else{
 400       assert(prefix_type == HashtableTextDump::StringPrefix, "Sanity");
 401       oop s = StringTable::intern(utf8_buffer, THREAD);
 402 
 403       if (HAS_PENDING_EXCEPTION) {
 404         log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d",
 405                                reader.last_line_no(), utf8_length);
 406         CLEAR_PENDING_EXCEPTION;
 407       } else {
 408 #if INCLUDE_G1GC
 409         if (UseG1GC) {
 410           typeArrayOop body = java_lang_String::value(s);
 411           const HeapRegion* hr = G1CollectedHeap::heap()->heap_region_containing(body);
 412           if (hr->is_humongous()) {
 413             // Don't keep it alive, so it will be GC'ed before we dump the strings, in order
 414             // to maximize free heap space and minimize fragmentation.
 415             log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d",
 416                                 reader.last_line_no(), utf8_length);
 417             continue;
 418           }
 419         }
 420 #endif
 421         // Interned strings are GC'ed if there are no references to it, so let's
 422         // add a reference to keep this string alive.
 423         assert(s != NULL, "must succeed");
 424         Handle h(THREAD, s);
 425         _extra_interned_strings->append(h);
 426       }
 427     }
 428   }
 429 }
 430 
 431 void MetaspaceShared::commit_to(ReservedSpace* rs, VirtualSpace* vs, char* newtop) {
 432   Arguments::assert_is_dumping_archive();
 433   char* base = rs->base();
 434   size_t need_committed_size = newtop - base;
 435   size_t has_committed_size = vs->committed_size();
 436   if (need_committed_size < has_committed_size) {
 437     return;
 438   }
 439 
 440   size_t min_bytes = need_committed_size - has_committed_size;
 441   size_t preferred_bytes = 1 * M;
 442   size_t uncommitted = vs->reserved_size() - has_committed_size;
 443 
 444   size_t commit =MAX2(min_bytes, preferred_bytes);
 445   commit = MIN2(commit, uncommitted);
 446   assert(commit <= uncommitted, "sanity");
 447 
 448   bool result = vs->expand_by(commit, false);
 449   if (rs == &_shared_rs) {
 450     ArchivePtrMarker::expand_ptr_end((address*)vs->high());
 451   }
 452 
 453   if (!result) {
 454     vm_exit_during_initialization(err_msg("Failed to expand shared space to " SIZE_FORMAT " bytes",
 455                                           need_committed_size));
 456   }
 457 
 458   assert(rs == &_shared_rs || rs == &_symbol_rs, "must be");
 459   const char* which = (rs == &_shared_rs) ? "shared" : "symbol";
 460   log_debug(cds)("Expanding %s spaces by " SIZE_FORMAT_W(7) " bytes [total " SIZE_FORMAT_W(9)  " bytes ending at %p]",
 461                  which, commit, vs->actual_committed_size(), vs->high());
 462 }
 463 
 464 void MetaspaceShared::initialize_ptr_marker(CHeapBitMap* ptrmap) {
 465   ArchivePtrMarker::initialize(ptrmap, (address*)_shared_vs.low(), (address*)_shared_vs.high());
 466 }
 467 
 468 // Read/write a data stream for restoring/preserving metadata pointers and
 469 // miscellaneous data from/to the shared archive file.
 470 
 471 void MetaspaceShared::serialize(SerializeClosure* soc) {
 472   int tag = 0;
 473   soc->do_tag(--tag);
 474 
 475   // Verify the sizes of various metadata in the system.
 476   soc->do_tag(sizeof(Method));
 477   soc->do_tag(sizeof(ConstMethod));
 478   soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
 479   soc->do_tag(sizeof(ConstantPool));
 480   soc->do_tag(sizeof(ConstantPoolCache));
 481   soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
 482   soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
 483   soc->do_tag(sizeof(Symbol));
 484 
 485   // Dump/restore miscellaneous metadata.
 486   JavaClasses::serialize_offsets(soc);
 487   Universe::serialize(soc);
 488   soc->do_tag(--tag);
 489 
 490   // Dump/restore references to commonly used names and signatures.
 491   vmSymbols::serialize(soc);
 492   soc->do_tag(--tag);
 493 
 494   // Dump/restore the symbol/string/subgraph_info tables
 495   SymbolTable::serialize_shared_table_header(soc);
 496   StringTable::serialize_shared_table_header(soc);
 497   HeapShared::serialize_subgraph_info_table_header(soc);
 498   SystemDictionaryShared::serialize_dictionary_headers(soc);
 499 
 500   InstanceMirrorKlass::serialize_offsets(soc);
 501 
 502   // Dump/restore well known classes (pointers)
 503   SystemDictionaryShared::serialize_well_known_klasses(soc);
 504   soc->do_tag(--tag);
 505 
 506   serialize_cloned_cpp_vtptrs(soc);
 507   soc->do_tag(--tag);
 508 
 509   CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc));
 510 
 511   soc->do_tag(666);
 512 }
 513 
 514 address MetaspaceShared::i2i_entry_code_buffers(size_t total_size) {
 515   if (DumpSharedSpaces) {
 516     if (_i2i_entry_code_buffers == NULL) {
 517       _i2i_entry_code_buffers = (address)misc_code_space_alloc(total_size);
 518       _i2i_entry_code_buffers_size = total_size;
 519     }
 520   } else if (UseSharedSpaces) {
 521     assert(_i2i_entry_code_buffers != NULL, "must already been initialized");
 522   } else {
 523     return NULL;
 524   }
 525 
 526   assert(_i2i_entry_code_buffers_size == total_size, "must not change");
 527   return _i2i_entry_code_buffers;
 528 }
 529 
 530 uintx MetaspaceShared::object_delta_uintx(void* obj) {
 531   Arguments::assert_is_dumping_archive();
 532   if (DumpSharedSpaces) {
 533     assert(shared_rs()->contains(obj), "must be");
 534   } else {
 535     assert(is_in_shared_metaspace(obj) || DynamicArchive::is_in_target_space(obj), "must be");
 536   }
 537   address base_address = address(SharedBaseAddress);
 538   uintx deltax = address(obj) - base_address;
 539   return deltax;
 540 }
 541 
 542 // Global object for holding classes that have been loaded.  Since this
 543 // is run at a safepoint just before exit, this is the entire set of classes.
 544 static GrowableArray<Klass*>* _global_klass_objects;
 545 
 546 GrowableArray<Klass*>* MetaspaceShared::collected_klasses() {
 547   return _global_klass_objects;
 548 }
 549 
 550 static void remove_unshareable_in_classes() {
 551   for (int i = 0; i < _global_klass_objects->length(); i++) {
 552     Klass* k = _global_klass_objects->at(i);
 553     if (!k->is_objArray_klass()) {
 554       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
 555       // on their array classes.
 556       assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be");
 557       k->remove_unshareable_info();
 558     }
 559   }
 560 }
 561 
 562 static void remove_java_mirror_in_classes() {
 563   for (int i = 0; i < _global_klass_objects->length(); i++) {
 564     Klass* k = _global_klass_objects->at(i);
 565     if (!k->is_objArray_klass()) {
 566       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
 567       // on their array classes.
 568       assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be");
 569       k->remove_java_mirror();
 570     }
 571   }
 572 }
 573 
 574 static void rewrite_nofast_bytecode(const methodHandle& method) {
 575   BytecodeStream bcs(method);
 576   while (!bcs.is_last_bytecode()) {
 577     Bytecodes::Code opcode = bcs.next();
 578     switch (opcode) {
 579     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
 580     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;
 581     case Bytecodes::_aload_0:       *bcs.bcp() = Bytecodes::_nofast_aload_0;       break;
 582     case Bytecodes::_iload: {
 583       if (!bcs.is_wide()) {
 584         *bcs.bcp() = Bytecodes::_nofast_iload;
 585       }
 586       break;
 587     }
 588     default: break;
 589     }
 590   }
 591 }
 592 
 593 // Walk all methods in the class list to ensure that they won't be modified at
 594 // run time. This includes:
 595 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified
 596 //     at run time by RewriteBytecodes/RewriteFrequentPairs
 597 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.
 598 static void rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread) {
 599   for (int i = 0; i < _global_klass_objects->length(); i++) {
 600     Klass* k = _global_klass_objects->at(i);
 601     if (k->is_instance_klass()) {
 602       InstanceKlass* ik = InstanceKlass::cast(k);
 603       MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(thread, ik);
 604     }
 605   }
 606 }
 607 
 608 void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) {
 609   for (int i = 0; i < ik->methods()->length(); i++) {
 610     methodHandle m(thread, ik->methods()->at(i));
 611     rewrite_nofast_bytecode(m);
 612     Fingerprinter fp(m);
 613     // The side effect of this call sets method's fingerprint field.
 614     fp.fingerprint();
 615   }
 616 }
 617 
 618 // Objects of the Metadata types (such as Klass and ConstantPool) have C++ vtables.
 619 // (In GCC this is the field <Type>::_vptr, i.e., first word in the object.)
 620 //
 621 // Addresses of the vtables and the methods may be different across JVM runs,
 622 // if libjvm.so is dynamically loaded at a different base address.
 623 //
 624 // To ensure that the Metadata objects in the CDS archive always have the correct vtable:
 625 //
 626 // + at dump time:  we redirect the _vptr to point to our own vtables inside
 627 //                  the CDS image
 628 // + at run time:   we clone the actual contents of the vtables from libjvm.so
 629 //                  into our own tables.
 630 
 631 // Currently, the archive contain ONLY the following types of objects that have C++ vtables.
 632 #define CPP_VTABLE_PATCH_TYPES_DO(f) \
 633   f(ConstantPool) \
 634   f(InstanceKlass) \
 635   f(InstanceClassLoaderKlass) \
 636   f(InstanceMirrorKlass) \
 637   f(InstanceRefKlass) \
 638   f(Method) \
 639   f(ObjArrayKlass) \
 640   f(TypeArrayKlass)
 641 
 642 class CppVtableInfo {
 643   intptr_t _vtable_size;
 644   intptr_t _cloned_vtable[1];
 645 public:
 646   static int num_slots(int vtable_size) {
 647     return 1 + vtable_size; // Need to add the space occupied by _vtable_size;
 648   }
 649   int vtable_size()           { return int(uintx(_vtable_size)); }
 650   void set_vtable_size(int n) { _vtable_size = intptr_t(n); }
 651   intptr_t* cloned_vtable()   { return &_cloned_vtable[0]; }
 652   void zero()                 { memset(_cloned_vtable, 0, sizeof(intptr_t) * vtable_size()); }
 653   // Returns the address of the next CppVtableInfo that can be placed immediately after this CppVtableInfo
 654   static size_t byte_size(int vtable_size) {
 655     CppVtableInfo i;
 656     return pointer_delta(&i._cloned_vtable[vtable_size], &i, sizeof(u1));
 657   }
 658 };
 659 
 660 static inline intptr_t* vtable_of(Metadata* m) {
 661   return *((intptr_t**)m);
 662 }
 663 
 664 template <class T> class CppVtableCloner : public T {
 665   static CppVtableInfo* _info;
 666 
 667   static int get_vtable_length(const char* name);
 668 
 669 public:
 670   // Allocate and initialize the C++ vtable, starting from top, but do not go past end.
 671   static intptr_t* allocate(const char* name);
 672 
 673   // Clone the vtable to ...
 674   static intptr_t* clone_vtable(const char* name, CppVtableInfo* info);
 675 
 676   static void zero_vtable_clone() {
 677     assert(DumpSharedSpaces, "dump-time only");
 678     _info->zero();
 679   }
 680 
 681   static bool is_valid_shared_object(const T* obj) {
 682     intptr_t* vptr = *(intptr_t**)obj;
 683     return vptr == _info->cloned_vtable();
 684   }
 685 
 686   static void init_orig_cpp_vtptr(int kind);
 687 };
 688 
 689 template <class T> CppVtableInfo* CppVtableCloner<T>::_info = NULL;
 690 
 691 template <class T>
 692 intptr_t* CppVtableCloner<T>::allocate(const char* name) {
 693   assert(is_aligned(_mc_region.top(), sizeof(intptr_t)), "bad alignment");
 694   int n = get_vtable_length(name);
 695   _info = (CppVtableInfo*)_mc_region.allocate(CppVtableInfo::byte_size(n), sizeof(intptr_t));
 696   _info->set_vtable_size(n);
 697 
 698   intptr_t* p = clone_vtable(name, _info);
 699   assert((char*)p == _mc_region.top(), "must be");
 700 
 701   return _info->cloned_vtable();
 702 }
 703 
 704 template <class T>
 705 intptr_t* CppVtableCloner<T>::clone_vtable(const char* name, CppVtableInfo* info) {
 706   if (!DumpSharedSpaces) {
 707     assert(_info == 0, "_info is initialized only at dump time");
 708     _info = info; // Remember it -- it will be used by MetaspaceShared::is_valid_shared_method()
 709   }
 710   T tmp; // Allocate temporary dummy metadata object to get to the original vtable.
 711   int n = info->vtable_size();
 712   intptr_t* srcvtable = vtable_of(&tmp);
 713   intptr_t* dstvtable = info->cloned_vtable();
 714 
 715   // We already checked (and, if necessary, adjusted n) when the vtables were allocated, so we are
 716   // safe to do memcpy.
 717   log_debug(cds, vtables)("Copying %3d vtable entries for %s", n, name);
 718   memcpy(dstvtable, srcvtable, sizeof(intptr_t) * n);
 719   return dstvtable + n;
 720 }
 721 
 722 // To determine the size of the vtable for each type, we use the following
 723 // trick by declaring 2 subclasses:
 724 //
 725 //   class CppVtableTesterA: public InstanceKlass {virtual int   last_virtual_method() {return 1;}    };
 726 //   class CppVtableTesterB: public InstanceKlass {virtual void* last_virtual_method() {return NULL}; };
 727 //
 728 // CppVtableTesterA and CppVtableTesterB's vtables have the following properties:
 729 // - Their size (N+1) is exactly one more than the size of InstanceKlass's vtable (N)
 730 // - The first N entries have are exactly the same as in InstanceKlass's vtable.
 731 // - Their last entry is different.
 732 //
 733 // So to determine the value of N, we just walk CppVtableTesterA and CppVtableTesterB's tables
 734 // and find the first entry that's different.
 735 //
 736 // This works on all C++ compilers supported by Oracle, but you may need to tweak it for more
 737 // esoteric compilers.
 738 
 739 template <class T> class CppVtableTesterB: public T {
 740 public:
 741   virtual int last_virtual_method() {return 1;}
 742 };
 743 
 744 template <class T> class CppVtableTesterA : public T {
 745 public:
 746   virtual void* last_virtual_method() {
 747     // Make this different than CppVtableTesterB::last_virtual_method so the C++
 748     // compiler/linker won't alias the two functions.
 749     return NULL;
 750   }
 751 };
 752 
 753 template <class T>
 754 int CppVtableCloner<T>::get_vtable_length(const char* name) {
 755   CppVtableTesterA<T> a;
 756   CppVtableTesterB<T> b;
 757 
 758   intptr_t* avtable = vtable_of(&a);
 759   intptr_t* bvtable = vtable_of(&b);
 760 
 761   // Start at slot 1, because slot 0 may be RTTI (on Solaris/Sparc)
 762   int vtable_len = 1;
 763   for (; ; vtable_len++) {
 764     if (avtable[vtable_len] != bvtable[vtable_len]) {
 765       break;
 766     }
 767   }
 768   log_debug(cds, vtables)("Found   %3d vtable entries for %s", vtable_len, name);
 769 
 770   return vtable_len;
 771 }
 772 
 773 #define ALLOC_CPP_VTABLE_CLONE(c) \
 774   _cloned_cpp_vtptrs[c##_Kind] = CppVtableCloner<c>::allocate(#c); \
 775   ArchivePtrMarker::mark_pointer(&_cloned_cpp_vtptrs[c##_Kind]);
 776 
 777 #define CLONE_CPP_VTABLE(c) \
 778   p = CppVtableCloner<c>::clone_vtable(#c, (CppVtableInfo*)p);
 779 
 780 #define ZERO_CPP_VTABLE(c) \
 781  CppVtableCloner<c>::zero_vtable_clone();
 782 
 783 #define INIT_ORIG_CPP_VTPTRS(c) \
 784   CppVtableCloner<c>::init_orig_cpp_vtptr(c##_Kind);
 785 
 786 #define DECLARE_CLONED_VTABLE_KIND(c) c ## _Kind,
 787 
 788 enum ClonedVtableKind {
 789   // E.g., ConstantPool_Kind == 0, InstanceKlass_Kind == 1, etc.
 790   CPP_VTABLE_PATCH_TYPES_DO(DECLARE_CLONED_VTABLE_KIND)
 791   _num_cloned_vtable_kinds
 792 };
 793 
 794 // This is a map of all the original vtptrs. E.g., for
 795 //     ConstantPool *cp = new (...) ConstantPool(...) ; // a dynamically allocated constant pool
 796 // the following holds true:
 797 //     _orig_cpp_vtptrs[ConstantPool_Kind] ==  ((intptr_t**)cp)[0]
 798 static intptr_t* _orig_cpp_vtptrs[_num_cloned_vtable_kinds];
 799 static bool _orig_cpp_vtptrs_inited = false;
 800 
 801 template <class T>
 802 void CppVtableCloner<T>::init_orig_cpp_vtptr(int kind) {
 803   assert(kind < _num_cloned_vtable_kinds, "sanity");
 804   T tmp; // Allocate temporary dummy metadata object to get to the original vtable.
 805   intptr_t* srcvtable = vtable_of(&tmp);
 806   _orig_cpp_vtptrs[kind] = srcvtable;
 807 }
 808 
 809 // This is the index of all the cloned vtables. E.g., for
 810 //     ConstantPool* cp = ....; // an archived constant pool
 811 //     InstanceKlass* ik = ....;// an archived class
 812 // the following holds true:
 813 //     _cloned_cpp_vtptrs[ConstantPool_Kind]  == ((intptr_t**)cp)[0]
 814 //     _cloned_cpp_vtptrs[InstanceKlass_Kind] == ((intptr_t**)ik)[0]
 815 static intptr_t** _cloned_cpp_vtptrs = NULL;
 816 
 817 void MetaspaceShared::allocate_cloned_cpp_vtptrs() {
 818   assert(DumpSharedSpaces, "must");
 819   size_t vtptrs_bytes = _num_cloned_vtable_kinds * sizeof(intptr_t*);
 820   _cloned_cpp_vtptrs = (intptr_t**)_mc_region.allocate(vtptrs_bytes, sizeof(intptr_t*));
 821 }
 822 
 823 void MetaspaceShared::serialize_cloned_cpp_vtptrs(SerializeClosure* soc) {
 824   soc->do_ptr((void**)&_cloned_cpp_vtptrs);
 825 }
 826 
 827 intptr_t* MetaspaceShared::get_archived_cpp_vtable(MetaspaceObj::Type msotype, address obj) {
 828   if (!_orig_cpp_vtptrs_inited) {
 829     CPP_VTABLE_PATCH_TYPES_DO(INIT_ORIG_CPP_VTPTRS);
 830     _orig_cpp_vtptrs_inited = true;
 831   }
 832 
 833   Arguments::assert_is_dumping_archive();
 834   int kind = -1;
 835   switch (msotype) {
 836   case MetaspaceObj::SymbolType:
 837   case MetaspaceObj::TypeArrayU1Type:
 838   case MetaspaceObj::TypeArrayU2Type:
 839   case MetaspaceObj::TypeArrayU4Type:
 840   case MetaspaceObj::TypeArrayU8Type:
 841   case MetaspaceObj::TypeArrayOtherType:
 842   case MetaspaceObj::ConstMethodType:
 843   case MetaspaceObj::ConstantPoolCacheType:
 844   case MetaspaceObj::AnnotationsType:
 845   case MetaspaceObj::MethodCountersType:
 846   case MetaspaceObj::RecordComponentType:
 847     // These have no vtables.
 848     break;
 849   case MetaspaceObj::MethodDataType:
 850     // We don't archive MethodData <-- should have been removed in removed_unsharable_info
 851     ShouldNotReachHere();
 852     break;
 853   default:
 854     for (kind = 0; kind < _num_cloned_vtable_kinds; kind ++) {
 855       if (vtable_of((Metadata*)obj) == _orig_cpp_vtptrs[kind]) {
 856         break;
 857       }
 858     }
 859     if (kind >= _num_cloned_vtable_kinds) {
 860       fatal("Cannot find C++ vtable for " INTPTR_FORMAT " -- you probably added"
 861             " a new subtype of Klass or MetaData without updating CPP_VTABLE_PATCH_TYPES_DO",
 862             p2i(obj));
 863     }
 864   }
 865 
 866   if (kind >= 0) {
 867     assert(kind < _num_cloned_vtable_kinds, "must be");
 868     return _cloned_cpp_vtptrs[kind];
 869   } else {
 870     return NULL;
 871   }
 872 }
 873 
 874 // This can be called at both dump time and run time:
 875 // - clone the contents of the c++ vtables into the space
 876 //   allocated by allocate_cpp_vtable_clones()
 877 void MetaspaceShared::clone_cpp_vtables(intptr_t* p) {
 878   assert(DumpSharedSpaces || UseSharedSpaces, "sanity");
 879   CPP_VTABLE_PATCH_TYPES_DO(CLONE_CPP_VTABLE);
 880 }
 881 
 882 void MetaspaceShared::zero_cpp_vtable_clones_for_writing() {
 883   assert(DumpSharedSpaces, "dump-time only");
 884   CPP_VTABLE_PATCH_TYPES_DO(ZERO_CPP_VTABLE);
 885 }
 886 
 887 // Allocate and initialize the C++ vtables, starting from top, but do not go past end.
 888 char* MetaspaceShared::allocate_cpp_vtable_clones() {
 889   char* cloned_vtables = _mc_region.top(); // This is the beginning of all the cloned vtables
 890 
 891   assert(DumpSharedSpaces, "dump-time only");
 892   // Layout (each slot is a intptr_t):
 893   //   [number of slots in the first vtable = n1]
 894   //   [ <n1> slots for the first vtable]
 895   //   [number of slots in the first second = n2]
 896   //   [ <n2> slots for the second vtable]
 897   //   ...
 898   // The order of the vtables is the same as the CPP_VTAB_PATCH_TYPES_DO macro.
 899   CPP_VTABLE_PATCH_TYPES_DO(ALLOC_CPP_VTABLE_CLONE);
 900 
 901   return cloned_vtables;
 902 }
 903 
 904 bool MetaspaceShared::is_valid_shared_method(const Method* m) {
 905   assert(is_in_shared_metaspace(m), "must be");
 906   return CppVtableCloner<Method>::is_valid_shared_object(m);
 907 }
 908 
 909 class VM_PopulateDumpSharedSpace: public VM_Operation {
 910 private:
 911   GrowableArray<MemRegion> *_closed_archive_heap_regions;
 912   GrowableArray<MemRegion> *_open_archive_heap_regions;
 913 
 914   GrowableArray<ArchiveHeapOopmapInfo> *_closed_archive_heap_oopmaps;
 915   GrowableArray<ArchiveHeapOopmapInfo> *_open_archive_heap_oopmaps;
 916 
 917   void dump_java_heap_objects() NOT_CDS_JAVA_HEAP_RETURN;
 918   void dump_archive_heap_oopmaps() NOT_CDS_JAVA_HEAP_RETURN;
 919   void dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
 920                                  GrowableArray<ArchiveHeapOopmapInfo>* oopmaps);
 921   void dump_symbols();
 922   char* dump_read_only_tables();
 923   void print_region_stats(FileMapInfo* map_info);
 924   void print_bitmap_region_stats(size_t size, size_t total_size);
 925   void print_heap_region_stats(GrowableArray<MemRegion> *heap_mem,
 926                                const char *name, size_t total_size);
 927   void relocate_to_requested_base_address(CHeapBitMap* ptrmap);
 928 
 929 public:
 930 
 931   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
 932   void doit();   // outline because gdb sucks
 933   bool allow_nested_vm_operations() const { return true; }
 934 }; // class VM_PopulateDumpSharedSpace
 935 
 936 class StaticArchiveBuilder : public ArchiveBuilder {
 937 public:
 938   StaticArchiveBuilder(DumpRegion* rw_region, DumpRegion* ro_region)
 939     : ArchiveBuilder(rw_region, ro_region) {}
 940 
 941   virtual void iterate_roots(MetaspaceClosure* it, bool is_relocating_pointers) {
 942     FileMapInfo::metaspace_pointers_do(it, false);
 943     SystemDictionaryShared::dumptime_classes_do(it);
 944     Universe::metaspace_pointers_do(it);
 945     SymbolTable::metaspace_pointers_do(it);
 946     vmSymbols::metaspace_pointers_do(it);
 947   }
 948 };
 949 
 950 void VM_PopulateDumpSharedSpace::dump_symbols() {
 951   log_info(cds)("Dumping symbol table ...");
 952 
 953   NOT_PRODUCT(SymbolTable::verify());
 954   SymbolTable::write_to_archive();
 955 }
 956 
 957 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
 958   ArchiveBuilder::OtherROAllocMark mark;
 959 
 960   log_info(cds)("Removing java_mirror ... ");
 961   if (!HeapShared::is_heap_object_archiving_allowed()) {
 962     Universe::clear_basic_type_mirrors();
 963   }
 964   remove_java_mirror_in_classes();
 965   log_info(cds)("done. ");
 966 
 967   SystemDictionaryShared::write_to_archive();
 968 
 969   // Write the other data to the output array.
 970   char* start = _ro_region.top();
 971   WriteClosure wc(&_ro_region);
 972   MetaspaceShared::serialize(&wc);
 973 
 974   // Write the bitmaps for patching the archive heap regions
 975   _closed_archive_heap_oopmaps = NULL;
 976   _open_archive_heap_oopmaps = NULL;
 977   dump_archive_heap_oopmaps();
 978 
 979   return start;
 980 }
 981 
 982 void VM_PopulateDumpSharedSpace::relocate_to_requested_base_address(CHeapBitMap* ptrmap) {
 983   intx addr_delta = MetaspaceShared::final_delta();
 984   if (addr_delta == 0) {
 985     ArchivePtrMarker::compact((address)SharedBaseAddress, (address)_ro_region.top());
 986   } else {
 987     // We are not able to reserve space at MetaspaceShared::requested_base_address() (due to ASLR).
 988     // This means that the current content of the archive is based on a random
 989     // address. Let's relocate all the pointers, so that it can be mapped to
 990     // MetaspaceShared::requested_base_address() without runtime relocation.
 991     //
 992     // Note: both the base and dynamic archive are written with
 993     // FileMapHeader::_requested_base_address == MetaspaceShared::requested_base_address()
 994 
 995     // Patch all pointers that are marked by ptrmap within this region,
 996     // where we have just dumped all the metaspace data.
 997     address patch_base = (address)SharedBaseAddress;
 998     address patch_end  = (address)_ro_region.top();
 999     size_t size = patch_end - patch_base;
1000 
1001     // the current value of the pointers to be patched must be within this
1002     // range (i.e., must point to valid metaspace objects)
1003     address valid_old_base = patch_base;
1004     address valid_old_end  = patch_end;
1005 
1006     // after patching, the pointers must point inside this range
1007     // (the requested location of the archive, as mapped at runtime).
1008     address valid_new_base = (address)MetaspaceShared::requested_base_address();
1009     address valid_new_end  = valid_new_base + size;
1010 
1011     log_debug(cds)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT " ] to "
1012                    "[" INTPTR_FORMAT " - " INTPTR_FORMAT " ]", p2i(patch_base), p2i(patch_end),
1013                    p2i(valid_new_base), p2i(valid_new_end));
1014 
1015     SharedDataRelocator<true> patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end,
1016                                       valid_new_base, valid_new_end, addr_delta, ptrmap);
1017     ptrmap->iterate(&patcher);
1018     ArchivePtrMarker::compact(patcher.max_non_null_offset());
1019   }
1020 }
1021 
1022 void VM_PopulateDumpSharedSpace::doit() {
1023   HeapShared::run_full_gc_in_vm_thread();
1024   CHeapBitMap ptrmap;
1025   MetaspaceShared::initialize_ptr_marker(&ptrmap);
1026 
1027   // We should no longer allocate anything from the metaspace, so that:
1028   //
1029   // (1) Metaspace::allocate might trigger GC if we have run out of
1030   //     committed metaspace, but we can't GC because we're running
1031   //     in the VM thread.
1032   // (2) ArchiveBuilder needs to work with a stable set of MetaspaceObjs.
1033   Metaspace::freeze();
1034   DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
1035 
1036   Thread* THREAD = VMThread::vm_thread();
1037 
1038   FileMapInfo::check_nonempty_dir_in_shared_path_table();
1039 
1040   NOT_PRODUCT(SystemDictionary::verify();)
1041   // The following guarantee is meant to ensure that no loader constraints
1042   // exist yet, since the constraints table is not shared.  This becomes
1043   // more important now that we don't re-initialize vtables/itables for
1044   // shared classes at runtime, where constraints were previously created.
1045   guarantee(SystemDictionary::constraints()->number_of_entries() == 0,
1046             "loader constraints are not saved");
1047   guarantee(SystemDictionary::placeholders()->number_of_entries() == 0,
1048           "placeholders are not saved");
1049 
1050   // At this point, many classes have been loaded.
1051   // Gather systemDictionary classes in a global array and do everything to
1052   // that so we don't have to walk the SystemDictionary again.
1053   SystemDictionaryShared::check_excluded_classes();
1054 
1055   StaticArchiveBuilder builder(&_rw_region, &_ro_region);
1056   builder.gather_klasses_and_symbols();
1057   _global_klass_objects = builder.klasses();
1058 
1059   // Ensure the ConstMethods won't be modified at run-time
1060   log_info(cds)("Updating ConstMethods ... ");
1061   rewrite_nofast_bytecodes_and_calculate_fingerprints(THREAD);
1062   log_info(cds)("done. ");
1063 
1064   // Remove all references outside the metadata
1065   log_info(cds)("Removing unshareable information ... ");
1066   remove_unshareable_in_classes();
1067   log_info(cds)("done. ");
1068 
1069   builder.gather_source_objs();
1070 
1071   MetaspaceShared::allocate_cloned_cpp_vtptrs();
1072   char* cloned_vtables = _mc_region.top();
1073   MetaspaceShared::allocate_cpp_vtable_clones();
1074 
1075   {
1076     _mc_region.pack(&_rw_region);
1077     builder.dump_rw_region();
1078 #if INCLUDE_CDS_JAVA_HEAP
1079     // Archive the ModuleEntry's and PackageEntry's of the 3 built-in loaders
1080     char* start = _rw_region.top();
1081     ClassLoaderDataShared::allocate_archived_tables();
1082     ArchiveBuilder::alloc_stats()->record_modules(_rw_region.top() - start, /*read_only*/false);
1083 #endif
1084   }
1085   {
1086     _rw_region.pack(&_ro_region);
1087     builder.dump_ro_region();
1088 #if INCLUDE_CDS_JAVA_HEAP
1089     char* start = _ro_region.top();
1090     ClassLoaderDataShared::init_archived_tables();
1091     ArchiveBuilder::alloc_stats()->record_modules(_ro_region.top() - start, /*read_only*/true);
1092 #endif
1093   }
1094   builder.relocate_pointers();
1095 
1096   dump_symbols();
1097 
1098   // Dump supported java heap objects
1099   _closed_archive_heap_regions = NULL;
1100   _open_archive_heap_regions = NULL;
1101   dump_java_heap_objects();
1102 
1103   builder.relocate_well_known_klasses();
1104 
1105   char* serialized_data = dump_read_only_tables();
1106   _ro_region.pack();
1107 
1108   // The vtable clones contain addresses of the current process.
1109   // We don't want to write these addresses into the archive. Same for i2i buffer.
1110   MetaspaceShared::zero_cpp_vtable_clones_for_writing();
1111   memset(MetaspaceShared::i2i_entry_code_buffers(), 0,
1112          MetaspaceShared::i2i_entry_code_buffers_size());
1113 
1114   // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
1115   // without runtime relocation.
1116   relocate_to_requested_base_address(&ptrmap);
1117 
1118   // Create and write the archive file that maps the shared spaces.
1119 
1120   FileMapInfo* mapinfo = new FileMapInfo(true);
1121   mapinfo->populate_header(os::vm_allocation_granularity());
1122   mapinfo->set_serialized_data(serialized_data);
1123   mapinfo->set_cloned_vtables(cloned_vtables);
1124   mapinfo->set_i2i_entry_code_buffers(MetaspaceShared::i2i_entry_code_buffers(),
1125                                       MetaspaceShared::i2i_entry_code_buffers_size());
1126   mapinfo->open_for_write();
1127   MetaspaceShared::write_core_archive_regions(mapinfo, _closed_archive_heap_oopmaps, _open_archive_heap_oopmaps);
1128   _total_closed_archive_region_size = mapinfo->write_archive_heap_regions(
1129                                         _closed_archive_heap_regions,
1130                                         _closed_archive_heap_oopmaps,
1131                                         MetaspaceShared::first_closed_archive_heap_region,
1132                                         MetaspaceShared::max_closed_archive_heap_region);
1133   _total_open_archive_region_size = mapinfo->write_archive_heap_regions(
1134                                         _open_archive_heap_regions,
1135                                         _open_archive_heap_oopmaps,
1136                                         MetaspaceShared::first_open_archive_heap_region,
1137                                         MetaspaceShared::max_open_archive_heap_region);
1138 
1139   mapinfo->set_final_requested_base((char*)MetaspaceShared::requested_base_address());
1140   mapinfo->set_header_crc(mapinfo->compute_header_crc());
1141   mapinfo->write_header();
1142   print_region_stats(mapinfo);
1143   mapinfo->close();
1144 
1145   if (log_is_enabled(Info, cds)) {
1146     builder.print_stats(int(_ro_region.used()), int(_rw_region.used()), int(_mc_region.used()));
1147   }
1148 
1149   if (PrintSystemDictionaryAtExit) {
1150     SystemDictionary::print();
1151   }
1152 
1153   if (AllowArchivingWithJavaAgent) {
1154     warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1155             "for testing purposes only and should not be used in a production environment");
1156   }
1157 
1158   // There may be other pending VM operations that operate on the InstanceKlasses,
1159   // which will fail because InstanceKlasses::remove_unshareable_info()
1160   // has been called. Forget these operations and exit the VM directly.
1161   vm_direct_exit(0);
1162 }
1163 
1164 void VM_PopulateDumpSharedSpace::print_region_stats(FileMapInfo *map_info) {
1165   // Print statistics of all the regions
1166   const size_t bitmap_used = map_info->space_at(MetaspaceShared::bm)->used();
1167   const size_t bitmap_reserved = map_info->space_at(MetaspaceShared::bm)->used_aligned();
1168   const size_t total_reserved = _ro_region.reserved()  + _rw_region.reserved() +
1169                                 _mc_region.reserved()  +
1170                                 bitmap_reserved +
1171                                 _total_closed_archive_region_size +
1172                                 _total_open_archive_region_size;
1173   const size_t total_bytes = _ro_region.used()  + _rw_region.used() +
1174                              _mc_region.used()  +
1175                              bitmap_used +
1176                              _total_closed_archive_region_size +
1177                              _total_open_archive_region_size;
1178   const double total_u_perc = percent_of(total_bytes, total_reserved);
1179 
1180   _mc_region.print(total_reserved);
1181   _rw_region.print(total_reserved);
1182   _ro_region.print(total_reserved);
1183   print_bitmap_region_stats(bitmap_used, total_reserved);
1184   print_heap_region_stats(_closed_archive_heap_regions, "ca", total_reserved);
1185   print_heap_region_stats(_open_archive_heap_regions, "oa", total_reserved);
1186 
1187   log_debug(cds)("total    : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]",
1188                  total_bytes, total_reserved, total_u_perc);
1189 }
1190 
1191 void VM_PopulateDumpSharedSpace::print_bitmap_region_stats(size_t size, size_t total_size) {
1192   log_debug(cds)("bm  space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used]",
1193                  size, size/double(total_size)*100.0, size);
1194 }
1195 
1196 void VM_PopulateDumpSharedSpace::print_heap_region_stats(GrowableArray<MemRegion> *heap_mem,
1197                                                          const char *name, size_t total_size) {
1198   int arr_len = heap_mem == NULL ? 0 : heap_mem->length();
1199   for (int i = 0; i < arr_len; i++) {
1200       char* start = (char*)heap_mem->at(i).start();
1201       size_t size = heap_mem->at(i).byte_size();
1202       char* top = start + size;
1203       log_debug(cds)("%s%d space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used] at " INTPTR_FORMAT,
1204                      name, i, size, size/double(total_size)*100.0, size, p2i(start));
1205 
1206   }
1207 }
1208 
1209 void MetaspaceShared::write_core_archive_regions(FileMapInfo* mapinfo,
1210                                                  GrowableArray<ArchiveHeapOopmapInfo>* closed_oopmaps,
1211                                                  GrowableArray<ArchiveHeapOopmapInfo>* open_oopmaps) {
1212   // Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with
1213   // MetaspaceShared::n_regions (internal to hotspot).
1214   assert(NUM_CDS_REGIONS == MetaspaceShared::n_regions, "sanity");
1215 
1216   // mc contains the trampoline code for method entries, which are patched at run time,
1217   // so it needs to be read/write.
1218   write_region(mapinfo, mc, &_mc_region, /*read_only=*/false,/*allow_exec=*/true);
1219   write_region(mapinfo, rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);
1220   write_region(mapinfo, ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);
1221   mapinfo->write_bitmap_region(ArchivePtrMarker::ptrmap(), closed_oopmaps, open_oopmaps);
1222 }
1223 
1224 void MetaspaceShared::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only,  bool allow_exec) {
1225   mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);
1226 }
1227 
1228 // Update a Java object to point its Klass* to the new location after
1229 // shared archive has been compacted.
1230 void MetaspaceShared::relocate_klass_ptr(oop o) {
1231   assert(DumpSharedSpaces, "sanity");
1232   Klass* k = ArchiveBuilder::get_relocated_klass(o->klass());
1233   o->set_klass(k);
1234 }
1235 
1236 Klass* MetaspaceShared::get_relocated_klass(Klass *k, bool is_final) {
1237   assert(DumpSharedSpaces, "sanity");
1238   k = ArchiveBuilder::get_relocated_klass(k);
1239   if (is_final) {
1240     k = (Klass*)(address(k) + final_delta());
1241   }
1242   return k;
1243 }
1244 
1245 Symbol* MetaspaceShared::get_relocated_symbol(Symbol* orig_symbol) {
1246   return ArchiveBuilder::get_relocated_symbol(orig_symbol);
1247 }
1248 
1249 class LinkSharedClassesClosure : public KlassClosure {
1250   Thread* THREAD;
1251   bool    _made_progress;
1252  public:
1253   LinkSharedClassesClosure(Thread* thread) : THREAD(thread), _made_progress(false) {}
1254 
1255   void reset()               { _made_progress = false; }
1256   bool made_progress() const { return _made_progress; }
1257 
1258   void do_klass(Klass* k) {
1259     if (k->is_instance_klass()) {
1260       InstanceKlass* ik = InstanceKlass::cast(k);
1261       // For dynamic CDS dump, only link classes loaded by the builtin class loaders.
1262       bool do_linking = DumpSharedSpaces ? true : !ik->is_shared_unregistered_class();
1263       if (do_linking) {
1264         // Link the class to cause the bytecodes to be rewritten and the
1265         // cpcache to be created. Class verification is done according
1266         // to -Xverify setting.
1267         _made_progress |= MetaspaceShared::try_link_class(ik, THREAD);
1268         guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1269 
1270         if (DumpSharedSpaces) {
1271           // The following function is used to resolve all Strings in the statically
1272           // dumped classes to archive all the Strings. The archive heap is not supported
1273           // for the dynamic archive.
1274           ik->constants()->resolve_class_constants(THREAD);
1275         }
1276       }
1277     }
1278   }
1279 };
1280 
1281 void MetaspaceShared::link_and_cleanup_shared_classes(TRAPS) {
1282   // We need to iterate because verification may cause additional classes
1283   // to be loaded.
1284   LinkSharedClassesClosure link_closure(THREAD);
1285   do {
1286     link_closure.reset();
1287     ClassLoaderDataGraph::unlocked_loaded_classes_do(&link_closure);
1288     guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1289   } while (link_closure.made_progress());
1290 }
1291 
1292 void MetaspaceShared::prepare_for_dumping() {
1293   Arguments::check_unsupported_dumping_properties();
1294   ClassLoader::initialize_shared_path();
1295 }
1296 
1297 // Preload classes from a list, populate the shared spaces and dump to a
1298 // file.
1299 void MetaspaceShared::preload_and_dump(TRAPS) {
1300   { TraceTime timer("Dump Shared Spaces", TRACETIME_LOG(Info, startuptime));
1301     ResourceMark rm(THREAD);
1302     char class_list_path_str[JVM_MAXPATHLEN];
1303     // Preload classes to be shared.
1304     const char* class_list_path;
1305     if (SharedClassListFile == NULL) {
1306       // Construct the path to the class list (in jre/lib)
1307       // Walk up two directories from the location of the VM and
1308       // optionally tack on "lib" (depending on platform)
1309       os::jvm_path(class_list_path_str, sizeof(class_list_path_str));
1310       for (int i = 0; i < 3; i++) {
1311         char *end = strrchr(class_list_path_str, *os::file_separator());
1312         if (end != NULL) *end = '\0';
1313       }
1314       int class_list_path_len = (int)strlen(class_list_path_str);
1315       if (class_list_path_len >= 3) {
1316         if (strcmp(class_list_path_str + class_list_path_len - 3, "lib") != 0) {
1317           if (class_list_path_len < JVM_MAXPATHLEN - 4) {
1318             jio_snprintf(class_list_path_str + class_list_path_len,
1319                          sizeof(class_list_path_str) - class_list_path_len,
1320                          "%slib", os::file_separator());
1321             class_list_path_len += 4;
1322           }
1323         }
1324       }
1325       if (class_list_path_len < JVM_MAXPATHLEN - 10) {
1326         jio_snprintf(class_list_path_str + class_list_path_len,
1327                      sizeof(class_list_path_str) - class_list_path_len,
1328                      "%sclasslist", os::file_separator());
1329       }
1330       class_list_path = class_list_path_str;
1331     } else {
1332       class_list_path = SharedClassListFile;
1333     }
1334 
1335     log_info(cds)("Loading classes to share ...");
1336     _has_error_classes = false;
1337     int class_count = preload_classes(class_list_path, THREAD);
1338     if (ExtraSharedClassListFile) {
1339       class_count += preload_classes(ExtraSharedClassListFile, THREAD);
1340     }
1341     log_info(cds)("Loading classes to share: done.");
1342 
1343     log_info(cds)("Shared spaces: preloaded %d classes", class_count);
1344 
1345     if (SharedArchiveConfigFile) {
1346       log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
1347       read_extra_data(SharedArchiveConfigFile, THREAD);
1348     }
1349     log_info(cds)("Reading extra data: done.");
1350 
1351     HeapShared::init_subgraph_entry_fields(THREAD);
1352 
1353     // Rewrite and link classes
1354     log_info(cds)("Rewriting and linking classes ...");
1355 
1356     // Link any classes which got missed. This would happen if we have loaded classes that
1357     // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
1358     // fails verification, all other interfaces that were not specified in the classlist but
1359     // are implemented by K are not verified.
1360     link_and_cleanup_shared_classes(CATCH);
1361     log_info(cds)("Rewriting and linking classes: done");
1362 
1363 #if INCLUDE_CDS_JAVA_HEAP
1364     if (use_full_module_graph()) {
1365       HeapShared::reset_archived_object_states(THREAD);
1366     }
1367 #endif
1368 
1369     VM_PopulateDumpSharedSpace op;
1370     MutexLocker ml(THREAD, HeapShared::is_heap_object_archiving_allowed() ?
1371                    Heap_lock : NULL);     // needed by HeapShared::run_gc()
1372     VMThread::execute(&op);
1373   }
1374 }
1375 
1376 
1377 int MetaspaceShared::preload_classes(const char* class_list_path, TRAPS) {
1378   ClassListParser parser(class_list_path);
1379   int class_count = 0;
1380 
1381   while (parser.parse_one_line()) {
1382     Klass* klass = parser.load_current_class(THREAD);
1383     if (HAS_PENDING_EXCEPTION) {
1384       if (klass == NULL &&
1385           (PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_ClassNotFoundException())) {
1386         // print a warning only when the pending exception is class not found
1387         log_warning(cds)("Preload Warning: Cannot find %s", parser.current_class_name());
1388       }
1389       CLEAR_PENDING_EXCEPTION;
1390     }
1391     if (klass != NULL) {
1392       if (log_is_enabled(Trace, cds)) {
1393         ResourceMark rm(THREAD);
1394         log_trace(cds)("Shared spaces preloaded: %s", klass->external_name());
1395       }
1396 
1397       if (klass->is_instance_klass()) {
1398         InstanceKlass* ik = InstanceKlass::cast(klass);
1399 
1400         // Link the class to cause the bytecodes to be rewritten and the
1401         // cpcache to be created. The linking is done as soon as classes
1402         // are loaded in order that the related data structures (klass and
1403         // cpCache) are located together.
1404         try_link_class(ik, THREAD);
1405         guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1406       }
1407 
1408       class_count++;
1409     }
1410   }
1411 
1412   return class_count;
1413 }
1414 
1415 // Returns true if the class's status has changed
1416 bool MetaspaceShared::try_link_class(InstanceKlass* ik, TRAPS) {
1417   Arguments::assert_is_dumping_archive();
1418   if (ik->init_state() < InstanceKlass::linked &&
1419       !SystemDictionaryShared::has_class_failed_verification(ik)) {
1420     bool saved = BytecodeVerificationLocal;
1421     if (ik->is_shared_unregistered_class() && ik->class_loader() == NULL) {
1422       // The verification decision is based on BytecodeVerificationRemote
1423       // for non-system classes. Since we are using the NULL classloader
1424       // to load non-system classes for customized class loaders during dumping,
1425       // we need to temporarily change BytecodeVerificationLocal to be the same as
1426       // BytecodeVerificationRemote. Note this can cause the parent system
1427       // classes also being verified. The extra overhead is acceptable during
1428       // dumping.
1429       BytecodeVerificationLocal = BytecodeVerificationRemote;
1430     }
1431     ik->link_class(THREAD);
1432     if (HAS_PENDING_EXCEPTION) {
1433       ResourceMark rm(THREAD);
1434       log_warning(cds)("Preload Warning: Verification failed for %s",
1435                     ik->external_name());
1436       CLEAR_PENDING_EXCEPTION;
1437       SystemDictionaryShared::set_class_has_failed_verification(ik);
1438       _has_error_classes = true;
1439     }
1440     BytecodeVerificationLocal = saved;
1441     return true;
1442   } else {
1443     return false;
1444   }
1445 }
1446 
1447 #if INCLUDE_CDS_JAVA_HEAP
1448 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() {
1449   // The closed and open archive heap space has maximum two regions.
1450   // See FileMapInfo::write_archive_heap_regions() for details.
1451   _closed_archive_heap_regions = new GrowableArray<MemRegion>(2);
1452   _open_archive_heap_regions = new GrowableArray<MemRegion>(2);
1453   HeapShared::archive_java_heap_objects(_closed_archive_heap_regions,
1454                                         _open_archive_heap_regions);
1455   ArchiveBuilder::OtherROAllocMark mark;
1456   HeapShared::write_subgraph_info_table();
1457 }
1458 
1459 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps() {
1460   if (HeapShared::is_heap_object_archiving_allowed()) {
1461     _closed_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
1462     dump_archive_heap_oopmaps(_closed_archive_heap_regions, _closed_archive_heap_oopmaps);
1463 
1464     _open_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
1465     dump_archive_heap_oopmaps(_open_archive_heap_regions, _open_archive_heap_oopmaps);
1466   }
1467 }
1468 
1469 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
1470                                                            GrowableArray<ArchiveHeapOopmapInfo>* oopmaps) {
1471   for (int i=0; i<regions->length(); i++) {
1472     ResourceBitMap oopmap = HeapShared::calculate_oopmap(regions->at(i));
1473     size_t size_in_bits = oopmap.size();
1474     size_t size_in_bytes = oopmap.size_in_bytes();
1475     uintptr_t* buffer = (uintptr_t*)NEW_C_HEAP_ARRAY(char, size_in_bytes, mtInternal);
1476     oopmap.write_to(buffer, size_in_bytes);
1477     log_info(cds, heap)("Oopmap = " INTPTR_FORMAT " (" SIZE_FORMAT_W(6) " bytes) for heap region "
1478                         INTPTR_FORMAT " (" SIZE_FORMAT_W(8) " bytes)",
1479                         p2i(buffer), size_in_bytes,
1480                         p2i(regions->at(i).start()), regions->at(i).byte_size());
1481 
1482     ArchiveHeapOopmapInfo info;
1483     info._oopmap = (address)buffer;
1484     info._oopmap_size_in_bits = size_in_bits;
1485     info._oopmap_size_in_bytes = size_in_bytes;
1486     oopmaps->append(info);
1487   }
1488 }
1489 #endif // INCLUDE_CDS_JAVA_HEAP
1490 
1491 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
1492   assert(base <= static_top && static_top <= top, "must be");
1493   _shared_metaspace_static_top = static_top;
1494   MetaspaceObj::set_shared_metaspace_range(base, top);
1495 }
1496 
1497 // Return true if given address is in the misc data region
1498 bool MetaspaceShared::is_in_shared_region(const void* p, int idx) {
1499   return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx);
1500 }
1501 
1502 bool MetaspaceShared::is_in_trampoline_frame(address addr) {
1503   if (UseSharedSpaces && is_in_shared_region(addr, MetaspaceShared::mc)) {
1504     return true;
1505   }
1506   return false;
1507 }
1508 
1509 bool MetaspaceShared::is_shared_dynamic(void* p) {
1510   if ((p < MetaspaceObj::shared_metaspace_top()) &&
1511       (p >= _shared_metaspace_static_top)) {
1512     return true;
1513   } else {
1514     return false;
1515   }
1516 }
1517 
1518 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
1519   assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");
1520   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1521 
1522   FileMapInfo* static_mapinfo = open_static_archive();
1523   FileMapInfo* dynamic_mapinfo = NULL;
1524 
1525   if (static_mapinfo != NULL) {
1526     dynamic_mapinfo = open_dynamic_archive();
1527 
1528     // First try to map at the requested address
1529     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1530     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1531       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1532       // by the OS.
1533       log_info(cds)("Try to map archive(s) at an alternative address");
1534       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1535     }
1536   }
1537 
1538   if (result == MAP_ARCHIVE_SUCCESS) {
1539     bool dynamic_mapped = (dynamic_mapinfo != NULL && dynamic_mapinfo->is_mapped());
1540     char* cds_base = static_mapinfo->mapped_base();
1541     char* cds_end =  dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
1542     set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
1543     _relocation_delta = static_mapinfo->relocation_delta();
1544     if (dynamic_mapped) {
1545       FileMapInfo::set_shared_path_table(dynamic_mapinfo);
1546     } else {
1547       FileMapInfo::set_shared_path_table(static_mapinfo);
1548     }
1549     _requested_base_address = static_mapinfo->requested_base_address();
1550   } else {
1551     set_shared_metaspace_range(NULL, NULL, NULL);
1552     UseSharedSpaces = false;
1553     FileMapInfo::fail_continue("Unable to map shared spaces");
1554     if (PrintSharedArchiveAndExit) {
1555       vm_exit_during_initialization("Unable to use shared archive.");
1556     }
1557   }
1558 
1559   if (static_mapinfo != NULL && !static_mapinfo->is_mapped()) {
1560     delete static_mapinfo;
1561   }
1562   if (dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped()) {
1563     delete dynamic_mapinfo;
1564   }
1565 }
1566 
1567 FileMapInfo* MetaspaceShared::open_static_archive() {
1568   FileMapInfo* mapinfo = new FileMapInfo(true);
1569   if (!mapinfo->initialize()) {
1570     delete(mapinfo);
1571     return NULL;
1572   }
1573   return mapinfo;
1574 }
1575 
1576 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1577   if (DynamicDumpSharedSpaces) {
1578     return NULL;
1579   }
1580   if (Arguments::GetSharedDynamicArchivePath() == NULL) {
1581     return NULL;
1582   }
1583 
1584   FileMapInfo* mapinfo = new FileMapInfo(false);
1585   if (!mapinfo->initialize()) {
1586     delete(mapinfo);
1587     return NULL;
1588   }
1589   return mapinfo;
1590 }
1591 
1592 // use_requested_addr:
1593 //  true  = map at FileMapHeader::_requested_base_address
1594 //  false = map at an alternative address picked by OS.
1595 MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,
1596                                                bool use_requested_addr) {
1597   if (use_requested_addr && static_mapinfo->requested_base_address() == NULL) {
1598     log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.");
1599     return MAP_ARCHIVE_MMAP_FAILURE;
1600   }
1601 
1602   PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1603       // For product build only -- this is for benchmarking the cost of doing relocation.
1604       // For debug builds, the check is done below, after reserving the space, for better test coverage
1605       // (see comment below).
1606       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1607       return MAP_ARCHIVE_MMAP_FAILURE;
1608     });
1609 
1610   if (ArchiveRelocationMode == 2 && !use_requested_addr) {
1611     log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");
1612     return MAP_ARCHIVE_MMAP_FAILURE;
1613   };
1614 
1615   if (dynamic_mapinfo != NULL) {
1616     // Ensure that the OS won't be able to allocate new memory spaces between the two
1617     // archives, or else it would mess up the simple comparision in MetaspaceObj::is_shared().
1618     assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");
1619   }
1620 
1621   ReservedSpace archive_space_rs, class_space_rs;
1622   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1623   char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo, dynamic_mapinfo,
1624                                                                  use_requested_addr, archive_space_rs,
1625                                                                  class_space_rs);
1626   if (mapped_base_address == NULL) {
1627     result = MAP_ARCHIVE_MMAP_FAILURE;
1628     log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr);
1629   } else {
1630 
1631 #ifdef ASSERT
1632     // Some sanity checks after reserving address spaces for archives
1633     //  and class space.
1634     assert(archive_space_rs.is_reserved(), "Sanity");
1635     if (Metaspace::using_class_space()) {
1636       // Class space must closely follow the archive space. Both spaces
1637       //  must be aligned correctly.
1638       assert(class_space_rs.is_reserved(),
1639              "A class space should have been reserved");
1640       assert(class_space_rs.base() >= archive_space_rs.end(),
1641              "class space should follow the cds archive space");
1642       assert(is_aligned(archive_space_rs.base(),
1643                         MetaspaceShared::reserved_space_alignment()),
1644              "Archive space misaligned");
1645       assert(is_aligned(class_space_rs.base(),
1646                         Metaspace::reserve_alignment()),
1647              "class space misaligned");
1648     }
1649 #endif // ASSERT
1650 
1651     log_debug(cds)("Reserved archive_space_rs     [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
1652                    p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size());
1653     log_debug(cds)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
1654                    p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());
1655 
1656     if (MetaspaceShared::use_windows_memory_mapping()) {
1657       // We have now reserved address space for the archives, and will map in
1658       //  the archive files into this space.
1659       //
1660       // Special handling for Windows: on Windows we cannot map a file view
1661       //  into an existing memory mapping. So, we unmap the address range we
1662       //  just reserved again, which will make it available for mapping the
1663       //  archives.
1664       // Reserving this range has not been for naught however since it makes
1665       //  us reasonably sure the address range is available.
1666       //
1667       // But still it may fail, since between unmapping the range and mapping
1668       //  in the archive someone else may grab the address space. Therefore
1669       //  there is a fallback in FileMap::map_region() where we just read in
1670       //  the archive files sequentially instead of mapping it in. We couple
1671       //  this with use_requested_addr, since we're going to patch all the
1672       //  pointers anyway so there's no benefit to mmap.
1673       if (use_requested_addr) {
1674         log_info(cds)("Windows mmap workaround: releasing archive space.");
1675         archive_space_rs.release();
1676       }
1677     }
1678     MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);
1679     MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?
1680                                      map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;
1681 
1682     DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1683       // This is for simulating mmap failures at the requested address. In
1684       //  debug builds, we do it here (after all archives have possibly been
1685       //  mapped), so we can thoroughly test the code for failure handling
1686       //  (releasing all allocated resource, etc).
1687       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1688       if (static_result == MAP_ARCHIVE_SUCCESS) {
1689         static_result = MAP_ARCHIVE_MMAP_FAILURE;
1690       }
1691       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1692         dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;
1693       }
1694     });
1695 
1696     if (static_result == MAP_ARCHIVE_SUCCESS) {
1697       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1698         result = MAP_ARCHIVE_SUCCESS;
1699       } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {
1700         assert(dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped(), "must have failed");
1701         // No need to retry mapping the dynamic archive again, as it will never succeed
1702         // (bad file, etc) -- just keep the base archive.
1703         log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",
1704                                   dynamic_mapinfo->full_path());
1705         result = MAP_ARCHIVE_SUCCESS;
1706         // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no
1707         // easy API to do that right now.
1708       } else {
1709         result = MAP_ARCHIVE_MMAP_FAILURE;
1710       }
1711     } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {
1712       result = MAP_ARCHIVE_OTHER_FAILURE;
1713     } else {
1714       result = MAP_ARCHIVE_MMAP_FAILURE;
1715     }
1716   }
1717 
1718   if (result == MAP_ARCHIVE_SUCCESS) {
1719     SharedBaseAddress = (size_t)mapped_base_address;
1720     LP64_ONLY({
1721         if (Metaspace::using_class_space()) {
1722           // Set up ccs in metaspace.
1723           Metaspace::initialize_class_space(class_space_rs);
1724 
1725           // Set up compressed Klass pointer encoding: the encoding range must
1726           //  cover both archive and class space.
1727           address cds_base = (address)static_mapinfo->mapped_base();
1728           address ccs_end = (address)class_space_rs.end();
1729           CompressedKlassPointers::initialize(cds_base, ccs_end - cds_base);
1730 
1731           // map_heap_regions() compares the current narrow oop and klass encodings
1732           // with the archived ones, so it must be done after all encodings are determined.
1733           static_mapinfo->map_heap_regions();
1734         }
1735       });
1736     log_info(cds)("optimized module handling: %s", MetaspaceShared::use_optimized_module_handling() ? "enabled" : "disabled");
1737     log_info(cds)("full module graph: %s", MetaspaceShared::use_full_module_graph() ? "enabled" : "disabled");
1738   } else {
1739     unmap_archive(static_mapinfo);
1740     unmap_archive(dynamic_mapinfo);
1741     release_reserved_spaces(archive_space_rs, class_space_rs);
1742   }
1743 
1744   return result;
1745 }
1746 
1747 
1748 // This will reserve two address spaces suitable to house Klass structures, one
1749 //  for the cds archives (static archive and optionally dynamic archive) and
1750 //  optionally one move for ccs.
1751 //
1752 // Since both spaces must fall within the compressed class pointer encoding
1753 //  range, they are allocated close to each other.
1754 //
1755 // Space for archives will be reserved first, followed by a potential gap,
1756 //  followed by the space for ccs:
1757 //
1758 // +-- Base address             A        B                     End
1759 // |                            |        |                      |
1760 // v                            v        v                      v
1761 // +-------------+--------------+        +----------------------+
1762 // | static arc  | [dyn. arch]  | [gap]  | compr. class space   |
1763 // +-------------+--------------+        +----------------------+
1764 //
1765 // (The gap may result from different alignment requirements between metaspace
1766 //  and CDS)
1767 //
1768 // If UseCompressedClassPointers is disabled, only one address space will be
1769 //  reserved:
1770 //
1771 // +-- Base address             End
1772 // |                            |
1773 // v                            v
1774 // +-------------+--------------+
1775 // | static arc  | [dyn. arch]  |
1776 // +-------------+--------------+
1777 //
1778 // Base address: If use_archive_base_addr address is true, the Base address is
1779 //  determined by the address stored in the static archive. If
1780 //  use_archive_base_addr address is false, this base address is determined
1781 //  by the platform.
1782 //
1783 // If UseCompressedClassPointers=1, the range encompassing both spaces will be
1784 //  suitable to en/decode narrow Klass pointers: the base will be valid for
1785 //  encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax.
1786 //
1787 // Return:
1788 //
1789 // - On success:
1790 //    - archive_space_rs will be reserved and large enough to host static and
1791 //      if needed dynamic archive: [Base, A).
1792 //      archive_space_rs.base and size will be aligned to CDS reserve
1793 //      granularity.
1794 //    - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will
1795 //      be reserved. Its start address will be aligned to metaspace reserve
1796 //      alignment, which may differ from CDS alignment. It will follow the cds
1797 //      archive space, close enough such that narrow class pointer encoding
1798 //      covers both spaces.
1799 //      If UseCompressedClassPointers=0, class_space_rs remains unreserved.
1800 // - On error: NULL is returned and the spaces remain unreserved.
1801 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,
1802                                                           FileMapInfo* dynamic_mapinfo,
1803                                                           bool use_archive_base_addr,
1804                                                           ReservedSpace& archive_space_rs,
1805                                                           ReservedSpace& class_space_rs) {
1806 
1807   address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : NULL);
1808   const size_t archive_space_alignment = MetaspaceShared::reserved_space_alignment();
1809 
1810   // Size and requested location of the archive_space_rs (for both static and dynamic archives)
1811   assert(static_mapinfo->mapping_base_offset() == 0, "Must be");
1812   size_t archive_end_offset  = (dynamic_mapinfo == NULL) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();
1813   size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);
1814 
1815   // If a base address is given, it must have valid alignment and be suitable as encoding base.
1816   if (base_address != NULL) {
1817     assert(is_aligned(base_address, archive_space_alignment),
1818            "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
1819     if (Metaspace::using_class_space()) {
1820       assert(CompressedKlassPointers::is_valid_base(base_address),
1821              "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
1822     }
1823   }
1824 
1825   if (!Metaspace::using_class_space()) {
1826     // Get the simple case out of the way first:
1827     // no compressed class space, simple allocation.
1828     archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
1829                                      false /* bool large */, (char*)base_address);
1830     if (archive_space_rs.is_reserved()) {
1831       assert(base_address == NULL ||
1832              (address)archive_space_rs.base() == base_address, "Sanity");
1833       // Register archive space with NMT.
1834       MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
1835       return archive_space_rs.base();
1836     }
1837     return NULL;
1838   }
1839 
1840 #ifdef _LP64
1841 
1842   // Complex case: two spaces adjacent to each other, both to be addressable
1843   //  with narrow class pointers.
1844   // We reserve the whole range spanning both spaces, then split that range up.
1845 
1846   const size_t class_space_alignment = Metaspace::reserve_alignment();
1847 
1848   // To simplify matters, lets assume that metaspace alignment will always be
1849   //  equal or a multiple of archive alignment.
1850   assert(is_power_of_2(class_space_alignment) &&
1851                        is_power_of_2(archive_space_alignment) &&
1852                        class_space_alignment >= archive_space_alignment,
1853                        "Sanity");
1854 
1855   const size_t class_space_size = CompressedClassSpaceSize;
1856   assert(CompressedClassSpaceSize > 0 &&
1857          is_aligned(CompressedClassSpaceSize, class_space_alignment),
1858          "CompressedClassSpaceSize malformed: "
1859          SIZE_FORMAT, CompressedClassSpaceSize);
1860 
1861   const size_t ccs_begin_offset = align_up(base_address + archive_space_size,
1862                                            class_space_alignment) - base_address;
1863   const size_t gap_size = ccs_begin_offset - archive_space_size;
1864 
1865   const size_t total_range_size =
1866       align_up(archive_space_size + gap_size + class_space_size,
1867                os::vm_allocation_granularity());
1868 
1869   ReservedSpace total_rs;
1870   if (base_address != NULL) {
1871     // Reserve at the given archive base address, or not at all.
1872     total_rs = ReservedSpace(total_range_size, archive_space_alignment,
1873                              false /* bool large */, (char*) base_address);
1874   } else {
1875     // Reserve at any address, but leave it up to the platform to choose a good one.
1876     total_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size);
1877   }
1878 
1879   if (!total_rs.is_reserved()) {
1880     return NULL;
1881   }
1882 
1883   // Paranoid checks:
1884   assert(base_address == NULL || (address)total_rs.base() == base_address,
1885          "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_rs.base()));
1886   assert(is_aligned(total_rs.base(), archive_space_alignment), "Sanity");
1887   assert(total_rs.size() == total_range_size, "Sanity");
1888   assert(CompressedKlassPointers::is_valid_base((address)total_rs.base()), "Sanity");
1889 
1890   // Now split up the space into ccs and cds archive. For simplicity, just leave
1891   //  the gap reserved at the end of the archive space.
1892   archive_space_rs = total_rs.first_part(ccs_begin_offset,
1893                                          (size_t)os::vm_allocation_granularity(),
1894                                          /*split=*/true);
1895   class_space_rs = total_rs.last_part(ccs_begin_offset);
1896 
1897   assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");
1898   assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");
1899   assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");
1900   assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");
1901 
1902   // NMT: fix up the space tags
1903   MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
1904   MemTracker::record_virtual_memory_type(class_space_rs.base(), mtClass);
1905 
1906   return archive_space_rs.base();
1907 
1908 #else
1909   ShouldNotReachHere();
1910   return NULL;
1911 #endif
1912 
1913 }
1914 
1915 void MetaspaceShared::release_reserved_spaces(ReservedSpace& archive_space_rs,
1916                                               ReservedSpace& class_space_rs) {
1917   if (archive_space_rs.is_reserved()) {
1918     log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
1919     archive_space_rs.release();
1920   }
1921   if (class_space_rs.is_reserved()) {
1922     log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1923     class_space_rs.release();
1924   }
1925 }
1926 
1927 static int archive_regions[]  = {MetaspaceShared::mc,
1928                                  MetaspaceShared::rw,
1929                                  MetaspaceShared::ro};
1930 static int archive_regions_count  = 3;
1931 
1932 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1933   assert(UseSharedSpaces, "must be runtime");
1934   if (mapinfo == NULL) {
1935     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1936   }
1937 
1938   mapinfo->set_is_mapped(false);
1939 
1940   if (mapinfo->alignment() != (size_t)os::vm_allocation_granularity()) {
1941     log_error(cds)("Unable to map CDS archive -- os::vm_allocation_granularity() expected: " SIZE_FORMAT
1942                    " actual: %d", mapinfo->alignment(), os::vm_allocation_granularity());
1943     return MAP_ARCHIVE_OTHER_FAILURE;
1944   }
1945 
1946   MapArchiveResult result =
1947     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1948 
1949   if (result != MAP_ARCHIVE_SUCCESS) {
1950     unmap_archive(mapinfo);
1951     return result;
1952   }
1953 
1954   if (!mapinfo->validate_shared_path_table()) {
1955     unmap_archive(mapinfo);
1956     return MAP_ARCHIVE_OTHER_FAILURE;
1957   }
1958 
1959   mapinfo->set_is_mapped(true);
1960   return MAP_ARCHIVE_SUCCESS;
1961 }
1962 
1963 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) {
1964   assert(UseSharedSpaces, "must be runtime");
1965   if (mapinfo != NULL) {
1966     mapinfo->unmap_regions(archive_regions, archive_regions_count);
1967     mapinfo->set_is_mapped(false);
1968   }
1969 }
1970 
1971 // Read the miscellaneous data from the shared file, and
1972 // serialize it out to its various destinations.
1973 
1974 void MetaspaceShared::initialize_shared_spaces() {
1975   FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1976   _i2i_entry_code_buffers = static_mapinfo->i2i_entry_code_buffers();
1977   _i2i_entry_code_buffers_size = static_mapinfo->i2i_entry_code_buffers_size();
1978   char* buffer = static_mapinfo->cloned_vtables();
1979   clone_cpp_vtables((intptr_t*)buffer);
1980 
1981   // Verify various attributes of the archive, plus initialize the
1982   // shared string/symbol tables
1983   buffer = static_mapinfo->serialized_data();
1984   intptr_t* array = (intptr_t*)buffer;
1985   ReadClosure rc(&array);
1986   serialize(&rc);
1987 
1988   // Initialize the run-time symbol table.
1989   SymbolTable::create_table();
1990 
1991   static_mapinfo->patch_archived_heap_embedded_pointers();
1992 
1993   // Close the mapinfo file
1994   static_mapinfo->close();
1995 
1996   static_mapinfo->unmap_region(MetaspaceShared::bm);
1997 
1998   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1999   if (dynamic_mapinfo != NULL) {
2000     intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
2001     ReadClosure rc(&buffer);
2002     SymbolTable::serialize_shared_table_header(&rc, false);
2003     SystemDictionaryShared::serialize_dictionary_headers(&rc, false);
2004     dynamic_mapinfo->close();
2005   }
2006 
2007   if (PrintSharedArchiveAndExit) {
2008     if (PrintSharedDictionary) {
2009       tty->print_cr("\nShared classes:\n");
2010       SystemDictionaryShared::print_on(tty);
2011     }
2012     if (FileMapInfo::current_info() == NULL || _archive_loading_failed) {
2013       tty->print_cr("archive is invalid");
2014       vm_exit(1);
2015     } else {
2016       tty->print_cr("archive is valid");
2017       vm_exit(0);
2018     }
2019   }
2020 }
2021 
2022 // JVM/TI RedefineClasses() support:
2023 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
2024   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2025 
2026   if (UseSharedSpaces) {
2027     // remap the shared readonly space to shared readwrite, private
2028     FileMapInfo* mapinfo = FileMapInfo::current_info();
2029     if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2030       return false;
2031     }
2032     if (FileMapInfo::dynamic_info() != NULL) {
2033       mapinfo = FileMapInfo::dynamic_info();
2034       if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2035         return false;
2036       }
2037     }
2038     _remapped_readwrite = true;
2039   }
2040   return true;
2041 }
2042 
2043 void MetaspaceShared::report_out_of_space(const char* name, size_t needed_bytes) {
2044   // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space.
2045   // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes
2046   // or so.
2047   _mc_region.print_out_of_space_msg(name, needed_bytes);
2048   _rw_region.print_out_of_space_msg(name, needed_bytes);
2049   _ro_region.print_out_of_space_msg(name, needed_bytes);
2050 
2051   vm_exit_during_initialization(err_msg("Unable to allocate from '%s' region", name),
2052                                 "Please reduce the number of shared classes.");
2053 }
2054 
2055 // This is used to relocate the pointers so that the base archive can be mapped at
2056 // MetaspaceShared::requested_base_address() without runtime relocation.
2057 intx MetaspaceShared::final_delta() {
2058   return intx(MetaspaceShared::requested_base_address())  // We want the base archive to be mapped to here at runtime
2059        - intx(SharedBaseAddress);                         // .. but the base archive is mapped at here at dump time
2060 }
2061 
2062 bool MetaspaceShared::use_full_module_graph() {
2063   return _use_optimized_module_handling && _use_full_module_graph &&
2064     (UseSharedSpaces || DumpSharedSpaces) && HeapShared::is_heap_object_archiving_allowed();
2065 }
2066 
2067 void MetaspaceShared::print_on(outputStream* st) {
2068   if (UseSharedSpaces || DumpSharedSpaces) {
2069     st->print("CDS archive(s) mapped at: ");
2070     address base;
2071     address top;
2072     if (UseSharedSpaces) { // Runtime
2073       base = (address)MetaspaceObj::shared_metaspace_base();
2074       address static_top = (address)_shared_metaspace_static_top;
2075       top = (address)MetaspaceObj::shared_metaspace_top();
2076       st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));
2077     } else if (DumpSharedSpaces) { // Dump Time
2078       base = (address)_shared_rs.base();
2079       top = (address)_shared_rs.end();
2080       st->print("[" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(top));
2081     }
2082     st->print("size " SIZE_FORMAT ", ", top - base);
2083     st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, (int)ArchiveRelocationMode);
2084   } else {
2085     st->print("CDS disabled.");
2086   }
2087   st->cr();
2088 }