1 /*
   2  * Copyright (c) 2012, 2018, 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/classListParser.hpp"
  28 #include "classfile/classLoaderExt.hpp"
  29 #include "classfile/dictionary.hpp"
  30 #include "classfile/loaderConstraints.hpp"
  31 #include "classfile/placeholders.hpp"
  32 #include "classfile/symbolTable.hpp"
  33 #include "classfile/stringTable.hpp"
  34 #include "classfile/systemDictionary.hpp"
  35 #include "classfile/systemDictionaryShared.hpp"
  36 #include "code/codeCache.hpp"
  37 #include "interpreter/bytecodeStream.hpp"
  38 #include "interpreter/bytecodes.hpp"
  39 #include "logging/log.hpp"
  40 #include "logging/logMessage.hpp"
  41 #include "memory/filemap.hpp"
  42 #include "memory/heapShared.inline.hpp"
  43 #include "memory/metaspace.hpp"
  44 #include "memory/metaspaceClosure.hpp"
  45 #include "memory/metaspaceShared.hpp"
  46 #include "memory/resourceArea.hpp"
  47 #include "oops/compressedOops.inline.hpp"
  48 #include "oops/instanceClassLoaderKlass.hpp"
  49 #include "oops/instanceMirrorKlass.hpp"
  50 #include "oops/instanceRefKlass.hpp"
  51 #include "oops/objArrayKlass.hpp"
  52 #include "oops/objArrayOop.hpp"
  53 #include "oops/oop.inline.hpp"
  54 #include "oops/typeArrayKlass.hpp"
  55 #include "prims/jvmtiRedefineClasses.hpp"
  56 #include "runtime/handles.inline.hpp"
  57 #include "runtime/os.hpp"
  58 #include "runtime/safepointVerifiers.hpp"
  59 #include "runtime/signature.hpp"
  60 #include "runtime/timerTrace.hpp"
  61 #include "runtime/vmThread.hpp"
  62 #include "runtime/vm_operations.hpp"
  63 #include "utilities/align.hpp"
  64 #include "utilities/bitMap.hpp"
  65 #include "utilities/defaultStream.hpp"
  66 #include "utilities/hashtable.inline.hpp"
  67 #if INCLUDE_G1GC
  68 #include "gc/g1/g1Allocator.inline.hpp"
  69 #include "gc/g1/g1CollectedHeap.hpp"
  70 #endif
  71 
  72 ReservedSpace MetaspaceShared::_shared_rs;
  73 VirtualSpace MetaspaceShared::_shared_vs;
  74 MetaspaceSharedStats MetaspaceShared::_stats;
  75 bool MetaspaceShared::_has_error_classes;
  76 bool MetaspaceShared::_archive_loading_failed = false;
  77 bool MetaspaceShared::_remapped_readwrite = false;
  78 bool MetaspaceShared::_open_archive_heap_region_mapped = false;
  79 address MetaspaceShared::_cds_i2i_entry_code_buffers = NULL;
  80 size_t MetaspaceShared::_cds_i2i_entry_code_buffers_size = 0;
  81 size_t MetaspaceShared::_core_spaces_size = 0;
  82 
  83 // The CDS archive is divided into the following regions:
  84 //     mc  - misc code (the method entry trampolines)
  85 //     rw  - read-write metadata
  86 //     ro  - read-only metadata and read-only tables
  87 //     md  - misc data (the c++ vtables)
  88 //     od  - optional data (original class files)
  89 //
  90 //     s0  - shared strings(closed archive heap space) #0
  91 //     s1  - shared strings(closed archive heap space) #1 (may be empty)
  92 //     oa0 - open archive heap space #0
  93 //     oa1 - open archive heap space #1 (may be empty)
  94 //
  95 // The mc, rw, ro, md and od regions are linearly allocated, starting from
  96 // SharedBaseAddress, in the order of mc->rw->ro->md->od. The size of these 5 regions
  97 // are page-aligned, and there's no gap between any consecutive regions.
  98 //
  99 // These 5 regions are populated in the following steps:
 100 // [1] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
 101 //     temporarily allocated outside of the shared regions. Only the method entry
 102 //     trampolines are written into the mc region.
 103 // [2] ArchiveCompactor copies RW metadata into the rw region.
 104 // [3] ArchiveCompactor copies RO metadata into the ro region.
 105 // [4] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
 106 //     are copied into the ro region as read-only tables.
 107 // [5] C++ vtables are copied into the md region.
 108 // [6] Original class files are copied into the od region.
 109 //
 110 // The s0/s1 and oa0/oa1 regions are populated inside MetaspaceShared::dump_java_heap_objects.
 111 // Their layout is independent of the other 5 regions.
 112 
 113 class DumpRegion {
 114 private:
 115   const char* _name;
 116   char* _base;
 117   char* _top;
 118   char* _end;
 119   bool _is_packed;
 120 
 121   char* 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     MetaspaceShared::commit_shared_space_to(newtop);
 129     _top = newtop;
 130     return _top;
 131   }
 132 
 133 public:
 134   DumpRegion(const char* name) : _name(name), _base(NULL), _top(NULL), _end(NULL), _is_packed(false) {}
 135 
 136   char* allocate(size_t num_bytes, size_t alignment=BytesPerWord) {
 137     char* p = (char*)align_up(_top, alignment);
 138     char* newtop = p + align_up(num_bytes, alignment);
 139     expand_top_to(newtop);
 140     memset(p, 0, newtop - p);
 141     return p;
 142   }
 143 
 144   void append_intptr_t(intptr_t n) {
 145     assert(is_aligned(_top, sizeof(intptr_t)), "bad alignment");
 146     intptr_t *p = (intptr_t*)_top;
 147     char* newtop = _top + sizeof(intptr_t);
 148     expand_top_to(newtop);
 149     *p = n;
 150   }
 151 
 152   char* base()      const { return _base;        }
 153   char* top()       const { return _top;         }
 154   char* end()       const { return _end;         }
 155   size_t reserved() const { return _end - _base; }
 156   size_t used()     const { return _top - _base; }
 157   bool is_packed()  const { return _is_packed;   }
 158   bool is_allocatable() const {
 159     return !is_packed() && _base != NULL;
 160   }
 161 
 162   void print(size_t total_bytes) const {
 163     tty->print_cr("%-3s space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used] at " INTPTR_FORMAT,
 164                   _name, used(), percent_of(used(), total_bytes), reserved(), percent_of(used(), reserved()), p2i(_base));
 165   }
 166   void print_out_of_space_msg(const char* failing_region, size_t needed_bytes) {
 167     tty->print("[%-8s] " PTR_FORMAT " - " PTR_FORMAT " capacity =%9d, allocated =%9d",
 168                _name, p2i(_base), p2i(_top), int(_end - _base), int(_top - _base));
 169     if (strcmp(_name, failing_region) == 0) {
 170       tty->print_cr(" required = %d", int(needed_bytes));
 171     } else {
 172       tty->cr();
 173     }
 174   }
 175 
 176   void init(const ReservedSpace* rs) {
 177     _base = _top = rs->base();
 178     _end = rs->end();
 179   }
 180   void init(char* b, char* t, char* e) {
 181     _base = b;
 182     _top = t;
 183     _end = e;
 184   }
 185 
 186   void pack(DumpRegion* next = NULL) {
 187     assert(!is_packed(), "sanity");
 188     _end = (char*)align_up(_top, Metaspace::reserve_alignment());
 189     _is_packed = true;
 190     if (next != NULL) {
 191       next->_base = next->_top = this->_end;
 192       next->_end = MetaspaceShared::shared_rs()->end();
 193     }
 194   }
 195   bool contains(char* p) {
 196     return base() <= p && p < top();
 197   }
 198 };
 199 
 200 
 201 DumpRegion _mc_region("mc"), _ro_region("ro"), _rw_region("rw"), _md_region("md"), _od_region("od");
 202 size_t _total_string_region_size = 0, _total_open_archive_region_size = 0;
 203 
 204 char* MetaspaceShared::misc_code_space_alloc(size_t num_bytes) {
 205   return _mc_region.allocate(num_bytes);
 206 }
 207 
 208 char* MetaspaceShared::read_only_space_alloc(size_t num_bytes) {
 209   return _ro_region.allocate(num_bytes);
 210 }
 211 
 212 char* MetaspaceShared::read_only_space_top() {
 213   return _ro_region.top();
 214 }
 215 
 216 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
 217   assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");
 218 
 219   // If using shared space, open the file that contains the shared space
 220   // and map in the memory before initializing the rest of metaspace (so
 221   // the addresses don't conflict)
 222   address cds_address = NULL;
 223   FileMapInfo* mapinfo = new FileMapInfo();
 224 
 225   // Open the shared archive file, read and validate the header. If
 226   // initialization fails, shared spaces [UseSharedSpaces] are
 227   // disabled and the file is closed.
 228   // Map in spaces now also
 229   if (mapinfo->initialize() && map_shared_spaces(mapinfo)) {
 230     size_t cds_total = core_spaces_size();
 231     cds_address = (address)mapinfo->header()->region_addr(0);
 232 #ifdef _LP64
 233     if (Metaspace::using_class_space()) {
 234       char* cds_end = (char*)(cds_address + cds_total);
 235       cds_end = (char *)align_up(cds_end, Metaspace::reserve_alignment());
 236       // If UseCompressedClassPointers is set then allocate the metaspace area
 237       // above the heap and above the CDS area (if it exists).
 238       Metaspace::allocate_metaspace_compressed_klass_ptrs(cds_end, cds_address);
 239       // map_heap_regions() compares the current narrow oop and klass encodings
 240       // with the archived ones, so it must be done after all encodings are determined.
 241       mapinfo->map_heap_regions();
 242     }
 243     Universe::set_narrow_klass_range(CompressedClassSpaceSize);
 244 #endif // _LP64
 245   } else {
 246     assert(!mapinfo->is_open() && !UseSharedSpaces,
 247            "archive file not closed or shared spaces not disabled.");
 248   }
 249 }
 250 
 251 void MetaspaceShared::initialize_dumptime_shared_and_meta_spaces() {
 252   assert(DumpSharedSpaces, "should be called for dump time only");
 253   const size_t reserve_alignment = Metaspace::reserve_alignment();
 254   bool large_pages = false; // No large pages when dumping the CDS archive.
 255   char* shared_base = (char*)align_up((char*)SharedBaseAddress, reserve_alignment);
 256 
 257 #ifdef _LP64
 258   // On 64-bit VM, the heap and class space layout will be the same as if
 259   // you're running in -Xshare:on mode:
 260   //
 261   //                              +-- SharedBaseAddress (default = 0x800000000)
 262   //                              v
 263   // +-..---------+---------+ ... +----+----+----+----+----+---------------+
 264   // |    Heap    | Archive |     | MC | RW | RO | MD | OD | class space   |
 265   // +-..---------+---------+ ... +----+----+----+----+----+---------------+
 266   // |<--   MaxHeapSize  -->|     |<-- UnscaledClassSpaceMax = 4GB ------->|
 267   //
 268   const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
 269   const size_t cds_total = align_down(UnscaledClassSpaceMax, reserve_alignment);
 270 #else
 271   // We don't support archives larger than 256MB on 32-bit due to limited virtual address space.
 272   size_t cds_total = align_down(256*M, reserve_alignment);
 273 #endif
 274 
 275   // First try to reserve the space at the specified SharedBaseAddress.
 276   _shared_rs = ReservedSpace(cds_total, reserve_alignment, large_pages, shared_base);
 277   if (_shared_rs.is_reserved()) {
 278     assert(shared_base == 0 || _shared_rs.base() == shared_base, "should match");
 279   } else {
 280     // Get a mmap region anywhere if the SharedBaseAddress fails.
 281     _shared_rs = ReservedSpace(cds_total, reserve_alignment, large_pages);
 282   }
 283   if (!_shared_rs.is_reserved()) {
 284     vm_exit_during_initialization("Unable to reserve memory for shared space",
 285                                   err_msg(SIZE_FORMAT " bytes.", cds_total));
 286   }
 287 
 288 #ifdef _LP64
 289   // During dump time, we allocate 4GB (UnscaledClassSpaceMax) of space and split it up:
 290   // + The upper 1 GB is used as the "temporary compressed class space" -- preload_classes()
 291   //   will store Klasses into this space.
 292   // + The lower 3 GB is used for the archive -- when preload_classes() is done,
 293   //   ArchiveCompactor will copy the class metadata into this space, first the RW parts,
 294   //   then the RO parts.
 295 
 296   assert(UseCompressedOops && UseCompressedClassPointers,
 297       "UseCompressedOops and UseCompressedClassPointers must be set");
 298 
 299   size_t max_archive_size = align_down(cds_total * 3 / 4, reserve_alignment);
 300   ReservedSpace tmp_class_space = _shared_rs.last_part(max_archive_size);
 301   CompressedClassSpaceSize = align_down(tmp_class_space.size(), reserve_alignment);
 302   _shared_rs = _shared_rs.first_part(max_archive_size);
 303 
 304   // Set up compress class pointers.
 305   Universe::set_narrow_klass_base((address)_shared_rs.base());
 306   // Set narrow_klass_shift to be LogKlassAlignmentInBytes. This is consistent
 307   // with AOT.
 308   Universe::set_narrow_klass_shift(LogKlassAlignmentInBytes);
 309   // Set the range of klass addresses to 4GB.
 310   Universe::set_narrow_klass_range(cds_total);
 311 
 312   Metaspace::initialize_class_space(tmp_class_space);
 313   log_info(cds)("narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
 314                 p2i(Universe::narrow_klass_base()), Universe::narrow_klass_shift());
 315 
 316   log_info(cds)("Allocated temporary class space: " SIZE_FORMAT " bytes at " PTR_FORMAT,
 317                 CompressedClassSpaceSize, p2i(tmp_class_space.base()));
 318 #endif
 319 
 320   // Start with 0 committed bytes. The memory will be committed as needed by
 321   // MetaspaceShared::commit_shared_space_to().
 322   if (!_shared_vs.initialize(_shared_rs, 0)) {
 323     vm_exit_during_initialization("Unable to allocate memory for shared space");
 324   }
 325 
 326   _mc_region.init(&_shared_rs);
 327   tty->print_cr("Allocated shared space: " SIZE_FORMAT " bytes at " PTR_FORMAT,
 328                 _shared_rs.size(), p2i(_shared_rs.base()));
 329 }
 330 
 331 // Called by universe_post_init()
 332 void MetaspaceShared::post_initialize(TRAPS) {
 333   if (UseSharedSpaces) {
 334     int size = FileMapInfo::get_number_of_shared_paths();
 335     if (size > 0) {
 336       SystemDictionaryShared::allocate_shared_data_arrays(size, THREAD);
 337       FileMapInfo::FileMapHeader* header = FileMapInfo::current_info()->header();
 338       ClassLoaderExt::init_paths_start_index(header->_app_class_paths_start_index);
 339       ClassLoaderExt::init_app_module_paths_start_index(header->_app_module_paths_start_index);
 340     }
 341   }
 342 
 343   if (DumpSharedSpaces) {
 344     if (SharedArchiveConfigFile) {
 345       read_extra_data(SharedArchiveConfigFile, THREAD);
 346     }
 347   }
 348 }
 349 
 350 void MetaspaceShared::read_extra_data(const char* filename, TRAPS) {
 351   HashtableTextDump reader(filename);
 352   reader.check_version("VERSION: 1.0");
 353 
 354   while (reader.remain() > 0) {
 355     int utf8_length;
 356     int prefix_type = reader.scan_prefix(&utf8_length);
 357     ResourceMark rm(THREAD);
 358     char* utf8_buffer = NEW_RESOURCE_ARRAY(char, utf8_length);
 359     reader.get_utf8(utf8_buffer, utf8_length);
 360 
 361     if (prefix_type == HashtableTextDump::SymbolPrefix) {
 362       SymbolTable::new_symbol(utf8_buffer, utf8_length, THREAD);
 363     } else{
 364       assert(prefix_type == HashtableTextDump::StringPrefix, "Sanity");
 365       utf8_buffer[utf8_length] = '\0';
 366       oop s = StringTable::intern(utf8_buffer, THREAD);
 367     }
 368   }
 369 }
 370 
 371 void MetaspaceShared::commit_shared_space_to(char* newtop) {
 372   assert(DumpSharedSpaces, "dump-time only");
 373   char* base = _shared_rs.base();
 374   size_t need_committed_size = newtop - base;
 375   size_t has_committed_size = _shared_vs.committed_size();
 376   if (need_committed_size < has_committed_size) {
 377     return;
 378   }
 379 
 380   size_t min_bytes = need_committed_size - has_committed_size;
 381   size_t preferred_bytes = 1 * M;
 382   size_t uncommitted = _shared_vs.reserved_size() - has_committed_size;
 383 
 384   size_t commit = MAX2(min_bytes, preferred_bytes);
 385   assert(commit <= uncommitted, "sanity");
 386 
 387   bool result = _shared_vs.expand_by(commit, false);
 388   if (!result) {
 389     vm_exit_during_initialization(err_msg("Failed to expand shared space to " SIZE_FORMAT " bytes",
 390                                           need_committed_size));
 391   }
 392 
 393   log_info(cds)("Expanding shared spaces by " SIZE_FORMAT_W(7) " bytes [total " SIZE_FORMAT_W(9)  " bytes ending at %p]",
 394                 commit, _shared_vs.actual_committed_size(), _shared_vs.high());
 395 }
 396 
 397 // Read/write a data stream for restoring/preserving metadata pointers and
 398 // miscellaneous data from/to the shared archive file.
 399 
 400 void MetaspaceShared::serialize(SerializeClosure* soc) {
 401   int tag = 0;
 402   soc->do_tag(--tag);
 403 
 404   // Verify the sizes of various metadata in the system.
 405   soc->do_tag(sizeof(Method));
 406   soc->do_tag(sizeof(ConstMethod));
 407   soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
 408   soc->do_tag(sizeof(ConstantPool));
 409   soc->do_tag(sizeof(ConstantPoolCache));
 410   soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
 411   soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
 412   soc->do_tag(sizeof(Symbol));
 413 
 414   // Dump/restore miscellaneous metadata.
 415   Universe::serialize(soc, true);
 416   soc->do_tag(--tag);
 417 
 418   // Dump/restore references to commonly used names and signatures.
 419   vmSymbols::serialize(soc);
 420   soc->do_tag(--tag);
 421 
 422   // Dump/restore the symbol and string tables
 423   SymbolTable::serialize(soc);
 424   StringTable::serialize(soc);
 425   soc->do_tag(--tag);
 426 
 427   serialize_well_known_classes(soc);
 428   soc->do_tag(--tag);
 429 
 430   soc->do_tag(666);
 431 }
 432 
 433 void MetaspaceShared::serialize_well_known_classes(SerializeClosure* soc) {
 434   java_lang_Class::serialize(soc);
 435   java_lang_String::serialize(soc);
 436   java_lang_System::serialize(soc);
 437   java_lang_ClassLoader::serialize(soc);
 438   java_lang_Throwable::serialize(soc);
 439   java_lang_Thread::serialize(soc);
 440   java_lang_ThreadGroup::serialize(soc);
 441   java_lang_AssertionStatusDirectives::serialize(soc);
 442   java_lang_module_Configuration::serialize(soc);
 443   java_lang_ref_SoftReference::serialize(soc);
 444   java_lang_invoke_MethodHandle::serialize(soc);
 445   java_lang_invoke_DirectMethodHandle::serialize(soc);
 446   java_lang_invoke_MemberName::serialize(soc);
 447   java_lang_invoke_ResolvedMethodName::serialize(soc);
 448   java_lang_invoke_LambdaForm::serialize(soc);
 449   java_lang_invoke_MethodType::serialize(soc);
 450   java_lang_invoke_CallSite::serialize(soc);
 451   java_lang_invoke_MethodHandleNatives_CallSiteContext::serialize(soc);
 452   java_security_AccessControlContext::serialize(soc);
 453   java_lang_reflect_AccessibleObject::serialize(soc);
 454   java_lang_reflect_Method::serialize(soc);
 455   java_lang_reflect_Constructor::serialize(soc);
 456   java_lang_reflect_Field::serialize(soc);
 457   java_nio_Buffer::serialize(soc);
 458   reflect_ConstantPool::serialize(soc);
 459   reflect_UnsafeStaticFieldAccessorImpl::serialize(soc);
 460   java_lang_reflect_Parameter::serialize(soc);
 461   java_lang_Module::serialize(soc);
 462   java_lang_StackTraceElement::serialize(soc);
 463   java_lang_StackFrameInfo::serialize(soc);
 464   java_lang_LiveStackFrameInfo::serialize(soc);
 465   java_util_concurrent_locks_AbstractOwnableSynchronizer::serialize(soc);
 466   java_util_ImmutableCollections_ListN::serialize(soc);
 467   java_util_ImmutableCollections_MapN::serialize(soc);
 468   java_util_ImmutableCollections_SetN::serialize(soc);
 469   jdk_internal_module_ArchivedModuleGraph::serialize(soc);
 470   InstanceMirrorKlass::serialize(soc);
 471 }
 472 
 473 address MetaspaceShared::cds_i2i_entry_code_buffers(size_t total_size) {
 474   if (DumpSharedSpaces) {
 475     if (_cds_i2i_entry_code_buffers == NULL) {
 476       _cds_i2i_entry_code_buffers = (address)misc_code_space_alloc(total_size);
 477       _cds_i2i_entry_code_buffers_size = total_size;
 478     }
 479   } else if (UseSharedSpaces) {
 480     assert(_cds_i2i_entry_code_buffers != NULL, "must already been initialized");
 481   } else {
 482     return NULL;
 483   }
 484 
 485   assert(_cds_i2i_entry_code_buffers_size == total_size, "must not change");
 486   return _cds_i2i_entry_code_buffers;
 487 }
 488 
 489 // CDS code for dumping shared archive.
 490 
 491 // Global object for holding classes that have been loaded.  Since this
 492 // is run at a safepoint just before exit, this is the entire set of classes.
 493 static GrowableArray<Klass*>* _global_klass_objects;
 494 
 495 static void collect_array_classes(Klass* k) {
 496   _global_klass_objects->append_if_missing(k);
 497   if (k->is_array_klass()) {
 498     // Add in the array classes too
 499     ArrayKlass* ak = ArrayKlass::cast(k);
 500     Klass* h = ak->higher_dimension();
 501     if (h != NULL) {
 502       h->array_klasses_do(collect_array_classes);
 503     }
 504   }
 505 }
 506 
 507 class CollectClassesClosure : public KlassClosure {
 508   void do_klass(Klass* k) {
 509     if (!(k->is_instance_klass() && InstanceKlass::cast(k)->is_in_error_state())) {
 510       if (k->is_instance_klass() && InstanceKlass::cast(k)->signers() != NULL) {
 511         // Mark any class with signers and don't add to the _global_klass_objects
 512         k->set_has_signer_and_not_archived();
 513       } else {
 514         _global_klass_objects->append_if_missing(k);
 515       }
 516     }
 517     if (k->is_array_klass()) {
 518       // Add in the array classes too
 519       ArrayKlass* ak = ArrayKlass::cast(k);
 520       Klass* h = ak->higher_dimension();
 521       if (h != NULL) {
 522         h->array_klasses_do(collect_array_classes);
 523       }
 524     }
 525   }
 526 };
 527 
 528 static void remove_unshareable_in_classes() {
 529   for (int i = 0; i < _global_klass_objects->length(); i++) {
 530     Klass* k = _global_klass_objects->at(i);
 531     if (!k->is_objArray_klass()) {
 532       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
 533       // on their array classes.
 534       assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be");
 535       k->remove_unshareable_info();
 536     }
 537   }
 538 }
 539 
 540 static void remove_java_mirror_in_classes() {
 541   for (int i = 0; i < _global_klass_objects->length(); i++) {
 542     Klass* k = _global_klass_objects->at(i);
 543     if (!k->is_objArray_klass()) {
 544       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
 545       // on their array classes.
 546       assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be");
 547       k->remove_java_mirror();
 548     }
 549   }
 550 }
 551 
 552 static void clear_basic_type_mirrors() {
 553   assert(!MetaspaceShared::is_heap_object_archiving_allowed(), "Sanity");
 554   Universe::set_int_mirror(NULL);
 555   Universe::set_float_mirror(NULL);
 556   Universe::set_double_mirror(NULL);
 557   Universe::set_byte_mirror(NULL);
 558   Universe::set_bool_mirror(NULL);
 559   Universe::set_char_mirror(NULL);
 560   Universe::set_long_mirror(NULL);
 561   Universe::set_short_mirror(NULL);
 562   Universe::set_void_mirror(NULL);
 563 }
 564 
 565 static void rewrite_nofast_bytecode(Method* method) {
 566   BytecodeStream bcs(method);
 567   while (!bcs.is_last_bytecode()) {
 568     Bytecodes::Code opcode = bcs.next();
 569     switch (opcode) {
 570     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
 571     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;
 572     case Bytecodes::_aload_0:       *bcs.bcp() = Bytecodes::_nofast_aload_0;       break;
 573     case Bytecodes::_iload: {
 574       if (!bcs.is_wide()) {
 575         *bcs.bcp() = Bytecodes::_nofast_iload;
 576       }
 577       break;
 578     }
 579     default: break;
 580     }
 581   }
 582 }
 583 
 584 // Walk all methods in the class list to ensure that they won't be modified at
 585 // run time. This includes:
 586 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified
 587 //     at run time by RewriteBytecodes/RewriteFrequentPairs
 588 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.
 589 static void rewrite_nofast_bytecodes_and_calculate_fingerprints() {
 590   for (int i = 0; i < _global_klass_objects->length(); i++) {
 591     Klass* k = _global_klass_objects->at(i);
 592     if (k->is_instance_klass()) {
 593       InstanceKlass* ik = InstanceKlass::cast(k);
 594       for (int i = 0; i < ik->methods()->length(); i++) {
 595         Method* m = ik->methods()->at(i);
 596         rewrite_nofast_bytecode(m);
 597         Fingerprinter fp(m);
 598         // The side effect of this call sets method's fingerprint field.
 599         fp.fingerprint();
 600       }
 601     }
 602   }
 603 }
 604 
 605 static void relocate_cached_class_file() {
 606   for (int i = 0; i < _global_klass_objects->length(); i++) {
 607     Klass* k = _global_klass_objects->at(i);
 608     if (k->is_instance_klass()) {
 609       InstanceKlass* ik = InstanceKlass::cast(k);
 610       JvmtiCachedClassFileData* p = ik->get_archived_class_data();
 611       if (p != NULL) {
 612         int size = offset_of(JvmtiCachedClassFileData, data) + p->length;
 613         JvmtiCachedClassFileData* q = (JvmtiCachedClassFileData*)_od_region.allocate(size);
 614         q->length = p->length;
 615         memcpy(q->data, p->data, p->length);
 616         ik->set_archived_class_data(q);
 617       }
 618     }
 619   }
 620 }
 621 
 622 NOT_PRODUCT(
 623 static void assert_not_anonymous_class(InstanceKlass* k) {
 624   assert(!(k->is_anonymous()), "cannot archive anonymous classes");
 625 }
 626 
 627 // Anonymous classes are not stored inside any dictionaries. They are created by
 628 // SystemDictionary::parse_stream() with a non-null host_klass.
 629 static void assert_no_anonymoys_classes_in_dictionaries() {
 630   ClassLoaderDataGraph::dictionary_classes_do(assert_not_anonymous_class);
 631 })
 632 
 633 // Objects of the Metadata types (such as Klass and ConstantPool) have C++ vtables.
 634 // (In GCC this is the field <Type>::_vptr, i.e., first word in the object.)
 635 //
 636 // Addresses of the vtables and the methods may be different across JVM runs,
 637 // if libjvm.so is dynamically loaded at a different base address.
 638 //
 639 // To ensure that the Metadata objects in the CDS archive always have the correct vtable:
 640 //
 641 // + at dump time:  we redirect the _vptr to point to our own vtables inside
 642 //                  the CDS image
 643 // + at run time:   we clone the actual contents of the vtables from libjvm.so
 644 //                  into our own tables.
 645 
 646 // Currently, the archive contain ONLY the following types of objects that have C++ vtables.
 647 #define CPP_VTABLE_PATCH_TYPES_DO(f) \
 648   f(ConstantPool) \
 649   f(InstanceKlass) \
 650   f(InstanceClassLoaderKlass) \
 651   f(InstanceMirrorKlass) \
 652   f(InstanceRefKlass) \
 653   f(Method) \
 654   f(ObjArrayKlass) \
 655   f(TypeArrayKlass)
 656 
 657 class CppVtableInfo {
 658   intptr_t _vtable_size;
 659   intptr_t _cloned_vtable[1];
 660 public:
 661   static int num_slots(int vtable_size) {
 662     return 1 + vtable_size; // Need to add the space occupied by _vtable_size;
 663   }
 664   int vtable_size()           { return int(uintx(_vtable_size)); }
 665   void set_vtable_size(int n) { _vtable_size = intptr_t(n); }
 666   intptr_t* cloned_vtable()   { return &_cloned_vtable[0]; }
 667   void zero()                 { memset(_cloned_vtable, 0, sizeof(intptr_t) * vtable_size()); }
 668   // Returns the address of the next CppVtableInfo that can be placed immediately after this CppVtableInfo
 669   static size_t byte_size(int vtable_size) {
 670     CppVtableInfo i;
 671     return pointer_delta(&i._cloned_vtable[vtable_size], &i, sizeof(u1));
 672   }
 673 };
 674 
 675 template <class T> class CppVtableCloner : public T {
 676   static intptr_t* vtable_of(Metadata& m) {
 677     return *((intptr_t**)&m);
 678   }
 679   static CppVtableInfo* _info;
 680 
 681   static int get_vtable_length(const char* name);
 682 
 683 public:
 684   // Allocate and initialize the C++ vtable, starting from top, but do not go past end.
 685   static intptr_t* allocate(const char* name);
 686 
 687   // Clone the vtable to ...
 688   static intptr_t* clone_vtable(const char* name, CppVtableInfo* info);
 689 
 690   static void zero_vtable_clone() {
 691     assert(DumpSharedSpaces, "dump-time only");
 692     _info->zero();
 693   }
 694 
 695   // Switch the vtable pointer to point to the cloned vtable.
 696   static void patch(Metadata* obj) {
 697     assert(DumpSharedSpaces, "dump-time only");
 698     *(void**)obj = (void*)(_info->cloned_vtable());
 699   }
 700 
 701   static bool is_valid_shared_object(const T* obj) {
 702     intptr_t* vptr = *(intptr_t**)obj;
 703     return vptr == _info->cloned_vtable();
 704   }
 705 };
 706 
 707 template <class T> CppVtableInfo* CppVtableCloner<T>::_info = NULL;
 708 
 709 template <class T>
 710 intptr_t* CppVtableCloner<T>::allocate(const char* name) {
 711   assert(is_aligned(_md_region.top(), sizeof(intptr_t)), "bad alignment");
 712   int n = get_vtable_length(name);
 713   _info = (CppVtableInfo*)_md_region.allocate(CppVtableInfo::byte_size(n), sizeof(intptr_t));
 714   _info->set_vtable_size(n);
 715 
 716   intptr_t* p = clone_vtable(name, _info);
 717   assert((char*)p == _md_region.top(), "must be");
 718 
 719   return p;
 720 }
 721 
 722 template <class T>
 723 intptr_t* CppVtableCloner<T>::clone_vtable(const char* name, CppVtableInfo* info) {
 724   if (!DumpSharedSpaces) {
 725     assert(_info == 0, "_info is initialized only at dump time");
 726     _info = info; // Remember it -- it will be used by MetaspaceShared::is_valid_shared_method()
 727   }
 728   T tmp; // Allocate temporary dummy metadata object to get to the original vtable.
 729   int n = info->vtable_size();
 730   intptr_t* srcvtable = vtable_of(tmp);
 731   intptr_t* dstvtable = info->cloned_vtable();
 732 
 733   // We already checked (and, if necessary, adjusted n) when the vtables were allocated, so we are
 734   // safe to do memcpy.
 735   log_debug(cds, vtables)("Copying %3d vtable entries for %s", n, name);
 736   memcpy(dstvtable, srcvtable, sizeof(intptr_t) * n);
 737   return dstvtable + n;
 738 }
 739 
 740 // To determine the size of the vtable for each type, we use the following
 741 // trick by declaring 2 subclasses:
 742 //
 743 //   class CppVtableTesterA: public InstanceKlass {virtual int   last_virtual_method() {return 1;}    };
 744 //   class CppVtableTesterB: public InstanceKlass {virtual void* last_virtual_method() {return NULL}; };
 745 //
 746 // CppVtableTesterA and CppVtableTesterB's vtables have the following properties:
 747 // - Their size (N+1) is exactly one more than the size of InstanceKlass's vtable (N)
 748 // - The first N entries have are exactly the same as in InstanceKlass's vtable.
 749 // - Their last entry is different.
 750 //
 751 // So to determine the value of N, we just walk CppVtableTesterA and CppVtableTesterB's tables
 752 // and find the first entry that's different.
 753 //
 754 // This works on all C++ compilers supported by Oracle, but you may need to tweak it for more
 755 // esoteric compilers.
 756 
 757 template <class T> class CppVtableTesterB: public T {
 758 public:
 759   virtual int last_virtual_method() {return 1;}
 760 };
 761 
 762 template <class T> class CppVtableTesterA : public T {
 763 public:
 764   virtual void* last_virtual_method() {
 765     // Make this different than CppVtableTesterB::last_virtual_method so the C++
 766     // compiler/linker won't alias the two functions.
 767     return NULL;
 768   }
 769 };
 770 
 771 template <class T>
 772 int CppVtableCloner<T>::get_vtable_length(const char* name) {
 773   CppVtableTesterA<T> a;
 774   CppVtableTesterB<T> b;
 775 
 776   intptr_t* avtable = vtable_of(a);
 777   intptr_t* bvtable = vtable_of(b);
 778 
 779   // Start at slot 1, because slot 0 may be RTTI (on Solaris/Sparc)
 780   int vtable_len = 1;
 781   for (; ; vtable_len++) {
 782     if (avtable[vtable_len] != bvtable[vtable_len]) {
 783       break;
 784     }
 785   }
 786   log_debug(cds, vtables)("Found   %3d vtable entries for %s", vtable_len, name);
 787 
 788   return vtable_len;
 789 }
 790 
 791 #define ALLOC_CPP_VTABLE_CLONE(c) \
 792   CppVtableCloner<c>::allocate(#c);
 793 
 794 #define CLONE_CPP_VTABLE(c) \
 795   p = CppVtableCloner<c>::clone_vtable(#c, (CppVtableInfo*)p);
 796 
 797 #define ZERO_CPP_VTABLE(c) \
 798  CppVtableCloner<c>::zero_vtable_clone();
 799 
 800 // This can be called at both dump time and run time.
 801 intptr_t* MetaspaceShared::clone_cpp_vtables(intptr_t* p) {
 802   assert(DumpSharedSpaces || UseSharedSpaces, "sanity");
 803   CPP_VTABLE_PATCH_TYPES_DO(CLONE_CPP_VTABLE);
 804   return p;
 805 }
 806 
 807 void MetaspaceShared::zero_cpp_vtable_clones_for_writing() {
 808   assert(DumpSharedSpaces, "dump-time only");
 809   CPP_VTABLE_PATCH_TYPES_DO(ZERO_CPP_VTABLE);
 810 }
 811 
 812 // Allocate and initialize the C++ vtables, starting from top, but do not go past end.
 813 void MetaspaceShared::allocate_cpp_vtable_clones() {
 814   assert(DumpSharedSpaces, "dump-time only");
 815   // Layout (each slot is a intptr_t):
 816   //   [number of slots in the first vtable = n1]
 817   //   [ <n1> slots for the first vtable]
 818   //   [number of slots in the first second = n2]
 819   //   [ <n2> slots for the second vtable]
 820   //   ...
 821   // The order of the vtables is the same as the CPP_VTAB_PATCH_TYPES_DO macro.
 822   CPP_VTABLE_PATCH_TYPES_DO(ALLOC_CPP_VTABLE_CLONE);
 823 }
 824 
 825 // Switch the vtable pointer to point to the cloned vtable. We assume the
 826 // vtable pointer is in first slot in object.
 827 void MetaspaceShared::patch_cpp_vtable_pointers() {
 828   int n = _global_klass_objects->length();
 829   for (int i = 0; i < n; i++) {
 830     Klass* obj = _global_klass_objects->at(i);
 831     if (obj->is_instance_klass()) {
 832       InstanceKlass* ik = InstanceKlass::cast(obj);
 833       if (ik->is_class_loader_instance_klass()) {
 834         CppVtableCloner<InstanceClassLoaderKlass>::patch(ik);
 835       } else if (ik->is_reference_instance_klass()) {
 836         CppVtableCloner<InstanceRefKlass>::patch(ik);
 837       } else if (ik->is_mirror_instance_klass()) {
 838         CppVtableCloner<InstanceMirrorKlass>::patch(ik);
 839       } else {
 840         CppVtableCloner<InstanceKlass>::patch(ik);
 841       }
 842       ConstantPool* cp = ik->constants();
 843       CppVtableCloner<ConstantPool>::patch(cp);
 844       for (int j = 0; j < ik->methods()->length(); j++) {
 845         Method* m = ik->methods()->at(j);
 846         CppVtableCloner<Method>::patch(m);
 847         assert(CppVtableCloner<Method>::is_valid_shared_object(m), "must be");
 848       }
 849     } else if (obj->is_objArray_klass()) {
 850       CppVtableCloner<ObjArrayKlass>::patch(obj);
 851     } else {
 852       assert(obj->is_typeArray_klass(), "sanity");
 853       CppVtableCloner<TypeArrayKlass>::patch(obj);
 854     }
 855   }
 856 }
 857 
 858 bool MetaspaceShared::is_valid_shared_method(const Method* m) {
 859   assert(is_in_shared_metaspace(m), "must be");
 860   return CppVtableCloner<Method>::is_valid_shared_object(m);
 861 }
 862 
 863 // Closure for serializing initialization data out to a data area to be
 864 // written to the shared file.
 865 
 866 class WriteClosure : public SerializeClosure {
 867 private:
 868   DumpRegion* _dump_region;
 869 
 870 public:
 871   WriteClosure(DumpRegion* r) {
 872     _dump_region = r;
 873   }
 874 
 875   void do_ptr(void** p) {
 876     _dump_region->append_intptr_t((intptr_t)*p);
 877   }
 878 
 879   void do_u4(u4* p) {
 880     void* ptr = (void*)(uintx(*p));
 881     do_ptr(&ptr);
 882   }
 883 
 884   void do_tag(int tag) {
 885     _dump_region->append_intptr_t((intptr_t)tag);
 886   }
 887 
 888   void do_oop(oop* o) {
 889     if (*o == NULL) {
 890       _dump_region->append_intptr_t(0);
 891     } else {
 892       assert(MetaspaceShared::is_heap_object_archiving_allowed(),
 893              "Archiving heap object is not allowed");
 894       _dump_region->append_intptr_t(
 895         (intptr_t)CompressedOops::encode_not_null(*o));
 896     }
 897   }
 898 
 899   void do_region(u_char* start, size_t size) {
 900     assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
 901     assert(size % sizeof(intptr_t) == 0, "bad size");
 902     do_tag((int)size);
 903     while (size > 0) {
 904       _dump_region->append_intptr_t(*(intptr_t*)start);
 905       start += sizeof(intptr_t);
 906       size -= sizeof(intptr_t);
 907     }
 908   }
 909 
 910   bool reading() const { return false; }
 911 };
 912 
 913 // This is for dumping detailed statistics for the allocations
 914 // in the shared spaces.
 915 class DumpAllocStats : public ResourceObj {
 916 public:
 917 
 918   // Here's poor man's enum inheritance
 919 #define SHAREDSPACE_OBJ_TYPES_DO(f) \
 920   METASPACE_OBJ_TYPES_DO(f) \
 921   f(SymbolHashentry) \
 922   f(SymbolBucket) \
 923   f(StringHashentry) \
 924   f(StringBucket) \
 925   f(Other)
 926 
 927   enum Type {
 928     // Types are MetaspaceObj::ClassType, MetaspaceObj::SymbolType, etc
 929     SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_DECLARE)
 930     _number_of_types
 931   };
 932 
 933   static const char * type_name(Type type) {
 934     switch(type) {
 935     SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_NAME_CASE)
 936     default:
 937       ShouldNotReachHere();
 938       return NULL;
 939     }
 940   }
 941 
 942 public:
 943   enum { RO = 0, RW = 1 };
 944 
 945   int _counts[2][_number_of_types];
 946   int _bytes [2][_number_of_types];
 947 
 948   DumpAllocStats() {
 949     memset(_counts, 0, sizeof(_counts));
 950     memset(_bytes,  0, sizeof(_bytes));
 951   };
 952 
 953   void record(MetaspaceObj::Type type, int byte_size, bool read_only) {
 954     assert(int(type) >= 0 && type < MetaspaceObj::_number_of_types, "sanity");
 955     int which = (read_only) ? RO : RW;
 956     _counts[which][type] ++;
 957     _bytes [which][type] += byte_size;
 958   }
 959 
 960   void record_other_type(int byte_size, bool read_only) {
 961     int which = (read_only) ? RO : RW;
 962     _bytes [which][OtherType] += byte_size;
 963   }
 964   void print_stats(int ro_all, int rw_all, int mc_all, int md_all);
 965 };
 966 
 967 void DumpAllocStats::print_stats(int ro_all, int rw_all, int mc_all, int md_all) {
 968   // Calculate size of data that was not allocated by Metaspace::allocate()
 969   MetaspaceSharedStats *stats = MetaspaceShared::stats();
 970 
 971   // symbols
 972   _counts[RO][SymbolHashentryType] = stats->symbol.hashentry_count;
 973   _bytes [RO][SymbolHashentryType] = stats->symbol.hashentry_bytes;
 974 
 975   _counts[RO][SymbolBucketType] = stats->symbol.bucket_count;
 976   _bytes [RO][SymbolBucketType] = stats->symbol.bucket_bytes;
 977 
 978   // strings
 979   _counts[RO][StringHashentryType] = stats->string.hashentry_count;
 980   _bytes [RO][StringHashentryType] = stats->string.hashentry_bytes;
 981 
 982   _counts[RO][StringBucketType] = stats->string.bucket_count;
 983   _bytes [RO][StringBucketType] = stats->string.bucket_bytes;
 984 
 985   // TODO: count things like dictionary, vtable, etc
 986   _bytes[RW][OtherType] += mc_all + md_all;
 987   rw_all += mc_all + md_all; // mc/md are mapped Read/Write
 988 
 989   // prevent divide-by-zero
 990   if (ro_all < 1) {
 991     ro_all = 1;
 992   }
 993   if (rw_all < 1) {
 994     rw_all = 1;
 995   }
 996 
 997   int all_ro_count = 0;
 998   int all_ro_bytes = 0;
 999   int all_rw_count = 0;
1000   int all_rw_bytes = 0;
1001 
1002 // To make fmt_stats be a syntactic constant (for format warnings), use #define.
1003 #define fmt_stats "%-20s: %8d %10d %5.1f | %8d %10d %5.1f | %8d %10d %5.1f"
1004   const char *sep = "--------------------+---------------------------+---------------------------+--------------------------";
1005   const char *hdr = "                        ro_cnt   ro_bytes     % |   rw_cnt   rw_bytes     % |  all_cnt  all_bytes     %";
1006 
1007   LogMessage(cds) msg;
1008 
1009   msg.info("Detailed metadata info (excluding od/st regions; rw stats include md/mc regions):");
1010   msg.info("%s", hdr);
1011   msg.info("%s", sep);
1012   for (int type = 0; type < int(_number_of_types); type ++) {
1013     const char *name = type_name((Type)type);
1014     int ro_count = _counts[RO][type];
1015     int ro_bytes = _bytes [RO][type];
1016     int rw_count = _counts[RW][type];
1017     int rw_bytes = _bytes [RW][type];
1018     int count = ro_count + rw_count;
1019     int bytes = ro_bytes + rw_bytes;
1020 
1021     double ro_perc = percent_of(ro_bytes, ro_all);
1022     double rw_perc = percent_of(rw_bytes, rw_all);
1023     double perc    = percent_of(bytes, ro_all + rw_all);
1024 
1025     msg.info(fmt_stats, name,
1026                          ro_count, ro_bytes, ro_perc,
1027                          rw_count, rw_bytes, rw_perc,
1028                          count, bytes, perc);
1029 
1030     all_ro_count += ro_count;
1031     all_ro_bytes += ro_bytes;
1032     all_rw_count += rw_count;
1033     all_rw_bytes += rw_bytes;
1034   }
1035 
1036   int all_count = all_ro_count + all_rw_count;
1037   int all_bytes = all_ro_bytes + all_rw_bytes;
1038 
1039   double all_ro_perc = percent_of(all_ro_bytes, ro_all);
1040   double all_rw_perc = percent_of(all_rw_bytes, rw_all);
1041   double all_perc    = percent_of(all_bytes, ro_all + rw_all);
1042 
1043   msg.info("%s", sep);
1044   msg.info(fmt_stats, "Total",
1045                        all_ro_count, all_ro_bytes, all_ro_perc,
1046                        all_rw_count, all_rw_bytes, all_rw_perc,
1047                        all_count, all_bytes, all_perc);
1048 
1049   assert(all_ro_bytes == ro_all, "everything should have been counted");
1050   assert(all_rw_bytes == rw_all, "everything should have been counted");
1051 
1052 #undef fmt_stats
1053 }
1054 
1055 // Populate the shared space.
1056 
1057 class VM_PopulateDumpSharedSpace: public VM_Operation {
1058 private:
1059   GrowableArray<MemRegion> *_closed_archive_heap_regions;
1060   GrowableArray<MemRegion> *_open_archive_heap_regions;
1061 
1062   GrowableArray<ArchiveHeapOopmapInfo> *_closed_archive_heap_oopmaps;
1063   GrowableArray<ArchiveHeapOopmapInfo> *_open_archive_heap_oopmaps;
1064 
1065   void dump_java_heap_objects() NOT_CDS_JAVA_HEAP_RETURN;
1066   void dump_archive_heap_oopmaps() NOT_CDS_JAVA_HEAP_RETURN;
1067   void dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
1068                                  GrowableArray<ArchiveHeapOopmapInfo>* oopmaps);
1069   void dump_symbols();
1070   char* dump_read_only_tables();
1071   void print_region_stats();
1072   void print_heap_region_stats(GrowableArray<MemRegion> *heap_mem,
1073                                const char *name, const size_t total_size);
1074 public:
1075 
1076   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
1077   void doit();   // outline because gdb sucks
1078   static void write_region(FileMapInfo* mapinfo, int region, DumpRegion* space, bool read_only,  bool allow_exec);
1079   bool allow_nested_vm_operations() const { return true; }
1080 }; // class VM_PopulateDumpSharedSpace
1081 
1082 class SortedSymbolClosure: public SymbolClosure {
1083   GrowableArray<Symbol*> _symbols;
1084   virtual void do_symbol(Symbol** sym) {
1085     assert((*sym)->is_permanent(), "archived symbols must be permanent");
1086     _symbols.append(*sym);
1087   }
1088   static int compare_symbols_by_address(Symbol** a, Symbol** b) {
1089     if (a[0] < b[0]) {
1090       return -1;
1091     } else if (a[0] == b[0]) {
1092       return 0;
1093     } else {
1094       return 1;
1095     }
1096   }
1097 
1098 public:
1099   SortedSymbolClosure() {
1100     SymbolTable::symbols_do(this);
1101     _symbols.sort(compare_symbols_by_address);
1102   }
1103   GrowableArray<Symbol*>* get_sorted_symbols() {
1104     return &_symbols;
1105   }
1106 };
1107 
1108 // ArchiveCompactor --
1109 //
1110 // This class is the central piece of shared archive compaction -- all metaspace data are
1111 // initially allocated outside of the shared regions. ArchiveCompactor copies the
1112 // metaspace data into their final location in the shared regions.
1113 
1114 class ArchiveCompactor : AllStatic {
1115   static DumpAllocStats* _alloc_stats;
1116   static SortedSymbolClosure* _ssc;
1117 
1118   static unsigned my_hash(const address& a) {
1119     return primitive_hash<address>(a);
1120   }
1121   static bool my_equals(const address& a0, const address& a1) {
1122     return primitive_equals<address>(a0, a1);
1123   }
1124   typedef ResourceHashtable<
1125       address, address,
1126       ArchiveCompactor::my_hash,   // solaris compiler doesn't like: primitive_hash<address>
1127       ArchiveCompactor::my_equals, // solaris compiler doesn't like: primitive_equals<address>
1128       16384, ResourceObj::C_HEAP> RelocationTable;
1129   static RelocationTable* _new_loc_table;
1130 
1131 public:
1132   static void initialize() {
1133     _alloc_stats = new(ResourceObj::C_HEAP, mtInternal)DumpAllocStats;
1134     _new_loc_table = new(ResourceObj::C_HEAP, mtInternal)RelocationTable;
1135   }
1136   static DumpAllocStats* alloc_stats() {
1137     return _alloc_stats;
1138   }
1139 
1140   static void allocate(MetaspaceClosure::Ref* ref, bool read_only) {
1141     address obj = ref->obj();
1142     int bytes = ref->size() * BytesPerWord;
1143     char* p;
1144     size_t alignment = BytesPerWord;
1145     char* oldtop;
1146     char* newtop;
1147 
1148     if (read_only) {
1149       oldtop = _ro_region.top();
1150       p = _ro_region.allocate(bytes, alignment);
1151       newtop = _ro_region.top();
1152     } else {
1153       oldtop = _rw_region.top();
1154       p = _rw_region.allocate(bytes, alignment);
1155       newtop = _rw_region.top();
1156     }
1157     memcpy(p, obj, bytes);
1158     bool isnew = _new_loc_table->put(obj, (address)p);
1159     log_trace(cds)("Copy: " PTR_FORMAT " ==> " PTR_FORMAT " %d", p2i(obj), p2i(p), bytes);
1160     assert(isnew, "must be");
1161 
1162     _alloc_stats->record(ref->msotype(), int(newtop - oldtop), read_only);
1163     if (ref->msotype() == MetaspaceObj::SymbolType) {
1164       uintx delta = MetaspaceShared::object_delta(p);
1165       if (delta > MAX_SHARED_DELTA) {
1166         // This is just a sanity check and should not appear in any real world usage. This
1167         // happens only if you allocate more than 2GB of Symbols and would require
1168         // millions of shared classes.
1169         vm_exit_during_initialization("Too many Symbols in the CDS archive",
1170                                       "Please reduce the number of shared classes.");
1171       }
1172     }
1173   }
1174 
1175   static address get_new_loc(MetaspaceClosure::Ref* ref) {
1176     address* pp = _new_loc_table->get(ref->obj());
1177     assert(pp != NULL, "must be");
1178     return *pp;
1179   }
1180 
1181 private:
1182   // Makes a shallow copy of visited MetaspaceObj's
1183   class ShallowCopier: public UniqueMetaspaceClosure {
1184     bool _read_only;
1185   public:
1186     ShallowCopier(bool read_only) : _read_only(read_only) {}
1187 
1188     virtual void do_unique_ref(Ref* ref, bool read_only) {
1189       if (read_only == _read_only) {
1190         allocate(ref, read_only);
1191       }
1192     }
1193   };
1194 
1195   // Relocate embedded pointers within a MetaspaceObj's shallow copy
1196   class ShallowCopyEmbeddedRefRelocator: public UniqueMetaspaceClosure {
1197   public:
1198     virtual void do_unique_ref(Ref* ref, bool read_only) {
1199       address new_loc = get_new_loc(ref);
1200       RefRelocator refer;
1201       ref->metaspace_pointers_do_at(&refer, new_loc);
1202     }
1203   };
1204 
1205   // Relocate a reference to point to its shallow copy
1206   class RefRelocator: public MetaspaceClosure {
1207   public:
1208     virtual bool do_ref(Ref* ref, bool read_only) {
1209       if (ref->not_null()) {
1210         ref->update(get_new_loc(ref));
1211       }
1212       return false; // Do not recurse.
1213     }
1214   };
1215 
1216 #ifdef ASSERT
1217   class IsRefInArchiveChecker: public MetaspaceClosure {
1218   public:
1219     virtual bool do_ref(Ref* ref, bool read_only) {
1220       if (ref->not_null()) {
1221         char* obj = (char*)ref->obj();
1222         assert(_ro_region.contains(obj) || _rw_region.contains(obj),
1223                "must be relocated to point to CDS archive");
1224       }
1225       return false; // Do not recurse.
1226     }
1227   };
1228 #endif
1229 
1230 public:
1231   static void copy_and_compact() {
1232     // We should no longer allocate anything from the metaspace, so that
1233     // we can have a stable set of MetaspaceObjs to work with.
1234     Metaspace::freeze();
1235 
1236     ResourceMark rm;
1237     SortedSymbolClosure the_ssc; // StackObj
1238     _ssc = &the_ssc;
1239 
1240     tty->print_cr("Scanning all metaspace objects ... ");
1241     {
1242       // allocate and shallow-copy RW objects, immediately following the MC region
1243       tty->print_cr("Allocating RW objects ... ");
1244       _mc_region.pack(&_rw_region);
1245 
1246       ResourceMark rm;
1247       ShallowCopier rw_copier(false);
1248       iterate_roots(&rw_copier);
1249     }
1250     {
1251       // allocate and shallow-copy of RO object, immediately following the RW region
1252       tty->print_cr("Allocating RO objects ... ");
1253       _rw_region.pack(&_ro_region);
1254 
1255       ResourceMark rm;
1256       ShallowCopier ro_copier(true);
1257       iterate_roots(&ro_copier);
1258     }
1259     {
1260       tty->print_cr("Relocating embedded pointers ... ");
1261       ResourceMark rm;
1262       ShallowCopyEmbeddedRefRelocator emb_reloc;
1263       iterate_roots(&emb_reloc);
1264     }
1265     {
1266       tty->print_cr("Relocating external roots ... ");
1267       ResourceMark rm;
1268       RefRelocator ext_reloc;
1269       iterate_roots(&ext_reloc);
1270     }
1271 
1272 #ifdef ASSERT
1273     {
1274       tty->print_cr("Verifying external roots ... ");
1275       ResourceMark rm;
1276       IsRefInArchiveChecker checker;
1277       iterate_roots(&checker);
1278     }
1279 #endif
1280 
1281 
1282     // cleanup
1283     _ssc = NULL;
1284   }
1285 
1286   // We must relocate the System::_well_known_klasses only after we have copied the
1287   // java objects in during dump_java_heap_objects(): during the object copy, we operate on
1288   // old objects which assert that their klass is the original klass.
1289   static void relocate_well_known_klasses() {
1290     {
1291       tty->print_cr("Relocating SystemDictionary::_well_known_klasses[] ... ");
1292       ResourceMark rm;
1293       RefRelocator ext_reloc;
1294       SystemDictionary::well_known_klasses_do(&ext_reloc);
1295     }
1296     // NOTE: after this point, we shouldn't have any globals that can reach the old
1297     // objects.
1298 
1299     // We cannot use any of the objects in the heap anymore (except for the objects
1300     // in the CDS shared string regions) because their headers no longer point to
1301     // valid Klasses.
1302   }
1303 
1304   static void iterate_roots(MetaspaceClosure* it) {
1305     GrowableArray<Symbol*>* symbols = _ssc->get_sorted_symbols();
1306     for (int i=0; i<symbols->length(); i++) {
1307       it->push(symbols->adr_at(i));
1308     }
1309     if (_global_klass_objects != NULL) {
1310       // Need to fix up the pointers
1311       for (int i = 0; i < _global_klass_objects->length(); i++) {
1312         // NOTE -- this requires that the vtable is NOT yet patched, or else we are hosed.
1313         it->push(_global_klass_objects->adr_at(i));
1314       }
1315     }
1316     FileMapInfo::metaspace_pointers_do(it);
1317     SystemDictionary::classes_do(it);
1318     Universe::metaspace_pointers_do(it);
1319     SymbolTable::metaspace_pointers_do(it);
1320     vmSymbols::metaspace_pointers_do(it);
1321   }
1322 
1323   static Klass* get_relocated_klass(Klass* orig_klass) {
1324     assert(DumpSharedSpaces, "dump time only");
1325     address* pp = _new_loc_table->get((address)orig_klass);
1326     assert(pp != NULL, "must be");
1327     Klass* klass = (Klass*)(*pp);
1328     assert(klass->is_klass(), "must be");
1329     return klass;
1330   }
1331 };
1332 
1333 DumpAllocStats* ArchiveCompactor::_alloc_stats;
1334 SortedSymbolClosure* ArchiveCompactor::_ssc;
1335 ArchiveCompactor::RelocationTable* ArchiveCompactor::_new_loc_table;
1336 
1337 void VM_PopulateDumpSharedSpace::write_region(FileMapInfo* mapinfo, int region_idx,
1338                                               DumpRegion* dump_region, bool read_only,  bool allow_exec) {
1339   mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);
1340 }
1341 
1342 void VM_PopulateDumpSharedSpace::dump_symbols() {
1343   tty->print_cr("Dumping symbol table ...");
1344 
1345   NOT_PRODUCT(SymbolTable::verify());
1346   SymbolTable::write_to_archive();
1347 }
1348 
1349 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
1350   char* oldtop = _ro_region.top();
1351   // Reorder the system dictionary. Moving the symbols affects
1352   // how the hash table indices are calculated.
1353   SystemDictionary::reorder_dictionary_for_sharing();
1354 
1355   tty->print("Removing java_mirror ... ");
1356   if (!MetaspaceShared::is_heap_object_archiving_allowed()) {
1357     clear_basic_type_mirrors();
1358   }
1359   remove_java_mirror_in_classes();
1360   tty->print_cr("done. ");
1361   NOT_PRODUCT(SystemDictionary::verify();)
1362 
1363   size_t buckets_bytes = SystemDictionary::count_bytes_for_buckets();
1364   char* buckets_top = _ro_region.allocate(buckets_bytes, sizeof(intptr_t));
1365   SystemDictionary::copy_buckets(buckets_top, _ro_region.top());
1366 
1367   size_t table_bytes = SystemDictionary::count_bytes_for_table();
1368   char* table_top = _ro_region.allocate(table_bytes, sizeof(intptr_t));
1369   SystemDictionary::copy_table(table_top, _ro_region.top());
1370 
1371   // Write the archived object sub-graph infos. For each klass with sub-graphs,
1372   // the info includes the static fields (sub-graph entry points) and Klasses
1373   // of objects included in the sub-graph.
1374   HeapShared::write_archived_subgraph_infos();
1375 
1376   // Write the other data to the output array.
1377   WriteClosure wc(&_ro_region);
1378   MetaspaceShared::serialize(&wc);
1379 
1380   // Write the bitmaps for patching the archive heap regions
1381   dump_archive_heap_oopmaps();
1382 
1383   char* newtop = _ro_region.top();
1384   ArchiveCompactor::alloc_stats()->record_other_type(int(newtop - oldtop), true);
1385   return buckets_top;
1386 }
1387 
1388 void VM_PopulateDumpSharedSpace::doit() {
1389   Thread* THREAD = VMThread::vm_thread();
1390 
1391   FileMapInfo::check_nonempty_dir_in_shared_path_table();
1392 
1393   NOT_PRODUCT(SystemDictionary::verify();)
1394   // The following guarantee is meant to ensure that no loader constraints
1395   // exist yet, since the constraints table is not shared.  This becomes
1396   // more important now that we don't re-initialize vtables/itables for
1397   // shared classes at runtime, where constraints were previously created.
1398   guarantee(SystemDictionary::constraints()->number_of_entries() == 0,
1399             "loader constraints are not saved");
1400   guarantee(SystemDictionary::placeholders()->number_of_entries() == 0,
1401           "placeholders are not saved");
1402   // Revisit and implement this if we prelink method handle call sites:
1403   guarantee(SystemDictionary::invoke_method_table() == NULL ||
1404             SystemDictionary::invoke_method_table()->number_of_entries() == 0,
1405             "invoke method table is not saved");
1406 
1407   // At this point, many classes have been loaded.
1408   // Gather systemDictionary classes in a global array and do everything to
1409   // that so we don't have to walk the SystemDictionary again.
1410   _global_klass_objects = new GrowableArray<Klass*>(1000);
1411   CollectClassesClosure collect_classes;
1412   ClassLoaderDataGraph::loaded_classes_do(&collect_classes);
1413 
1414   tty->print_cr("Number of classes %d", _global_klass_objects->length());
1415   {
1416     int num_type_array = 0, num_obj_array = 0, num_inst = 0;
1417     for (int i = 0; i < _global_klass_objects->length(); i++) {
1418       Klass* k = _global_klass_objects->at(i);
1419       if (k->is_instance_klass()) {
1420         num_inst ++;
1421       } else if (k->is_objArray_klass()) {
1422         num_obj_array ++;
1423       } else {
1424         assert(k->is_typeArray_klass(), "sanity");
1425         num_type_array ++;
1426       }
1427     }
1428     tty->print_cr("    instance classes   = %5d", num_inst);
1429     tty->print_cr("    obj array classes  = %5d", num_obj_array);
1430     tty->print_cr("    type array classes = %5d", num_type_array);
1431   }
1432 
1433   // Ensure the ConstMethods won't be modified at run-time
1434   tty->print("Updating ConstMethods ... ");
1435   rewrite_nofast_bytecodes_and_calculate_fingerprints();
1436   tty->print_cr("done. ");
1437 
1438   // Move classes from platform/system dictionaries into the boot dictionary
1439   SystemDictionary::combine_shared_dictionaries();
1440 
1441   // Make sure all classes have a correct loader type.
1442   ClassLoaderData::the_null_class_loader_data()->dictionary()->classes_do(MetaspaceShared::check_shared_class_loader_type);
1443 
1444   // Remove all references outside the metadata
1445   tty->print("Removing unshareable information ... ");
1446   remove_unshareable_in_classes();
1447   tty->print_cr("done. ");
1448 
1449   // We don't support archiving anonymous classes. Verify that they are not stored in
1450   // the any dictionaries.
1451   NOT_PRODUCT(assert_no_anonymoys_classes_in_dictionaries());
1452 
1453   SystemDictionaryShared::finalize_verification_constraints();
1454 
1455   ArchiveCompactor::initialize();
1456   ArchiveCompactor::copy_and_compact();
1457 
1458   dump_symbols();
1459 
1460   // Dump supported java heap objects
1461   _closed_archive_heap_regions = NULL;
1462   _open_archive_heap_regions = NULL;
1463   dump_java_heap_objects();
1464 
1465   ArchiveCompactor::relocate_well_known_klasses();
1466 
1467   char* read_only_tables_start = dump_read_only_tables();
1468   _ro_region.pack(&_md_region);
1469 
1470   char* vtbl_list = _md_region.top();
1471   MetaspaceShared::allocate_cpp_vtable_clones();
1472   _md_region.pack(&_od_region);
1473 
1474   // Relocate the archived class file data into the od region
1475   relocate_cached_class_file();
1476   _od_region.pack();
1477 
1478   // The 5 core spaces are allocated consecutively mc->rw->ro->md->od, so there total size
1479   // is just the spaces between the two ends.
1480   size_t core_spaces_size = _od_region.end() - _mc_region.base();
1481   assert(core_spaces_size == (size_t)align_up(core_spaces_size, Metaspace::reserve_alignment()),
1482          "should already be aligned");
1483 
1484   // During patching, some virtual methods may be called, so at this point
1485   // the vtables must contain valid methods (as filled in by CppVtableCloner::allocate).
1486   MetaspaceShared::patch_cpp_vtable_pointers();
1487 
1488   // The vtable clones contain addresses of the current process.
1489   // We don't want to write these addresses into the archive.
1490   MetaspaceShared::zero_cpp_vtable_clones_for_writing();
1491 
1492   // Create and write the archive file that maps the shared spaces.
1493 
1494   FileMapInfo* mapinfo = new FileMapInfo();
1495   mapinfo->populate_header(os::vm_allocation_granularity());
1496   mapinfo->set_read_only_tables_start(read_only_tables_start);
1497   mapinfo->set_misc_data_patching_start(vtbl_list);
1498   mapinfo->set_cds_i2i_entry_code_buffers(MetaspaceShared::cds_i2i_entry_code_buffers());
1499   mapinfo->set_cds_i2i_entry_code_buffers_size(MetaspaceShared::cds_i2i_entry_code_buffers_size());
1500   mapinfo->set_core_spaces_size(core_spaces_size);
1501 
1502   for (int pass=1; pass<=2; pass++) {
1503     if (pass == 1) {
1504       // The first pass doesn't actually write the data to disk. All it
1505       // does is to update the fields in the mapinfo->_header.
1506     } else {
1507       // After the first pass, the contents of mapinfo->_header are finalized,
1508       // so we can compute the header's CRC, and write the contents of the header
1509       // and the regions into disk.
1510       mapinfo->open_for_write();
1511       mapinfo->set_header_crc(mapinfo->compute_header_crc());
1512     }
1513     mapinfo->write_header();
1514 
1515     // NOTE: md contains the trampoline code for method entries, which are patched at run time,
1516     // so it needs to be read/write.
1517     write_region(mapinfo, MetaspaceShared::mc, &_mc_region, /*read_only=*/false,/*allow_exec=*/true);
1518     write_region(mapinfo, MetaspaceShared::rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);
1519     write_region(mapinfo, MetaspaceShared::ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);
1520     write_region(mapinfo, MetaspaceShared::md, &_md_region, /*read_only=*/false,/*allow_exec=*/false);
1521     write_region(mapinfo, MetaspaceShared::od, &_od_region, /*read_only=*/true, /*allow_exec=*/false);
1522 
1523     _total_string_region_size = mapinfo->write_archive_heap_regions(
1524                                         _closed_archive_heap_regions,
1525                                         _closed_archive_heap_oopmaps,
1526                                         MetaspaceShared::first_string,
1527                                         MetaspaceShared::max_strings);
1528     _total_open_archive_region_size = mapinfo->write_archive_heap_regions(
1529                                         _open_archive_heap_regions,
1530                                         _open_archive_heap_oopmaps,
1531                                         MetaspaceShared::first_open_archive_heap_region,
1532                                         MetaspaceShared::max_open_archive_heap_region);
1533   }
1534 
1535   mapinfo->close();
1536 
1537   // Restore the vtable in case we invoke any virtual methods.
1538   MetaspaceShared::clone_cpp_vtables((intptr_t*)vtbl_list);
1539 
1540   print_region_stats();
1541 
1542   if (log_is_enabled(Info, cds)) {
1543     ArchiveCompactor::alloc_stats()->print_stats(int(_ro_region.used()), int(_rw_region.used()),
1544                                                  int(_mc_region.used()), int(_md_region.used()));
1545   }
1546 
1547   if (PrintSystemDictionaryAtExit) {
1548     SystemDictionary::print();
1549   }
1550   // There may be other pending VM operations that operate on the InstanceKlasses,
1551   // which will fail because InstanceKlasses::remove_unshareable_info()
1552   // has been called. Forget these operations and exit the VM directly.
1553   vm_direct_exit(0);
1554 }
1555 
1556 void VM_PopulateDumpSharedSpace::print_region_stats() {
1557   // Print statistics of all the regions
1558   const size_t total_reserved = _ro_region.reserved()  + _rw_region.reserved() +
1559                                 _mc_region.reserved()  + _md_region.reserved() +
1560                                 _od_region.reserved()  +
1561                                 _total_string_region_size +
1562                                 _total_open_archive_region_size;
1563   const size_t total_bytes = _ro_region.used()  + _rw_region.used() +
1564                              _mc_region.used()  + _md_region.used() +
1565                              _od_region.used()  +
1566                              _total_string_region_size +
1567                              _total_open_archive_region_size;
1568   const double total_u_perc = percent_of(total_bytes, total_reserved);
1569 
1570   _mc_region.print(total_reserved);
1571   _rw_region.print(total_reserved);
1572   _ro_region.print(total_reserved);
1573   _md_region.print(total_reserved);
1574   _od_region.print(total_reserved);
1575   print_heap_region_stats(_closed_archive_heap_regions, "st", total_reserved);
1576   print_heap_region_stats(_open_archive_heap_regions, "oa", total_reserved);
1577 
1578   tty->print_cr("total    : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]",
1579                  total_bytes, total_reserved, total_u_perc);
1580 }
1581 
1582 void VM_PopulateDumpSharedSpace::print_heap_region_stats(GrowableArray<MemRegion> *heap_mem,
1583                                                          const char *name, const size_t total_size) {
1584   int arr_len = heap_mem == NULL ? 0 : heap_mem->length();
1585   for (int i = 0; i < arr_len; i++) {
1586       char* start = (char*)heap_mem->at(i).start();
1587       size_t size = heap_mem->at(i).byte_size();
1588       char* top = start + size;
1589       tty->print_cr("%s%d space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used] at " INTPTR_FORMAT,
1590                     name, i, size, size/double(total_size)*100.0, size, p2i(start));
1591 
1592   }
1593 }
1594 
1595 // Update a Java object to point its Klass* to the new location after
1596 // shared archive has been compacted.
1597 void MetaspaceShared::relocate_klass_ptr(oop o) {
1598   assert(DumpSharedSpaces, "sanity");
1599   Klass* k = ArchiveCompactor::get_relocated_klass(o->klass());
1600   o->set_klass(k);
1601 }
1602 
1603 Klass* MetaspaceShared::get_relocated_klass(Klass *k) {
1604   assert(DumpSharedSpaces, "sanity");
1605   return ArchiveCompactor::get_relocated_klass(k);
1606 }
1607 
1608 class LinkSharedClassesClosure : public KlassClosure {
1609   Thread* THREAD;
1610   bool    _made_progress;
1611  public:
1612   LinkSharedClassesClosure(Thread* thread) : THREAD(thread), _made_progress(false) {}
1613 
1614   void reset()               { _made_progress = false; }
1615   bool made_progress() const { return _made_progress; }
1616 
1617   void do_klass(Klass* k) {
1618     if (k->is_instance_klass()) {
1619       InstanceKlass* ik = InstanceKlass::cast(k);
1620       // Link the class to cause the bytecodes to be rewritten and the
1621       // cpcache to be created. Class verification is done according
1622       // to -Xverify setting.
1623       _made_progress |= MetaspaceShared::try_link_class(ik, THREAD);
1624       guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1625 
1626       ik->constants()->resolve_class_constants(THREAD);
1627     }
1628   }
1629 };
1630 
1631 class CheckSharedClassesClosure : public KlassClosure {
1632   bool    _made_progress;
1633  public:
1634   CheckSharedClassesClosure() : _made_progress(false) {}
1635 
1636   void reset()               { _made_progress = false; }
1637   bool made_progress() const { return _made_progress; }
1638   void do_klass(Klass* k) {
1639     if (k->is_instance_klass() && InstanceKlass::cast(k)->check_sharing_error_state()) {
1640       _made_progress = true;
1641     }
1642   }
1643 };
1644 
1645 void MetaspaceShared::check_shared_class_loader_type(InstanceKlass* ik) {
1646   ResourceMark rm;
1647   if (ik->shared_classpath_index() == UNREGISTERED_INDEX) {
1648     guarantee(ik->loader_type() == 0,
1649             "Class loader type must not be set for this class %s", ik->name()->as_C_string());
1650   } else {
1651     guarantee(ik->loader_type() != 0,
1652             "Class loader type must be set for this class %s", ik->name()->as_C_string());
1653   }
1654 }
1655 
1656 void MetaspaceShared::link_and_cleanup_shared_classes(TRAPS) {
1657   // We need to iterate because verification may cause additional classes
1658   // to be loaded.
1659   LinkSharedClassesClosure link_closure(THREAD);
1660   do {
1661     link_closure.reset();
1662     ClassLoaderDataGraph::loaded_classes_do(&link_closure);
1663     guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1664   } while (link_closure.made_progress());
1665 
1666   if (_has_error_classes) {
1667     // Mark all classes whose super class or interfaces failed verification.
1668     CheckSharedClassesClosure check_closure;
1669     do {
1670       // Not completely sure if we need to do this iteratively. Anyway,
1671       // we should come here only if there are unverifiable classes, which
1672       // shouldn't happen in normal cases. So better safe than sorry.
1673       check_closure.reset();
1674       ClassLoaderDataGraph::loaded_classes_do(&check_closure);
1675     } while (check_closure.made_progress());
1676 
1677     if (IgnoreUnverifiableClassesDuringDump) {
1678       // This is useful when running JCK or SQE tests. You should not
1679       // enable this when running real apps.
1680       SystemDictionary::remove_classes_in_error_state();
1681     } else {
1682       tty->print_cr("Please remove the unverifiable classes from your class list and try again");
1683       exit(1);
1684     }
1685   }
1686 }
1687 
1688 void MetaspaceShared::prepare_for_dumping() {
1689   Arguments::check_unsupported_dumping_properties();
1690   ClassLoader::initialize_shared_path();
1691 }
1692 
1693 // Preload classes from a list, populate the shared spaces and dump to a
1694 // file.
1695 void MetaspaceShared::preload_and_dump(TRAPS) {
1696   { TraceTime timer("Dump Shared Spaces", TRACETIME_LOG(Info, startuptime));
1697     ResourceMark rm;
1698     char class_list_path_str[JVM_MAXPATHLEN];
1699     // Preload classes to be shared.
1700     // Should use some os:: method rather than fopen() here. aB.
1701     const char* class_list_path;
1702     if (SharedClassListFile == NULL) {
1703       // Construct the path to the class list (in jre/lib)
1704       // Walk up two directories from the location of the VM and
1705       // optionally tack on "lib" (depending on platform)
1706       os::jvm_path(class_list_path_str, sizeof(class_list_path_str));
1707       for (int i = 0; i < 3; i++) {
1708         char *end = strrchr(class_list_path_str, *os::file_separator());
1709         if (end != NULL) *end = '\0';
1710       }
1711       int class_list_path_len = (int)strlen(class_list_path_str);
1712       if (class_list_path_len >= 3) {
1713         if (strcmp(class_list_path_str + class_list_path_len - 3, "lib") != 0) {
1714           if (class_list_path_len < JVM_MAXPATHLEN - 4) {
1715             jio_snprintf(class_list_path_str + class_list_path_len,
1716                          sizeof(class_list_path_str) - class_list_path_len,
1717                          "%slib", os::file_separator());
1718             class_list_path_len += 4;
1719           }
1720         }
1721       }
1722       if (class_list_path_len < JVM_MAXPATHLEN - 10) {
1723         jio_snprintf(class_list_path_str + class_list_path_len,
1724                      sizeof(class_list_path_str) - class_list_path_len,
1725                      "%sclasslist", os::file_separator());
1726       }
1727       class_list_path = class_list_path_str;
1728     } else {
1729       class_list_path = SharedClassListFile;
1730     }
1731 
1732     tty->print_cr("Loading classes to share ...");
1733     _has_error_classes = false;
1734     int class_count = preload_classes(class_list_path, THREAD);
1735     if (ExtraSharedClassListFile) {
1736       class_count += preload_classes(ExtraSharedClassListFile, THREAD);
1737     }
1738     tty->print_cr("Loading classes to share: done.");
1739 
1740     log_info(cds)("Shared spaces: preloaded %d classes", class_count);
1741 
1742     // Rewrite and link classes
1743     tty->print_cr("Rewriting and linking classes ...");
1744 
1745     // Link any classes which got missed. This would happen if we have loaded classes that
1746     // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
1747     // fails verification, all other interfaces that were not specified in the classlist but
1748     // are implemented by K are not verified.
1749     link_and_cleanup_shared_classes(CATCH);
1750     tty->print_cr("Rewriting and linking classes: done");
1751 
1752     SystemDictionary::clear_invoke_method_table();
1753 
1754     VM_PopulateDumpSharedSpace op;
1755     VMThread::execute(&op);
1756   }
1757 }
1758 
1759 
1760 int MetaspaceShared::preload_classes(const char* class_list_path, TRAPS) {
1761   ClassListParser parser(class_list_path);
1762   int class_count = 0;
1763 
1764     while (parser.parse_one_line()) {
1765       Klass* klass = ClassLoaderExt::load_one_class(&parser, THREAD);
1766       if (HAS_PENDING_EXCEPTION) {
1767         if (klass == NULL &&
1768              (PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_ClassNotFoundException())) {
1769           // print a warning only when the pending exception is class not found
1770           tty->print_cr("Preload Warning: Cannot find %s", parser.current_class_name());
1771         }
1772         CLEAR_PENDING_EXCEPTION;
1773       }
1774       if (klass != NULL) {
1775         if (log_is_enabled(Trace, cds)) {
1776           ResourceMark rm;
1777           log_trace(cds)("Shared spaces preloaded: %s", klass->external_name());
1778         }
1779 
1780         if (klass->is_instance_klass()) {
1781           InstanceKlass* ik = InstanceKlass::cast(klass);
1782 
1783           // Link the class to cause the bytecodes to be rewritten and the
1784           // cpcache to be created. The linking is done as soon as classes
1785           // are loaded in order that the related data structures (klass and
1786           // cpCache) are located together.
1787           try_link_class(ik, THREAD);
1788           guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1789         }
1790 
1791         class_count++;
1792       }
1793     }
1794 
1795   return class_count;
1796 }
1797 
1798 // Returns true if the class's status has changed
1799 bool MetaspaceShared::try_link_class(InstanceKlass* ik, TRAPS) {
1800   assert(DumpSharedSpaces, "should only be called during dumping");
1801   if (ik->init_state() < InstanceKlass::linked) {
1802     bool saved = BytecodeVerificationLocal;
1803     if (ik->loader_type() == 0 && ik->class_loader() == NULL) {
1804       // The verification decision is based on BytecodeVerificationRemote
1805       // for non-system classes. Since we are using the NULL classloader
1806       // to load non-system classes for customized class loaders during dumping,
1807       // we need to temporarily change BytecodeVerificationLocal to be the same as
1808       // BytecodeVerificationRemote. Note this can cause the parent system
1809       // classes also being verified. The extra overhead is acceptable during
1810       // dumping.
1811       BytecodeVerificationLocal = BytecodeVerificationRemote;
1812     }
1813     ik->link_class(THREAD);
1814     if (HAS_PENDING_EXCEPTION) {
1815       ResourceMark rm;
1816       tty->print_cr("Preload Warning: Verification failed for %s",
1817                     ik->external_name());
1818       CLEAR_PENDING_EXCEPTION;
1819       ik->set_in_error_state();
1820       _has_error_classes = true;
1821     }
1822     BytecodeVerificationLocal = saved;
1823     return true;
1824   } else {
1825     return false;
1826   }
1827 }
1828 
1829 #if INCLUDE_CDS_JAVA_HEAP
1830 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() {
1831   if (!MetaspaceShared::is_heap_object_archiving_allowed()) {
1832     if (log_is_enabled(Info, cds)) {
1833       log_info(cds)(
1834         "Archived java heap is not supported as UseG1GC, "
1835         "UseCompressedOops and UseCompressedClassPointers are required."
1836         "Current settings: UseG1GC=%s, UseCompressedOops=%s, UseCompressedClassPointers=%s.",
1837         BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedOops),
1838         BOOL_TO_STR(UseCompressedClassPointers));
1839     }
1840     return;
1841   }
1842 
1843   {
1844     NoSafepointVerifier nsv;
1845 
1846     // Cache for recording where the archived objects are copied to
1847     MetaspaceShared::create_archive_object_cache();
1848 
1849     tty->print_cr("Dumping objects to closed archive heap region ...");
1850     NOT_PRODUCT(StringTable::verify());
1851     // The closed space has maximum two regions. See FileMapInfo::write_archive_heap_regions() for details.
1852     _closed_archive_heap_regions = new GrowableArray<MemRegion>(2);
1853     MetaspaceShared::dump_closed_archive_heap_objects(_closed_archive_heap_regions);
1854 
1855     tty->print_cr("Dumping objects to open archive heap region ...");
1856     _open_archive_heap_regions = new GrowableArray<MemRegion>(2);
1857     MetaspaceShared::dump_open_archive_heap_objects(_open_archive_heap_regions);
1858 
1859     MetaspaceShared::destroy_archive_object_cache();
1860   }
1861 
1862   G1HeapVerifier::verify_archive_regions();
1863 }
1864 
1865 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps() {
1866   if (MetaspaceShared::is_heap_object_archiving_allowed()) {
1867     _closed_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
1868     dump_archive_heap_oopmaps(_closed_archive_heap_regions, _closed_archive_heap_oopmaps);
1869 
1870     _open_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
1871     dump_archive_heap_oopmaps(_open_archive_heap_regions, _open_archive_heap_oopmaps);
1872   }
1873 }
1874 
1875 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
1876                                                            GrowableArray<ArchiveHeapOopmapInfo>* oopmaps) {
1877   for (int i=0; i<regions->length(); i++) {
1878     ResourceBitMap oopmap = HeapShared::calculate_oopmap(regions->at(i));
1879     size_t size_in_bits = oopmap.size();
1880     size_t size_in_bytes = oopmap.size_in_bytes();
1881     uintptr_t* buffer = (uintptr_t*)_ro_region.allocate(size_in_bytes, sizeof(intptr_t));
1882     oopmap.write_to(buffer, size_in_bytes);
1883     log_info(cds)("Oopmap = " INTPTR_FORMAT " (%6d bytes) for heap region " INTPTR_FORMAT " (%8d bytes)",
1884                   p2i(buffer), (int)(size_in_bytes),
1885                   p2i(regions->at(i).start()), (int)regions->at(i).byte_size());
1886 
1887     ArchiveHeapOopmapInfo info;
1888     info._oopmap = (address)buffer;
1889     info._oopmap_size_in_bits = size_in_bits;
1890     oopmaps->append(info);
1891   }
1892 }
1893 
1894 void MetaspaceShared::dump_closed_archive_heap_objects(
1895                                     GrowableArray<MemRegion> * closed_archive) {
1896   assert(is_heap_object_archiving_allowed(), "Cannot dump java heap objects");
1897 
1898   Thread* THREAD = Thread::current();
1899   G1CollectedHeap::heap()->begin_archive_alloc_range();
1900 
1901   // Archive interned string objects
1902   StringTable::write_to_archive();
1903 
1904   G1CollectedHeap::heap()->end_archive_alloc_range(closed_archive,
1905                                                    os::vm_allocation_granularity());
1906 }
1907 
1908 void MetaspaceShared::dump_open_archive_heap_objects(
1909                                     GrowableArray<MemRegion> * open_archive) {
1910   assert(UseG1GC, "Only support G1 GC");
1911   assert(UseCompressedOops && UseCompressedClassPointers,
1912          "Only support UseCompressedOops and UseCompressedClassPointers enabled");
1913 
1914   Thread* THREAD = Thread::current();
1915   G1CollectedHeap::heap()->begin_archive_alloc_range(true /* open */);
1916 
1917   java_lang_Class::archive_basic_type_mirrors(THREAD);
1918 
1919   MetaspaceShared::archive_klass_objects(THREAD);
1920 
1921   HeapShared::archive_module_graph_objects(THREAD);
1922 
1923   G1CollectedHeap::heap()->end_archive_alloc_range(open_archive,
1924                                                    os::vm_allocation_granularity());
1925 }
1926 
1927 unsigned MetaspaceShared::obj_hash(oop const& p) {
1928   assert(!p->mark()->has_bias_pattern(),
1929          "this object should never have been locked");  // so identity_hash won't safepoin
1930   unsigned hash = (unsigned)p->identity_hash();
1931   return hash;
1932 }
1933 
1934 MetaspaceShared::ArchivedObjectCache* MetaspaceShared::_archive_object_cache = NULL;
1935 oop MetaspaceShared::find_archived_heap_object(oop obj) {
1936   assert(DumpSharedSpaces, "dump-time only");
1937   ArchivedObjectCache* cache = MetaspaceShared::archive_object_cache();
1938   oop* p = cache->get(obj);
1939   if (p != NULL) {
1940     return *p;
1941   } else {
1942     return NULL;
1943   }
1944 }
1945 
1946 oop MetaspaceShared::archive_heap_object(oop obj, Thread* THREAD) {
1947   assert(DumpSharedSpaces, "dump-time only");
1948 
1949   oop ao = find_archived_heap_object(obj);
1950   if (ao != NULL) {
1951     // already archived
1952     return ao;
1953   }
1954 
1955   int len = obj->size();
1956   if (G1CollectedHeap::heap()->is_archive_alloc_too_large(len)) {
1957     return NULL;
1958   }
1959 
1960   int hash = obj->identity_hash();
1961   oop archived_oop = (oop)G1CollectedHeap::heap()->archive_mem_allocate(len);
1962   if (archived_oop != NULL) {
1963     Copy::aligned_disjoint_words((HeapWord*)obj, (HeapWord*)archived_oop, len);
1964     relocate_klass_ptr(archived_oop);
1965     ArchivedObjectCache* cache = MetaspaceShared::archive_object_cache();
1966     cache->put(obj, archived_oop);
1967   }
1968   log_debug(cds, heap)("Archived heap object " PTR_FORMAT " ==> " PTR_FORMAT,
1969                        p2i(obj), p2i(archived_oop));
1970   return archived_oop;
1971 }
1972 
1973 oop MetaspaceShared::materialize_archived_object(narrowOop v) {
1974   if (!CompressedOops::is_null(v)) {
1975     oop obj = HeapShared::decode_with_archived_oop_encoding_mode(v);
1976     return G1CollectedHeap::heap()->materialize_archived_object(obj);
1977   }
1978   return NULL;
1979 }
1980 
1981 void MetaspaceShared::archive_klass_objects(Thread* THREAD) {
1982   int i;
1983   for (i = 0; i < _global_klass_objects->length(); i++) {
1984     Klass* k = _global_klass_objects->at(i);
1985 
1986     // archive mirror object
1987     java_lang_Class::archive_mirror(k, CHECK);
1988 
1989     // archive the resolved_referenes array
1990     if (k->is_instance_klass()) {
1991       InstanceKlass* ik = InstanceKlass::cast(k);
1992       ik->constants()->archive_resolved_references(THREAD);
1993     }
1994   }
1995 }
1996 
1997 bool MetaspaceShared::is_archive_object(oop p) {
1998   return (p == NULL) ? false : G1ArchiveAllocator::is_archive_object(p);
1999 }
2000 
2001 void MetaspaceShared::fixup_mapped_heap_regions() {
2002   FileMapInfo *mapinfo = FileMapInfo::current_info();
2003   mapinfo->fixup_mapped_heap_regions();
2004 }
2005 #endif // INCLUDE_CDS_JAVA_HEAP
2006 
2007 // Closure for serializing initialization data in from a data area
2008 // (ptr_array) read from the shared file.
2009 
2010 class ReadClosure : public SerializeClosure {
2011 private:
2012   intptr_t** _ptr_array;
2013 
2014   inline intptr_t nextPtr() {
2015     return *(*_ptr_array)++;
2016   }
2017 
2018 public:
2019   ReadClosure(intptr_t** ptr_array) { _ptr_array = ptr_array; }
2020 
2021   void do_ptr(void** p) {
2022     assert(*p == NULL, "initializing previous initialized pointer.");
2023     intptr_t obj = nextPtr();
2024     assert((intptr_t)obj >= 0 || (intptr_t)obj < -100,
2025            "hit tag while initializing ptrs.");
2026     *p = (void*)obj;
2027   }
2028 
2029   void do_u4(u4* p) {
2030     intptr_t obj = nextPtr();
2031     *p = (u4)(uintx(obj));
2032   }
2033 
2034   void do_tag(int tag) {
2035     int old_tag;
2036     old_tag = (int)(intptr_t)nextPtr();
2037     // do_int(&old_tag);
2038     assert(tag == old_tag, "old tag doesn't match");
2039     FileMapInfo::assert_mark(tag == old_tag);
2040   }
2041 
2042   void do_oop(oop *p) {
2043     narrowOop o = (narrowOop)nextPtr();
2044     if (o == 0 || !MetaspaceShared::open_archive_heap_region_mapped()) {
2045       p = NULL;
2046     } else {
2047       assert(MetaspaceShared::is_heap_object_archiving_allowed(),
2048              "Archived heap object is not allowed");
2049       assert(MetaspaceShared::open_archive_heap_region_mapped(),
2050              "Open archive heap region is not mapped");
2051       *p = HeapShared::decode_with_archived_oop_encoding_mode(o);
2052     }
2053   }
2054 
2055   void do_region(u_char* start, size_t size) {
2056     assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
2057     assert(size % sizeof(intptr_t) == 0, "bad size");
2058     do_tag((int)size);
2059     while (size > 0) {
2060       *(intptr_t*)start = nextPtr();
2061       start += sizeof(intptr_t);
2062       size -= sizeof(intptr_t);
2063     }
2064   }
2065 
2066   bool reading() const { return true; }
2067 };
2068 
2069 // Return true if given address is in the misc data region
2070 bool MetaspaceShared::is_in_shared_region(const void* p, int idx) {
2071   return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx);
2072 }
2073 
2074 bool MetaspaceShared::is_in_trampoline_frame(address addr) {
2075   if (UseSharedSpaces && is_in_shared_region(addr, MetaspaceShared::mc)) {
2076     return true;
2077   }
2078   return false;
2079 }
2080 
2081 // Map shared spaces at requested addresses and return if succeeded.
2082 bool MetaspaceShared::map_shared_spaces(FileMapInfo* mapinfo) {
2083   size_t image_alignment = mapinfo->alignment();
2084 
2085 #ifndef _WINDOWS
2086   // Map in the shared memory and then map the regions on top of it.
2087   // On Windows, don't map the memory here because it will cause the
2088   // mappings of the regions to fail.
2089   ReservedSpace shared_rs = mapinfo->reserve_shared_memory();
2090   if (!shared_rs.is_reserved()) return false;
2091 #endif
2092 
2093   assert(!DumpSharedSpaces, "Should not be called with DumpSharedSpaces");
2094 
2095   char* ro_base = NULL; char* ro_top;
2096   char* rw_base = NULL; char* rw_top;
2097   char* mc_base = NULL; char* mc_top;
2098   char* md_base = NULL; char* md_top;
2099   char* od_base = NULL; char* od_top;
2100 
2101   // Map each shared region
2102   if ((mc_base = mapinfo->map_region(mc, &mc_top)) != NULL &&
2103       (rw_base = mapinfo->map_region(rw, &rw_top)) != NULL &&
2104       (ro_base = mapinfo->map_region(ro, &ro_top)) != NULL &&
2105       (md_base = mapinfo->map_region(md, &md_top)) != NULL &&
2106       (od_base = mapinfo->map_region(od, &od_top)) != NULL &&
2107       (image_alignment == (size_t)os::vm_allocation_granularity()) &&
2108       mapinfo->validate_shared_path_table()) {
2109     // Success -- set up MetaspaceObj::_shared_metaspace_{base,top} for
2110     // fast checking in MetaspaceShared::is_in_shared_metaspace() and
2111     // MetaspaceObj::is_shared().
2112     //
2113     // We require that mc->rw->ro->md->od to be laid out consecutively, with no
2114     // gaps between them. That way, we can ensure that the OS won't be able to
2115     // allocate any new memory spaces inside _shared_metaspace_{base,top}, which
2116     // would mess up the simple comparision in MetaspaceShared::is_in_shared_metaspace().
2117     assert(mc_base < ro_base && mc_base < rw_base && mc_base < md_base && mc_base < od_base, "must be");
2118     assert(od_top  > ro_top  && od_top  > rw_top  && od_top  > md_top  && od_top  > mc_top , "must be");
2119     assert(mc_top == rw_base, "must be");
2120     assert(rw_top == ro_base, "must be");
2121     assert(ro_top == md_base, "must be");
2122     assert(md_top == od_base, "must be");
2123 
2124     MetaspaceObj::_shared_metaspace_base = (void*)mc_base;
2125     MetaspaceObj::_shared_metaspace_top  = (void*)od_top;
2126     return true;
2127   } else {
2128     // If there was a failure in mapping any of the spaces, unmap the ones
2129     // that succeeded
2130     if (ro_base != NULL) mapinfo->unmap_region(ro);
2131     if (rw_base != NULL) mapinfo->unmap_region(rw);
2132     if (mc_base != NULL) mapinfo->unmap_region(mc);
2133     if (md_base != NULL) mapinfo->unmap_region(md);
2134     if (od_base != NULL) mapinfo->unmap_region(od);
2135 #ifndef _WINDOWS
2136     // Release the entire mapped region
2137     shared_rs.release();
2138 #endif
2139     // If -Xshare:on is specified, print out the error message and exit VM,
2140     // otherwise, set UseSharedSpaces to false and continue.
2141     if (RequireSharedSpaces || PrintSharedArchiveAndExit) {
2142       vm_exit_during_initialization("Unable to use shared archive.", "Failed map_region for using -Xshare:on.");
2143     } else {
2144       FLAG_SET_DEFAULT(UseSharedSpaces, false);
2145     }
2146     return false;
2147   }
2148 }
2149 
2150 // Read the miscellaneous data from the shared file, and
2151 // serialize it out to its various destinations.
2152 
2153 void MetaspaceShared::initialize_shared_spaces() {
2154   FileMapInfo *mapinfo = FileMapInfo::current_info();
2155   _cds_i2i_entry_code_buffers = mapinfo->cds_i2i_entry_code_buffers();
2156   _cds_i2i_entry_code_buffers_size = mapinfo->cds_i2i_entry_code_buffers_size();
2157   _core_spaces_size = mapinfo->core_spaces_size();
2158   char* buffer = mapinfo->misc_data_patching_start();
2159   clone_cpp_vtables((intptr_t*)buffer);
2160 
2161   // The rest of the data is now stored in the RW region
2162   buffer = mapinfo->read_only_tables_start();
2163   int sharedDictionaryLen = *(intptr_t*)buffer;
2164   buffer += sizeof(intptr_t);
2165   int number_of_entries = *(intptr_t*)buffer;
2166   buffer += sizeof(intptr_t);
2167   SystemDictionary::set_shared_dictionary((HashtableBucket<mtClass>*)buffer,
2168                                           sharedDictionaryLen,
2169                                           number_of_entries);
2170   buffer += sharedDictionaryLen;
2171 
2172   // The following data are the linked list elements
2173   // (HashtableEntry objects) for the shared dictionary table.
2174 
2175   int len = *(intptr_t*)buffer;     // skip over shared dictionary entries
2176   buffer += sizeof(intptr_t);
2177   buffer += len;
2178 
2179   // The table of archived java heap object sub-graph infos
2180   buffer = HeapShared::read_archived_subgraph_infos(buffer);
2181 
2182   // Verify various attributes of the archive, plus initialize the
2183   // shared string/symbol tables
2184   intptr_t* array = (intptr_t*)buffer;
2185   ReadClosure rc(&array);
2186   serialize(&rc);
2187 
2188   // Initialize the run-time symbol table.
2189   SymbolTable::create_table();
2190 
2191   mapinfo->patch_archived_heap_embedded_pointers();
2192 
2193   // Close the mapinfo file
2194   mapinfo->close();
2195 
2196   if (PrintSharedArchiveAndExit) {
2197     if (PrintSharedDictionary) {
2198       tty->print_cr("\nShared classes:\n");
2199       SystemDictionary::print_shared(tty);
2200     }
2201     if (_archive_loading_failed) {
2202       tty->print_cr("archive is invalid");
2203       vm_exit(1);
2204     } else {
2205       tty->print_cr("archive is valid");
2206       vm_exit(0);
2207     }
2208   }
2209 }
2210 
2211 // JVM/TI RedefineClasses() support:
2212 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
2213   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2214 
2215   if (UseSharedSpaces) {
2216     // remap the shared readonly space to shared readwrite, private
2217     FileMapInfo* mapinfo = FileMapInfo::current_info();
2218     if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2219       return false;
2220     }
2221     _remapped_readwrite = true;
2222   }
2223   return true;
2224 }
2225 
2226 void MetaspaceShared::report_out_of_space(const char* name, size_t needed_bytes) {
2227   // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space.
2228   // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes
2229   // or so.
2230   _mc_region.print_out_of_space_msg(name, needed_bytes);
2231   _rw_region.print_out_of_space_msg(name, needed_bytes);
2232   _ro_region.print_out_of_space_msg(name, needed_bytes);
2233   _md_region.print_out_of_space_msg(name, needed_bytes);
2234   _od_region.print_out_of_space_msg(name, needed_bytes);
2235 
2236   vm_exit_during_initialization(err_msg("Unable to allocate from '%s' region", name),
2237                                 "Please reduce the number of shared classes.");
2238 }