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 "jvm.h"
  27 #include "classfile/classLoaderDataGraph.hpp"
  28 #include "classfile/classListParser.hpp"
  29 #include "classfile/classLoaderExt.hpp"
  30 #include "classfile/dictionary.hpp"
  31 #include "classfile/loaderConstraints.hpp"
  32 #include "classfile/javaClasses.inline.hpp"
  33 #include "classfile/placeholders.hpp"
  34 #include "classfile/symbolTable.hpp"
  35 #include "classfile/stringTable.hpp"
  36 #include "classfile/systemDictionary.hpp"
  37 #include "classfile/systemDictionaryShared.hpp"
  38 #include "code/codeCache.hpp"
  39 #include "gc/shared/softRefPolicy.hpp"
  40 #include "interpreter/bytecodeStream.hpp"
  41 #include "interpreter/bytecodes.hpp"
  42 #include "logging/log.hpp"
  43 #include "logging/logMessage.hpp"
  44 #include "memory/archiveUtils.inline.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 "prims/jvmtiRedefineClasses.hpp"
  63 #include "runtime/handles.inline.hpp"
  64 #include "runtime/os.hpp"
  65 #include "runtime/safepointVerifiers.hpp"
  66 #include "runtime/signature.hpp"
  67 #include "runtime/timerTrace.hpp"
  68 #include "runtime/vmThread.hpp"
  69 #include "runtime/vmOperations.hpp"
  70 #include "utilities/align.hpp"
  71 #include "utilities/bitMap.inline.hpp"
  72 #include "utilities/ostream.hpp"
  73 #include "utilities/defaultStream.hpp"
  74 #include "utilities/hashtable.inline.hpp"
  75 #if INCLUDE_G1GC
  76 #include "gc/g1/g1CollectedHeap.hpp"
  77 #endif
  78 
  79 ReservedSpace MetaspaceShared::_shared_rs;
  80 VirtualSpace MetaspaceShared::_shared_vs;
  81 ReservedSpace MetaspaceShared::_symbol_rs;
  82 VirtualSpace MetaspaceShared::_symbol_vs;
  83 MetaspaceSharedStats MetaspaceShared::_stats;
  84 bool MetaspaceShared::_has_error_classes;
  85 bool MetaspaceShared::_archive_loading_failed = false;
  86 bool MetaspaceShared::_remapped_readwrite = false;
  87 address MetaspaceShared::_i2i_entry_code_buffers = NULL;
  88 size_t MetaspaceShared::_i2i_entry_code_buffers_size = 0;
  89 void* MetaspaceShared::_shared_metaspace_static_top = NULL;
  90 intx MetaspaceShared::_relocation_delta;
  91 char* MetaspaceShared::_requested_base_address;
  92 bool MetaspaceShared::_use_optimized_module_handling = true;
  93 bool MetaspaceShared::_use_full_module_graph = true;
  94 
  95 // The CDS archive is divided into the following regions:
  96 //     mc  - misc code (the method entry trampolines, c++ vtables)
  97 //     rw  - read-write metadata
  98 //     ro  - read-only metadata and read-only tables
  99 //
 100 //     ca0 - closed archive heap space #0
 101 //     ca1 - closed archive heap space #1 (may be empty)
 102 //     oa0 - open archive heap space #0
 103 //     oa1 - open archive heap space #1 (may be empty)
 104 //
 105 // The mc, rw, and ro regions are linearly allocated, starting from
 106 // SharedBaseAddress, in the order of mc->rw->ro. The size of these 3 regions
 107 // are page-aligned, and there's no gap between any consecutive regions.
 108 //
 109 // These 3 regions are populated in the following steps:
 110 // [1] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
 111 //     temporarily allocated outside of the shared regions. Only the method entry
 112 //     trampolines are written into the mc region.
 113 // [2] C++ vtables are copied into the mc region.
 114 // [3] ArchiveCompactor copies RW metadata into the rw region.
 115 // [4] ArchiveCompactor copies RO metadata into the ro region.
 116 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
 117 //     are copied into the ro region as read-only tables.
 118 //
 119 // The s0/s1 and oa0/oa1 regions are populated inside HeapShared::archive_java_heap_objects.
 120 // Their layout is independent of the other 4 regions.
 121 
 122 char* DumpRegion::expand_top_to(char* newtop) {
 123   assert(is_allocatable(), "must be initialized and not packed");
 124   assert(newtop >= _top, "must not grow backwards");
 125   if (newtop > _end) {
 126     MetaspaceShared::report_out_of_space(_name, newtop - _top);
 127     ShouldNotReachHere();
 128   }
 129 
 130   if (_rs == MetaspaceShared::shared_rs()) {
 131     uintx delta;
 132     if (DynamicDumpSharedSpaces) {
 133       delta = DynamicArchive::object_delta_uintx(newtop);
 134     } else {
 135       delta = MetaspaceShared::object_delta_uintx(newtop);
 136     }
 137     if (delta > MAX_SHARED_DELTA) {
 138       // This is just a sanity check and should not appear in any real world usage. This
 139       // happens only if you allocate more than 2GB of shared objects and would require
 140       // millions of shared classes.
 141       vm_exit_during_initialization("Out of memory in the CDS archive",
 142                                     "Please reduce the number of shared classes.");
 143     }
 144   }
 145 
 146   MetaspaceShared::commit_to(_rs, _vs, newtop);
 147   _top = newtop;
 148   return _top;
 149 }
 150 
 151 char* DumpRegion::allocate(size_t num_bytes, size_t alignment) {
 152   char* p = (char*)align_up(_top, alignment);
 153   char* newtop = p + align_up(num_bytes, alignment);
 154   expand_top_to(newtop);
 155   memset(p, 0, newtop - p);
 156   return p;
 157 }
 158 
 159 void DumpRegion::append_intptr_t(intptr_t n, bool need_to_mark) {
 160   assert(is_aligned(_top, sizeof(intptr_t)), "bad alignment");
 161   intptr_t *p = (intptr_t*)_top;
 162   char* newtop = _top + sizeof(intptr_t);
 163   expand_top_to(newtop);
 164   *p = n;
 165   if (need_to_mark) {
 166     ArchivePtrMarker::mark_pointer(p);
 167   }
 168 }
 169 
 170 void DumpRegion::print(size_t total_bytes) const {
 171   log_debug(cds)("%-3s space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used] at " INTPTR_FORMAT,
 172                  _name, used(), percent_of(used(), total_bytes), reserved(), percent_of(used(), reserved()),
 173                  p2i(_base + MetaspaceShared::final_delta()));
 174 }
 175 
 176 void DumpRegion::print_out_of_space_msg(const char* failing_region, size_t needed_bytes) {
 177   log_error(cds)("[%-8s] " PTR_FORMAT " - " PTR_FORMAT " capacity =%9d, allocated =%9d",
 178                  _name, p2i(_base), p2i(_top), int(_end - _base), int(_top - _base));
 179   if (strcmp(_name, failing_region) == 0) {
 180     log_error(cds)(" required = %d", int(needed_bytes));
 181   }
 182 }
 183 
 184 void DumpRegion::init(ReservedSpace* rs, VirtualSpace* vs) {
 185   _rs = rs;
 186   _vs = vs;
 187   // Start with 0 committed bytes. The memory will be committed as needed by
 188   // MetaspaceShared::commit_to().
 189   if (!_vs->initialize(*_rs, 0)) {
 190     fatal("Unable to allocate memory for shared space");
 191   }
 192   _base = _top = _rs->base();
 193   _end = _rs->end();
 194 }
 195 
 196 void DumpRegion::pack(DumpRegion* next) {
 197   assert(!is_packed(), "sanity");
 198   _end = (char*)align_up(_top, MetaspaceShared::reserved_space_alignment());
 199   _is_packed = true;
 200   if (next != NULL) {
 201     next->_rs = _rs;
 202     next->_vs = _vs;
 203     next->_base = next->_top = this->_end;
 204     next->_end = _rs->end();
 205   }
 206 }
 207 
 208 static DumpRegion _mc_region("mc"), _ro_region("ro"), _rw_region("rw"), _symbol_region("symbols");
 209 static size_t _total_closed_archive_region_size = 0, _total_open_archive_region_size = 0;
 210 
 211 void MetaspaceShared::init_shared_dump_space(DumpRegion* first_space) {
 212   first_space->init(&_shared_rs, &_shared_vs);
 213 }
 214 
 215 DumpRegion* MetaspaceShared::misc_code_dump_space() {
 216   return &_mc_region;
 217 }
 218 
 219 DumpRegion* MetaspaceShared::read_write_dump_space() {
 220   return &_rw_region;
 221 }
 222 
 223 DumpRegion* MetaspaceShared::read_only_dump_space() {
 224   return &_ro_region;
 225 }
 226 
 227 void MetaspaceShared::pack_dump_space(DumpRegion* current, DumpRegion* next,
 228                                       ReservedSpace* rs) {
 229   current->pack(next);
 230 }
 231 
 232 char* MetaspaceShared::symbol_space_alloc(size_t num_bytes) {
 233   return _symbol_region.allocate(num_bytes);
 234 }
 235 
 236 char* MetaspaceShared::misc_code_space_alloc(size_t num_bytes) {
 237   return _mc_region.allocate(num_bytes);
 238 }
 239 
 240 char* MetaspaceShared::read_only_space_alloc(size_t num_bytes) {
 241   return _ro_region.allocate(num_bytes);
 242 }
 243 
 244 char* MetaspaceShared::read_write_space_alloc(size_t num_bytes) {
 245   return _rw_region.allocate(num_bytes);
 246 }
 247 
 248 size_t MetaspaceShared::reserved_space_alignment() { return os::vm_allocation_granularity(); }
 249 
 250 static bool shared_base_valid(char* shared_base) {
 251 #ifdef _LP64
 252   return CompressedKlassPointers::is_valid_base((address)shared_base);
 253 #else
 254   return true;
 255 #endif
 256 }
 257 
 258 static bool shared_base_too_high(char* shared_base, size_t cds_total) {
 259   if (SharedBaseAddress != 0 && shared_base < (char*)SharedBaseAddress) {
 260     // SharedBaseAddress is very high (e.g., 0xffffffffffffff00) so
 261     // align_up(SharedBaseAddress, MetaspaceShared::reserved_space_alignment()) has wrapped around.
 262     return true;
 263   }
 264   if (max_uintx - uintx(shared_base) < uintx(cds_total)) {
 265     // The end of the archive will wrap around
 266     return true;
 267   }
 268 
 269   return false;
 270 }
 271 
 272 static char* compute_shared_base(size_t cds_total) {
 273   char* shared_base = (char*)align_up((char*)SharedBaseAddress, MetaspaceShared::reserved_space_alignment());
 274   const char* err = NULL;
 275   if (shared_base_too_high(shared_base, cds_total)) {
 276     err = "too high";
 277   } else if (!shared_base_valid(shared_base)) {
 278     err = "invalid for this platform";
 279   }
 280   if (err) {
 281     log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
 282                      p2i((void*)SharedBaseAddress), err,
 283                      p2i((void*)Arguments::default_SharedBaseAddress()));
 284     SharedBaseAddress = Arguments::default_SharedBaseAddress();
 285     shared_base = (char*)align_up((char*)SharedBaseAddress, MetaspaceShared::reserved_space_alignment());
 286   }
 287   assert(!shared_base_too_high(shared_base, cds_total) && shared_base_valid(shared_base), "Sanity");
 288   return shared_base;
 289 }
 290 
 291 void MetaspaceShared::initialize_dumptime_shared_and_meta_spaces() {
 292   assert(DumpSharedSpaces, "should be called for dump time only");
 293 
 294   const size_t reserve_alignment = MetaspaceShared::reserved_space_alignment();
 295 
 296 #ifdef _LP64
 297   // On 64-bit VM we reserve a 4G range and, if UseCompressedClassPointers=1,
 298   //  will use that to house both the archives and the ccs. See below for
 299   //  details.
 300   const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
 301   const size_t cds_total = align_down(UnscaledClassSpaceMax, reserve_alignment);
 302 #else
 303   // We don't support archives larger than 256MB on 32-bit due to limited
 304   //  virtual address space.
 305   size_t cds_total = align_down(256*M, reserve_alignment);
 306 #endif
 307 
 308   char* shared_base = compute_shared_base(cds_total);
 309   _requested_base_address = shared_base;
 310 
 311   // Whether to use SharedBaseAddress as attach address.
 312   bool use_requested_base = true;
 313 
 314   if (shared_base == NULL) {
 315     use_requested_base = false;
 316   }
 317 
 318   if (ArchiveRelocationMode == 1) {
 319     log_info(cds)("ArchiveRelocationMode == 1: always allocate class space at an alternative address");
 320     use_requested_base = false;
 321   }
 322 
 323   // First try to reserve the space at the specified SharedBaseAddress.
 324   assert(!_shared_rs.is_reserved(), "must be");
 325   if (use_requested_base) {
 326     _shared_rs = ReservedSpace(cds_total, reserve_alignment,
 327                                false /* large */, (char*)shared_base);
 328     if (_shared_rs.is_reserved()) {
 329       assert(_shared_rs.base() == shared_base, "should match");
 330     } else {
 331       log_info(cds)("dumptime space reservation: failed to map at "
 332                     "SharedBaseAddress " PTR_FORMAT, p2i(shared_base));
 333     }
 334   }
 335   if (!_shared_rs.is_reserved()) {
 336     // Get a reserved space anywhere if attaching at the SharedBaseAddress
 337     //  fails:
 338     if (UseCompressedClassPointers) {
 339       // If we need to reserve class space as well, let the platform handle
 340       //  the reservation.
 341       LP64_ONLY(_shared_rs =
 342                 Metaspace::reserve_address_space_for_compressed_classes(cds_total);)
 343       NOT_LP64(ShouldNotReachHere();)
 344     } else {
 345       // anywhere is fine.
 346       _shared_rs = ReservedSpace(cds_total, reserve_alignment,
 347                                  false /* large */, (char*)NULL);
 348     }
 349   }
 350 
 351   if (!_shared_rs.is_reserved()) {
 352     vm_exit_during_initialization("Unable to reserve memory for shared space",
 353                                   err_msg(SIZE_FORMAT " bytes.", cds_total));
 354   }
 355 
 356 #ifdef _LP64
 357 
 358   if (UseCompressedClassPointers) {
 359 
 360     assert(CompressedKlassPointers::is_valid_base((address)_shared_rs.base()), "Sanity");
 361 
 362     // On 64-bit VM, if UseCompressedClassPointers=1, the compressed class space
 363     //  must be allocated near the cds such as that the compressed Klass pointer
 364     //  encoding can be used to en/decode pointers from both cds and ccs. Since
 365     //  Metaspace cannot do this (it knows nothing about cds), we do it for
 366     //  Metaspace here and pass it the space to use for ccs.
 367     //
 368     // We do this by reserving space for the ccs behind the archives. Note
 369     //  however that ccs follows a different alignment
 370     //  (Metaspace::reserve_alignment), so there may be a gap between ccs and
 371     //  cds.
 372     // We use a similar layout at runtime, see reserve_address_space_for_archives().
 373     //
 374     //                              +-- SharedBaseAddress (default = 0x800000000)
 375     //                              v
 376     // +-..---------+---------+ ... +----+----+----+--------+-----------------+
 377     // |    Heap    | Archive |     | MC | RW | RO | [gap]  |    class space  |
 378     // +-..---------+---------+ ... +----+----+----+--------+-----------------+
 379     // |<--   MaxHeapSize  -->|     |<-- UnscaledClassSpaceMax = 4GB -->|
 380     //
 381     // Note: ccs must follow the archives, and the archives must start at the
 382     //  encoding base. However, the exact placement of ccs does not matter as
 383     //  long as it it resides in the encoding range of CompressedKlassPointers
 384     //  and comes after the archive.
 385     //
 386     // We do this by splitting up the allocated 4G into 3G of archive space,
 387     //  followed by 1G for the ccs:
 388     // + The upper 1 GB is used as the "temporary compressed class space"
 389     //   -- preload_classes() will store Klasses into this space.
 390     // + The lower 3 GB is used for the archive -- when preload_classes()
 391     //   is done, ArchiveCompactor will copy the class metadata into this
 392     //   space, first the RW parts, then the RO parts.
 393 
 394     // Starting address of ccs must be aligned to Metaspace::reserve_alignment()...
 395     size_t class_space_size = align_down(_shared_rs.size() / 4, Metaspace::reserve_alignment());
 396     address class_space_start = (address)align_down(_shared_rs.end() - class_space_size, Metaspace::reserve_alignment());
 397     size_t archive_size = class_space_start - (address)_shared_rs.base();
 398 
 399     ReservedSpace tmp_class_space = _shared_rs.last_part(archive_size);
 400     _shared_rs = _shared_rs.first_part(archive_size);
 401 
 402     // ... as does the size of ccs.
 403     tmp_class_space = tmp_class_space.first_part(class_space_size);
 404     CompressedClassSpaceSize = class_space_size;
 405 
 406     // Let Metaspace initialize ccs
 407     Metaspace::initialize_class_space(tmp_class_space);
 408 
 409     // and set up CompressedKlassPointers encoding.
 410     CompressedKlassPointers::initialize((address)_shared_rs.base(), cds_total);
 411 
 412     log_info(cds)("narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
 413                   p2i(CompressedKlassPointers::base()), CompressedKlassPointers::shift());
 414 
 415     log_info(cds)("Allocated temporary class space: " SIZE_FORMAT " bytes at " PTR_FORMAT,
 416                   CompressedClassSpaceSize, p2i(tmp_class_space.base()));
 417 
 418     assert(_shared_rs.end() == tmp_class_space.base() &&
 419            is_aligned(_shared_rs.base(), MetaspaceShared::reserved_space_alignment()) &&
 420            is_aligned(tmp_class_space.base(), Metaspace::reserve_alignment()) &&
 421            is_aligned(tmp_class_space.size(), Metaspace::reserve_alignment()), "Sanity");
 422   }
 423 
 424 #endif
 425 
 426   init_shared_dump_space(&_mc_region);
 427   SharedBaseAddress = (size_t)_shared_rs.base();
 428   log_info(cds)("Allocated shared space: " SIZE_FORMAT " bytes at " PTR_FORMAT,
 429                 _shared_rs.size(), p2i(_shared_rs.base()));
 430 
 431   // We don't want any valid object to be at the very bottom of the archive.
 432   // See ArchivePtrMarker::mark_pointer().
 433   MetaspaceShared::misc_code_space_alloc(16);
 434 
 435   size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
 436   _symbol_rs = ReservedSpace(symbol_rs_size);
 437   if (!_symbol_rs.is_reserved()) {
 438     vm_exit_during_initialization("Unable to reserve memory for symbols",
 439                                   err_msg(SIZE_FORMAT " bytes.", symbol_rs_size));
 440   }
 441   _symbol_region.init(&_symbol_rs, &_symbol_vs);
 442 }
 443 
 444 // Called by universe_post_init()
 445 void MetaspaceShared::post_initialize(TRAPS) {
 446   if (UseSharedSpaces) {
 447     int size = FileMapInfo::get_number_of_shared_paths();
 448     if (size > 0) {
 449       SystemDictionaryShared::allocate_shared_data_arrays(size, THREAD);
 450       if (!DynamicDumpSharedSpaces) {
 451         FileMapInfo* info;
 452         if (FileMapInfo::dynamic_info() == NULL) {
 453           info = FileMapInfo::current_info();
 454         } else {
 455           info = FileMapInfo::dynamic_info();
 456         }
 457         ClassLoaderExt::init_paths_start_index(info->app_class_paths_start_index());
 458         ClassLoaderExt::init_app_module_paths_start_index(info->app_module_paths_start_index());
 459       }
 460     }
 461   }
 462 }
 463 
 464 static GrowableArrayCHeap<Handle, mtClassShared>* _extra_interned_strings = NULL;
 465 
 466 void MetaspaceShared::read_extra_data(const char* filename, TRAPS) {
 467   _extra_interned_strings = new GrowableArrayCHeap<Handle, mtClassShared>(10000);
 468 
 469   HashtableTextDump reader(filename);
 470   reader.check_version("VERSION: 1.0");
 471 
 472   while (reader.remain() > 0) {
 473     int utf8_length;
 474     int prefix_type = reader.scan_prefix(&utf8_length);
 475     ResourceMark rm(THREAD);
 476     if (utf8_length == 0x7fffffff) {
 477       // buf_len will overflown 32-bit value.
 478       vm_exit_during_initialization(err_msg("string length too large: %d", utf8_length));
 479     }
 480     int buf_len = utf8_length+1;
 481     char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len);
 482     reader.get_utf8(utf8_buffer, utf8_length);
 483     utf8_buffer[utf8_length] = '\0';
 484 
 485     if (prefix_type == HashtableTextDump::SymbolPrefix) {
 486       SymbolTable::new_permanent_symbol(utf8_buffer);
 487     } else{
 488       assert(prefix_type == HashtableTextDump::StringPrefix, "Sanity");
 489       oop s = StringTable::intern(utf8_buffer, THREAD);
 490 
 491       if (HAS_PENDING_EXCEPTION) {
 492         log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d",
 493                                reader.last_line_no(), utf8_length);
 494         CLEAR_PENDING_EXCEPTION;
 495       } else {
 496 #if INCLUDE_G1GC
 497         if (UseG1GC) {
 498           typeArrayOop body = java_lang_String::value(s);
 499           const HeapRegion* hr = G1CollectedHeap::heap()->heap_region_containing(body);
 500           if (hr->is_humongous()) {
 501             // Don't keep it alive, so it will be GC'ed before we dump the strings, in order
 502             // to maximize free heap space and minimize fragmentation.
 503             log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d",
 504                                 reader.last_line_no(), utf8_length);
 505             continue;
 506           }
 507         }
 508 #endif
 509         // Interned strings are GC'ed if there are no references to it, so let's
 510         // add a reference to keep this string alive.
 511         assert(s != NULL, "must succeed");
 512         Handle h(THREAD, s);
 513         _extra_interned_strings->append(h);
 514       }
 515     }
 516   }
 517 }
 518 
 519 void MetaspaceShared::commit_to(ReservedSpace* rs, VirtualSpace* vs, char* newtop) {
 520   Arguments::assert_is_dumping_archive();
 521   char* base = rs->base();
 522   size_t need_committed_size = newtop - base;
 523   size_t has_committed_size = vs->committed_size();
 524   if (need_committed_size < has_committed_size) {
 525     return;
 526   }
 527 
 528   size_t min_bytes = need_committed_size - has_committed_size;
 529   size_t preferred_bytes = 1 * M;
 530   size_t uncommitted = vs->reserved_size() - has_committed_size;
 531 
 532   size_t commit =MAX2(min_bytes, preferred_bytes);
 533   commit = MIN2(commit, uncommitted);
 534   assert(commit <= uncommitted, "sanity");
 535 
 536   bool result = vs->expand_by(commit, false);
 537   if (rs == &_shared_rs) {
 538     ArchivePtrMarker::expand_ptr_end((address*)vs->high());
 539   }
 540 
 541   if (!result) {
 542     vm_exit_during_initialization(err_msg("Failed to expand shared space to " SIZE_FORMAT " bytes",
 543                                           need_committed_size));
 544   }
 545 
 546   assert(rs == &_shared_rs || rs == &_symbol_rs, "must be");
 547   const char* which = (rs == &_shared_rs) ? "shared" : "symbol";
 548   log_debug(cds)("Expanding %s spaces by " SIZE_FORMAT_W(7) " bytes [total " SIZE_FORMAT_W(9)  " bytes ending at %p]",
 549                  which, commit, vs->actual_committed_size(), vs->high());
 550 }
 551 
 552 void MetaspaceShared::initialize_ptr_marker(CHeapBitMap* ptrmap) {
 553   ArchivePtrMarker::initialize(ptrmap, (address*)_shared_vs.low(), (address*)_shared_vs.high());
 554 }
 555 
 556 // Read/write a data stream for restoring/preserving metadata pointers and
 557 // miscellaneous data from/to the shared archive file.
 558 
 559 void MetaspaceShared::serialize(SerializeClosure* soc) {
 560   int tag = 0;
 561   soc->do_tag(--tag);
 562 
 563   // Verify the sizes of various metadata in the system.
 564   soc->do_tag(sizeof(Method));
 565   soc->do_tag(sizeof(ConstMethod));
 566   soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
 567   soc->do_tag(sizeof(ConstantPool));
 568   soc->do_tag(sizeof(ConstantPoolCache));
 569   soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
 570   soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
 571   soc->do_tag(sizeof(Symbol));
 572 
 573   // Dump/restore miscellaneous metadata.
 574   JavaClasses::serialize_offsets(soc);
 575   Universe::serialize(soc);
 576   soc->do_tag(--tag);
 577 
 578   // Dump/restore references to commonly used names and signatures.
 579   vmSymbols::serialize(soc);
 580   soc->do_tag(--tag);
 581 
 582   // Dump/restore the symbol/string/subgraph_info tables
 583   SymbolTable::serialize_shared_table_header(soc);
 584   StringTable::serialize_shared_table_header(soc);
 585   HeapShared::serialize_subgraph_info_table_header(soc);
 586   SystemDictionaryShared::serialize_dictionary_headers(soc);
 587 
 588   InstanceMirrorKlass::serialize_offsets(soc);
 589 
 590   // Dump/restore well known classes (pointers)
 591   SystemDictionaryShared::serialize_well_known_klasses(soc);
 592   soc->do_tag(--tag);
 593 
 594   serialize_cloned_cpp_vtptrs(soc);
 595   soc->do_tag(--tag);
 596 
 597   CDS_JAVA_HEAP_ONLY(ClassLoaderData::serialize(soc));
 598 
 599   soc->do_tag(666);
 600 }
 601 
 602 address MetaspaceShared::i2i_entry_code_buffers(size_t total_size) {
 603   if (DumpSharedSpaces) {
 604     if (_i2i_entry_code_buffers == NULL) {
 605       _i2i_entry_code_buffers = (address)misc_code_space_alloc(total_size);
 606       _i2i_entry_code_buffers_size = total_size;
 607     }
 608   } else if (UseSharedSpaces) {
 609     assert(_i2i_entry_code_buffers != NULL, "must already been initialized");
 610   } else {
 611     return NULL;
 612   }
 613 
 614   assert(_i2i_entry_code_buffers_size == total_size, "must not change");
 615   return _i2i_entry_code_buffers;
 616 }
 617 
 618 uintx MetaspaceShared::object_delta_uintx(void* obj) {
 619   Arguments::assert_is_dumping_archive();
 620   if (DumpSharedSpaces) {
 621     assert(shared_rs()->contains(obj), "must be");
 622   } else {
 623     assert(is_in_shared_metaspace(obj) || DynamicArchive::is_in_target_space(obj), "must be");
 624   }
 625   address base_address = address(SharedBaseAddress);
 626   uintx deltax = address(obj) - base_address;
 627   return deltax;
 628 }
 629 
 630 // Global object for holding classes that have been loaded.  Since this
 631 // is run at a safepoint just before exit, this is the entire set of classes.
 632 static GrowableArray<Klass*>* _global_klass_objects;
 633 
 634 static int global_klass_compare(Klass** a, Klass **b) {
 635   return a[0]->name()->fast_compare(b[0]->name());
 636 }
 637 
 638 GrowableArray<Klass*>* MetaspaceShared::collected_klasses() {
 639   return _global_klass_objects;
 640 }
 641 
 642 static void collect_array_classes(Klass* k) {
 643   _global_klass_objects->append_if_missing(k);
 644   if (k->is_array_klass()) {
 645     // Add in the array classes too
 646     ArrayKlass* ak = ArrayKlass::cast(k);
 647     Klass* h = ak->higher_dimension();
 648     if (h != NULL) {
 649       h->array_klasses_do(collect_array_classes);
 650     }
 651   }
 652 }
 653 
 654 class CollectClassesClosure : public KlassClosure {
 655   void do_klass(Klass* k) {
 656     if (k->is_instance_klass() &&
 657         SystemDictionaryShared::is_excluded_class(InstanceKlass::cast(k))) {
 658       // Don't add to the _global_klass_objects
 659     } else {
 660       _global_klass_objects->append_if_missing(k);
 661     }
 662     if (k->is_array_klass()) {
 663       // Add in the array classes too
 664       ArrayKlass* ak = ArrayKlass::cast(k);
 665       Klass* h = ak->higher_dimension();
 666       if (h != NULL) {
 667         h->array_klasses_do(collect_array_classes);
 668       }
 669     }
 670   }
 671 };
 672 
 673 // Global object for holding symbols that created during class loading. See SymbolTable::new_symbol
 674 static GrowableArray<Symbol*>* _global_symbol_objects = NULL;
 675 
 676 static int compare_symbols_by_address(Symbol** a, Symbol** b) {
 677   if (a[0] < b[0]) {
 678     return -1;
 679   } else if (a[0] == b[0]) {
 680     ResourceMark rm;
 681     log_warning(cds)("Duplicated symbol %s unexpected", (*a)->as_C_string());
 682     return 0;
 683   } else {
 684     return 1;
 685   }
 686 }
 687 
 688 void MetaspaceShared::add_symbol(Symbol* sym) {
 689   MutexLocker ml(CDSAddSymbol_lock, Mutex::_no_safepoint_check_flag);
 690   if (_global_symbol_objects == NULL) {
 691     _global_symbol_objects = new (ResourceObj::C_HEAP, mtSymbol) GrowableArray<Symbol*>(2048, mtSymbol);
 692   }
 693   _global_symbol_objects->append(sym);
 694 }
 695 
 696 GrowableArray<Symbol*>* MetaspaceShared::collected_symbols() {
 697   return _global_symbol_objects;
 698 }
 699 
 700 static void remove_unshareable_in_classes() {
 701   for (int i = 0; i < _global_klass_objects->length(); i++) {
 702     Klass* k = _global_klass_objects->at(i);
 703     if (!k->is_objArray_klass()) {
 704       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
 705       // on their array classes.
 706       assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be");
 707       k->remove_unshareable_info();
 708     }
 709   }
 710 }
 711 
 712 static void remove_java_mirror_in_classes() {
 713   for (int i = 0; i < _global_klass_objects->length(); i++) {
 714     Klass* k = _global_klass_objects->at(i);
 715     if (!k->is_objArray_klass()) {
 716       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
 717       // on their array classes.
 718       assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be");
 719       k->remove_java_mirror();
 720     }
 721   }
 722 }
 723 
 724 static void rewrite_nofast_bytecode(const methodHandle& method) {
 725   BytecodeStream bcs(method);
 726   while (!bcs.is_last_bytecode()) {
 727     Bytecodes::Code opcode = bcs.next();
 728     switch (opcode) {
 729     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
 730     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;
 731     case Bytecodes::_aload_0:       *bcs.bcp() = Bytecodes::_nofast_aload_0;       break;
 732     case Bytecodes::_iload: {
 733       if (!bcs.is_wide()) {
 734         *bcs.bcp() = Bytecodes::_nofast_iload;
 735       }
 736       break;
 737     }
 738     default: break;
 739     }
 740   }
 741 }
 742 
 743 // Walk all methods in the class list to ensure that they won't be modified at
 744 // run time. This includes:
 745 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified
 746 //     at run time by RewriteBytecodes/RewriteFrequentPairs
 747 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.
 748 static void rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread) {
 749   for (int i = 0; i < _global_klass_objects->length(); i++) {
 750     Klass* k = _global_klass_objects->at(i);
 751     if (k->is_instance_klass()) {
 752       InstanceKlass* ik = InstanceKlass::cast(k);
 753       MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(thread, ik);
 754     }
 755   }
 756 }
 757 
 758 void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) {
 759   for (int i = 0; i < ik->methods()->length(); i++) {
 760     methodHandle m(thread, ik->methods()->at(i));
 761     rewrite_nofast_bytecode(m);
 762     Fingerprinter fp(m);
 763     // The side effect of this call sets method's fingerprint field.
 764     fp.fingerprint();
 765   }
 766 }
 767 
 768 // Objects of the Metadata types (such as Klass and ConstantPool) have C++ vtables.
 769 // (In GCC this is the field <Type>::_vptr, i.e., first word in the object.)
 770 //
 771 // Addresses of the vtables and the methods may be different across JVM runs,
 772 // if libjvm.so is dynamically loaded at a different base address.
 773 //
 774 // To ensure that the Metadata objects in the CDS archive always have the correct vtable:
 775 //
 776 // + at dump time:  we redirect the _vptr to point to our own vtables inside
 777 //                  the CDS image
 778 // + at run time:   we clone the actual contents of the vtables from libjvm.so
 779 //                  into our own tables.
 780 
 781 // Currently, the archive contain ONLY the following types of objects that have C++ vtables.
 782 #define CPP_VTABLE_PATCH_TYPES_DO(f) \
 783   f(ConstantPool) \
 784   f(InstanceKlass) \
 785   f(InstanceClassLoaderKlass) \
 786   f(InstanceMirrorKlass) \
 787   f(InstanceRefKlass) \
 788   f(Method) \
 789   f(ObjArrayKlass) \
 790   f(TypeArrayKlass)
 791 
 792 class CppVtableInfo {
 793   intptr_t _vtable_size;
 794   intptr_t _cloned_vtable[1];
 795 public:
 796   static int num_slots(int vtable_size) {
 797     return 1 + vtable_size; // Need to add the space occupied by _vtable_size;
 798   }
 799   int vtable_size()           { return int(uintx(_vtable_size)); }
 800   void set_vtable_size(int n) { _vtable_size = intptr_t(n); }
 801   intptr_t* cloned_vtable()   { return &_cloned_vtable[0]; }
 802   void zero()                 { memset(_cloned_vtable, 0, sizeof(intptr_t) * vtable_size()); }
 803   // Returns the address of the next CppVtableInfo that can be placed immediately after this CppVtableInfo
 804   static size_t byte_size(int vtable_size) {
 805     CppVtableInfo i;
 806     return pointer_delta(&i._cloned_vtable[vtable_size], &i, sizeof(u1));
 807   }
 808 };
 809 
 810 static inline intptr_t* vtable_of(Metadata* m) {
 811   return *((intptr_t**)m);
 812 }
 813 
 814 template <class T> class CppVtableCloner : public T {
 815   static CppVtableInfo* _info;
 816 
 817   static int get_vtable_length(const char* name);
 818 
 819 public:
 820   // Allocate and initialize the C++ vtable, starting from top, but do not go past end.
 821   static intptr_t* allocate(const char* name);
 822 
 823   // Clone the vtable to ...
 824   static intptr_t* clone_vtable(const char* name, CppVtableInfo* info);
 825 
 826   static void zero_vtable_clone() {
 827     assert(DumpSharedSpaces, "dump-time only");
 828     _info->zero();
 829   }
 830 
 831   static bool is_valid_shared_object(const T* obj) {
 832     intptr_t* vptr = *(intptr_t**)obj;
 833     return vptr == _info->cloned_vtable();
 834   }
 835 
 836   static void init_orig_cpp_vtptr(int kind);
 837 };
 838 
 839 template <class T> CppVtableInfo* CppVtableCloner<T>::_info = NULL;
 840 
 841 template <class T>
 842 intptr_t* CppVtableCloner<T>::allocate(const char* name) {
 843   assert(is_aligned(_mc_region.top(), sizeof(intptr_t)), "bad alignment");
 844   int n = get_vtable_length(name);
 845   _info = (CppVtableInfo*)_mc_region.allocate(CppVtableInfo::byte_size(n), sizeof(intptr_t));
 846   _info->set_vtable_size(n);
 847 
 848   intptr_t* p = clone_vtable(name, _info);
 849   assert((char*)p == _mc_region.top(), "must be");
 850 
 851   return _info->cloned_vtable();
 852 }
 853 
 854 template <class T>
 855 intptr_t* CppVtableCloner<T>::clone_vtable(const char* name, CppVtableInfo* info) {
 856   if (!DumpSharedSpaces) {
 857     assert(_info == 0, "_info is initialized only at dump time");
 858     _info = info; // Remember it -- it will be used by MetaspaceShared::is_valid_shared_method()
 859   }
 860   T tmp; // Allocate temporary dummy metadata object to get to the original vtable.
 861   int n = info->vtable_size();
 862   intptr_t* srcvtable = vtable_of(&tmp);
 863   intptr_t* dstvtable = info->cloned_vtable();
 864 
 865   // We already checked (and, if necessary, adjusted n) when the vtables were allocated, so we are
 866   // safe to do memcpy.
 867   log_debug(cds, vtables)("Copying %3d vtable entries for %s", n, name);
 868   memcpy(dstvtable, srcvtable, sizeof(intptr_t) * n);
 869   return dstvtable + n;
 870 }
 871 
 872 // To determine the size of the vtable for each type, we use the following
 873 // trick by declaring 2 subclasses:
 874 //
 875 //   class CppVtableTesterA: public InstanceKlass {virtual int   last_virtual_method() {return 1;}    };
 876 //   class CppVtableTesterB: public InstanceKlass {virtual void* last_virtual_method() {return NULL}; };
 877 //
 878 // CppVtableTesterA and CppVtableTesterB's vtables have the following properties:
 879 // - Their size (N+1) is exactly one more than the size of InstanceKlass's vtable (N)
 880 // - The first N entries have are exactly the same as in InstanceKlass's vtable.
 881 // - Their last entry is different.
 882 //
 883 // So to determine the value of N, we just walk CppVtableTesterA and CppVtableTesterB's tables
 884 // and find the first entry that's different.
 885 //
 886 // This works on all C++ compilers supported by Oracle, but you may need to tweak it for more
 887 // esoteric compilers.
 888 
 889 template <class T> class CppVtableTesterB: public T {
 890 public:
 891   virtual int last_virtual_method() {return 1;}
 892 };
 893 
 894 template <class T> class CppVtableTesterA : public T {
 895 public:
 896   virtual void* last_virtual_method() {
 897     // Make this different than CppVtableTesterB::last_virtual_method so the C++
 898     // compiler/linker won't alias the two functions.
 899     return NULL;
 900   }
 901 };
 902 
 903 template <class T>
 904 int CppVtableCloner<T>::get_vtable_length(const char* name) {
 905   CppVtableTesterA<T> a;
 906   CppVtableTesterB<T> b;
 907 
 908   intptr_t* avtable = vtable_of(&a);
 909   intptr_t* bvtable = vtable_of(&b);
 910 
 911   // Start at slot 1, because slot 0 may be RTTI (on Solaris/Sparc)
 912   int vtable_len = 1;
 913   for (; ; vtable_len++) {
 914     if (avtable[vtable_len] != bvtable[vtable_len]) {
 915       break;
 916     }
 917   }
 918   log_debug(cds, vtables)("Found   %3d vtable entries for %s", vtable_len, name);
 919 
 920   return vtable_len;
 921 }
 922 
 923 #define ALLOC_CPP_VTABLE_CLONE(c) \
 924   _cloned_cpp_vtptrs[c##_Kind] = CppVtableCloner<c>::allocate(#c); \
 925   ArchivePtrMarker::mark_pointer(&_cloned_cpp_vtptrs[c##_Kind]);
 926 
 927 #define CLONE_CPP_VTABLE(c) \
 928   p = CppVtableCloner<c>::clone_vtable(#c, (CppVtableInfo*)p);
 929 
 930 #define ZERO_CPP_VTABLE(c) \
 931  CppVtableCloner<c>::zero_vtable_clone();
 932 
 933 #define INIT_ORIG_CPP_VTPTRS(c) \
 934   CppVtableCloner<c>::init_orig_cpp_vtptr(c##_Kind);
 935 
 936 #define DECLARE_CLONED_VTABLE_KIND(c) c ## _Kind,
 937 
 938 enum ClonedVtableKind {
 939   // E.g., ConstantPool_Kind == 0, InstanceKlass_Kind == 1, etc.
 940   CPP_VTABLE_PATCH_TYPES_DO(DECLARE_CLONED_VTABLE_KIND)
 941   _num_cloned_vtable_kinds
 942 };
 943 
 944 // This is a map of all the original vtptrs. E.g., for
 945 //     ConstantPool *cp = new (...) ConstantPool(...) ; // a dynamically allocated constant pool
 946 // the following holds true:
 947 //     _orig_cpp_vtptrs[ConstantPool_Kind] ==  ((intptr_t**)cp)[0]
 948 static intptr_t* _orig_cpp_vtptrs[_num_cloned_vtable_kinds];
 949 static bool _orig_cpp_vtptrs_inited = false;
 950 
 951 template <class T>
 952 void CppVtableCloner<T>::init_orig_cpp_vtptr(int kind) {
 953   assert(kind < _num_cloned_vtable_kinds, "sanity");
 954   T tmp; // Allocate temporary dummy metadata object to get to the original vtable.
 955   intptr_t* srcvtable = vtable_of(&tmp);
 956   _orig_cpp_vtptrs[kind] = srcvtable;
 957 }
 958 
 959 // This is the index of all the cloned vtables. E.g., for
 960 //     ConstantPool* cp = ....; // an archived constant pool
 961 //     InstanceKlass* ik = ....;// an archived class
 962 // the following holds true:
 963 //     _cloned_cpp_vtptrs[ConstantPool_Kind]  == ((intptr_t**)cp)[0]
 964 //     _cloned_cpp_vtptrs[InstanceKlass_Kind] == ((intptr_t**)ik)[0]
 965 static intptr_t** _cloned_cpp_vtptrs = NULL;
 966 
 967 void MetaspaceShared::allocate_cloned_cpp_vtptrs() {
 968   assert(DumpSharedSpaces, "must");
 969   size_t vtptrs_bytes = _num_cloned_vtable_kinds * sizeof(intptr_t*);
 970   _cloned_cpp_vtptrs = (intptr_t**)_mc_region.allocate(vtptrs_bytes, sizeof(intptr_t*));
 971 }
 972 
 973 void MetaspaceShared::serialize_cloned_cpp_vtptrs(SerializeClosure* soc) {
 974   soc->do_ptr((void**)&_cloned_cpp_vtptrs);
 975 }
 976 
 977 intptr_t* MetaspaceShared::get_archived_cpp_vtable(MetaspaceObj::Type msotype, address obj) {
 978   if (!_orig_cpp_vtptrs_inited) {
 979     CPP_VTABLE_PATCH_TYPES_DO(INIT_ORIG_CPP_VTPTRS);
 980     _orig_cpp_vtptrs_inited = true;
 981   }
 982 
 983   Arguments::assert_is_dumping_archive();
 984   int kind = -1;
 985   switch (msotype) {
 986   case MetaspaceObj::SymbolType:
 987   case MetaspaceObj::TypeArrayU1Type:
 988   case MetaspaceObj::TypeArrayU2Type:
 989   case MetaspaceObj::TypeArrayU4Type:
 990   case MetaspaceObj::TypeArrayU8Type:
 991   case MetaspaceObj::TypeArrayOtherType:
 992   case MetaspaceObj::ConstMethodType:
 993   case MetaspaceObj::ConstantPoolCacheType:
 994   case MetaspaceObj::AnnotationsType:
 995   case MetaspaceObj::MethodCountersType:
 996   case MetaspaceObj::RecordComponentType:
 997     // These have no vtables.
 998     break;
 999   case MetaspaceObj::MethodDataType:
1000     // We don't archive MethodData <-- should have been removed in removed_unsharable_info
1001     ShouldNotReachHere();
1002     break;
1003   default:
1004     for (kind = 0; kind < _num_cloned_vtable_kinds; kind ++) {
1005       if (vtable_of((Metadata*)obj) == _orig_cpp_vtptrs[kind]) {
1006         break;
1007       }
1008     }
1009     if (kind >= _num_cloned_vtable_kinds) {
1010       fatal("Cannot find C++ vtable for " INTPTR_FORMAT " -- you probably added"
1011             " a new subtype of Klass or MetaData without updating CPP_VTABLE_PATCH_TYPES_DO",
1012             p2i(obj));
1013     }
1014   }
1015 
1016   if (kind >= 0) {
1017     assert(kind < _num_cloned_vtable_kinds, "must be");
1018     return _cloned_cpp_vtptrs[kind];
1019   } else {
1020     return NULL;
1021   }
1022 }
1023 
1024 // This can be called at both dump time and run time:
1025 // - clone the contents of the c++ vtables into the space
1026 //   allocated by allocate_cpp_vtable_clones()
1027 void MetaspaceShared::clone_cpp_vtables(intptr_t* p) {
1028   assert(DumpSharedSpaces || UseSharedSpaces, "sanity");
1029   CPP_VTABLE_PATCH_TYPES_DO(CLONE_CPP_VTABLE);
1030 }
1031 
1032 void MetaspaceShared::zero_cpp_vtable_clones_for_writing() {
1033   assert(DumpSharedSpaces, "dump-time only");
1034   CPP_VTABLE_PATCH_TYPES_DO(ZERO_CPP_VTABLE);
1035 }
1036 
1037 // Allocate and initialize the C++ vtables, starting from top, but do not go past end.
1038 char* MetaspaceShared::allocate_cpp_vtable_clones() {
1039   char* cloned_vtables = _mc_region.top(); // This is the beginning of all the cloned vtables
1040 
1041   assert(DumpSharedSpaces, "dump-time only");
1042   // Layout (each slot is a intptr_t):
1043   //   [number of slots in the first vtable = n1]
1044   //   [ <n1> slots for the first vtable]
1045   //   [number of slots in the first second = n2]
1046   //   [ <n2> slots for the second vtable]
1047   //   ...
1048   // The order of the vtables is the same as the CPP_VTAB_PATCH_TYPES_DO macro.
1049   CPP_VTABLE_PATCH_TYPES_DO(ALLOC_CPP_VTABLE_CLONE);
1050 
1051   return cloned_vtables;
1052 }
1053 
1054 bool MetaspaceShared::is_valid_shared_method(const Method* m) {
1055   assert(is_in_shared_metaspace(m), "must be");
1056   return CppVtableCloner<Method>::is_valid_shared_object(m);
1057 }
1058 
1059 void WriteClosure::do_oop(oop* o) {
1060   if (*o == NULL) {
1061     _dump_region->append_intptr_t(0);
1062   } else {
1063     assert(HeapShared::is_heap_object_archiving_allowed(),
1064            "Archiving heap object is not allowed");
1065     _dump_region->append_intptr_t(
1066       (intptr_t)CompressedOops::encode_not_null(*o));
1067   }
1068 }
1069 
1070 void WriteClosure::do_region(u_char* start, size_t size) {
1071   assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
1072   assert(size % sizeof(intptr_t) == 0, "bad size");
1073   do_tag((int)size);
1074   while (size > 0) {
1075     _dump_region->append_intptr_t(*(intptr_t*)start, true);
1076     start += sizeof(intptr_t);
1077     size -= sizeof(intptr_t);
1078   }
1079 }
1080 
1081 // This is for dumping detailed statistics for the allocations
1082 // in the shared spaces.
1083 class DumpAllocStats : public ResourceObj {
1084 public:
1085 
1086   // Here's poor man's enum inheritance
1087 #define SHAREDSPACE_OBJ_TYPES_DO(f) \
1088   METASPACE_OBJ_TYPES_DO(f) \
1089   f(SymbolHashentry) \
1090   f(SymbolBucket) \
1091   f(StringHashentry) \
1092   f(StringBucket) \
1093   f(ModulesNatives) \
1094   f(Other)
1095 
1096   enum Type {
1097     // Types are MetaspaceObj::ClassType, MetaspaceObj::SymbolType, etc
1098     SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_DECLARE)
1099     _number_of_types
1100   };
1101 
1102   static const char * type_name(Type type) {
1103     switch(type) {
1104     SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_NAME_CASE)
1105     default:
1106       ShouldNotReachHere();
1107       return NULL;
1108     }
1109   }
1110 
1111 public:
1112   enum { RO = 0, RW = 1 };
1113 
1114   int _counts[2][_number_of_types];
1115   int _bytes [2][_number_of_types];
1116 
1117   DumpAllocStats() {
1118     memset(_counts, 0, sizeof(_counts));
1119     memset(_bytes,  0, sizeof(_bytes));
1120   };
1121 
1122   void record(MetaspaceObj::Type type, int byte_size, bool read_only) {
1123     assert(int(type) >= 0 && type < MetaspaceObj::_number_of_types, "sanity");
1124     int which = (read_only) ? RO : RW;
1125     _counts[which][type] ++;
1126     _bytes [which][type] += byte_size;
1127   }
1128 
1129   void record_modules(int byte_size, bool read_only) {
1130     int which = (read_only) ? RO : RW;
1131     _bytes [which][ModulesNativesType] += byte_size;
1132   }
1133 
1134   void record_other_type(int byte_size, bool read_only) {
1135     int which = (read_only) ? RO : RW;
1136     _bytes [which][OtherType] += byte_size;
1137   }
1138   void print_stats(int ro_all, int rw_all, int mc_all);
1139 };
1140 
1141 void DumpAllocStats::print_stats(int ro_all, int rw_all, int mc_all) {
1142   // Calculate size of data that was not allocated by Metaspace::allocate()
1143   MetaspaceSharedStats *stats = MetaspaceShared::stats();
1144 
1145   // symbols
1146   _counts[RO][SymbolHashentryType] = stats->symbol.hashentry_count;
1147   _bytes [RO][SymbolHashentryType] = stats->symbol.hashentry_bytes;
1148 
1149   _counts[RO][SymbolBucketType] = stats->symbol.bucket_count;
1150   _bytes [RO][SymbolBucketType] = stats->symbol.bucket_bytes;
1151 
1152   // strings
1153   _counts[RO][StringHashentryType] = stats->string.hashentry_count;
1154   _bytes [RO][StringHashentryType] = stats->string.hashentry_bytes;
1155 
1156   _counts[RO][StringBucketType] = stats->string.bucket_count;
1157   _bytes [RO][StringBucketType] = stats->string.bucket_bytes;
1158 
1159   // TODO: count things like dictionary, vtable, etc
1160   _bytes[RW][OtherType] += mc_all;
1161   rw_all += mc_all; // mc is mapped Read/Write
1162 
1163   // prevent divide-by-zero
1164   if (ro_all < 1) {
1165     ro_all = 1;
1166   }
1167   if (rw_all < 1) {
1168     rw_all = 1;
1169   }
1170 
1171   int all_ro_count = 0;
1172   int all_ro_bytes = 0;
1173   int all_rw_count = 0;
1174   int all_rw_bytes = 0;
1175 
1176 // To make fmt_stats be a syntactic constant (for format warnings), use #define.
1177 #define fmt_stats "%-20s: %8d %10d %5.1f | %8d %10d %5.1f | %8d %10d %5.1f"
1178   const char *sep = "--------------------+---------------------------+---------------------------+--------------------------";
1179   const char *hdr = "                        ro_cnt   ro_bytes     % |   rw_cnt   rw_bytes     % |  all_cnt  all_bytes     %";
1180 
1181   LogMessage(cds) msg;
1182 
1183   msg.debug("Detailed metadata info (excluding st regions; rw stats include mc regions):");
1184   msg.debug("%s", hdr);
1185   msg.debug("%s", sep);
1186   for (int type = 0; type < int(_number_of_types); type ++) {
1187     const char *name = type_name((Type)type);
1188     int ro_count = _counts[RO][type];
1189     int ro_bytes = _bytes [RO][type];
1190     int rw_count = _counts[RW][type];
1191     int rw_bytes = _bytes [RW][type];
1192     int count = ro_count + rw_count;
1193     int bytes = ro_bytes + rw_bytes;
1194 
1195     double ro_perc = percent_of(ro_bytes, ro_all);
1196     double rw_perc = percent_of(rw_bytes, rw_all);
1197     double perc    = percent_of(bytes, ro_all + rw_all);
1198 
1199     msg.debug(fmt_stats, name,
1200                          ro_count, ro_bytes, ro_perc,
1201                          rw_count, rw_bytes, rw_perc,
1202                          count, bytes, perc);
1203 
1204     all_ro_count += ro_count;
1205     all_ro_bytes += ro_bytes;
1206     all_rw_count += rw_count;
1207     all_rw_bytes += rw_bytes;
1208   }
1209 
1210   int all_count = all_ro_count + all_rw_count;
1211   int all_bytes = all_ro_bytes + all_rw_bytes;
1212 
1213   double all_ro_perc = percent_of(all_ro_bytes, ro_all);
1214   double all_rw_perc = percent_of(all_rw_bytes, rw_all);
1215   double all_perc    = percent_of(all_bytes, ro_all + rw_all);
1216 
1217   msg.debug("%s", sep);
1218   msg.debug(fmt_stats, "Total",
1219                        all_ro_count, all_ro_bytes, all_ro_perc,
1220                        all_rw_count, all_rw_bytes, all_rw_perc,
1221                        all_count, all_bytes, all_perc);
1222 
1223   assert(all_ro_bytes == ro_all, "everything should have been counted");
1224   assert(all_rw_bytes == rw_all, "everything should have been counted");
1225 
1226 #undef fmt_stats
1227 }
1228 
1229 // Populate the shared space.
1230 
1231 class VM_PopulateDumpSharedSpace: public VM_Operation {
1232 private:
1233   GrowableArray<MemRegion> *_closed_archive_heap_regions;
1234   GrowableArray<MemRegion> *_open_archive_heap_regions;
1235 
1236   GrowableArray<ArchiveHeapOopmapInfo> *_closed_archive_heap_oopmaps;
1237   GrowableArray<ArchiveHeapOopmapInfo> *_open_archive_heap_oopmaps;
1238 
1239   void dump_java_heap_objects() NOT_CDS_JAVA_HEAP_RETURN;
1240   void dump_archive_heap_oopmaps() NOT_CDS_JAVA_HEAP_RETURN;
1241   void dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
1242                                  GrowableArray<ArchiveHeapOopmapInfo>* oopmaps);
1243   void dump_symbols();
1244   char* dump_read_only_tables();
1245   void print_class_stats();
1246   void print_region_stats(FileMapInfo* map_info);
1247   void print_bitmap_region_stats(size_t size, size_t total_size);
1248   void print_heap_region_stats(GrowableArray<MemRegion> *heap_mem,
1249                                const char *name, size_t total_size);
1250   void relocate_to_requested_base_address(CHeapBitMap* ptrmap);
1251 
1252 public:
1253 
1254   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
1255   void doit();   // outline because gdb sucks
1256   bool allow_nested_vm_operations() const { return true; }
1257 }; // class VM_PopulateDumpSharedSpace
1258 
1259 // ArchiveCompactor --
1260 //
1261 // This class is the central piece of shared archive compaction -- all metaspace data are
1262 // initially allocated outside of the shared regions. ArchiveCompactor copies the
1263 // metaspace data into their final location in the shared regions.
1264 
1265 class ArchiveCompactor : AllStatic {
1266   static const int INITIAL_TABLE_SIZE = 8087;
1267   static const int MAX_TABLE_SIZE     = 1000000;
1268 
1269   static DumpAllocStats* _alloc_stats;
1270 
1271   typedef KVHashtable<address, address, mtInternal> RelocationTable;
1272   static RelocationTable* _new_loc_table;
1273 
1274 public:
1275   static void initialize() {
1276     _alloc_stats = new(ResourceObj::C_HEAP, mtInternal)DumpAllocStats;
1277     _new_loc_table = new RelocationTable(INITIAL_TABLE_SIZE);
1278   }
1279   static DumpAllocStats* alloc_stats() {
1280     return _alloc_stats;
1281   }
1282 
1283   // Use this when you allocate space with MetaspaceShare::read_only_space_alloc()
1284   // outside of ArchiveCompactor::allocate(). These are usually for misc tables
1285   // that are allocated in the RO space.
1286   class OtherROAllocMark {
1287     char* _oldtop;
1288   public:
1289     OtherROAllocMark() {
1290       _oldtop = _ro_region.top();
1291     }
1292     ~OtherROAllocMark() {
1293       char* newtop = _ro_region.top();
1294       ArchiveCompactor::alloc_stats()->record_other_type(int(newtop - _oldtop), true);
1295     }
1296   };
1297 
1298   static void allocate(MetaspaceClosure::Ref* ref, bool read_only) {
1299     address obj = ref->obj();
1300     int bytes = ref->size() * BytesPerWord;
1301     char* p;
1302     size_t alignment = BytesPerWord;
1303     char* oldtop;
1304     char* newtop;
1305 
1306     if (read_only) {
1307       oldtop = _ro_region.top();
1308       p = _ro_region.allocate(bytes, alignment);
1309       newtop = _ro_region.top();
1310     } else {
1311       oldtop = _rw_region.top();
1312       if (ref->msotype() == MetaspaceObj::ClassType) {
1313         // Save a pointer immediate in front of an InstanceKlass, so
1314         // we can do a quick lookup from InstanceKlass* -> RunTimeSharedClassInfo*
1315         // without building another hashtable. See RunTimeSharedClassInfo::get_for()
1316         // in systemDictionaryShared.cpp.
1317         Klass* klass = (Klass*)obj;
1318         if (klass->is_instance_klass()) {
1319           SystemDictionaryShared::validate_before_archiving(InstanceKlass::cast(klass));
1320           _rw_region.allocate(sizeof(address), BytesPerWord);
1321         }
1322       }
1323       p = _rw_region.allocate(bytes, alignment);
1324       newtop = _rw_region.top();
1325     }
1326     memcpy(p, obj, bytes);
1327 
1328     intptr_t* archived_vtable = MetaspaceShared::get_archived_cpp_vtable(ref->msotype(), (address)p);
1329     if (archived_vtable != NULL) {
1330       *(address*)p = (address)archived_vtable;
1331       ArchivePtrMarker::mark_pointer((address*)p);
1332     }
1333 
1334     assert(_new_loc_table->lookup(obj) == NULL, "each object can be relocated at most once");
1335     _new_loc_table->add(obj, (address)p);
1336     log_trace(cds)("Copy: " PTR_FORMAT " ==> " PTR_FORMAT " %d", p2i(obj), p2i(p), bytes);
1337     if (_new_loc_table->maybe_grow(MAX_TABLE_SIZE)) {
1338       log_info(cds, hashtables)("Expanded _new_loc_table to %d", _new_loc_table->table_size());
1339     }
1340     _alloc_stats->record(ref->msotype(), int(newtop - oldtop), read_only);
1341   }
1342 
1343   static address get_new_loc(MetaspaceClosure::Ref* ref) {
1344     address* pp = _new_loc_table->lookup(ref->obj());
1345     assert(pp != NULL, "must be");
1346     return *pp;
1347   }
1348 
1349 private:
1350   // Makes a shallow copy of visited MetaspaceObj's
1351   class ShallowCopier: public UniqueMetaspaceClosure {
1352     bool _read_only;
1353   public:
1354     ShallowCopier(bool read_only) : _read_only(read_only) {}
1355 
1356     virtual bool do_unique_ref(Ref* ref, bool read_only) {
1357       if (read_only == _read_only) {
1358         allocate(ref, read_only);
1359       }
1360       return true; // recurse into ref.obj()
1361     }
1362   };
1363 
1364   // Relocate embedded pointers within a MetaspaceObj's shallow copy
1365   class ShallowCopyEmbeddedRefRelocator: public UniqueMetaspaceClosure {
1366   public:
1367     virtual bool do_unique_ref(Ref* ref, bool read_only) {
1368       address new_loc = get_new_loc(ref);
1369       RefRelocator refer;
1370       ref->metaspace_pointers_do_at(&refer, new_loc);
1371       return true; // recurse into ref.obj()
1372     }
1373     virtual void push_special(SpecialRef type, Ref* ref, intptr_t* p) {
1374       assert(type == _method_entry_ref, "only special type allowed for now");
1375       address obj = ref->obj();
1376       address new_obj = get_new_loc(ref);
1377       size_t offset = pointer_delta(p, obj,  sizeof(u1));
1378       intptr_t* new_p = (intptr_t*)(new_obj + offset);
1379       assert(*p == *new_p, "must be a copy");
1380       ArchivePtrMarker::mark_pointer((address*)new_p);
1381     }
1382   };
1383 
1384   // Relocate a reference to point to its shallow copy
1385   class RefRelocator: public MetaspaceClosure {
1386   public:
1387     virtual bool do_ref(Ref* ref, bool read_only) {
1388       if (ref->not_null()) {
1389         ref->update(get_new_loc(ref));
1390         ArchivePtrMarker::mark_pointer(ref->addr());
1391       }
1392       return false; // Do not recurse.
1393     }
1394   };
1395 
1396 #ifdef ASSERT
1397   class IsRefInArchiveChecker: public MetaspaceClosure {
1398   public:
1399     virtual bool do_ref(Ref* ref, bool read_only) {
1400       if (ref->not_null()) {
1401         char* obj = (char*)ref->obj();
1402         assert(_ro_region.contains(obj) || _rw_region.contains(obj),
1403                "must be relocated to point to CDS archive");
1404       }
1405       return false; // Do not recurse.
1406     }
1407   };
1408 #endif
1409 
1410 public:
1411   static void copy_and_compact() {
1412     ResourceMark rm;
1413 
1414     log_info(cds)("Scanning all metaspace objects ... ");
1415     {
1416       // allocate and shallow-copy RW objects, immediately following the MC region
1417       log_info(cds)("Allocating RW objects ... ");
1418       _mc_region.pack(&_rw_region);
1419 
1420       ResourceMark rm;
1421       ShallowCopier rw_copier(false);
1422       iterate_roots(&rw_copier);
1423 
1424 #if INCLUDE_CDS_JAVA_HEAP
1425       // Archive the ModuleEntry's and PackageEntry's of the 3 built-in loaders
1426       char* start = _rw_region.top();
1427       ClassLoaderData::allocate_archived_tables();
1428       ArchiveCompactor::alloc_stats()->record_modules(_rw_region.top() - start, /*read_only*/false);
1429 #endif
1430     }
1431     {
1432       // allocate and shallow-copy of RO object, immediately following the RW region
1433       log_info(cds)("Allocating RO objects ... ");
1434       _rw_region.pack(&_ro_region);
1435 
1436       ResourceMark rm;
1437       ShallowCopier ro_copier(true);
1438       iterate_roots(&ro_copier);
1439 #if INCLUDE_CDS_JAVA_HEAP
1440       char* start = _ro_region.top();
1441       ClassLoaderData::init_archived_tables();
1442       ArchiveCompactor::alloc_stats()->record_modules(_ro_region.top() - start, /*read_only*/true);
1443 #endif
1444     }
1445     {
1446       log_info(cds)("Relocating embedded pointers ... ");
1447       ResourceMark rm;
1448       ShallowCopyEmbeddedRefRelocator emb_reloc;
1449       iterate_roots(&emb_reloc);
1450     }
1451     {
1452       log_info(cds)("Relocating external roots ... ");
1453       ResourceMark rm;
1454       RefRelocator ext_reloc;
1455       iterate_roots(&ext_reloc);
1456     }
1457     {
1458       log_info(cds)("Fixing symbol identity hash ... ");
1459       os::init_random(0x12345678);
1460       GrowableArray<Symbol*>* all_symbols = MetaspaceShared::collected_symbols();
1461       all_symbols->sort(compare_symbols_by_address);
1462       for (int i = 0; i < all_symbols->length(); i++) {
1463         assert(all_symbols->at(i)->is_permanent(), "archived symbols must be permanent");
1464         all_symbols->at(i)->update_identity_hash();
1465       }
1466     }
1467 #ifdef ASSERT
1468     {
1469       log_info(cds)("Verifying external roots ... ");
1470       ResourceMark rm;
1471       IsRefInArchiveChecker checker;
1472       iterate_roots(&checker);
1473     }
1474 #endif
1475   }
1476 
1477   // We must relocate the System::_well_known_klasses only after we have copied the
1478   // java objects in during dump_java_heap_objects(): during the object copy, we operate on
1479   // old objects which assert that their klass is the original klass.
1480   static void relocate_well_known_klasses() {
1481     {
1482       log_info(cds)("Relocating SystemDictionary::_well_known_klasses[] ... ");
1483       ResourceMark rm;
1484       RefRelocator ext_reloc;
1485       SystemDictionary::well_known_klasses_do(&ext_reloc);
1486     }
1487     // NOTE: after this point, we shouldn't have any globals that can reach the old
1488     // objects.
1489 
1490     // We cannot use any of the objects in the heap anymore (except for the
1491     // shared strings) because their headers no longer point to valid Klasses.
1492   }
1493 
1494   static void iterate_roots(MetaspaceClosure* it) {
1495     // To ensure deterministic contents in the archive, we just need to ensure that
1496     // we iterate the MetsapceObjs in a deterministic order. It doesn't matter where
1497     // the MetsapceObjs are located originally, as they are copied sequentially into
1498     // the archive during the iteration.
1499     //
1500     // The only issue here is that the symbol table and the system directories may be
1501     // randomly ordered, so we copy the symbols and klasses into two arrays and sort
1502     // them deterministically.
1503     //
1504     // During -Xshare:dump, the order of Symbol creation is strictly determined by
1505     // the SharedClassListFile (class loading is done in a single thread and the JIT
1506     // is disabled). Also, Symbols are allocated in monotonically increasing addresses
1507     // (see Symbol::operator new(size_t, int)). So if we iterate the Symbols by
1508     // ascending address order, we ensure that all Symbols are copied into deterministic
1509     // locations in the archive.
1510     GrowableArray<Symbol*>* symbols = _global_symbol_objects;
1511     for (int i = 0; i < symbols->length(); i++) {
1512       it->push(symbols->adr_at(i));
1513     }
1514     if (_global_klass_objects != NULL) {
1515       // Need to fix up the pointers
1516       for (int i = 0; i < _global_klass_objects->length(); i++) {
1517         // NOTE -- this requires that the vtable is NOT yet patched, or else we are hosed.
1518         it->push(_global_klass_objects->adr_at(i));
1519       }
1520     }
1521     FileMapInfo::metaspace_pointers_do(it, false);
1522     SystemDictionaryShared::dumptime_classes_do(it);
1523     Universe::metaspace_pointers_do(it);
1524     SymbolTable::metaspace_pointers_do(it);
1525     vmSymbols::metaspace_pointers_do(it);
1526 
1527     it->finish();
1528   }
1529 
1530   static Klass* get_relocated_klass(Klass* orig_klass) {
1531     assert(DumpSharedSpaces, "dump time only");
1532     address* pp = _new_loc_table->lookup((address)orig_klass);
1533     assert(pp != NULL, "must be");
1534     Klass* klass = (Klass*)(*pp);
1535     assert(klass->is_klass(), "must be");
1536     return klass;
1537   }
1538 
1539   static Symbol* get_relocated_symbol(Symbol* orig_symbol) {
1540     assert(DumpSharedSpaces, "dump time only");
1541     address* pp = _new_loc_table->lookup((address)orig_symbol);
1542     assert(pp != NULL, "must be");
1543     return (Symbol*)(*pp);
1544   }
1545 };
1546 
1547 DumpAllocStats* ArchiveCompactor::_alloc_stats;
1548 ArchiveCompactor::RelocationTable* ArchiveCompactor::_new_loc_table;
1549 
1550 void VM_PopulateDumpSharedSpace::dump_symbols() {
1551   log_info(cds)("Dumping symbol table ...");
1552 
1553   NOT_PRODUCT(SymbolTable::verify());
1554   SymbolTable::write_to_archive();
1555 }
1556 
1557 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
1558   ArchiveCompactor::OtherROAllocMark mark;
1559 
1560   log_info(cds)("Removing java_mirror ... ");
1561   if (!HeapShared::is_heap_object_archiving_allowed()) {
1562     Universe::clear_basic_type_mirrors();
1563   }
1564   remove_java_mirror_in_classes();
1565   log_info(cds)("done. ");
1566 
1567   SystemDictionaryShared::write_to_archive();
1568 
1569   // Write the other data to the output array.
1570   char* start = _ro_region.top();
1571   WriteClosure wc(&_ro_region);
1572   MetaspaceShared::serialize(&wc);
1573 
1574   // Write the bitmaps for patching the archive heap regions
1575   _closed_archive_heap_oopmaps = NULL;
1576   _open_archive_heap_oopmaps = NULL;
1577   dump_archive_heap_oopmaps();
1578 
1579   return start;
1580 }
1581 
1582 void VM_PopulateDumpSharedSpace::print_class_stats() {
1583   log_info(cds)("Number of classes %d", _global_klass_objects->length());
1584   {
1585     int num_type_array = 0, num_obj_array = 0, num_inst = 0;
1586     for (int i = 0; i < _global_klass_objects->length(); i++) {
1587       Klass* k = _global_klass_objects->at(i);
1588       if (k->is_instance_klass()) {
1589         num_inst ++;
1590       } else if (k->is_objArray_klass()) {
1591         num_obj_array ++;
1592       } else {
1593         assert(k->is_typeArray_klass(), "sanity");
1594         num_type_array ++;
1595       }
1596     }
1597     log_info(cds)("    instance classes   = %5d", num_inst);
1598     log_info(cds)("    obj array classes  = %5d", num_obj_array);
1599     log_info(cds)("    type array classes = %5d", num_type_array);
1600   }
1601 }
1602 
1603 void VM_PopulateDumpSharedSpace::relocate_to_requested_base_address(CHeapBitMap* ptrmap) {
1604   intx addr_delta = MetaspaceShared::final_delta();
1605   if (addr_delta == 0) {
1606     ArchivePtrMarker::compact((address)SharedBaseAddress, (address)_ro_region.top());
1607   } else {
1608     // We are not able to reserve space at MetaspaceShared::requested_base_address() (due to ASLR).
1609     // This means that the current content of the archive is based on a random
1610     // address. Let's relocate all the pointers, so that it can be mapped to
1611     // MetaspaceShared::requested_base_address() without runtime relocation.
1612     //
1613     // Note: both the base and dynamic archive are written with
1614     // FileMapHeader::_requested_base_address == MetaspaceShared::requested_base_address()
1615 
1616     // Patch all pointers that are marked by ptrmap within this region,
1617     // where we have just dumped all the metaspace data.
1618     address patch_base = (address)SharedBaseAddress;
1619     address patch_end  = (address)_ro_region.top();
1620     size_t size = patch_end - patch_base;
1621 
1622     // the current value of the pointers to be patched must be within this
1623     // range (i.e., must point to valid metaspace objects)
1624     address valid_old_base = patch_base;
1625     address valid_old_end  = patch_end;
1626 
1627     // after patching, the pointers must point inside this range
1628     // (the requested location of the archive, as mapped at runtime).
1629     address valid_new_base = (address)MetaspaceShared::requested_base_address();
1630     address valid_new_end  = valid_new_base + size;
1631 
1632     log_debug(cds)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT " ] to "
1633                    "[" INTPTR_FORMAT " - " INTPTR_FORMAT " ]", p2i(patch_base), p2i(patch_end),
1634                    p2i(valid_new_base), p2i(valid_new_end));
1635 
1636     SharedDataRelocator<true> patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end,
1637                                       valid_new_base, valid_new_end, addr_delta, ptrmap);
1638     ptrmap->iterate(&patcher);
1639     ArchivePtrMarker::compact(patcher.max_non_null_offset());
1640   }
1641 }
1642 
1643 void VM_PopulateDumpSharedSpace::doit() {
1644   HeapShared::run_full_gc_in_vm_thread();
1645   CHeapBitMap ptrmap;
1646   MetaspaceShared::initialize_ptr_marker(&ptrmap);
1647 
1648   // We should no longer allocate anything from the metaspace, so that:
1649   //
1650   // (1) Metaspace::allocate might trigger GC if we have run out of
1651   //     committed metaspace, but we can't GC because we're running
1652   //     in the VM thread.
1653   // (2) ArchiveCompactor needs to work with a stable set of MetaspaceObjs.
1654   Metaspace::freeze();
1655   DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
1656 
1657   Thread* THREAD = VMThread::vm_thread();
1658 
1659   FileMapInfo::check_nonempty_dir_in_shared_path_table();
1660 
1661   NOT_PRODUCT(SystemDictionary::verify();)
1662   // The following guarantee is meant to ensure that no loader constraints
1663   // exist yet, since the constraints table is not shared.  This becomes
1664   // more important now that we don't re-initialize vtables/itables for
1665   // shared classes at runtime, where constraints were previously created.
1666   guarantee(SystemDictionary::constraints()->number_of_entries() == 0,
1667             "loader constraints are not saved");
1668   guarantee(SystemDictionary::placeholders()->number_of_entries() == 0,
1669           "placeholders are not saved");
1670 
1671   // At this point, many classes have been loaded.
1672   // Gather systemDictionary classes in a global array and do everything to
1673   // that so we don't have to walk the SystemDictionary again.
1674   SystemDictionaryShared::check_excluded_classes();
1675   _global_klass_objects = new GrowableArray<Klass*>(1000);
1676   CollectClassesClosure collect_classes;
1677   ClassLoaderDataGraph::loaded_classes_do(&collect_classes);
1678   _global_klass_objects->sort(global_klass_compare);
1679 
1680   print_class_stats();
1681 
1682   // Ensure the ConstMethods won't be modified at run-time
1683   log_info(cds)("Updating ConstMethods ... ");
1684   rewrite_nofast_bytecodes_and_calculate_fingerprints(THREAD);
1685   log_info(cds)("done. ");
1686 
1687   // Remove all references outside the metadata
1688   log_info(cds)("Removing unshareable information ... ");
1689   remove_unshareable_in_classes();
1690   log_info(cds)("done. ");
1691 
1692   MetaspaceShared::allocate_cloned_cpp_vtptrs();
1693   char* cloned_vtables = _mc_region.top();
1694   MetaspaceShared::allocate_cpp_vtable_clones();
1695 
1696   ArchiveCompactor::initialize();
1697   ArchiveCompactor::copy_and_compact();
1698 
1699   dump_symbols();
1700 
1701   // Dump supported java heap objects
1702   _closed_archive_heap_regions = NULL;
1703   _open_archive_heap_regions = NULL;
1704   dump_java_heap_objects();
1705 
1706   ArchiveCompactor::relocate_well_known_klasses();
1707 
1708   char* serialized_data = dump_read_only_tables();
1709   _ro_region.pack();
1710 
1711   // The vtable clones contain addresses of the current process.
1712   // We don't want to write these addresses into the archive. Same for i2i buffer.
1713   MetaspaceShared::zero_cpp_vtable_clones_for_writing();
1714   memset(MetaspaceShared::i2i_entry_code_buffers(), 0,
1715          MetaspaceShared::i2i_entry_code_buffers_size());
1716 
1717   // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
1718   // without runtime relocation.
1719   relocate_to_requested_base_address(&ptrmap);
1720 
1721   // Create and write the archive file that maps the shared spaces.
1722 
1723   FileMapInfo* mapinfo = new FileMapInfo(true);
1724   mapinfo->populate_header(os::vm_allocation_granularity());
1725   mapinfo->set_serialized_data(serialized_data);
1726   mapinfo->set_cloned_vtables(cloned_vtables);
1727   mapinfo->set_i2i_entry_code_buffers(MetaspaceShared::i2i_entry_code_buffers(),
1728                                       MetaspaceShared::i2i_entry_code_buffers_size());
1729   mapinfo->open_for_write();
1730   MetaspaceShared::write_core_archive_regions(mapinfo, _closed_archive_heap_oopmaps, _open_archive_heap_oopmaps);
1731   _total_closed_archive_region_size = mapinfo->write_archive_heap_regions(
1732                                         _closed_archive_heap_regions,
1733                                         _closed_archive_heap_oopmaps,
1734                                         MetaspaceShared::first_closed_archive_heap_region,
1735                                         MetaspaceShared::max_closed_archive_heap_region);
1736   _total_open_archive_region_size = mapinfo->write_archive_heap_regions(
1737                                         _open_archive_heap_regions,
1738                                         _open_archive_heap_oopmaps,
1739                                         MetaspaceShared::first_open_archive_heap_region,
1740                                         MetaspaceShared::max_open_archive_heap_region);
1741 
1742   mapinfo->set_final_requested_base((char*)MetaspaceShared::requested_base_address());
1743   mapinfo->set_header_crc(mapinfo->compute_header_crc());
1744   mapinfo->write_header();
1745   print_region_stats(mapinfo);
1746   mapinfo->close();
1747 
1748   if (log_is_enabled(Info, cds)) {
1749     ArchiveCompactor::alloc_stats()->print_stats(int(_ro_region.used()), int(_rw_region.used()),
1750                                                  int(_mc_region.used()));
1751   }
1752 
1753   if (PrintSystemDictionaryAtExit) {
1754     SystemDictionary::print();
1755   }
1756 
1757   if (AllowArchivingWithJavaAgent) {
1758     warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1759             "for testing purposes only and should not be used in a production environment");
1760   }
1761 
1762   // There may be other pending VM operations that operate on the InstanceKlasses,
1763   // which will fail because InstanceKlasses::remove_unshareable_info()
1764   // has been called. Forget these operations and exit the VM directly.
1765   vm_direct_exit(0);
1766 }
1767 
1768 void VM_PopulateDumpSharedSpace::print_region_stats(FileMapInfo *map_info) {
1769   // Print statistics of all the regions
1770   const size_t bitmap_used = map_info->space_at(MetaspaceShared::bm)->used();
1771   const size_t bitmap_reserved = map_info->space_at(MetaspaceShared::bm)->used_aligned();
1772   const size_t total_reserved = _ro_region.reserved()  + _rw_region.reserved() +
1773                                 _mc_region.reserved()  +
1774                                 bitmap_reserved +
1775                                 _total_closed_archive_region_size +
1776                                 _total_open_archive_region_size;
1777   const size_t total_bytes = _ro_region.used()  + _rw_region.used() +
1778                              _mc_region.used()  +
1779                              bitmap_used +
1780                              _total_closed_archive_region_size +
1781                              _total_open_archive_region_size;
1782   const double total_u_perc = percent_of(total_bytes, total_reserved);
1783 
1784   _mc_region.print(total_reserved);
1785   _rw_region.print(total_reserved);
1786   _ro_region.print(total_reserved);
1787   print_bitmap_region_stats(bitmap_used, total_reserved);
1788   print_heap_region_stats(_closed_archive_heap_regions, "ca", total_reserved);
1789   print_heap_region_stats(_open_archive_heap_regions, "oa", total_reserved);
1790 
1791   log_debug(cds)("total    : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]",
1792                  total_bytes, total_reserved, total_u_perc);
1793 }
1794 
1795 void VM_PopulateDumpSharedSpace::print_bitmap_region_stats(size_t size, size_t total_size) {
1796   log_debug(cds)("bm  space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used]",
1797                  size, size/double(total_size)*100.0, size);
1798 }
1799 
1800 void VM_PopulateDumpSharedSpace::print_heap_region_stats(GrowableArray<MemRegion> *heap_mem,
1801                                                          const char *name, size_t total_size) {
1802   int arr_len = heap_mem == NULL ? 0 : heap_mem->length();
1803   for (int i = 0; i < arr_len; i++) {
1804       char* start = (char*)heap_mem->at(i).start();
1805       size_t size = heap_mem->at(i).byte_size();
1806       char* top = start + size;
1807       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,
1808                      name, i, size, size/double(total_size)*100.0, size, p2i(start));
1809 
1810   }
1811 }
1812 
1813 void MetaspaceShared::write_core_archive_regions(FileMapInfo* mapinfo,
1814                                                  GrowableArray<ArchiveHeapOopmapInfo>* closed_oopmaps,
1815                                                  GrowableArray<ArchiveHeapOopmapInfo>* open_oopmaps) {
1816   // Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with
1817   // MetaspaceShared::n_regions (internal to hotspot).
1818   assert(NUM_CDS_REGIONS == MetaspaceShared::n_regions, "sanity");
1819 
1820   // mc contains the trampoline code for method entries, which are patched at run time,
1821   // so it needs to be read/write.
1822   write_region(mapinfo, mc, &_mc_region, /*read_only=*/false,/*allow_exec=*/true);
1823   write_region(mapinfo, rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);
1824   write_region(mapinfo, ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);
1825   mapinfo->write_bitmap_region(ArchivePtrMarker::ptrmap(), closed_oopmaps, open_oopmaps);
1826 }
1827 
1828 void MetaspaceShared::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only,  bool allow_exec) {
1829   mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);
1830 }
1831 
1832 // Update a Java object to point its Klass* to the new location after
1833 // shared archive has been compacted.
1834 void MetaspaceShared::relocate_klass_ptr(oop o) {
1835   assert(DumpSharedSpaces, "sanity");
1836   Klass* k = ArchiveCompactor::get_relocated_klass(o->klass());
1837   o->set_klass(k);
1838 }
1839 
1840 Klass* MetaspaceShared::get_relocated_klass(Klass *k, bool is_final) {
1841   assert(DumpSharedSpaces, "sanity");
1842   k = ArchiveCompactor::get_relocated_klass(k);
1843   if (is_final) {
1844     k = (Klass*)(address(k) + final_delta());
1845   }
1846   return k;
1847 }
1848 
1849 Symbol* MetaspaceShared::get_relocated_symbol(Symbol* orig_symbol) {
1850   return ArchiveCompactor::get_relocated_symbol(orig_symbol);
1851 }
1852 
1853 class LinkSharedClassesClosure : public KlassClosure {
1854   Thread* THREAD;
1855   bool    _made_progress;
1856  public:
1857   LinkSharedClassesClosure(Thread* thread) : THREAD(thread), _made_progress(false) {}
1858 
1859   void reset()               { _made_progress = false; }
1860   bool made_progress() const { return _made_progress; }
1861 
1862   void do_klass(Klass* k) {
1863     if (k->is_instance_klass()) {
1864       InstanceKlass* ik = InstanceKlass::cast(k);
1865       // For dynamic CDS dump, only link classes loaded by the builtin class loaders.
1866       bool do_linking = DumpSharedSpaces ? true : !ik->is_shared_unregistered_class();
1867       if (do_linking) {
1868         // Link the class to cause the bytecodes to be rewritten and the
1869         // cpcache to be created. Class verification is done according
1870         // to -Xverify setting.
1871         _made_progress |= MetaspaceShared::try_link_class(ik, THREAD);
1872         guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1873 
1874         if (DumpSharedSpaces) {
1875           // The following function is used to resolve all Strings in the statically
1876           // dumped classes to archive all the Strings. The archive heap is not supported
1877           // for the dynamic archive.
1878           ik->constants()->resolve_class_constants(THREAD);
1879         }
1880       }
1881     }
1882   }
1883 };
1884 
1885 void MetaspaceShared::link_and_cleanup_shared_classes(TRAPS) {
1886   // We need to iterate because verification may cause additional classes
1887   // to be loaded.
1888   LinkSharedClassesClosure link_closure(THREAD);
1889   do {
1890     link_closure.reset();
1891     ClassLoaderDataGraph::unlocked_loaded_classes_do(&link_closure);
1892     guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1893   } while (link_closure.made_progress());
1894 }
1895 
1896 void MetaspaceShared::prepare_for_dumping() {
1897   Arguments::check_unsupported_dumping_properties();
1898   ClassLoader::initialize_shared_path();
1899 }
1900 
1901 // Preload classes from a list, populate the shared spaces and dump to a
1902 // file.
1903 void MetaspaceShared::preload_and_dump(TRAPS) {
1904   { TraceTime timer("Dump Shared Spaces", TRACETIME_LOG(Info, startuptime));
1905     ResourceMark rm(THREAD);
1906     char class_list_path_str[JVM_MAXPATHLEN];
1907     // Preload classes to be shared.
1908     const char* class_list_path;
1909     if (SharedClassListFile == NULL) {
1910       // Construct the path to the class list (in jre/lib)
1911       // Walk up two directories from the location of the VM and
1912       // optionally tack on "lib" (depending on platform)
1913       os::jvm_path(class_list_path_str, sizeof(class_list_path_str));
1914       for (int i = 0; i < 3; i++) {
1915         char *end = strrchr(class_list_path_str, *os::file_separator());
1916         if (end != NULL) *end = '\0';
1917       }
1918       int class_list_path_len = (int)strlen(class_list_path_str);
1919       if (class_list_path_len >= 3) {
1920         if (strcmp(class_list_path_str + class_list_path_len - 3, "lib") != 0) {
1921           if (class_list_path_len < JVM_MAXPATHLEN - 4) {
1922             jio_snprintf(class_list_path_str + class_list_path_len,
1923                          sizeof(class_list_path_str) - class_list_path_len,
1924                          "%slib", os::file_separator());
1925             class_list_path_len += 4;
1926           }
1927         }
1928       }
1929       if (class_list_path_len < JVM_MAXPATHLEN - 10) {
1930         jio_snprintf(class_list_path_str + class_list_path_len,
1931                      sizeof(class_list_path_str) - class_list_path_len,
1932                      "%sclasslist", os::file_separator());
1933       }
1934       class_list_path = class_list_path_str;
1935     } else {
1936       class_list_path = SharedClassListFile;
1937     }
1938 
1939     log_info(cds)("Loading classes to share ...");
1940     _has_error_classes = false;
1941     int class_count = preload_classes(class_list_path, THREAD);
1942     if (ExtraSharedClassListFile) {
1943       class_count += preload_classes(ExtraSharedClassListFile, THREAD);
1944     }
1945     log_info(cds)("Loading classes to share: done.");
1946 
1947     log_info(cds)("Shared spaces: preloaded %d classes", class_count);
1948 
1949     if (SharedArchiveConfigFile) {
1950       log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
1951       read_extra_data(SharedArchiveConfigFile, THREAD);
1952     }
1953     log_info(cds)("Reading extra data: done.");
1954 
1955     HeapShared::init_subgraph_entry_fields(THREAD);
1956 
1957     // Rewrite and link classes
1958     log_info(cds)("Rewriting and linking classes ...");
1959 
1960     // Link any classes which got missed. This would happen if we have loaded classes that
1961     // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
1962     // fails verification, all other interfaces that were not specified in the classlist but
1963     // are implemented by K are not verified.
1964     link_and_cleanup_shared_classes(CATCH);
1965     log_info(cds)("Rewriting and linking classes: done");
1966 
1967 #if INCLUDE_CDS_JAVA_HEAP
1968     if (use_full_module_graph()) {
1969       HeapShared::reset_archived_object_states(THREAD);
1970     }
1971 #endif
1972 
1973     VM_PopulateDumpSharedSpace op;
1974     MutexLocker ml(THREAD, HeapShared::is_heap_object_archiving_allowed() ?
1975                    Heap_lock : NULL);     // needed by HeapShared::run_gc()
1976     VMThread::execute(&op);
1977   }
1978 }
1979 
1980 
1981 int MetaspaceShared::preload_classes(const char* class_list_path, TRAPS) {
1982   ClassListParser parser(class_list_path);
1983   int class_count = 0;
1984 
1985   while (parser.parse_one_line()) {
1986     Klass* klass = parser.load_current_class(THREAD);
1987     if (HAS_PENDING_EXCEPTION) {
1988       if (klass == NULL &&
1989           (PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_ClassNotFoundException())) {
1990         // print a warning only when the pending exception is class not found
1991         log_warning(cds)("Preload Warning: Cannot find %s", parser.current_class_name());
1992       }
1993       CLEAR_PENDING_EXCEPTION;
1994     }
1995     if (klass != NULL) {
1996       if (log_is_enabled(Trace, cds)) {
1997         ResourceMark rm(THREAD);
1998         log_trace(cds)("Shared spaces preloaded: %s", klass->external_name());
1999       }
2000 
2001       if (klass->is_instance_klass()) {
2002         InstanceKlass* ik = InstanceKlass::cast(klass);
2003 
2004         // Link the class to cause the bytecodes to be rewritten and the
2005         // cpcache to be created. The linking is done as soon as classes
2006         // are loaded in order that the related data structures (klass and
2007         // cpCache) are located together.
2008         try_link_class(ik, THREAD);
2009         guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
2010       }
2011 
2012       class_count++;
2013     }
2014   }
2015 
2016   return class_count;
2017 }
2018 
2019 // Returns true if the class's status has changed
2020 bool MetaspaceShared::try_link_class(InstanceKlass* ik, TRAPS) {
2021   Arguments::assert_is_dumping_archive();
2022   if (ik->init_state() < InstanceKlass::linked &&
2023       !SystemDictionaryShared::has_class_failed_verification(ik)) {
2024     bool saved = BytecodeVerificationLocal;
2025     if (ik->is_shared_unregistered_class() && ik->class_loader() == NULL) {
2026       // The verification decision is based on BytecodeVerificationRemote
2027       // for non-system classes. Since we are using the NULL classloader
2028       // to load non-system classes for customized class loaders during dumping,
2029       // we need to temporarily change BytecodeVerificationLocal to be the same as
2030       // BytecodeVerificationRemote. Note this can cause the parent system
2031       // classes also being verified. The extra overhead is acceptable during
2032       // dumping.
2033       BytecodeVerificationLocal = BytecodeVerificationRemote;
2034     }
2035     ik->link_class(THREAD);
2036     if (HAS_PENDING_EXCEPTION) {
2037       ResourceMark rm(THREAD);
2038       log_warning(cds)("Preload Warning: Verification failed for %s",
2039                     ik->external_name());
2040       CLEAR_PENDING_EXCEPTION;
2041       SystemDictionaryShared::set_class_has_failed_verification(ik);
2042       _has_error_classes = true;
2043     }
2044     BytecodeVerificationLocal = saved;
2045     return true;
2046   } else {
2047     return false;
2048   }
2049 }
2050 
2051 #if INCLUDE_CDS_JAVA_HEAP
2052 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() {
2053   // The closed and open archive heap space has maximum two regions.
2054   // See FileMapInfo::write_archive_heap_regions() for details.
2055   _closed_archive_heap_regions = new GrowableArray<MemRegion>(2);
2056   _open_archive_heap_regions = new GrowableArray<MemRegion>(2);
2057   HeapShared::archive_java_heap_objects(_closed_archive_heap_regions,
2058                                         _open_archive_heap_regions);
2059   ArchiveCompactor::OtherROAllocMark mark;
2060   HeapShared::write_subgraph_info_table();
2061 }
2062 
2063 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps() {
2064   if (HeapShared::is_heap_object_archiving_allowed()) {
2065     _closed_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
2066     dump_archive_heap_oopmaps(_closed_archive_heap_regions, _closed_archive_heap_oopmaps);
2067 
2068     _open_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
2069     dump_archive_heap_oopmaps(_open_archive_heap_regions, _open_archive_heap_oopmaps);
2070   }
2071 }
2072 
2073 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
2074                                                            GrowableArray<ArchiveHeapOopmapInfo>* oopmaps) {
2075   for (int i=0; i<regions->length(); i++) {
2076     ResourceBitMap oopmap = HeapShared::calculate_oopmap(regions->at(i));
2077     size_t size_in_bits = oopmap.size();
2078     size_t size_in_bytes = oopmap.size_in_bytes();
2079     uintptr_t* buffer = (uintptr_t*)NEW_C_HEAP_ARRAY(char, size_in_bytes, mtInternal);
2080     oopmap.write_to(buffer, size_in_bytes);
2081     log_info(cds, heap)("Oopmap = " INTPTR_FORMAT " (" SIZE_FORMAT_W(6) " bytes) for heap region "
2082                         INTPTR_FORMAT " (" SIZE_FORMAT_W(8) " bytes)",
2083                         p2i(buffer), size_in_bytes,
2084                         p2i(regions->at(i).start()), regions->at(i).byte_size());
2085 
2086     ArchiveHeapOopmapInfo info;
2087     info._oopmap = (address)buffer;
2088     info._oopmap_size_in_bits = size_in_bits;
2089     info._oopmap_size_in_bytes = size_in_bytes;
2090     oopmaps->append(info);
2091   }
2092 }
2093 #endif // INCLUDE_CDS_JAVA_HEAP
2094 
2095 void ReadClosure::do_ptr(void** p) {
2096   assert(*p == NULL, "initializing previous initialized pointer.");
2097   intptr_t obj = nextPtr();
2098   assert((intptr_t)obj >= 0 || (intptr_t)obj < -100,
2099          "hit tag while initializing ptrs.");
2100   *p = (void*)obj;
2101 }
2102 
2103 void ReadClosure::do_u4(u4* p) {
2104   intptr_t obj = nextPtr();
2105   *p = (u4)(uintx(obj));
2106 }
2107 
2108 void ReadClosure::do_bool(bool* p) {
2109   intptr_t obj = nextPtr();
2110   *p = (bool)(uintx(obj));
2111 }
2112 
2113 void ReadClosure::do_tag(int tag) {
2114   int old_tag;
2115   old_tag = (int)(intptr_t)nextPtr();
2116   // do_int(&old_tag);
2117   assert(tag == old_tag, "old tag doesn't match");
2118   FileMapInfo::assert_mark(tag == old_tag);
2119 }
2120 
2121 void ReadClosure::do_oop(oop *p) {
2122   narrowOop o = (narrowOop)nextPtr();
2123   if (o == 0 || !HeapShared::open_archive_heap_region_mapped()) {
2124     *p = NULL;
2125   } else {
2126     assert(HeapShared::is_heap_object_archiving_allowed(),
2127            "Archived heap object is not allowed");
2128     assert(HeapShared::open_archive_heap_region_mapped(),
2129            "Open archive heap region is not mapped");
2130     *p = HeapShared::decode_from_archive(o);
2131   }
2132 }
2133 
2134 void ReadClosure::do_region(u_char* start, size_t size) {
2135   assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
2136   assert(size % sizeof(intptr_t) == 0, "bad size");
2137   do_tag((int)size);
2138   while (size > 0) {
2139     *(intptr_t*)start = nextPtr();
2140     start += sizeof(intptr_t);
2141     size -= sizeof(intptr_t);
2142   }
2143 }
2144 
2145 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
2146   assert(base <= static_top && static_top <= top, "must be");
2147   _shared_metaspace_static_top = static_top;
2148   MetaspaceObj::set_shared_metaspace_range(base, top);
2149 }
2150 
2151 // Return true if given address is in the misc data region
2152 bool MetaspaceShared::is_in_shared_region(const void* p, int idx) {
2153   return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx);
2154 }
2155 
2156 bool MetaspaceShared::is_in_trampoline_frame(address addr) {
2157   if (UseSharedSpaces && is_in_shared_region(addr, MetaspaceShared::mc)) {
2158     return true;
2159   }
2160   return false;
2161 }
2162 
2163 bool MetaspaceShared::is_shared_dynamic(void* p) {
2164   if ((p < MetaspaceObj::shared_metaspace_top()) &&
2165       (p >= _shared_metaspace_static_top)) {
2166     return true;
2167   } else {
2168     return false;
2169   }
2170 }
2171 
2172 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
2173   assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");
2174   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
2175 
2176   FileMapInfo* static_mapinfo = open_static_archive();
2177   FileMapInfo* dynamic_mapinfo = NULL;
2178 
2179   if (static_mapinfo != NULL) {
2180     dynamic_mapinfo = open_dynamic_archive();
2181 
2182     // First try to map at the requested address
2183     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
2184     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
2185       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
2186       // by the OS.
2187       log_info(cds)("Try to map archive(s) at an alternative address");
2188       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
2189     }
2190   }
2191 
2192   if (result == MAP_ARCHIVE_SUCCESS) {
2193     bool dynamic_mapped = (dynamic_mapinfo != NULL && dynamic_mapinfo->is_mapped());
2194     char* cds_base = static_mapinfo->mapped_base();
2195     char* cds_end =  dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
2196     set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
2197     _relocation_delta = static_mapinfo->relocation_delta();
2198     if (dynamic_mapped) {
2199       FileMapInfo::set_shared_path_table(dynamic_mapinfo);
2200     } else {
2201       FileMapInfo::set_shared_path_table(static_mapinfo);
2202     }
2203     _requested_base_address = static_mapinfo->requested_base_address();
2204   } else {
2205     set_shared_metaspace_range(NULL, NULL, NULL);
2206     UseSharedSpaces = false;
2207     FileMapInfo::fail_continue("Unable to map shared spaces");
2208     if (PrintSharedArchiveAndExit) {
2209       vm_exit_during_initialization("Unable to use shared archive.");
2210     }
2211   }
2212 
2213   if (static_mapinfo != NULL && !static_mapinfo->is_mapped()) {
2214     delete static_mapinfo;
2215   }
2216   if (dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped()) {
2217     delete dynamic_mapinfo;
2218   }
2219 }
2220 
2221 FileMapInfo* MetaspaceShared::open_static_archive() {
2222   FileMapInfo* mapinfo = new FileMapInfo(true);
2223   if (!mapinfo->initialize()) {
2224     delete(mapinfo);
2225     return NULL;
2226   }
2227   return mapinfo;
2228 }
2229 
2230 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
2231   if (DynamicDumpSharedSpaces) {
2232     return NULL;
2233   }
2234   if (Arguments::GetSharedDynamicArchivePath() == NULL) {
2235     return NULL;
2236   }
2237 
2238   FileMapInfo* mapinfo = new FileMapInfo(false);
2239   if (!mapinfo->initialize()) {
2240     delete(mapinfo);
2241     return NULL;
2242   }
2243   return mapinfo;
2244 }
2245 
2246 // use_requested_addr:
2247 //  true  = map at FileMapHeader::_requested_base_address
2248 //  false = map at an alternative address picked by OS.
2249 MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,
2250                                                bool use_requested_addr) {
2251   if (use_requested_addr && static_mapinfo->requested_base_address() == NULL) {
2252     log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.");
2253     return MAP_ARCHIVE_MMAP_FAILURE;
2254   }
2255 
2256   PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
2257       // For product build only -- this is for benchmarking the cost of doing relocation.
2258       // For debug builds, the check is done below, after reserving the space, for better test coverage
2259       // (see comment below).
2260       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
2261       return MAP_ARCHIVE_MMAP_FAILURE;
2262     });
2263 
2264   if (ArchiveRelocationMode == 2 && !use_requested_addr) {
2265     log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");
2266     return MAP_ARCHIVE_MMAP_FAILURE;
2267   };
2268 
2269   if (dynamic_mapinfo != NULL) {
2270     // Ensure that the OS won't be able to allocate new memory spaces between the two
2271     // archives, or else it would mess up the simple comparision in MetaspaceObj::is_shared().
2272     assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");
2273   }
2274 
2275   ReservedSpace archive_space_rs, class_space_rs;
2276   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
2277   char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo, dynamic_mapinfo,
2278                                                                  use_requested_addr, archive_space_rs,
2279                                                                  class_space_rs);
2280   if (mapped_base_address == NULL) {
2281     result = MAP_ARCHIVE_MMAP_FAILURE;
2282     log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr);
2283   } else {
2284 
2285 #ifdef ASSERT
2286     // Some sanity checks after reserving address spaces for archives
2287     //  and class space.
2288     assert(archive_space_rs.is_reserved(), "Sanity");
2289     if (Metaspace::using_class_space()) {
2290       // Class space must closely follow the archive space. Both spaces
2291       //  must be aligned correctly.
2292       assert(class_space_rs.is_reserved(),
2293              "A class space should have been reserved");
2294       assert(class_space_rs.base() >= archive_space_rs.end(),
2295              "class space should follow the cds archive space");
2296       assert(is_aligned(archive_space_rs.base(),
2297                         MetaspaceShared::reserved_space_alignment()),
2298              "Archive space misaligned");
2299       assert(is_aligned(class_space_rs.base(),
2300                         Metaspace::reserve_alignment()),
2301              "class space misaligned");
2302     }
2303 #endif // ASSERT
2304 
2305     log_debug(cds)("Reserved archive_space_rs     [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
2306                    p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size());
2307     log_debug(cds)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
2308                    p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());
2309 
2310     if (MetaspaceShared::use_windows_memory_mapping()) {
2311       // We have now reserved address space for the archives, and will map in
2312       //  the archive files into this space.
2313       //
2314       // Special handling for Windows: on Windows we cannot map a file view
2315       //  into an existing memory mapping. So, we unmap the address range we
2316       //  just reserved again, which will make it available for mapping the
2317       //  archives.
2318       // Reserving this range has not been for naught however since it makes
2319       //  us reasonably sure the address range is available.
2320       //
2321       // But still it may fail, since between unmapping the range and mapping
2322       //  in the archive someone else may grab the address space. Therefore
2323       //  there is a fallback in FileMap::map_region() where we just read in
2324       //  the archive files sequentially instead of mapping it in. We couple
2325       //  this with use_requested_addr, since we're going to patch all the
2326       //  pointers anyway so there's no benefit to mmap.
2327       if (use_requested_addr) {
2328         log_info(cds)("Windows mmap workaround: releasing archive space.");
2329         archive_space_rs.release();
2330       }
2331     }
2332     MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);
2333     MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?
2334                                      map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;
2335 
2336     DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
2337       // This is for simulating mmap failures at the requested address. In
2338       //  debug builds, we do it here (after all archives have possibly been
2339       //  mapped), so we can thoroughly test the code for failure handling
2340       //  (releasing all allocated resource, etc).
2341       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
2342       if (static_result == MAP_ARCHIVE_SUCCESS) {
2343         static_result = MAP_ARCHIVE_MMAP_FAILURE;
2344       }
2345       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
2346         dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;
2347       }
2348     });
2349 
2350     if (static_result == MAP_ARCHIVE_SUCCESS) {
2351       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
2352         result = MAP_ARCHIVE_SUCCESS;
2353       } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {
2354         assert(dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped(), "must have failed");
2355         // No need to retry mapping the dynamic archive again, as it will never succeed
2356         // (bad file, etc) -- just keep the base archive.
2357         log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",
2358                                   dynamic_mapinfo->full_path());
2359         result = MAP_ARCHIVE_SUCCESS;
2360         // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no
2361         // easy API to do that right now.
2362       } else {
2363         result = MAP_ARCHIVE_MMAP_FAILURE;
2364       }
2365     } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {
2366       result = MAP_ARCHIVE_OTHER_FAILURE;
2367     } else {
2368       result = MAP_ARCHIVE_MMAP_FAILURE;
2369     }
2370   }
2371 
2372   if (result == MAP_ARCHIVE_SUCCESS) {
2373     SharedBaseAddress = (size_t)mapped_base_address;
2374     LP64_ONLY({
2375         if (Metaspace::using_class_space()) {
2376           // Set up ccs in metaspace.
2377           Metaspace::initialize_class_space(class_space_rs);
2378 
2379           // Set up compressed Klass pointer encoding: the encoding range must
2380           //  cover both archive and class space.
2381           address cds_base = (address)static_mapinfo->mapped_base();
2382           address ccs_end = (address)class_space_rs.end();
2383           CompressedKlassPointers::initialize(cds_base, ccs_end - cds_base);
2384 
2385           // map_heap_regions() compares the current narrow oop and klass encodings
2386           // with the archived ones, so it must be done after all encodings are determined.
2387           static_mapinfo->map_heap_regions();
2388         }
2389       });
2390     log_info(cds)("optimized module handling: %s", MetaspaceShared::use_optimized_module_handling() ? "enabled" : "disabled");
2391     log_info(cds)("full module graph: %s", MetaspaceShared::use_full_module_graph() ? "enabled" : "disabled");
2392   } else {
2393     unmap_archive(static_mapinfo);
2394     unmap_archive(dynamic_mapinfo);
2395     release_reserved_spaces(archive_space_rs, class_space_rs);
2396   }
2397 
2398   return result;
2399 }
2400 
2401 
2402 // This will reserve two address spaces suitable to house Klass structures, one
2403 //  for the cds archives (static archive and optionally dynamic archive) and
2404 //  optionally one move for ccs.
2405 //
2406 // Since both spaces must fall within the compressed class pointer encoding
2407 //  range, they are allocated close to each other.
2408 //
2409 // Space for archives will be reserved first, followed by a potential gap,
2410 //  followed by the space for ccs:
2411 //
2412 // +-- Base address             A        B                     End
2413 // |                            |        |                      |
2414 // v                            v        v                      v
2415 // +-------------+--------------+        +----------------------+
2416 // | static arc  | [dyn. arch]  | [gap]  | compr. class space   |
2417 // +-------------+--------------+        +----------------------+
2418 //
2419 // (The gap may result from different alignment requirements between metaspace
2420 //  and CDS)
2421 //
2422 // If UseCompressedClassPointers is disabled, only one address space will be
2423 //  reserved:
2424 //
2425 // +-- Base address             End
2426 // |                            |
2427 // v                            v
2428 // +-------------+--------------+
2429 // | static arc  | [dyn. arch]  |
2430 // +-------------+--------------+
2431 //
2432 // Base address: If use_archive_base_addr address is true, the Base address is
2433 //  determined by the address stored in the static archive. If
2434 //  use_archive_base_addr address is false, this base address is determined
2435 //  by the platform.
2436 //
2437 // If UseCompressedClassPointers=1, the range encompassing both spaces will be
2438 //  suitable to en/decode narrow Klass pointers: the base will be valid for
2439 //  encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax.
2440 //
2441 // Return:
2442 //
2443 // - On success:
2444 //    - archive_space_rs will be reserved and large enough to host static and
2445 //      if needed dynamic archive: [Base, A).
2446 //      archive_space_rs.base and size will be aligned to CDS reserve
2447 //      granularity.
2448 //    - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will
2449 //      be reserved. Its start address will be aligned to metaspace reserve
2450 //      alignment, which may differ from CDS alignment. It will follow the cds
2451 //      archive space, close enough such that narrow class pointer encoding
2452 //      covers both spaces.
2453 //      If UseCompressedClassPointers=0, class_space_rs remains unreserved.
2454 // - On error: NULL is returned and the spaces remain unreserved.
2455 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,
2456                                                           FileMapInfo* dynamic_mapinfo,
2457                                                           bool use_archive_base_addr,
2458                                                           ReservedSpace& archive_space_rs,
2459                                                           ReservedSpace& class_space_rs) {
2460 
2461   address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : NULL);
2462   const size_t archive_space_alignment = MetaspaceShared::reserved_space_alignment();
2463 
2464   // Size and requested location of the archive_space_rs (for both static and dynamic archives)
2465   assert(static_mapinfo->mapping_base_offset() == 0, "Must be");
2466   size_t archive_end_offset  = (dynamic_mapinfo == NULL) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();
2467   size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);
2468 
2469   // If a base address is given, it must have valid alignment and be suitable as encoding base.
2470   if (base_address != NULL) {
2471     assert(is_aligned(base_address, archive_space_alignment),
2472            "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
2473     if (Metaspace::using_class_space()) {
2474       assert(CompressedKlassPointers::is_valid_base(base_address),
2475              "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
2476     }
2477   }
2478 
2479   if (!Metaspace::using_class_space()) {
2480     // Get the simple case out of the way first:
2481     // no compressed class space, simple allocation.
2482     archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
2483                                      false /* bool large */, (char*)base_address);
2484     if (archive_space_rs.is_reserved()) {
2485       assert(base_address == NULL ||
2486              (address)archive_space_rs.base() == base_address, "Sanity");
2487       // Register archive space with NMT.
2488       MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
2489       return archive_space_rs.base();
2490     }
2491     return NULL;
2492   }
2493 
2494 #ifdef _LP64
2495 
2496   // Complex case: two spaces adjacent to each other, both to be addressable
2497   //  with narrow class pointers.
2498   // We reserve the whole range spanning both spaces, then split that range up.
2499 
2500   const size_t class_space_alignment = Metaspace::reserve_alignment();
2501 
2502   // To simplify matters, lets assume that metaspace alignment will always be
2503   //  equal or a multiple of archive alignment.
2504   assert(is_power_of_2(class_space_alignment) &&
2505                        is_power_of_2(archive_space_alignment) &&
2506                        class_space_alignment >= archive_space_alignment,
2507                        "Sanity");
2508 
2509   const size_t class_space_size = CompressedClassSpaceSize;
2510   assert(CompressedClassSpaceSize > 0 &&
2511          is_aligned(CompressedClassSpaceSize, class_space_alignment),
2512          "CompressedClassSpaceSize malformed: "
2513          SIZE_FORMAT, CompressedClassSpaceSize);
2514 
2515   const size_t ccs_begin_offset = align_up(base_address + archive_space_size,
2516                                            class_space_alignment) - base_address;
2517   const size_t gap_size = ccs_begin_offset - archive_space_size;
2518 
2519   const size_t total_range_size =
2520       align_up(archive_space_size + gap_size + class_space_size,
2521                os::vm_allocation_granularity());
2522 
2523   ReservedSpace total_rs;
2524   if (base_address != NULL) {
2525     // Reserve at the given archive base address, or not at all.
2526     total_rs = ReservedSpace(total_range_size, archive_space_alignment,
2527                              false /* bool large */, (char*) base_address);
2528   } else {
2529     // Reserve at any address, but leave it up to the platform to choose a good one.
2530     total_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size);
2531   }
2532 
2533   if (!total_rs.is_reserved()) {
2534     return NULL;
2535   }
2536 
2537   // Paranoid checks:
2538   assert(base_address == NULL || (address)total_rs.base() == base_address,
2539          "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_rs.base()));
2540   assert(is_aligned(total_rs.base(), archive_space_alignment), "Sanity");
2541   assert(total_rs.size() == total_range_size, "Sanity");
2542   assert(CompressedKlassPointers::is_valid_base((address)total_rs.base()), "Sanity");
2543 
2544   // Now split up the space into ccs and cds archive. For simplicity, just leave
2545   //  the gap reserved at the end of the archive space.
2546   archive_space_rs = total_rs.first_part(ccs_begin_offset,
2547                                          (size_t)os::vm_allocation_granularity(),
2548                                          /*split=*/true);
2549   class_space_rs = total_rs.last_part(ccs_begin_offset);
2550 
2551   assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");
2552   assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");
2553   assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");
2554   assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");
2555 
2556   // NMT: fix up the space tags
2557   MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
2558   MemTracker::record_virtual_memory_type(class_space_rs.base(), mtClass);
2559 
2560   return archive_space_rs.base();
2561 
2562 #else
2563   ShouldNotReachHere();
2564   return NULL;
2565 #endif
2566 
2567 }
2568 
2569 void MetaspaceShared::release_reserved_spaces(ReservedSpace& archive_space_rs,
2570                                               ReservedSpace& class_space_rs) {
2571   if (archive_space_rs.is_reserved()) {
2572     log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
2573     archive_space_rs.release();
2574   }
2575   if (class_space_rs.is_reserved()) {
2576     log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
2577     class_space_rs.release();
2578   }
2579 }
2580 
2581 static int archive_regions[]  = {MetaspaceShared::mc,
2582                                  MetaspaceShared::rw,
2583                                  MetaspaceShared::ro};
2584 static int archive_regions_count  = 3;
2585 
2586 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
2587   assert(UseSharedSpaces, "must be runtime");
2588   if (mapinfo == NULL) {
2589     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
2590   }
2591 
2592   mapinfo->set_is_mapped(false);
2593 
2594   if (mapinfo->alignment() != (size_t)os::vm_allocation_granularity()) {
2595     log_error(cds)("Unable to map CDS archive -- os::vm_allocation_granularity() expected: " SIZE_FORMAT
2596                    " actual: %d", mapinfo->alignment(), os::vm_allocation_granularity());
2597     return MAP_ARCHIVE_OTHER_FAILURE;
2598   }
2599 
2600   MapArchiveResult result =
2601     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
2602 
2603   if (result != MAP_ARCHIVE_SUCCESS) {
2604     unmap_archive(mapinfo);
2605     return result;
2606   }
2607 
2608   if (!mapinfo->validate_shared_path_table()) {
2609     unmap_archive(mapinfo);
2610     return MAP_ARCHIVE_OTHER_FAILURE;
2611   }
2612 
2613   mapinfo->set_is_mapped(true);
2614   return MAP_ARCHIVE_SUCCESS;
2615 }
2616 
2617 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) {
2618   assert(UseSharedSpaces, "must be runtime");
2619   if (mapinfo != NULL) {
2620     mapinfo->unmap_regions(archive_regions, archive_regions_count);
2621     mapinfo->set_is_mapped(false);
2622   }
2623 }
2624 
2625 // Read the miscellaneous data from the shared file, and
2626 // serialize it out to its various destinations.
2627 
2628 void MetaspaceShared::initialize_shared_spaces() {
2629   FileMapInfo *static_mapinfo = FileMapInfo::current_info();
2630   _i2i_entry_code_buffers = static_mapinfo->i2i_entry_code_buffers();
2631   _i2i_entry_code_buffers_size = static_mapinfo->i2i_entry_code_buffers_size();
2632   char* buffer = static_mapinfo->cloned_vtables();
2633   clone_cpp_vtables((intptr_t*)buffer);
2634 
2635   // Verify various attributes of the archive, plus initialize the
2636   // shared string/symbol tables
2637   buffer = static_mapinfo->serialized_data();
2638   intptr_t* array = (intptr_t*)buffer;
2639   ReadClosure rc(&array);
2640   serialize(&rc);
2641 
2642   // Initialize the run-time symbol table.
2643   SymbolTable::create_table();
2644 
2645   static_mapinfo->patch_archived_heap_embedded_pointers();
2646 
2647   // Close the mapinfo file
2648   static_mapinfo->close();
2649 
2650   static_mapinfo->unmap_region(MetaspaceShared::bm);
2651 
2652   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
2653   if (dynamic_mapinfo != NULL) {
2654     intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
2655     ReadClosure rc(&buffer);
2656     SymbolTable::serialize_shared_table_header(&rc, false);
2657     SystemDictionaryShared::serialize_dictionary_headers(&rc, false);
2658     dynamic_mapinfo->close();
2659   }
2660 
2661   if (PrintSharedArchiveAndExit) {
2662     if (PrintSharedDictionary) {
2663       tty->print_cr("\nShared classes:\n");
2664       SystemDictionaryShared::print_on(tty);
2665     }
2666     if (FileMapInfo::current_info() == NULL || _archive_loading_failed) {
2667       tty->print_cr("archive is invalid");
2668       vm_exit(1);
2669     } else {
2670       tty->print_cr("archive is valid");
2671       vm_exit(0);
2672     }
2673   }
2674 }
2675 
2676 // JVM/TI RedefineClasses() support:
2677 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
2678   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2679 
2680   if (UseSharedSpaces) {
2681     // remap the shared readonly space to shared readwrite, private
2682     FileMapInfo* mapinfo = FileMapInfo::current_info();
2683     if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2684       return false;
2685     }
2686     if (FileMapInfo::dynamic_info() != NULL) {
2687       mapinfo = FileMapInfo::dynamic_info();
2688       if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2689         return false;
2690       }
2691     }
2692     _remapped_readwrite = true;
2693   }
2694   return true;
2695 }
2696 
2697 void MetaspaceShared::report_out_of_space(const char* name, size_t needed_bytes) {
2698   // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space.
2699   // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes
2700   // or so.
2701   _mc_region.print_out_of_space_msg(name, needed_bytes);
2702   _rw_region.print_out_of_space_msg(name, needed_bytes);
2703   _ro_region.print_out_of_space_msg(name, needed_bytes);
2704 
2705   vm_exit_during_initialization(err_msg("Unable to allocate from '%s' region", name),
2706                                 "Please reduce the number of shared classes.");
2707 }
2708 
2709 // This is used to relocate the pointers so that the base archive can be mapped at
2710 // MetaspaceShared::requested_base_address() without runtime relocation.
2711 intx MetaspaceShared::final_delta() {
2712   return intx(MetaspaceShared::requested_base_address())  // We want the base archive to be mapped to here at runtime
2713        - intx(SharedBaseAddress);                         // .. but the base archive is mapped at here at dump time
2714 }
2715 
2716 bool MetaspaceShared::use_full_module_graph() {
2717   return _use_optimized_module_handling && _use_full_module_graph &&
2718     (UseSharedSpaces || DumpSharedSpaces) && HeapShared::is_heap_object_archiving_allowed();
2719 }
2720 
2721 void MetaspaceShared::print_on(outputStream* st) {
2722   if (UseSharedSpaces || DumpSharedSpaces) {
2723     st->print("CDS archive(s) mapped at: ");
2724     address base;
2725     address top;
2726     if (UseSharedSpaces) { // Runtime
2727       base = (address)MetaspaceObj::shared_metaspace_base();
2728       address static_top = (address)_shared_metaspace_static_top;
2729       top = (address)MetaspaceObj::shared_metaspace_top();
2730       st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));
2731     } else if (DumpSharedSpaces) { // Dump Time
2732       base = (address)_shared_rs.base();
2733       top = (address)_shared_rs.end();
2734       st->print("[" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(top));
2735     }
2736     st->print("size " SIZE_FORMAT ", ", top - base);
2737     st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, (int)ArchiveRelocationMode);
2738   } else {
2739     st->print("CDS disabled.");
2740   }
2741   st->cr();
2742 }