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/gcLocker.hpp"
  40 #include "gc/shared/softRefPolicy.hpp"
  41 #include "interpreter/bytecodeStream.hpp"
  42 #include "interpreter/bytecodes.hpp"
  43 #include "logging/log.hpp"
  44 #include "logging/logMessage.hpp"
  45 #include "memory/archiveUtils.inline.hpp"
  46 #include "memory/dynamicArchive.hpp"
  47 #include "memory/filemap.hpp"
  48 #include "memory/heapShared.inline.hpp"
  49 #include "memory/metaspace.hpp"
  50 #include "memory/metaspaceClosure.hpp"
  51 #include "memory/metaspaceShared.hpp"
  52 #include "memory/resourceArea.hpp"
  53 #include "memory/universe.hpp"
  54 #include "oops/compressedOops.inline.hpp"
  55 #include "oops/instanceClassLoaderKlass.hpp"
  56 #include "oops/instanceMirrorKlass.hpp"
  57 #include "oops/instanceRefKlass.hpp"
  58 #include "oops/methodData.hpp"
  59 #include "oops/objArrayKlass.hpp"
  60 #include "oops/objArrayOop.hpp"
  61 #include "oops/oop.inline.hpp"
  62 #include "oops/typeArrayKlass.hpp"
  63 #include "prims/jvmtiRedefineClasses.hpp"
  64 #include "runtime/handles.inline.hpp"
  65 #include "runtime/os.hpp"
  66 #include "runtime/safepointVerifiers.hpp"
  67 #include "runtime/signature.hpp"
  68 #include "runtime/timerTrace.hpp"
  69 #include "runtime/vmThread.hpp"
  70 #include "runtime/vmOperations.hpp"
  71 #include "utilities/align.hpp"
  72 #include "utilities/bitMap.inline.hpp"
  73 #include "utilities/ostream.hpp"
  74 #include "utilities/defaultStream.hpp"
  75 #include "utilities/hashtable.inline.hpp"
  76 #if INCLUDE_G1GC
  77 #include "gc/g1/g1CollectedHeap.hpp"
  78 #endif
  79 
  80 ReservedSpace MetaspaceShared::_shared_rs;
  81 VirtualSpace MetaspaceShared::_shared_vs;
  82 ReservedSpace MetaspaceShared::_symbol_rs;
  83 VirtualSpace MetaspaceShared::_symbol_vs;
  84 MetaspaceSharedStats MetaspaceShared::_stats;
  85 bool MetaspaceShared::_has_error_classes;
  86 bool MetaspaceShared::_archive_loading_failed = false;
  87 bool MetaspaceShared::_remapped_readwrite = false;
  88 address MetaspaceShared::_i2i_entry_code_buffers = NULL;
  89 size_t MetaspaceShared::_i2i_entry_code_buffers_size = 0;
  90 void* MetaspaceShared::_shared_metaspace_static_top = NULL;
  91 intx MetaspaceShared::_relocation_delta;
  92 char* MetaspaceShared::_requested_base_address;
  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, mtInternal)GrowableArray<Handle>(10000, true);
 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 static void remove_unshareable_in_classes() {
 667   for (int i = 0; i < _global_klass_objects->length(); i++) {
 668     Klass* k = _global_klass_objects->at(i);
 669     if (!k->is_objArray_klass()) {
 670       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
 671       // on their array classes.
 672       assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be");
 673       k->remove_unshareable_info();
 674     }
 675   }
 676 }
 677 
 678 static void remove_java_mirror_in_classes() {
 679   for (int i = 0; i < _global_klass_objects->length(); i++) {
 680     Klass* k = _global_klass_objects->at(i);
 681     if (!k->is_objArray_klass()) {
 682       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
 683       // on their array classes.
 684       assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be");
 685       k->remove_java_mirror();
 686     }
 687   }
 688 }
 689 
 690 static void clear_basic_type_mirrors() {
 691   assert(!HeapShared::is_heap_object_archiving_allowed(), "Sanity");
 692   Universe::set_int_mirror(NULL);
 693   Universe::set_float_mirror(NULL);
 694   Universe::set_double_mirror(NULL);
 695   Universe::set_byte_mirror(NULL);
 696   Universe::set_bool_mirror(NULL);
 697   Universe::set_char_mirror(NULL);
 698   Universe::set_long_mirror(NULL);
 699   Universe::set_short_mirror(NULL);
 700   Universe::set_void_mirror(NULL);
 701 }
 702 
 703 static void rewrite_nofast_bytecode(const methodHandle& method) {
 704   BytecodeStream bcs(method);
 705   while (!bcs.is_last_bytecode()) {
 706     Bytecodes::Code opcode = bcs.next();
 707     switch (opcode) {
 708     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
 709     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;
 710     case Bytecodes::_aload_0:       *bcs.bcp() = Bytecodes::_nofast_aload_0;       break;
 711     case Bytecodes::_iload: {
 712       if (!bcs.is_wide()) {
 713         *bcs.bcp() = Bytecodes::_nofast_iload;
 714       }
 715       break;
 716     }
 717     default: break;
 718     }
 719   }
 720 }
 721 
 722 // Walk all methods in the class list to ensure that they won't be modified at
 723 // run time. This includes:
 724 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified
 725 //     at run time by RewriteBytecodes/RewriteFrequentPairs
 726 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.
 727 static void rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread) {
 728   for (int i = 0; i < _global_klass_objects->length(); i++) {
 729     Klass* k = _global_klass_objects->at(i);
 730     if (k->is_instance_klass()) {
 731       InstanceKlass* ik = InstanceKlass::cast(k);
 732       MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(thread, ik);
 733     }
 734   }
 735 }
 736 
 737 void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) {
 738   for (int i = 0; i < ik->methods()->length(); i++) {
 739     methodHandle m(thread, ik->methods()->at(i));
 740     rewrite_nofast_bytecode(m);
 741     Fingerprinter fp(m);
 742     // The side effect of this call sets method's fingerprint field.
 743     fp.fingerprint();
 744   }
 745 }
 746 
 747 // Objects of the Metadata types (such as Klass and ConstantPool) have C++ vtables.
 748 // (In GCC this is the field <Type>::_vptr, i.e., first word in the object.)
 749 //
 750 // Addresses of the vtables and the methods may be different across JVM runs,
 751 // if libjvm.so is dynamically loaded at a different base address.
 752 //
 753 // To ensure that the Metadata objects in the CDS archive always have the correct vtable:
 754 //
 755 // + at dump time:  we redirect the _vptr to point to our own vtables inside
 756 //                  the CDS image
 757 // + at run time:   we clone the actual contents of the vtables from libjvm.so
 758 //                  into our own tables.
 759 
 760 // Currently, the archive contain ONLY the following types of objects that have C++ vtables.
 761 #define CPP_VTABLE_PATCH_TYPES_DO(f) \
 762   f(ConstantPool) \
 763   f(InstanceKlass) \
 764   f(InstanceClassLoaderKlass) \
 765   f(InstanceMirrorKlass) \
 766   f(InstanceRefKlass) \
 767   f(Method) \
 768   f(ObjArrayKlass) \
 769   f(TypeArrayKlass)
 770 
 771 class CppVtableInfo {
 772   intptr_t _vtable_size;
 773   intptr_t _cloned_vtable[1];
 774 public:
 775   static int num_slots(int vtable_size) {
 776     return 1 + vtable_size; // Need to add the space occupied by _vtable_size;
 777   }
 778   int vtable_size()           { return int(uintx(_vtable_size)); }
 779   void set_vtable_size(int n) { _vtable_size = intptr_t(n); }
 780   intptr_t* cloned_vtable()   { return &_cloned_vtable[0]; }
 781   void zero()                 { memset(_cloned_vtable, 0, sizeof(intptr_t) * vtable_size()); }
 782   // Returns the address of the next CppVtableInfo that can be placed immediately after this CppVtableInfo
 783   static size_t byte_size(int vtable_size) {
 784     CppVtableInfo i;
 785     return pointer_delta(&i._cloned_vtable[vtable_size], &i, sizeof(u1));
 786   }
 787 };
 788 
 789 template <class T> class CppVtableCloner : public T {
 790   static intptr_t* vtable_of(Metadata& m) {
 791     return *((intptr_t**)&m);
 792   }
 793   static CppVtableInfo* _info;
 794 
 795   static int get_vtable_length(const char* name);
 796 
 797 public:
 798   // Allocate and initialize the C++ vtable, starting from top, but do not go past end.
 799   static intptr_t* allocate(const char* name);
 800 
 801   // Clone the vtable to ...
 802   static intptr_t* clone_vtable(const char* name, CppVtableInfo* info);
 803 
 804   static void zero_vtable_clone() {
 805     assert(DumpSharedSpaces, "dump-time only");
 806     _info->zero();
 807   }
 808 
 809   static bool is_valid_shared_object(const T* obj) {
 810     intptr_t* vptr = *(intptr_t**)obj;
 811     return vptr == _info->cloned_vtable();
 812   }
 813 };
 814 
 815 template <class T> CppVtableInfo* CppVtableCloner<T>::_info = NULL;
 816 
 817 template <class T>
 818 intptr_t* CppVtableCloner<T>::allocate(const char* name) {
 819   assert(is_aligned(_mc_region.top(), sizeof(intptr_t)), "bad alignment");
 820   int n = get_vtable_length(name);
 821   _info = (CppVtableInfo*)_mc_region.allocate(CppVtableInfo::byte_size(n), sizeof(intptr_t));
 822   _info->set_vtable_size(n);
 823 
 824   intptr_t* p = clone_vtable(name, _info);
 825   assert((char*)p == _mc_region.top(), "must be");
 826 
 827   return _info->cloned_vtable();
 828 }
 829 
 830 template <class T>
 831 intptr_t* CppVtableCloner<T>::clone_vtable(const char* name, CppVtableInfo* info) {
 832   if (!DumpSharedSpaces) {
 833     assert(_info == 0, "_info is initialized only at dump time");
 834     _info = info; // Remember it -- it will be used by MetaspaceShared::is_valid_shared_method()
 835   }
 836   T tmp; // Allocate temporary dummy metadata object to get to the original vtable.
 837   int n = info->vtable_size();
 838   intptr_t* srcvtable = vtable_of(tmp);
 839   intptr_t* dstvtable = info->cloned_vtable();
 840 
 841   // We already checked (and, if necessary, adjusted n) when the vtables were allocated, so we are
 842   // safe to do memcpy.
 843   log_debug(cds, vtables)("Copying %3d vtable entries for %s", n, name);
 844   memcpy(dstvtable, srcvtable, sizeof(intptr_t) * n);
 845   return dstvtable + n;
 846 }
 847 
 848 // To determine the size of the vtable for each type, we use the following
 849 // trick by declaring 2 subclasses:
 850 //
 851 //   class CppVtableTesterA: public InstanceKlass {virtual int   last_virtual_method() {return 1;}    };
 852 //   class CppVtableTesterB: public InstanceKlass {virtual void* last_virtual_method() {return NULL}; };
 853 //
 854 // CppVtableTesterA and CppVtableTesterB's vtables have the following properties:
 855 // - Their size (N+1) is exactly one more than the size of InstanceKlass's vtable (N)
 856 // - The first N entries have are exactly the same as in InstanceKlass's vtable.
 857 // - Their last entry is different.
 858 //
 859 // So to determine the value of N, we just walk CppVtableTesterA and CppVtableTesterB's tables
 860 // and find the first entry that's different.
 861 //
 862 // This works on all C++ compilers supported by Oracle, but you may need to tweak it for more
 863 // esoteric compilers.
 864 
 865 template <class T> class CppVtableTesterB: public T {
 866 public:
 867   virtual int last_virtual_method() {return 1;}
 868 };
 869 
 870 template <class T> class CppVtableTesterA : public T {
 871 public:
 872   virtual void* last_virtual_method() {
 873     // Make this different than CppVtableTesterB::last_virtual_method so the C++
 874     // compiler/linker won't alias the two functions.
 875     return NULL;
 876   }
 877 };
 878 
 879 template <class T>
 880 int CppVtableCloner<T>::get_vtable_length(const char* name) {
 881   CppVtableTesterA<T> a;
 882   CppVtableTesterB<T> b;
 883 
 884   intptr_t* avtable = vtable_of(a);
 885   intptr_t* bvtable = vtable_of(b);
 886 
 887   // Start at slot 1, because slot 0 may be RTTI (on Solaris/Sparc)
 888   int vtable_len = 1;
 889   for (; ; vtable_len++) {
 890     if (avtable[vtable_len] != bvtable[vtable_len]) {
 891       break;
 892     }
 893   }
 894   log_debug(cds, vtables)("Found   %3d vtable entries for %s", vtable_len, name);
 895 
 896   return vtable_len;
 897 }
 898 
 899 #define ALLOC_CPP_VTABLE_CLONE(c) \
 900   _cloned_cpp_vtptrs[c##_Kind] = CppVtableCloner<c>::allocate(#c); \
 901   ArchivePtrMarker::mark_pointer(&_cloned_cpp_vtptrs[c##_Kind]);
 902 
 903 #define CLONE_CPP_VTABLE(c) \
 904   p = CppVtableCloner<c>::clone_vtable(#c, (CppVtableInfo*)p);
 905 
 906 #define ZERO_CPP_VTABLE(c) \
 907  CppVtableCloner<c>::zero_vtable_clone();
 908 
 909 //------------------------------ for DynamicDumpSharedSpaces - start
 910 #define DECLARE_CLONED_VTABLE_KIND(c) c ## _Kind,
 911 
 912 enum {
 913   // E.g., ConstantPool_Kind == 0, InstanceKlass == 1, etc.
 914   CPP_VTABLE_PATCH_TYPES_DO(DECLARE_CLONED_VTABLE_KIND)
 915   _num_cloned_vtable_kinds
 916 };
 917 
 918 // This is the index of all the cloned vtables. E.g., for
 919 //     ConstantPool* cp = ....; // an archived constant pool
 920 //     InstanceKlass* ik = ....;// an archived class
 921 // the following holds true:
 922 //     _cloned_cpp_vtptrs[ConstantPool_Kind]  == ((intptr_t**)cp)[0]
 923 //     _cloned_cpp_vtptrs[InstanceKlass_Kind] == ((intptr_t**)ik)[0]
 924 static intptr_t** _cloned_cpp_vtptrs = NULL;
 925 
 926 void MetaspaceShared::allocate_cloned_cpp_vtptrs() {
 927   assert(DumpSharedSpaces, "must");
 928   size_t vtptrs_bytes = _num_cloned_vtable_kinds * sizeof(intptr_t*);
 929   _cloned_cpp_vtptrs = (intptr_t**)_mc_region.allocate(vtptrs_bytes, sizeof(intptr_t*));
 930 }
 931 
 932 void MetaspaceShared::serialize_cloned_cpp_vtptrs(SerializeClosure* soc) {
 933   soc->do_ptr((void**)&_cloned_cpp_vtptrs);
 934 }
 935 
 936 intptr_t* MetaspaceShared::fix_cpp_vtable_for_dynamic_archive(MetaspaceObj::Type msotype, address obj) {
 937   Arguments::assert_is_dumping_archive();
 938   int kind = -1;
 939   switch (msotype) {
 940   case MetaspaceObj::SymbolType:
 941   case MetaspaceObj::TypeArrayU1Type:
 942   case MetaspaceObj::TypeArrayU2Type:
 943   case MetaspaceObj::TypeArrayU4Type:
 944   case MetaspaceObj::TypeArrayU8Type:
 945   case MetaspaceObj::TypeArrayOtherType:
 946   case MetaspaceObj::ConstMethodType:
 947   case MetaspaceObj::ConstantPoolCacheType:
 948   case MetaspaceObj::AnnotationsType:
 949   case MetaspaceObj::MethodCountersType:
 950   case MetaspaceObj::RecordComponentType:
 951     // These have no vtables.
 952     break;
 953   case MetaspaceObj::ClassType:
 954     {
 955       Klass* k = (Klass*)obj;
 956       assert(k->is_klass(), "must be");
 957       if (k->is_instance_klass()) {
 958         InstanceKlass* ik = InstanceKlass::cast(k);
 959         if (ik->is_class_loader_instance_klass()) {
 960           kind = InstanceClassLoaderKlass_Kind;
 961         } else if (ik->is_reference_instance_klass()) {
 962           kind = InstanceRefKlass_Kind;
 963         } else if (ik->is_mirror_instance_klass()) {
 964           kind = InstanceMirrorKlass_Kind;
 965         } else {
 966           kind = InstanceKlass_Kind;
 967         }
 968       } else if (k->is_typeArray_klass()) {
 969         kind = TypeArrayKlass_Kind;
 970       } else {
 971         assert(k->is_objArray_klass(), "must be");
 972         kind = ObjArrayKlass_Kind;
 973       }
 974     }
 975     break;
 976 
 977   case MetaspaceObj::MethodType:
 978     {
 979       Method* m = (Method*)obj;
 980       assert(m->is_method(), "must be");
 981       kind = Method_Kind;
 982     }
 983     break;
 984 
 985   case MetaspaceObj::MethodDataType:
 986     // We don't archive MethodData <-- should have been removed in removed_unsharable_info
 987     ShouldNotReachHere();
 988     break;
 989 
 990   case MetaspaceObj::ConstantPoolType:
 991     {
 992       ConstantPool *cp = (ConstantPool*)obj;
 993       assert(cp->is_constantPool(), "must be");
 994       kind = ConstantPool_Kind;
 995     }
 996     break;
 997 
 998   default:
 999     ShouldNotReachHere();
1000   }
1001 
1002   if (kind >= 0) {
1003     assert(kind < _num_cloned_vtable_kinds, "must be");
1004     return _cloned_cpp_vtptrs[kind];
1005   } else {
1006     return NULL;
1007   }
1008 }
1009 
1010 //------------------------------ for DynamicDumpSharedSpaces - end
1011 
1012 // This can be called at both dump time and run time:
1013 // - clone the contents of the c++ vtables into the space
1014 //   allocated by allocate_cpp_vtable_clones()
1015 void MetaspaceShared::clone_cpp_vtables(intptr_t* p) {
1016   assert(DumpSharedSpaces || UseSharedSpaces, "sanity");
1017   CPP_VTABLE_PATCH_TYPES_DO(CLONE_CPP_VTABLE);
1018 }
1019 
1020 void MetaspaceShared::zero_cpp_vtable_clones_for_writing() {
1021   assert(DumpSharedSpaces, "dump-time only");
1022   CPP_VTABLE_PATCH_TYPES_DO(ZERO_CPP_VTABLE);
1023 }
1024 
1025 // Allocate and initialize the C++ vtables, starting from top, but do not go past end.
1026 char* MetaspaceShared::allocate_cpp_vtable_clones() {
1027   char* cloned_vtables = _mc_region.top(); // This is the beginning of all the cloned vtables
1028 
1029   assert(DumpSharedSpaces, "dump-time only");
1030   // Layout (each slot is a intptr_t):
1031   //   [number of slots in the first vtable = n1]
1032   //   [ <n1> slots for the first vtable]
1033   //   [number of slots in the first second = n2]
1034   //   [ <n2> slots for the second vtable]
1035   //   ...
1036   // The order of the vtables is the same as the CPP_VTAB_PATCH_TYPES_DO macro.
1037   CPP_VTABLE_PATCH_TYPES_DO(ALLOC_CPP_VTABLE_CLONE);
1038 
1039   return cloned_vtables;
1040 }
1041 
1042 bool MetaspaceShared::is_valid_shared_method(const Method* m) {
1043   assert(is_in_shared_metaspace(m), "must be");
1044   return CppVtableCloner<Method>::is_valid_shared_object(m);
1045 }
1046 
1047 void WriteClosure::do_oop(oop* o) {
1048   if (*o == NULL) {
1049     _dump_region->append_intptr_t(0);
1050   } else {
1051     assert(HeapShared::is_heap_object_archiving_allowed(),
1052            "Archiving heap object is not allowed");
1053     _dump_region->append_intptr_t(
1054       (intptr_t)CompressedOops::encode_not_null(*o));
1055   }
1056 }
1057 
1058 void WriteClosure::do_region(u_char* start, size_t size) {
1059   assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
1060   assert(size % sizeof(intptr_t) == 0, "bad size");
1061   do_tag((int)size);
1062   while (size > 0) {
1063     _dump_region->append_intptr_t(*(intptr_t*)start, true);
1064     start += sizeof(intptr_t);
1065     size -= sizeof(intptr_t);
1066   }
1067 }
1068 
1069 // This is for dumping detailed statistics for the allocations
1070 // in the shared spaces.
1071 class DumpAllocStats : public ResourceObj {
1072 public:
1073 
1074   // Here's poor man's enum inheritance
1075 #define SHAREDSPACE_OBJ_TYPES_DO(f) \
1076   METASPACE_OBJ_TYPES_DO(f) \
1077   f(SymbolHashentry) \
1078   f(SymbolBucket) \
1079   f(StringHashentry) \
1080   f(StringBucket) \
1081   f(Other)
1082 
1083   enum Type {
1084     // Types are MetaspaceObj::ClassType, MetaspaceObj::SymbolType, etc
1085     SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_DECLARE)
1086     _number_of_types
1087   };
1088 
1089   static const char * type_name(Type type) {
1090     switch(type) {
1091     SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_NAME_CASE)
1092     default:
1093       ShouldNotReachHere();
1094       return NULL;
1095     }
1096   }
1097 
1098 public:
1099   enum { RO = 0, RW = 1 };
1100 
1101   int _counts[2][_number_of_types];
1102   int _bytes [2][_number_of_types];
1103 
1104   DumpAllocStats() {
1105     memset(_counts, 0, sizeof(_counts));
1106     memset(_bytes,  0, sizeof(_bytes));
1107   };
1108 
1109   void record(MetaspaceObj::Type type, int byte_size, bool read_only) {
1110     assert(int(type) >= 0 && type < MetaspaceObj::_number_of_types, "sanity");
1111     int which = (read_only) ? RO : RW;
1112     _counts[which][type] ++;
1113     _bytes [which][type] += byte_size;
1114   }
1115 
1116   void record_other_type(int byte_size, bool read_only) {
1117     int which = (read_only) ? RO : RW;
1118     _bytes [which][OtherType] += byte_size;
1119   }
1120   void print_stats(int ro_all, int rw_all, int mc_all);
1121 };
1122 
1123 void DumpAllocStats::print_stats(int ro_all, int rw_all, int mc_all) {
1124   // Calculate size of data that was not allocated by Metaspace::allocate()
1125   MetaspaceSharedStats *stats = MetaspaceShared::stats();
1126 
1127   // symbols
1128   _counts[RO][SymbolHashentryType] = stats->symbol.hashentry_count;
1129   _bytes [RO][SymbolHashentryType] = stats->symbol.hashentry_bytes;
1130 
1131   _counts[RO][SymbolBucketType] = stats->symbol.bucket_count;
1132   _bytes [RO][SymbolBucketType] = stats->symbol.bucket_bytes;
1133 
1134   // strings
1135   _counts[RO][StringHashentryType] = stats->string.hashentry_count;
1136   _bytes [RO][StringHashentryType] = stats->string.hashentry_bytes;
1137 
1138   _counts[RO][StringBucketType] = stats->string.bucket_count;
1139   _bytes [RO][StringBucketType] = stats->string.bucket_bytes;
1140 
1141   // TODO: count things like dictionary, vtable, etc
1142   _bytes[RW][OtherType] += mc_all;
1143   rw_all += mc_all; // mc is mapped Read/Write
1144 
1145   // prevent divide-by-zero
1146   if (ro_all < 1) {
1147     ro_all = 1;
1148   }
1149   if (rw_all < 1) {
1150     rw_all = 1;
1151   }
1152 
1153   int all_ro_count = 0;
1154   int all_ro_bytes = 0;
1155   int all_rw_count = 0;
1156   int all_rw_bytes = 0;
1157 
1158 // To make fmt_stats be a syntactic constant (for format warnings), use #define.
1159 #define fmt_stats "%-20s: %8d %10d %5.1f | %8d %10d %5.1f | %8d %10d %5.1f"
1160   const char *sep = "--------------------+---------------------------+---------------------------+--------------------------";
1161   const char *hdr = "                        ro_cnt   ro_bytes     % |   rw_cnt   rw_bytes     % |  all_cnt  all_bytes     %";
1162 
1163   LogMessage(cds) msg;
1164 
1165   msg.debug("Detailed metadata info (excluding st regions; rw stats include mc regions):");
1166   msg.debug("%s", hdr);
1167   msg.debug("%s", sep);
1168   for (int type = 0; type < int(_number_of_types); type ++) {
1169     const char *name = type_name((Type)type);
1170     int ro_count = _counts[RO][type];
1171     int ro_bytes = _bytes [RO][type];
1172     int rw_count = _counts[RW][type];
1173     int rw_bytes = _bytes [RW][type];
1174     int count = ro_count + rw_count;
1175     int bytes = ro_bytes + rw_bytes;
1176 
1177     double ro_perc = percent_of(ro_bytes, ro_all);
1178     double rw_perc = percent_of(rw_bytes, rw_all);
1179     double perc    = percent_of(bytes, ro_all + rw_all);
1180 
1181     msg.debug(fmt_stats, name,
1182                          ro_count, ro_bytes, ro_perc,
1183                          rw_count, rw_bytes, rw_perc,
1184                          count, bytes, perc);
1185 
1186     all_ro_count += ro_count;
1187     all_ro_bytes += ro_bytes;
1188     all_rw_count += rw_count;
1189     all_rw_bytes += rw_bytes;
1190   }
1191 
1192   int all_count = all_ro_count + all_rw_count;
1193   int all_bytes = all_ro_bytes + all_rw_bytes;
1194 
1195   double all_ro_perc = percent_of(all_ro_bytes, ro_all);
1196   double all_rw_perc = percent_of(all_rw_bytes, rw_all);
1197   double all_perc    = percent_of(all_bytes, ro_all + rw_all);
1198 
1199   msg.debug("%s", sep);
1200   msg.debug(fmt_stats, "Total",
1201                        all_ro_count, all_ro_bytes, all_ro_perc,
1202                        all_rw_count, all_rw_bytes, all_rw_perc,
1203                        all_count, all_bytes, all_perc);
1204 
1205   assert(all_ro_bytes == ro_all, "everything should have been counted");
1206   assert(all_rw_bytes == rw_all, "everything should have been counted");
1207 
1208 #undef fmt_stats
1209 }
1210 
1211 // Populate the shared space.
1212 
1213 class VM_PopulateDumpSharedSpace: public VM_Operation {
1214 private:
1215   GrowableArray<MemRegion> *_closed_archive_heap_regions;
1216   GrowableArray<MemRegion> *_open_archive_heap_regions;
1217 
1218   GrowableArray<ArchiveHeapOopmapInfo> *_closed_archive_heap_oopmaps;
1219   GrowableArray<ArchiveHeapOopmapInfo> *_open_archive_heap_oopmaps;
1220 
1221   void dump_java_heap_objects() NOT_CDS_JAVA_HEAP_RETURN;
1222   void dump_archive_heap_oopmaps() NOT_CDS_JAVA_HEAP_RETURN;
1223   void dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
1224                                  GrowableArray<ArchiveHeapOopmapInfo>* oopmaps);
1225   void dump_symbols();
1226   char* dump_read_only_tables();
1227   void print_class_stats();
1228   void print_region_stats(FileMapInfo* map_info);
1229   void print_bitmap_region_stats(size_t size, size_t total_size);
1230   void print_heap_region_stats(GrowableArray<MemRegion> *heap_mem,
1231                                const char *name, size_t total_size);
1232   void relocate_to_requested_base_address(CHeapBitMap* ptrmap);
1233   void run_gc();
1234 
1235 public:
1236 
1237   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
1238   void doit();   // outline because gdb sucks
1239   bool allow_nested_vm_operations() const { return true; }
1240 }; // class VM_PopulateDumpSharedSpace
1241 
1242 class SortedSymbolClosure: public SymbolClosure {
1243   GrowableArray<Symbol*> _symbols;
1244   virtual void do_symbol(Symbol** sym) {
1245     assert((*sym)->is_permanent(), "archived symbols must be permanent");
1246     _symbols.append(*sym);
1247   }
1248   static int compare_symbols_by_address(Symbol** a, Symbol** b) {
1249     if (a[0] < b[0]) {
1250       return -1;
1251     } else if (a[0] == b[0]) {
1252       ResourceMark rm;
1253       log_warning(cds)("Duplicated symbol %s unexpected", (*a)->as_C_string());
1254       return 0;
1255     } else {
1256       return 1;
1257     }
1258   }
1259 
1260 public:
1261   SortedSymbolClosure() {
1262     SymbolTable::symbols_do(this);
1263     _symbols.sort(compare_symbols_by_address);
1264   }
1265   GrowableArray<Symbol*>* get_sorted_symbols() {
1266     return &_symbols;
1267   }
1268 };
1269 
1270 // ArchiveCompactor --
1271 //
1272 // This class is the central piece of shared archive compaction -- all metaspace data are
1273 // initially allocated outside of the shared regions. ArchiveCompactor copies the
1274 // metaspace data into their final location in the shared regions.
1275 
1276 class ArchiveCompactor : AllStatic {
1277   static const int INITIAL_TABLE_SIZE = 8087;
1278   static const int MAX_TABLE_SIZE     = 1000000;
1279 
1280   static DumpAllocStats* _alloc_stats;
1281   static SortedSymbolClosure* _ssc;
1282 
1283   typedef KVHashtable<address, address, mtInternal> RelocationTable;
1284   static RelocationTable* _new_loc_table;
1285 
1286 public:
1287   static void initialize() {
1288     _alloc_stats = new(ResourceObj::C_HEAP, mtInternal)DumpAllocStats;
1289     _new_loc_table = new RelocationTable(INITIAL_TABLE_SIZE);
1290   }
1291   static DumpAllocStats* alloc_stats() {
1292     return _alloc_stats;
1293   }
1294 
1295   // Use this when you allocate space with MetaspaceShare::read_only_space_alloc()
1296   // outside of ArchiveCompactor::allocate(). These are usually for misc tables
1297   // that are allocated in the RO space.
1298   class OtherROAllocMark {
1299     char* _oldtop;
1300   public:
1301     OtherROAllocMark() {
1302       _oldtop = _ro_region.top();
1303     }
1304     ~OtherROAllocMark() {
1305       char* newtop = _ro_region.top();
1306       ArchiveCompactor::alloc_stats()->record_other_type(int(newtop - _oldtop), true);
1307     }
1308   };
1309 
1310   static void allocate(MetaspaceClosure::Ref* ref, bool read_only) {
1311     address obj = ref->obj();
1312     int bytes = ref->size() * BytesPerWord;
1313     char* p;
1314     size_t alignment = BytesPerWord;
1315     char* oldtop;
1316     char* newtop;
1317 
1318     if (read_only) {
1319       oldtop = _ro_region.top();
1320       p = _ro_region.allocate(bytes, alignment);
1321       newtop = _ro_region.top();
1322     } else {
1323       oldtop = _rw_region.top();
1324       if (ref->msotype() == MetaspaceObj::ClassType) {
1325         // Save a pointer immediate in front of an InstanceKlass, so
1326         // we can do a quick lookup from InstanceKlass* -> RunTimeSharedClassInfo*
1327         // without building another hashtable. See RunTimeSharedClassInfo::get_for()
1328         // in systemDictionaryShared.cpp.
1329         Klass* klass = (Klass*)obj;
1330         if (klass->is_instance_klass()) {
1331           SystemDictionaryShared::validate_before_archiving(InstanceKlass::cast(klass));
1332           _rw_region.allocate(sizeof(address), BytesPerWord);
1333         }
1334       }
1335       p = _rw_region.allocate(bytes, alignment);
1336       newtop = _rw_region.top();
1337     }
1338     memcpy(p, obj, bytes);
1339 
1340     intptr_t* cloned_vtable = MetaspaceShared::fix_cpp_vtable_for_dynamic_archive(ref->msotype(), (address)p);
1341     if (cloned_vtable != NULL) {
1342       *(address*)p = (address)cloned_vtable;
1343       ArchivePtrMarker::mark_pointer((address*)p);
1344     }
1345 
1346     assert(_new_loc_table->lookup(obj) == NULL, "each object can be relocated at most once");
1347     _new_loc_table->add(obj, (address)p);
1348     log_trace(cds)("Copy: " PTR_FORMAT " ==> " PTR_FORMAT " %d", p2i(obj), p2i(p), bytes);
1349     if (_new_loc_table->maybe_grow(MAX_TABLE_SIZE)) {
1350       log_info(cds, hashtables)("Expanded _new_loc_table to %d", _new_loc_table->table_size());
1351     }
1352     _alloc_stats->record(ref->msotype(), int(newtop - oldtop), read_only);
1353   }
1354 
1355   static address get_new_loc(MetaspaceClosure::Ref* ref) {
1356     address* pp = _new_loc_table->lookup(ref->obj());
1357     assert(pp != NULL, "must be");
1358     return *pp;
1359   }
1360 
1361 private:
1362   // Makes a shallow copy of visited MetaspaceObj's
1363   class ShallowCopier: public UniqueMetaspaceClosure {
1364     bool _read_only;
1365   public:
1366     ShallowCopier(bool read_only) : _read_only(read_only) {}
1367 
1368     virtual bool do_unique_ref(Ref* ref, bool read_only) {
1369       if (read_only == _read_only) {
1370         allocate(ref, read_only);
1371       }
1372       return true; // recurse into ref.obj()
1373     }
1374   };
1375 
1376   // Relocate embedded pointers within a MetaspaceObj's shallow copy
1377   class ShallowCopyEmbeddedRefRelocator: public UniqueMetaspaceClosure {
1378   public:
1379     virtual bool do_unique_ref(Ref* ref, bool read_only) {
1380       address new_loc = get_new_loc(ref);
1381       RefRelocator refer;
1382       ref->metaspace_pointers_do_at(&refer, new_loc);
1383       return true; // recurse into ref.obj()
1384     }
1385     virtual void push_special(SpecialRef type, Ref* ref, intptr_t* p) {
1386       assert(type == _method_entry_ref, "only special type allowed for now");
1387       address obj = ref->obj();
1388       address new_obj = get_new_loc(ref);
1389       size_t offset = pointer_delta(p, obj,  sizeof(u1));
1390       intptr_t* new_p = (intptr_t*)(new_obj + offset);
1391       assert(*p == *new_p, "must be a copy");
1392       ArchivePtrMarker::mark_pointer((address*)new_p);
1393     }
1394   };
1395 
1396   // Relocate a reference to point to its shallow copy
1397   class RefRelocator: public MetaspaceClosure {
1398   public:
1399     virtual bool do_ref(Ref* ref, bool read_only) {
1400       if (ref->not_null()) {
1401         ref->update(get_new_loc(ref));
1402         ArchivePtrMarker::mark_pointer(ref->addr());
1403       }
1404       return false; // Do not recurse.
1405     }
1406   };
1407 
1408 #ifdef ASSERT
1409   class IsRefInArchiveChecker: public MetaspaceClosure {
1410   public:
1411     virtual bool do_ref(Ref* ref, bool read_only) {
1412       if (ref->not_null()) {
1413         char* obj = (char*)ref->obj();
1414         assert(_ro_region.contains(obj) || _rw_region.contains(obj),
1415                "must be relocated to point to CDS archive");
1416       }
1417       return false; // Do not recurse.
1418     }
1419   };
1420 #endif
1421 
1422 public:
1423   static void copy_and_compact() {
1424     ResourceMark rm;
1425     SortedSymbolClosure the_ssc; // StackObj
1426     _ssc = &the_ssc;
1427 
1428     log_info(cds)("Scanning all metaspace objects ... ");
1429     {
1430       // allocate and shallow-copy RW objects, immediately following the MC region
1431       log_info(cds)("Allocating RW objects ... ");
1432       _mc_region.pack(&_rw_region);
1433 
1434       ResourceMark rm;
1435       ShallowCopier rw_copier(false);
1436       iterate_roots(&rw_copier);
1437     }
1438     {
1439       // allocate and shallow-copy of RO object, immediately following the RW region
1440       log_info(cds)("Allocating RO objects ... ");
1441       _rw_region.pack(&_ro_region);
1442 
1443       ResourceMark rm;
1444       ShallowCopier ro_copier(true);
1445       iterate_roots(&ro_copier);
1446     }
1447     {
1448       log_info(cds)("Relocating embedded pointers ... ");
1449       ResourceMark rm;
1450       ShallowCopyEmbeddedRefRelocator emb_reloc;
1451       iterate_roots(&emb_reloc);
1452     }
1453     {
1454       log_info(cds)("Relocating external roots ... ");
1455       ResourceMark rm;
1456       RefRelocator ext_reloc;
1457       iterate_roots(&ext_reloc);
1458     }
1459     {
1460       log_info(cds)("Fixing symbol identity hash ... ");
1461       os::init_random(0x12345678);
1462       GrowableArray<Symbol*>* symbols = _ssc->get_sorted_symbols();
1463       for (int i=0; i<symbols->length(); i++) {
1464         symbols->at(i)->update_identity_hash();
1465       }
1466     }
1467 #ifdef ASSERT
1468     {
1469       log_info(cds)("Verifying external roots ... ");
1470       ResourceMark rm;
1471       IsRefInArchiveChecker checker;
1472       iterate_roots(&checker);
1473     }
1474 #endif
1475 
1476 
1477     // cleanup
1478     _ssc = NULL;
1479   }
1480 
1481   // We must relocate the System::_well_known_klasses only after we have copied the
1482   // java objects in during dump_java_heap_objects(): during the object copy, we operate on
1483   // old objects which assert that their klass is the original klass.
1484   static void relocate_well_known_klasses() {
1485     {
1486       log_info(cds)("Relocating SystemDictionary::_well_known_klasses[] ... ");
1487       ResourceMark rm;
1488       RefRelocator ext_reloc;
1489       SystemDictionary::well_known_klasses_do(&ext_reloc);
1490     }
1491     // NOTE: after this point, we shouldn't have any globals that can reach the old
1492     // objects.
1493 
1494     // We cannot use any of the objects in the heap anymore (except for the
1495     // shared strings) because their headers no longer point to valid Klasses.
1496   }
1497 
1498   static void iterate_roots(MetaspaceClosure* it) {
1499     // To ensure deterministic contents in the archive, we just need to ensure that
1500     // we iterate the MetsapceObjs in a deterministic order. It doesn't matter where
1501     // the MetsapceObjs are located originally, as they are copied sequentially into
1502     // the archive during the iteration.
1503     //
1504     // The only issue here is that the symbol table and the system directories may be
1505     // randomly ordered, so we copy the symbols and klasses into two arrays and sort
1506     // them deterministically.
1507     //
1508     // During -Xshare:dump, the order of Symbol creation is strictly determined by
1509     // the SharedClassListFile (class loading is done in a single thread and the JIT
1510     // is disabled). Also, Symbols are allocated in monotonically increasing addresses
1511     // (see Symbol::operator new(size_t, int)). So if we iterate the Symbols by
1512     // ascending address order, we ensure that all Symbols are copied into deterministic
1513     // locations in the archive.
1514     GrowableArray<Symbol*>* symbols = _ssc->get_sorted_symbols();
1515     for (int i=0; i<symbols->length(); i++) {
1516       it->push(symbols->adr_at(i));
1517     }
1518     if (_global_klass_objects != NULL) {
1519       // Need to fix up the pointers
1520       for (int i = 0; i < _global_klass_objects->length(); i++) {
1521         // NOTE -- this requires that the vtable is NOT yet patched, or else we are hosed.
1522         it->push(_global_klass_objects->adr_at(i));
1523       }
1524     }
1525     FileMapInfo::metaspace_pointers_do(it, false);
1526     SystemDictionaryShared::dumptime_classes_do(it);
1527     Universe::metaspace_pointers_do(it);
1528     SymbolTable::metaspace_pointers_do(it);
1529     vmSymbols::metaspace_pointers_do(it);
1530 
1531     it->finish();
1532   }
1533 
1534   static Klass* get_relocated_klass(Klass* orig_klass) {
1535     assert(DumpSharedSpaces, "dump time only");
1536     address* pp = _new_loc_table->lookup((address)orig_klass);
1537     assert(pp != NULL, "must be");
1538     Klass* klass = (Klass*)(*pp);
1539     assert(klass->is_klass(), "must be");
1540     return klass;
1541   }
1542 };
1543 
1544 DumpAllocStats* ArchiveCompactor::_alloc_stats;
1545 SortedSymbolClosure* ArchiveCompactor::_ssc;
1546 ArchiveCompactor::RelocationTable* ArchiveCompactor::_new_loc_table;
1547 
1548 void VM_PopulateDumpSharedSpace::dump_symbols() {
1549   log_info(cds)("Dumping symbol table ...");
1550 
1551   NOT_PRODUCT(SymbolTable::verify());
1552   SymbolTable::write_to_archive();
1553 }
1554 
1555 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
1556   ArchiveCompactor::OtherROAllocMark mark;
1557 
1558   log_info(cds)("Removing java_mirror ... ");
1559   if (!HeapShared::is_heap_object_archiving_allowed()) {
1560     clear_basic_type_mirrors();
1561   }
1562   remove_java_mirror_in_classes();
1563   log_info(cds)("done. ");
1564 
1565   SystemDictionaryShared::write_to_archive();
1566 
1567   // Write the other data to the output array.
1568   char* start = _ro_region.top();
1569   WriteClosure wc(&_ro_region);
1570   MetaspaceShared::serialize(&wc);
1571 
1572   // Write the bitmaps for patching the archive heap regions
1573   _closed_archive_heap_oopmaps = NULL;
1574   _open_archive_heap_oopmaps = NULL;
1575   dump_archive_heap_oopmaps();
1576 
1577   return start;
1578 }
1579 
1580 void VM_PopulateDumpSharedSpace::print_class_stats() {
1581   log_info(cds)("Number of classes %d", _global_klass_objects->length());
1582   {
1583     int num_type_array = 0, num_obj_array = 0, num_inst = 0;
1584     for (int i = 0; i < _global_klass_objects->length(); i++) {
1585       Klass* k = _global_klass_objects->at(i);
1586       if (k->is_instance_klass()) {
1587         num_inst ++;
1588       } else if (k->is_objArray_klass()) {
1589         num_obj_array ++;
1590       } else {
1591         assert(k->is_typeArray_klass(), "sanity");
1592         num_type_array ++;
1593       }
1594     }
1595     log_info(cds)("    instance classes   = %5d", num_inst);
1596     log_info(cds)("    obj array classes  = %5d", num_obj_array);
1597     log_info(cds)("    type array classes = %5d", num_type_array);
1598   }
1599 }
1600 
1601 void VM_PopulateDumpSharedSpace::relocate_to_requested_base_address(CHeapBitMap* ptrmap) {
1602   intx addr_delta = MetaspaceShared::final_delta();
1603   if (addr_delta == 0) {
1604     ArchivePtrMarker::compact((address)SharedBaseAddress, (address)_ro_region.top());
1605   } else {
1606     // We are not able to reserve space at MetaspaceShared::requested_base_address() (due to ASLR).
1607     // This means that the current content of the archive is based on a random
1608     // address. Let's relocate all the pointers, so that it can be mapped to
1609     // MetaspaceShared::requested_base_address() without runtime relocation.
1610     //
1611     // Note: both the base and dynamic archive are written with
1612     // FileMapHeader::_requested_base_address == MetaspaceShared::requested_base_address()
1613 
1614     // Patch all pointers that are marked by ptrmap within this region,
1615     // where we have just dumped all the metaspace data.
1616     address patch_base = (address)SharedBaseAddress;
1617     address patch_end  = (address)_ro_region.top();
1618     size_t size = patch_end - patch_base;
1619 
1620     // the current value of the pointers to be patched must be within this
1621     // range (i.e., must point to valid metaspace objects)
1622     address valid_old_base = patch_base;
1623     address valid_old_end  = patch_end;
1624 
1625     // after patching, the pointers must point inside this range
1626     // (the requested location of the archive, as mapped at runtime).
1627     address valid_new_base = (address)MetaspaceShared::requested_base_address();
1628     address valid_new_end  = valid_new_base + size;
1629 
1630     log_debug(cds)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT " ] to "
1631                    "[" INTPTR_FORMAT " - " INTPTR_FORMAT " ]", p2i(patch_base), p2i(patch_end),
1632                    p2i(valid_new_base), p2i(valid_new_end));
1633 
1634     SharedDataRelocator<true> patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end,
1635                                       valid_new_base, valid_new_end, addr_delta, ptrmap);
1636     ptrmap->iterate(&patcher);
1637     ArchivePtrMarker::compact(patcher.max_non_null_offset());
1638   }
1639 }
1640 
1641 void VM_PopulateDumpSharedSpace::run_gc() {
1642   if (HeapShared::is_heap_object_archiving_allowed()) {
1643     // Avoid fragmentation while archiving heap objects.
1644     // We do this inside a safepoint, so that no further allocation can happen after GC
1645     // has finished.
1646     if (GCLocker::is_active()) {
1647       // This should not happen during -Xshare:dump. If you see this, probably the Java core lib
1648       // has been modified such that JNI code is executed in some clean up threads after
1649       // we have finished class loading.
1650       log_warning(cds)("GC locker is held; GC is skipped. This may produce suboptimal archive heap regions.");
1651     } else {
1652       log_info(cds)("Run GC ...");
1653       Universe::heap()->collect_as_vm_thread(GCCause::_archive_time_gc);
1654       log_info(cds)("Run GC done");
1655     }
1656   }
1657 }
1658 
1659 void VM_PopulateDumpSharedSpace::doit() {
1660   run_gc();
1661   CHeapBitMap ptrmap;
1662   MetaspaceShared::initialize_ptr_marker(&ptrmap);
1663 
1664   // We should no longer allocate anything from the metaspace, so that:
1665   //
1666   // (1) Metaspace::allocate might trigger GC if we have run out of
1667   //     committed metaspace, but we can't GC because we're running
1668   //     in the VM thread.
1669   // (2) ArchiveCompactor needs to work with a stable set of MetaspaceObjs.
1670   Metaspace::freeze();
1671   DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
1672 
1673   Thread* THREAD = VMThread::vm_thread();
1674 
1675   FileMapInfo::check_nonempty_dir_in_shared_path_table();
1676 
1677   NOT_PRODUCT(SystemDictionary::verify();)
1678   // The following guarantee is meant to ensure that no loader constraints
1679   // exist yet, since the constraints table is not shared.  This becomes
1680   // more important now that we don't re-initialize vtables/itables for
1681   // shared classes at runtime, where constraints were previously created.
1682   guarantee(SystemDictionary::constraints()->number_of_entries() == 0,
1683             "loader constraints are not saved");
1684   guarantee(SystemDictionary::placeholders()->number_of_entries() == 0,
1685           "placeholders are not saved");
1686 
1687   // At this point, many classes have been loaded.
1688   // Gather systemDictionary classes in a global array and do everything to
1689   // that so we don't have to walk the SystemDictionary again.
1690   SystemDictionaryShared::check_excluded_classes();
1691   _global_klass_objects = new GrowableArray<Klass*>(1000);
1692   CollectClassesClosure collect_classes;
1693   ClassLoaderDataGraph::loaded_classes_do(&collect_classes);
1694   _global_klass_objects->sort(global_klass_compare);
1695 
1696   print_class_stats();
1697 
1698   // Ensure the ConstMethods won't be modified at run-time
1699   log_info(cds)("Updating ConstMethods ... ");
1700   rewrite_nofast_bytecodes_and_calculate_fingerprints(THREAD);
1701   log_info(cds)("done. ");
1702 
1703   // Remove all references outside the metadata
1704   log_info(cds)("Removing unshareable information ... ");
1705   remove_unshareable_in_classes();
1706   log_info(cds)("done. ");
1707 
1708   MetaspaceShared::allocate_cloned_cpp_vtptrs();
1709   char* cloned_vtables = _mc_region.top();
1710   MetaspaceShared::allocate_cpp_vtable_clones();
1711 
1712   ArchiveCompactor::initialize();
1713   ArchiveCompactor::copy_and_compact();
1714 
1715   dump_symbols();
1716 
1717   // Dump supported java heap objects
1718   _closed_archive_heap_regions = NULL;
1719   _open_archive_heap_regions = NULL;
1720   dump_java_heap_objects();
1721 
1722   ArchiveCompactor::relocate_well_known_klasses();
1723 
1724   char* serialized_data = dump_read_only_tables();
1725   _ro_region.pack();
1726 
1727   // The vtable clones contain addresses of the current process.
1728   // We don't want to write these addresses into the archive. Same for i2i buffer.
1729   MetaspaceShared::zero_cpp_vtable_clones_for_writing();
1730   memset(MetaspaceShared::i2i_entry_code_buffers(), 0,
1731          MetaspaceShared::i2i_entry_code_buffers_size());
1732 
1733   // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
1734   // without runtime relocation.
1735   relocate_to_requested_base_address(&ptrmap);
1736 
1737   // Create and write the archive file that maps the shared spaces.
1738 
1739   FileMapInfo* mapinfo = new FileMapInfo(true);
1740   mapinfo->populate_header(os::vm_allocation_granularity());
1741   mapinfo->set_serialized_data(serialized_data);
1742   mapinfo->set_cloned_vtables(cloned_vtables);
1743   mapinfo->set_i2i_entry_code_buffers(MetaspaceShared::i2i_entry_code_buffers(),
1744                                       MetaspaceShared::i2i_entry_code_buffers_size());
1745   mapinfo->open_for_write();
1746   MetaspaceShared::write_core_archive_regions(mapinfo, _closed_archive_heap_oopmaps, _open_archive_heap_oopmaps);
1747   _total_closed_archive_region_size = mapinfo->write_archive_heap_regions(
1748                                         _closed_archive_heap_regions,
1749                                         _closed_archive_heap_oopmaps,
1750                                         MetaspaceShared::first_closed_archive_heap_region,
1751                                         MetaspaceShared::max_closed_archive_heap_region);
1752   _total_open_archive_region_size = mapinfo->write_archive_heap_regions(
1753                                         _open_archive_heap_regions,
1754                                         _open_archive_heap_oopmaps,
1755                                         MetaspaceShared::first_open_archive_heap_region,
1756                                         MetaspaceShared::max_open_archive_heap_region);
1757 
1758   mapinfo->set_final_requested_base((char*)MetaspaceShared::requested_base_address());
1759   mapinfo->set_header_crc(mapinfo->compute_header_crc());
1760   mapinfo->write_header();
1761   print_region_stats(mapinfo);
1762   mapinfo->close();
1763 
1764   if (log_is_enabled(Info, cds)) {
1765     ArchiveCompactor::alloc_stats()->print_stats(int(_ro_region.used()), int(_rw_region.used()),
1766                                                  int(_mc_region.used()));
1767   }
1768 
1769   if (PrintSystemDictionaryAtExit) {
1770     SystemDictionary::print();
1771   }
1772 
1773   if (AllowArchivingWithJavaAgent) {
1774     warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1775             "for testing purposes only and should not be used in a production environment");
1776   }
1777 
1778   // There may be other pending VM operations that operate on the InstanceKlasses,
1779   // which will fail because InstanceKlasses::remove_unshareable_info()
1780   // has been called. Forget these operations and exit the VM directly.
1781   vm_direct_exit(0);
1782 }
1783 
1784 void VM_PopulateDumpSharedSpace::print_region_stats(FileMapInfo *map_info) {
1785   // Print statistics of all the regions
1786   const size_t bitmap_used = map_info->space_at(MetaspaceShared::bm)->used();
1787   const size_t bitmap_reserved = map_info->space_at(MetaspaceShared::bm)->used_aligned();
1788   const size_t total_reserved = _ro_region.reserved()  + _rw_region.reserved() +
1789                                 _mc_region.reserved()  +
1790                                 bitmap_reserved +
1791                                 _total_closed_archive_region_size +
1792                                 _total_open_archive_region_size;
1793   const size_t total_bytes = _ro_region.used()  + _rw_region.used() +
1794                              _mc_region.used()  +
1795                              bitmap_used +
1796                              _total_closed_archive_region_size +
1797                              _total_open_archive_region_size;
1798   const double total_u_perc = percent_of(total_bytes, total_reserved);
1799 
1800   _mc_region.print(total_reserved);
1801   _rw_region.print(total_reserved);
1802   _ro_region.print(total_reserved);
1803   print_bitmap_region_stats(bitmap_used, total_reserved);
1804   print_heap_region_stats(_closed_archive_heap_regions, "ca", total_reserved);
1805   print_heap_region_stats(_open_archive_heap_regions, "oa", total_reserved);
1806 
1807   log_debug(cds)("total    : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]",
1808                  total_bytes, total_reserved, total_u_perc);
1809 }
1810 
1811 void VM_PopulateDumpSharedSpace::print_bitmap_region_stats(size_t size, size_t total_size) {
1812   log_debug(cds)("bm  space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used]",
1813                  size, size/double(total_size)*100.0, size);
1814 }
1815 
1816 void VM_PopulateDumpSharedSpace::print_heap_region_stats(GrowableArray<MemRegion> *heap_mem,
1817                                                          const char *name, size_t total_size) {
1818   int arr_len = heap_mem == NULL ? 0 : heap_mem->length();
1819   for (int i = 0; i < arr_len; i++) {
1820       char* start = (char*)heap_mem->at(i).start();
1821       size_t size = heap_mem->at(i).byte_size();
1822       char* top = start + size;
1823       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,
1824                      name, i, size, size/double(total_size)*100.0, size, p2i(start));
1825 
1826   }
1827 }
1828 
1829 void MetaspaceShared::write_core_archive_regions(FileMapInfo* mapinfo,
1830                                                  GrowableArray<ArchiveHeapOopmapInfo>* closed_oopmaps,
1831                                                  GrowableArray<ArchiveHeapOopmapInfo>* open_oopmaps) {
1832   // Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with
1833   // MetaspaceShared::n_regions (internal to hotspot).
1834   assert(NUM_CDS_REGIONS == MetaspaceShared::n_regions, "sanity");
1835 
1836   // mc contains the trampoline code for method entries, which are patched at run time,
1837   // so it needs to be read/write.
1838   write_region(mapinfo, mc, &_mc_region, /*read_only=*/false,/*allow_exec=*/true);
1839   write_region(mapinfo, rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);
1840   write_region(mapinfo, ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);
1841   mapinfo->write_bitmap_region(ArchivePtrMarker::ptrmap(), closed_oopmaps, open_oopmaps);
1842 }
1843 
1844 void MetaspaceShared::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only,  bool allow_exec) {
1845   mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);
1846 }
1847 
1848 // Update a Java object to point its Klass* to the new location after
1849 // shared archive has been compacted.
1850 void MetaspaceShared::relocate_klass_ptr(oop o) {
1851   assert(DumpSharedSpaces, "sanity");
1852   Klass* k = ArchiveCompactor::get_relocated_klass(o->klass());
1853   o->set_klass(k);
1854 }
1855 
1856 Klass* MetaspaceShared::get_relocated_klass(Klass *k, bool is_final) {
1857   assert(DumpSharedSpaces, "sanity");
1858   k = ArchiveCompactor::get_relocated_klass(k);
1859   if (is_final) {
1860     k = (Klass*)(address(k) + final_delta());
1861   }
1862   return k;
1863 }
1864 
1865 class LinkSharedClassesClosure : public KlassClosure {
1866   Thread* THREAD;
1867   bool    _made_progress;
1868  public:
1869   LinkSharedClassesClosure(Thread* thread) : THREAD(thread), _made_progress(false) {}
1870 
1871   void reset()               { _made_progress = false; }
1872   bool made_progress() const { return _made_progress; }
1873 
1874   void do_klass(Klass* k) {
1875     if (k->is_instance_klass()) {
1876       InstanceKlass* ik = InstanceKlass::cast(k);
1877       // For dynamic CDS dump, only link classes loaded by the builtin class loaders.
1878       bool do_linking = DumpSharedSpaces ? true : !ik->is_shared_unregistered_class();
1879       if (do_linking) {
1880         // Link the class to cause the bytecodes to be rewritten and the
1881         // cpcache to be created. Class verification is done according
1882         // to -Xverify setting.
1883         _made_progress |= MetaspaceShared::try_link_class(ik, THREAD);
1884         guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1885 
1886         if (DumpSharedSpaces) {
1887           // The following function is used to resolve all Strings in the statically
1888           // dumped classes to archive all the Strings. The archive heap is not supported
1889           // for the dynamic archive.
1890           ik->constants()->resolve_class_constants(THREAD);
1891         }
1892       }
1893     }
1894   }
1895 };
1896 
1897 void MetaspaceShared::link_and_cleanup_shared_classes(TRAPS) {
1898   // We need to iterate because verification may cause additional classes
1899   // to be loaded.
1900   LinkSharedClassesClosure link_closure(THREAD);
1901   do {
1902     link_closure.reset();
1903     ClassLoaderDataGraph::unlocked_loaded_classes_do(&link_closure);
1904     guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1905   } while (link_closure.made_progress());
1906 }
1907 
1908 void MetaspaceShared::prepare_for_dumping() {
1909   Arguments::check_unsupported_dumping_properties();
1910   ClassLoader::initialize_shared_path();
1911 }
1912 
1913 // Preload classes from a list, populate the shared spaces and dump to a
1914 // file.
1915 void MetaspaceShared::preload_and_dump(TRAPS) {
1916   { TraceTime timer("Dump Shared Spaces", TRACETIME_LOG(Info, startuptime));
1917     ResourceMark rm(THREAD);
1918     char class_list_path_str[JVM_MAXPATHLEN];
1919     // Preload classes to be shared.
1920     const char* class_list_path;
1921     if (SharedClassListFile == NULL) {
1922       // Construct the path to the class list (in jre/lib)
1923       // Walk up two directories from the location of the VM and
1924       // optionally tack on "lib" (depending on platform)
1925       os::jvm_path(class_list_path_str, sizeof(class_list_path_str));
1926       for (int i = 0; i < 3; i++) {
1927         char *end = strrchr(class_list_path_str, *os::file_separator());
1928         if (end != NULL) *end = '\0';
1929       }
1930       int class_list_path_len = (int)strlen(class_list_path_str);
1931       if (class_list_path_len >= 3) {
1932         if (strcmp(class_list_path_str + class_list_path_len - 3, "lib") != 0) {
1933           if (class_list_path_len < JVM_MAXPATHLEN - 4) {
1934             jio_snprintf(class_list_path_str + class_list_path_len,
1935                          sizeof(class_list_path_str) - class_list_path_len,
1936                          "%slib", os::file_separator());
1937             class_list_path_len += 4;
1938           }
1939         }
1940       }
1941       if (class_list_path_len < JVM_MAXPATHLEN - 10) {
1942         jio_snprintf(class_list_path_str + class_list_path_len,
1943                      sizeof(class_list_path_str) - class_list_path_len,
1944                      "%sclasslist", os::file_separator());
1945       }
1946       class_list_path = class_list_path_str;
1947     } else {
1948       class_list_path = SharedClassListFile;
1949     }
1950 
1951     log_info(cds)("Loading classes to share ...");
1952     _has_error_classes = false;
1953     int class_count = preload_classes(class_list_path, THREAD);
1954     if (ExtraSharedClassListFile) {
1955       class_count += preload_classes(ExtraSharedClassListFile, THREAD);
1956     }
1957     log_info(cds)("Loading classes to share: done.");
1958 
1959     log_info(cds)("Shared spaces: preloaded %d classes", class_count);
1960 
1961     if (SharedArchiveConfigFile) {
1962       log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
1963       read_extra_data(SharedArchiveConfigFile, THREAD);
1964     }
1965     log_info(cds)("Reading extra data: done.");
1966 
1967     HeapShared::init_subgraph_entry_fields(THREAD);
1968 
1969     // Rewrite and link classes
1970     log_info(cds)("Rewriting and linking classes ...");
1971 
1972     // Link any classes which got missed. This would happen if we have loaded classes that
1973     // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
1974     // fails verification, all other interfaces that were not specified in the classlist but
1975     // are implemented by K are not verified.
1976     link_and_cleanup_shared_classes(CATCH);
1977     log_info(cds)("Rewriting and linking classes: done");
1978 
1979     VM_PopulateDumpSharedSpace op;
1980     MutexLocker ml(THREAD, HeapShared::is_heap_object_archiving_allowed() ?
1981                    Heap_lock : NULL);     // needed for collect_as_vm_thread
1982     VMThread::execute(&op);
1983   }
1984 }
1985 
1986 
1987 int MetaspaceShared::preload_classes(const char* class_list_path, TRAPS) {
1988   ClassListParser parser(class_list_path);
1989   int class_count = 0;
1990 
1991   while (parser.parse_one_line()) {
1992     Klass* klass = parser.load_current_class(THREAD);
1993     if (HAS_PENDING_EXCEPTION) {
1994       if (klass == NULL &&
1995           (PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_ClassNotFoundException())) {
1996         // print a warning only when the pending exception is class not found
1997         log_warning(cds)("Preload Warning: Cannot find %s", parser.current_class_name());
1998       }
1999       CLEAR_PENDING_EXCEPTION;
2000     }
2001     if (klass != NULL) {
2002       if (log_is_enabled(Trace, cds)) {
2003         ResourceMark rm(THREAD);
2004         log_trace(cds)("Shared spaces preloaded: %s", klass->external_name());
2005       }
2006 
2007       if (klass->is_instance_klass()) {
2008         InstanceKlass* ik = InstanceKlass::cast(klass);
2009 
2010         // Link the class to cause the bytecodes to be rewritten and the
2011         // cpcache to be created. The linking is done as soon as classes
2012         // are loaded in order that the related data structures (klass and
2013         // cpCache) are located together.
2014         try_link_class(ik, THREAD);
2015         guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
2016       }
2017 
2018       class_count++;
2019     }
2020   }
2021 
2022   return class_count;
2023 }
2024 
2025 // Returns true if the class's status has changed
2026 bool MetaspaceShared::try_link_class(InstanceKlass* ik, TRAPS) {
2027   Arguments::assert_is_dumping_archive();
2028   if (ik->init_state() < InstanceKlass::linked &&
2029       !SystemDictionaryShared::has_class_failed_verification(ik)) {
2030     bool saved = BytecodeVerificationLocal;
2031     if (ik->is_shared_unregistered_class() && ik->class_loader() == NULL) {
2032       // The verification decision is based on BytecodeVerificationRemote
2033       // for non-system classes. Since we are using the NULL classloader
2034       // to load non-system classes for customized class loaders during dumping,
2035       // we need to temporarily change BytecodeVerificationLocal to be the same as
2036       // BytecodeVerificationRemote. Note this can cause the parent system
2037       // classes also being verified. The extra overhead is acceptable during
2038       // dumping.
2039       BytecodeVerificationLocal = BytecodeVerificationRemote;
2040     }
2041     ik->link_class(THREAD);
2042     if (HAS_PENDING_EXCEPTION) {
2043       ResourceMark rm(THREAD);
2044       log_warning(cds)("Preload Warning: Verification failed for %s",
2045                     ik->external_name());
2046       CLEAR_PENDING_EXCEPTION;
2047       SystemDictionaryShared::set_class_has_failed_verification(ik);
2048       _has_error_classes = true;
2049     }
2050     BytecodeVerificationLocal = saved;
2051     return true;
2052   } else {
2053     return false;
2054   }
2055 }
2056 
2057 #if INCLUDE_CDS_JAVA_HEAP
2058 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() {
2059   // The closed and open archive heap space has maximum two regions.
2060   // See FileMapInfo::write_archive_heap_regions() for details.
2061   _closed_archive_heap_regions = new GrowableArray<MemRegion>(2);
2062   _open_archive_heap_regions = new GrowableArray<MemRegion>(2);
2063   HeapShared::archive_java_heap_objects(_closed_archive_heap_regions,
2064                                         _open_archive_heap_regions);
2065   ArchiveCompactor::OtherROAllocMark mark;
2066   HeapShared::write_subgraph_info_table();
2067 }
2068 
2069 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps() {
2070   if (HeapShared::is_heap_object_archiving_allowed()) {
2071     _closed_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
2072     dump_archive_heap_oopmaps(_closed_archive_heap_regions, _closed_archive_heap_oopmaps);
2073 
2074     _open_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
2075     dump_archive_heap_oopmaps(_open_archive_heap_regions, _open_archive_heap_oopmaps);
2076   }
2077 }
2078 
2079 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
2080                                                            GrowableArray<ArchiveHeapOopmapInfo>* oopmaps) {
2081   for (int i=0; i<regions->length(); i++) {
2082     ResourceBitMap oopmap = HeapShared::calculate_oopmap(regions->at(i));
2083     size_t size_in_bits = oopmap.size();
2084     size_t size_in_bytes = oopmap.size_in_bytes();
2085     uintptr_t* buffer = (uintptr_t*)NEW_C_HEAP_ARRAY(char, size_in_bytes, mtInternal);
2086     oopmap.write_to(buffer, size_in_bytes);
2087     log_info(cds, heap)("Oopmap = " INTPTR_FORMAT " (" SIZE_FORMAT_W(6) " bytes) for heap region "
2088                         INTPTR_FORMAT " (" SIZE_FORMAT_W(8) " bytes)",
2089                         p2i(buffer), size_in_bytes,
2090                         p2i(regions->at(i).start()), regions->at(i).byte_size());
2091 
2092     ArchiveHeapOopmapInfo info;
2093     info._oopmap = (address)buffer;
2094     info._oopmap_size_in_bits = size_in_bits;
2095     info._oopmap_size_in_bytes = size_in_bytes;
2096     oopmaps->append(info);
2097   }
2098 }
2099 #endif // INCLUDE_CDS_JAVA_HEAP
2100 
2101 void ReadClosure::do_ptr(void** p) {
2102   assert(*p == NULL, "initializing previous initialized pointer.");
2103   intptr_t obj = nextPtr();
2104   assert((intptr_t)obj >= 0 || (intptr_t)obj < -100,
2105          "hit tag while initializing ptrs.");
2106   *p = (void*)obj;
2107 }
2108 
2109 void ReadClosure::do_u4(u4* p) {
2110   intptr_t obj = nextPtr();
2111   *p = (u4)(uintx(obj));
2112 }
2113 
2114 void ReadClosure::do_bool(bool* p) {
2115   intptr_t obj = nextPtr();
2116   *p = (bool)(uintx(obj));
2117 }
2118 
2119 void ReadClosure::do_tag(int tag) {
2120   int old_tag;
2121   old_tag = (int)(intptr_t)nextPtr();
2122   // do_int(&old_tag);
2123   assert(tag == old_tag, "old tag doesn't match");
2124   FileMapInfo::assert_mark(tag == old_tag);
2125 }
2126 
2127 void ReadClosure::do_oop(oop *p) {
2128   narrowOop o = (narrowOop)nextPtr();
2129   if (o == 0 || !HeapShared::open_archive_heap_region_mapped()) {
2130     p = NULL;
2131   } else {
2132     assert(HeapShared::is_heap_object_archiving_allowed(),
2133            "Archived heap object is not allowed");
2134     assert(HeapShared::open_archive_heap_region_mapped(),
2135            "Open archive heap region is not mapped");
2136     *p = HeapShared::decode_from_archive(o);
2137   }
2138 }
2139 
2140 void ReadClosure::do_region(u_char* start, size_t size) {
2141   assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
2142   assert(size % sizeof(intptr_t) == 0, "bad size");
2143   do_tag((int)size);
2144   while (size > 0) {
2145     *(intptr_t*)start = nextPtr();
2146     start += sizeof(intptr_t);
2147     size -= sizeof(intptr_t);
2148   }
2149 }
2150 
2151 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
2152   assert(base <= static_top && static_top <= top, "must be");
2153   _shared_metaspace_static_top = static_top;
2154   MetaspaceObj::set_shared_metaspace_range(base, top);
2155 }
2156 
2157 // Return true if given address is in the misc data region
2158 bool MetaspaceShared::is_in_shared_region(const void* p, int idx) {
2159   return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx);
2160 }
2161 
2162 bool MetaspaceShared::is_in_trampoline_frame(address addr) {
2163   if (UseSharedSpaces && is_in_shared_region(addr, MetaspaceShared::mc)) {
2164     return true;
2165   }
2166   return false;
2167 }
2168 
2169 bool MetaspaceShared::is_shared_dynamic(void* p) {
2170   if ((p < MetaspaceObj::shared_metaspace_top()) &&
2171       (p >= _shared_metaspace_static_top)) {
2172     return true;
2173   } else {
2174     return false;
2175   }
2176 }
2177 
2178 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
2179   assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");
2180   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
2181 
2182   FileMapInfo* static_mapinfo = open_static_archive();
2183   FileMapInfo* dynamic_mapinfo = NULL;
2184 
2185   if (static_mapinfo != NULL) {
2186     dynamic_mapinfo = open_dynamic_archive();
2187 
2188     // First try to map at the requested address
2189     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
2190     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
2191       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
2192       // by the OS.
2193       log_info(cds)("Try to map archive(s) at an alternative address");
2194       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
2195     }
2196   }
2197 
2198   if (result == MAP_ARCHIVE_SUCCESS) {
2199     bool dynamic_mapped = (dynamic_mapinfo != NULL && dynamic_mapinfo->is_mapped());
2200     char* cds_base = static_mapinfo->mapped_base();
2201     char* cds_end =  dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
2202     set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
2203     _relocation_delta = static_mapinfo->relocation_delta();
2204     if (dynamic_mapped) {
2205       FileMapInfo::set_shared_path_table(dynamic_mapinfo);
2206     } else {
2207       FileMapInfo::set_shared_path_table(static_mapinfo);
2208     }
2209     _requested_base_address = static_mapinfo->requested_base_address();
2210   } else {
2211     set_shared_metaspace_range(NULL, NULL, NULL);
2212     UseSharedSpaces = false;
2213     FileMapInfo::fail_continue("Unable to map shared spaces");
2214     if (PrintSharedArchiveAndExit) {
2215       vm_exit_during_initialization("Unable to use shared archive.");
2216     }
2217   }
2218 
2219   if (static_mapinfo != NULL && !static_mapinfo->is_mapped()) {
2220     delete static_mapinfo;
2221   }
2222   if (dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped()) {
2223     delete dynamic_mapinfo;
2224   }
2225 }
2226 
2227 FileMapInfo* MetaspaceShared::open_static_archive() {
2228   FileMapInfo* mapinfo = new FileMapInfo(true);
2229   if (!mapinfo->initialize()) {
2230     delete(mapinfo);
2231     return NULL;
2232   }
2233   return mapinfo;
2234 }
2235 
2236 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
2237   if (DynamicDumpSharedSpaces) {
2238     return NULL;
2239   }
2240   if (Arguments::GetSharedDynamicArchivePath() == NULL) {
2241     return NULL;
2242   }
2243 
2244   FileMapInfo* mapinfo = new FileMapInfo(false);
2245   if (!mapinfo->initialize()) {
2246     delete(mapinfo);
2247     return NULL;
2248   }
2249   return mapinfo;
2250 }
2251 
2252 // use_requested_addr:
2253 //  true  = map at FileMapHeader::_requested_base_address
2254 //  false = map at an alternative address picked by OS.
2255 MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,
2256                                                bool use_requested_addr) {
2257   if (use_requested_addr && static_mapinfo->requested_base_address() == NULL) {
2258     log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.");
2259     return MAP_ARCHIVE_MMAP_FAILURE;
2260   }
2261 
2262   PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
2263       // For product build only -- this is for benchmarking the cost of doing relocation.
2264       // For debug builds, the check is done below, after reserving the space, for better test coverage
2265       // (see comment below).
2266       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
2267       return MAP_ARCHIVE_MMAP_FAILURE;
2268     });
2269 
2270   if (ArchiveRelocationMode == 2 && !use_requested_addr) {
2271     log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");
2272     return MAP_ARCHIVE_MMAP_FAILURE;
2273   };
2274 
2275   if (dynamic_mapinfo != NULL) {
2276     // Ensure that the OS won't be able to allocate new memory spaces between the two
2277     // archives, or else it would mess up the simple comparision in MetaspaceObj::is_shared().
2278     assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");
2279   }
2280 
2281   ReservedSpace archive_space_rs, class_space_rs;
2282   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
2283   char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo, dynamic_mapinfo,
2284                                                                  use_requested_addr, archive_space_rs,
2285                                                                  class_space_rs);
2286   if (mapped_base_address == NULL) {
2287     result = MAP_ARCHIVE_MMAP_FAILURE;
2288   } else {
2289 
2290 #ifdef ASSERT
2291     // Some sanity checks after reserving address spaces for archives
2292     //  and class space.
2293     assert(archive_space_rs.is_reserved(), "Sanity");
2294     if (Metaspace::using_class_space()) {
2295       // Class space must closely follow the archive space. Both spaces
2296       //  must be aligned correctly.
2297       assert(class_space_rs.is_reserved(),
2298              "A class space should have been reserved");
2299       assert(class_space_rs.base() >= archive_space_rs.end(),
2300              "class space should follow the cds archive space");
2301       assert(is_aligned(archive_space_rs.base(),
2302                         MetaspaceShared::reserved_space_alignment()),
2303              "Archive space misaligned");
2304       assert(is_aligned(class_space_rs.base(),
2305                         Metaspace::reserve_alignment()),
2306              "class space misaligned");
2307     }
2308 #endif // ASSERT
2309 
2310     log_debug(cds)("Reserved archive_space_rs     [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
2311                    p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size());
2312     log_debug(cds)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
2313                    p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());
2314 
2315     if (MetaspaceShared::use_windows_memory_mapping()) {
2316       // We have now reserved address space for the archives, and will map in
2317       //  the archive files into this space.
2318       //
2319       // Special handling for Windows: on Windows we cannot map a file view
2320       //  into an existing memory mapping. So, we unmap the address range we
2321       //  just reserved again, which will make it available for mapping the
2322       //  archives.
2323       // Reserving this range has not been for naught however since it makes
2324       //  us reasonably sure the address range is available.
2325       //
2326       // But still it may fail, since between unmapping the range and mapping
2327       //  in the archive someone else may grab the address space. Therefore
2328       //  there is a fallback in FileMap::map_region() where we just read in
2329       //  the archive files sequentially instead of mapping it in. We couple
2330       //  this with use_requested_addr, since we're going to patch all the
2331       //  pointers anyway so there's no benefit to mmap.
2332       if (use_requested_addr) {
2333         log_info(cds)("Windows mmap workaround: releasing archive space.");
2334         archive_space_rs.release();
2335       }
2336     }
2337     MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);
2338     MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?
2339                                      map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;
2340 
2341     DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
2342       // This is for simulating mmap failures at the requested address. In
2343       //  debug builds, we do it here (after all archives have possibly been
2344       //  mapped), so we can thoroughly test the code for failure handling
2345       //  (releasing all allocated resource, etc).
2346       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
2347       if (static_result == MAP_ARCHIVE_SUCCESS) {
2348         static_result = MAP_ARCHIVE_MMAP_FAILURE;
2349       }
2350       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
2351         dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;
2352       }
2353     });
2354 
2355     if (static_result == MAP_ARCHIVE_SUCCESS) {
2356       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
2357         result = MAP_ARCHIVE_SUCCESS;
2358       } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {
2359         assert(dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped(), "must have failed");
2360         // No need to retry mapping the dynamic archive again, as it will never succeed
2361         // (bad file, etc) -- just keep the base archive.
2362         log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",
2363                                   dynamic_mapinfo->full_path());
2364         result = MAP_ARCHIVE_SUCCESS;
2365         // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no
2366         // easy API to do that right now.
2367       } else {
2368         result = MAP_ARCHIVE_MMAP_FAILURE;
2369       }
2370     } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {
2371       result = MAP_ARCHIVE_OTHER_FAILURE;
2372     } else {
2373       result = MAP_ARCHIVE_MMAP_FAILURE;
2374     }
2375   }
2376 
2377   if (result == MAP_ARCHIVE_SUCCESS) {
2378     SharedBaseAddress = (size_t)mapped_base_address;
2379     LP64_ONLY({
2380         if (Metaspace::using_class_space()) {
2381           // Set up ccs in metaspace.
2382           Metaspace::initialize_class_space(class_space_rs);
2383 
2384           // Set up compressed Klass pointer encoding: the encoding range must
2385           //  cover both archive and class space.
2386           address cds_base = (address)static_mapinfo->mapped_base();
2387           address ccs_end = (address)class_space_rs.end();
2388           CompressedKlassPointers::initialize(cds_base, ccs_end - cds_base);
2389 
2390           // map_heap_regions() compares the current narrow oop and klass encodings
2391           // with the archived ones, so it must be done after all encodings are determined.
2392           static_mapinfo->map_heap_regions();
2393         }
2394       });
2395   } else {
2396     unmap_archive(static_mapinfo);
2397     unmap_archive(dynamic_mapinfo);
2398     release_reserved_spaces(archive_space_rs, class_space_rs);
2399   }
2400 
2401   return result;
2402 }
2403 
2404 
2405 // This will reserve two address spaces suitable to house Klass structures, one
2406 //  for the cds archives (static archive and optionally dynamic archive) and
2407 //  optionally one move for ccs.
2408 //
2409 // Since both spaces must fall within the compressed class pointer encoding
2410 //  range, they are allocated close to each other.
2411 //
2412 // Space for archives will be reserved first, followed by a potential gap,
2413 //  followed by the space for ccs:
2414 //
2415 // +-- Base address             A        B                     End
2416 // |                            |        |                      |
2417 // v                            v        v                      v
2418 // +-------------+--------------+        +----------------------+
2419 // | static arc  | [dyn. arch]  | [gap]  | compr. class space   |
2420 // +-------------+--------------+        +----------------------+
2421 //
2422 // (The gap may result from different alignment requirements between metaspace
2423 //  and CDS)
2424 //
2425 // If UseCompressedClassPointers is disabled, only one address space will be
2426 //  reserved:
2427 //
2428 // +-- Base address             End
2429 // |                            |
2430 // v                            v
2431 // +-------------+--------------+
2432 // | static arc  | [dyn. arch]  |
2433 // +-------------+--------------+
2434 //
2435 // Base address: If use_archive_base_addr address is true, the Base address is
2436 //  determined by the address stored in the static archive. If
2437 //  use_archive_base_addr address is false, this base address is determined
2438 //  by the platform.
2439 //
2440 // If UseCompressedClassPointers=1, the range encompassing both spaces will be
2441 //  suitable to en/decode narrow Klass pointers: the base will be valid for
2442 //  encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax.
2443 //
2444 // Return:
2445 //
2446 // - On success:
2447 //    - archive_space_rs will be reserved and large enough to host static and
2448 //      if needed dynamic archive: [Base, A).
2449 //      archive_space_rs.base and size will be aligned to CDS reserve
2450 //      granularity.
2451 //    - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will
2452 //      be reserved. Its start address will be aligned to metaspace reserve
2453 //      alignment, which may differ from CDS alignment. It will follow the cds
2454 //      archive space, close enough such that narrow class pointer encoding
2455 //      covers both spaces.
2456 //      If UseCompressedClassPointers=0, class_space_rs remains unreserved.
2457 // - On error: NULL is returned and the spaces remain unreserved.
2458 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,
2459                                                           FileMapInfo* dynamic_mapinfo,
2460                                                           bool use_archive_base_addr,
2461                                                           ReservedSpace& archive_space_rs,
2462                                                           ReservedSpace& class_space_rs) {
2463 
2464   address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : NULL);
2465   const size_t archive_space_alignment = MetaspaceShared::reserved_space_alignment();
2466 
2467   // Size and requested location of the archive_space_rs (for both static and dynamic archives)
2468   assert(static_mapinfo->mapping_base_offset() == 0, "Must be");
2469   size_t archive_end_offset  = (dynamic_mapinfo == NULL) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();
2470   size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);
2471 
2472   // If a base address is given, it must have valid alignment and be suitable as encoding base.
2473   if (base_address != NULL) {
2474     assert(is_aligned(base_address, archive_space_alignment),
2475            "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
2476     if (Metaspace::using_class_space()) {
2477       assert(CompressedKlassPointers::is_valid_base(base_address),
2478              "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
2479     }
2480   }
2481 
2482   if (!Metaspace::using_class_space()) {
2483     // Get the simple case out of the way first:
2484     // no compressed class space, simple allocation.
2485     archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
2486                                      false /* bool large */, (char*)base_address);
2487     if (archive_space_rs.is_reserved()) {
2488       assert(base_address == NULL ||
2489              (address)archive_space_rs.base() == base_address, "Sanity");
2490       return archive_space_rs.base();
2491     }
2492     return NULL;
2493   }
2494 
2495 #ifdef _LP64
2496 
2497   // Complex case: two spaces adjacent to each other, both to be addressable
2498   //  with narrow class pointers.
2499   // We reserve the whole range spanning both spaces, then split that range up.
2500 
2501   const size_t class_space_alignment = Metaspace::reserve_alignment();
2502 
2503   // To simplify matters, lets assume that metaspace alignment will always be
2504   //  equal or a multiple of archive alignment.
2505   assert(is_power_of_2(class_space_alignment) &&
2506                        is_power_of_2(archive_space_alignment) &&
2507                        class_space_alignment >= archive_space_alignment,
2508                        "Sanity");
2509 
2510   const size_t class_space_size = CompressedClassSpaceSize;
2511   assert(CompressedClassSpaceSize > 0 &&
2512          is_aligned(CompressedClassSpaceSize, class_space_alignment),
2513          "CompressedClassSpaceSize malformed: "
2514          SIZE_FORMAT, CompressedClassSpaceSize);
2515 
2516   const size_t ccs_begin_offset = align_up(archive_space_size,
2517                                            class_space_alignment);
2518   const size_t gap_size = ccs_begin_offset - archive_space_size;
2519 
2520   const size_t total_range_size =
2521       align_up(archive_space_size + gap_size + class_space_size,
2522                os::vm_allocation_granularity());
2523 
2524   ReservedSpace total_rs;
2525   if (base_address != NULL) {
2526     // Reserve at the given archive base address, or not at all.
2527     total_rs = ReservedSpace(total_range_size, archive_space_alignment,
2528                              false /* bool large */, (char*) base_address);
2529   } else {
2530     // Reserve at any address, but leave it up to the platform to choose a good one.
2531     total_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size);
2532   }
2533 
2534   if (!total_rs.is_reserved()) {
2535     return NULL;
2536   }
2537 
2538   // Paranoid checks:
2539   assert(base_address == NULL || (address)total_rs.base() == base_address,
2540          "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_rs.base()));
2541   assert(is_aligned(total_rs.base(), archive_space_alignment), "Sanity");
2542   assert(total_rs.size() == total_range_size, "Sanity");
2543   assert(CompressedKlassPointers::is_valid_base((address)total_rs.base()), "Sanity");
2544 
2545   // Now split up the space into ccs and cds archive. For simplicity, just leave
2546   //  the gap reserved at the end of the archive space.
2547   archive_space_rs = total_rs.first_part(ccs_begin_offset,
2548                                          (size_t)os::vm_allocation_granularity(),
2549                                          /*split=*/true);
2550   class_space_rs = total_rs.last_part(ccs_begin_offset);
2551 
2552   assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");
2553   assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");
2554   assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");
2555   assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");
2556 
2557   return archive_space_rs.base();
2558 
2559 #else
2560   ShouldNotReachHere();
2561   return NULL;
2562 #endif
2563 
2564 }
2565 
2566 void MetaspaceShared::release_reserved_spaces(ReservedSpace& archive_space_rs,
2567                                               ReservedSpace& class_space_rs) {
2568   if (archive_space_rs.is_reserved()) {
2569     log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
2570     archive_space_rs.release();
2571   }
2572   if (class_space_rs.is_reserved()) {
2573     log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
2574     class_space_rs.release();
2575   }
2576 }
2577 
2578 static int archive_regions[]  = {MetaspaceShared::mc,
2579                                  MetaspaceShared::rw,
2580                                  MetaspaceShared::ro};
2581 static int archive_regions_count  = 3;
2582 
2583 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
2584   assert(UseSharedSpaces, "must be runtime");
2585   if (mapinfo == NULL) {
2586     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
2587   }
2588 
2589   mapinfo->set_is_mapped(false);
2590 
2591   if (mapinfo->alignment() != (size_t)os::vm_allocation_granularity()) {
2592     log_error(cds)("Unable to map CDS archive -- os::vm_allocation_granularity() expected: " SIZE_FORMAT
2593                    " actual: %d", mapinfo->alignment(), os::vm_allocation_granularity());
2594     return MAP_ARCHIVE_OTHER_FAILURE;
2595   }
2596 
2597   MapArchiveResult result =
2598     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
2599 
2600   if (result != MAP_ARCHIVE_SUCCESS) {
2601     unmap_archive(mapinfo);
2602     return result;
2603   }
2604 
2605   if (mapinfo->is_static()) {
2606     if (!mapinfo->validate_shared_path_table()) {
2607       unmap_archive(mapinfo);
2608       return MAP_ARCHIVE_OTHER_FAILURE;
2609     }
2610   } else {
2611     if (!DynamicArchive::validate(mapinfo)) {
2612       unmap_archive(mapinfo);
2613       return MAP_ARCHIVE_OTHER_FAILURE;
2614     }
2615   }
2616 
2617   mapinfo->set_is_mapped(true);
2618   return MAP_ARCHIVE_SUCCESS;
2619 }
2620 
2621 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) {
2622   assert(UseSharedSpaces, "must be runtime");
2623   if (mapinfo != NULL) {
2624     mapinfo->unmap_regions(archive_regions, archive_regions_count);
2625     mapinfo->set_is_mapped(false);
2626   }
2627 }
2628 
2629 // Read the miscellaneous data from the shared file, and
2630 // serialize it out to its various destinations.
2631 
2632 void MetaspaceShared::initialize_shared_spaces() {
2633   FileMapInfo *static_mapinfo = FileMapInfo::current_info();
2634   _i2i_entry_code_buffers = static_mapinfo->i2i_entry_code_buffers();
2635   _i2i_entry_code_buffers_size = static_mapinfo->i2i_entry_code_buffers_size();
2636   char* buffer = static_mapinfo->cloned_vtables();
2637   clone_cpp_vtables((intptr_t*)buffer);
2638 
2639   // Verify various attributes of the archive, plus initialize the
2640   // shared string/symbol tables
2641   buffer = static_mapinfo->serialized_data();
2642   intptr_t* array = (intptr_t*)buffer;
2643   ReadClosure rc(&array);
2644   serialize(&rc);
2645 
2646   // Initialize the run-time symbol table.
2647   SymbolTable::create_table();
2648 
2649   static_mapinfo->patch_archived_heap_embedded_pointers();
2650 
2651   // Close the mapinfo file
2652   static_mapinfo->close();
2653 
2654   static_mapinfo->unmap_region(MetaspaceShared::bm);
2655 
2656   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
2657   if (dynamic_mapinfo != NULL) {
2658     intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
2659     ReadClosure rc(&buffer);
2660     SymbolTable::serialize_shared_table_header(&rc, false);
2661     SystemDictionaryShared::serialize_dictionary_headers(&rc, false);
2662     dynamic_mapinfo->close();
2663   }
2664 
2665   if (PrintSharedArchiveAndExit) {
2666     if (PrintSharedDictionary) {
2667       tty->print_cr("\nShared classes:\n");
2668       SystemDictionaryShared::print_on(tty);
2669     }
2670     if (FileMapInfo::current_info() == NULL || _archive_loading_failed) {
2671       tty->print_cr("archive is invalid");
2672       vm_exit(1);
2673     } else {
2674       tty->print_cr("archive is valid");
2675       vm_exit(0);
2676     }
2677   }
2678 }
2679 
2680 // JVM/TI RedefineClasses() support:
2681 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
2682   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2683 
2684   if (UseSharedSpaces) {
2685     // remap the shared readonly space to shared readwrite, private
2686     FileMapInfo* mapinfo = FileMapInfo::current_info();
2687     if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2688       return false;
2689     }
2690     if (FileMapInfo::dynamic_info() != NULL) {
2691       mapinfo = FileMapInfo::dynamic_info();
2692       if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2693         return false;
2694       }
2695     }
2696     _remapped_readwrite = true;
2697   }
2698   return true;
2699 }
2700 
2701 void MetaspaceShared::report_out_of_space(const char* name, size_t needed_bytes) {
2702   // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space.
2703   // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes
2704   // or so.
2705   _mc_region.print_out_of_space_msg(name, needed_bytes);
2706   _rw_region.print_out_of_space_msg(name, needed_bytes);
2707   _ro_region.print_out_of_space_msg(name, needed_bytes);
2708 
2709   vm_exit_during_initialization(err_msg("Unable to allocate from '%s' region", name),
2710                                 "Please reduce the number of shared classes.");
2711 }
2712 
2713 // This is used to relocate the pointers so that the base archive can be mapped at
2714 // MetaspaceShared::requested_base_address() without runtime relocation.
2715 intx MetaspaceShared::final_delta() {
2716   return intx(MetaspaceShared::requested_base_address())  // We want the base archive to be mapped to here at runtime
2717        - intx(SharedBaseAddress);                         // .. but the base archive is mapped at here at dump time
2718 }
2719 
2720 void MetaspaceShared::print_on(outputStream* st) {
2721   if (UseSharedSpaces || DumpSharedSpaces) {
2722     st->print("CDS archive(s) mapped at: ");
2723     address base;
2724     address top;
2725     if (UseSharedSpaces) { // Runtime
2726       base = (address)MetaspaceObj::shared_metaspace_base();
2727       address static_top = (address)_shared_metaspace_static_top;
2728       top = (address)MetaspaceObj::shared_metaspace_top();
2729       st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));
2730     } else if (DumpSharedSpaces) { // Dump Time
2731       base = (address)_shared_rs.base();
2732       top = (address)_shared_rs.end();
2733       st->print("[" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(top));
2734     }
2735     st->print("size " SIZE_FORMAT ", ", top - base);
2736     st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, (int)ArchiveRelocationMode);
2737   } else {
2738     st->print("CDS disabled.");
2739   }
2740   st->cr();
2741 }
2742 
2743 
2744 
2745 
2746