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