1 /*
   2  * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classListParser.hpp"
  27 #include "classfile/classLoaderExt.hpp"
  28 #include "classfile/dictionary.hpp"
  29 #include "classfile/loaderConstraints.hpp"
  30 #include "classfile/placeholders.hpp"
  31 #include "classfile/sharedClassUtil.hpp"
  32 #include "classfile/symbolTable.hpp"
  33 #include "classfile/systemDictionary.hpp"
  34 #include "classfile/systemDictionaryShared.hpp"
  35 #include "code/codeCache.hpp"
  36 #include "gc/shared/gcLocker.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/metaspace.hpp"
  43 #include "memory/metaspaceShared.hpp"
  44 #include "memory/resourceArea.hpp"
  45 #include "oops/instanceClassLoaderKlass.hpp"
  46 #include "oops/instanceMirrorKlass.hpp"
  47 #include "oops/instanceRefKlass.hpp"
  48 #include "oops/objArrayKlass.hpp"
  49 #include "oops/objArrayOop.hpp"
  50 #include "oops/oop.inline.hpp"
  51 #include "oops/typeArrayKlass.hpp"
  52 #include "prims/jvm.h"
  53 #include "prims/jvmtiRedefineClasses.hpp"
  54 #include "runtime/timerTrace.hpp"
  55 #include "runtime/os.hpp"
  56 #include "runtime/signature.hpp"
  57 #include "runtime/vmThread.hpp"
  58 #include "runtime/vm_operations.hpp"
  59 #include "utilities/align.hpp"
  60 #include "utilities/defaultStream.hpp"
  61 #include "utilities/hashtable.inline.hpp"
  62 #include "memory/metaspaceClosure.hpp"
  63 
  64 ReservedSpace MetaspaceShared::_shared_rs;
  65 VirtualSpace MetaspaceShared::_shared_vs;
  66 MetaspaceSharedStats MetaspaceShared::_stats;
  67 bool MetaspaceShared::_has_error_classes;
  68 bool MetaspaceShared::_archive_loading_failed = false;
  69 bool MetaspaceShared::_remapped_readwrite = false;
  70 address MetaspaceShared::_cds_i2i_entry_code_buffers = NULL;
  71 size_t MetaspaceShared::_cds_i2i_entry_code_buffers_size = 0;
  72 size_t MetaspaceShared::_core_spaces_size = 0;
  73 
  74 // The CDS archive is divided into 6 regions:
  75 //     mc - misc code (the method entry trampolines)
  76 //     rw - read-write metadata
  77 //     ro - read-only metadata and read-only tables
  78 //     md - misc data (the c++ vtables)
  79 //     od - other data (original class files)
  80 //     st - shared strings
  81 //
  82 // Except for the st region, the other 5 regions are linearly allocated, starting from
  83 // SharedBaseAddress, in the order of mc->rw->ro->md->od. The size of these 5 regions
  84 // are page-aligned, and there's no gap between any consecutive regions.
  85 //
  86 // These 5 regions are populated in the following steps:
  87 // [1] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
  88 //     temporarily allocated outside of the shared regions. Only the method entry
  89 //     trampolines are written into the mc region.
  90 // [2] ArchiveCompactor copies RW metadata into the rw region.
  91 // [3] ArchiveCompactor copies RO metadata into the ro region.
  92 // [4] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
  93 //     are copied into the ro region as read-only tables.
  94 // [5] C++ vtables are copied into the md region.
  95 // [6] Original class files are copied into the od region.
  96 //
  97 // The st region is populated inside MetaspaceShared::dump_string_and_symbols. Its
  98 // layout is independent of the other 5 regions.
  99 
 100 class DumpRegion {
 101 private:
 102   const char* _name;
 103   char* _base;
 104   char* _top;
 105   char* _end;
 106   bool _is_packed;
 107 
 108   char* expand_top_to(char* newtop) {
 109     assert(is_allocatable(), "must be initialized and not packed");
 110     assert(newtop >= _top, "must not grow backwards");
 111     if (newtop > _end) {
 112       MetaspaceShared::report_out_of_space(_name, newtop - _top);
 113       ShouldNotReachHere();
 114     }
 115     MetaspaceShared::commit_shared_space_to(newtop);
 116     _top = newtop;
 117     return _top;
 118   }
 119 
 120 public:
 121   DumpRegion(const char* name) : _name(name), _base(NULL), _top(NULL), _end(NULL), _is_packed(false) {}
 122 
 123   char* allocate(size_t num_bytes, size_t alignment=BytesPerWord) {
 124     char* p = (char*)align_ptr_up(_top, alignment);
 125     char* newtop = p + align_size_up(num_bytes, alignment);
 126     expand_top_to(newtop);
 127     memset(p, 0, newtop - p);
 128     return p;
 129   }
 130 
 131   void append_intptr_t(intptr_t n) {
 132     assert(is_ptr_aligned(_top, sizeof(intptr_t)), "bad alignment");
 133     intptr_t *p = (intptr_t*)_top;
 134     char* newtop = _top + sizeof(intptr_t);
 135     expand_top_to(newtop);
 136     *p = n;
 137   }
 138 
 139   char* base()      const { return _base;        }
 140   char* top()       const { return _top;         }
 141   char* end()       const { return _end;         }
 142   size_t reserved() const { return _end - _base; }
 143   size_t used()     const { return _top - _base; }
 144   bool is_packed()  const { return _is_packed;   }
 145   bool is_allocatable() const {
 146     return !is_packed() && _base != NULL;
 147   }
 148 
 149   double perc(size_t used, size_t total) const {
 150     if (total == 0) {total = 1;}
 151     return used / double(total) * 100.0;
 152   }
 153 
 154   void print(size_t total_bytes) const {
 155     tty->print_cr("%s space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used] at " INTPTR_FORMAT,
 156                   _name, used(), perc(used(), total_bytes), reserved(), perc(used(), reserved()), p2i(_base));
 157   }
 158   void print_out_of_space_msg(const char* failing_region, size_t needed_bytes) {
 159     tty->print("[%-8s] " PTR_FORMAT " - " PTR_FORMAT " capacity =%9d, allocated =%9d",
 160                _name, p2i(_base), p2i(_top), int(_end - _base), int(_top - _base));
 161     if (strcmp(_name, failing_region) == 0) {
 162       tty->print_cr(" required = %d", int(needed_bytes));
 163     } else {
 164       tty->cr();
 165     }
 166   }
 167 
 168   void init(const ReservedSpace* rs) {
 169     _base = _top = rs->base();
 170     _end = rs->end();
 171   }
 172   void init(char* b, char* t, char* e) {
 173     _base = b;
 174     _top = t;
 175     _end = e;
 176   }
 177 
 178   void pack(DumpRegion* next = NULL) {
 179     assert(!is_packed(), "sanity");
 180     _end = (char*)align_ptr_up(_top, Metaspace::reserve_alignment());
 181     _is_packed = true;
 182     if (next != NULL) {
 183       next->_base = next->_top = this->_end;
 184       next->_end = MetaspaceShared::shared_rs()->end();
 185     }
 186   }
 187   bool contains(char* p) {
 188     return base() <= p && p < top();
 189   }
 190 };
 191 
 192 DumpRegion _mc_region("mc"), _ro_region("ro"), _rw_region("rw"), _md_region("md");
 193 DumpRegion _st_region("st"), _od_region("od");
 194 
 195 char* MetaspaceShared::misc_code_space_alloc(size_t num_bytes) {
 196   return _mc_region.allocate(num_bytes);
 197 }
 198 
 199 char* MetaspaceShared::read_only_space_alloc(size_t num_bytes) {
 200   return _ro_region.allocate(num_bytes);
 201 }
 202 
 203 void MetaspaceShared::initialize_shared_rs() {
 204   const size_t reserve_alignment = Metaspace::reserve_alignment();
 205   bool large_pages = false; // No large pages when dumping the CDS archive.
 206   char* shared_base = (char*)align_ptr_up((char*)SharedBaseAddress, reserve_alignment);
 207 
 208 #ifdef _LP64
 209   const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
 210   const size_t cds_total = align_size_down(UnscaledClassSpaceMax, reserve_alignment);
 211 #else
 212   // We don't support archives larger than 256MB on 32-bit due to limited virtual address space.
 213   size_t cds_total = align_size_down(256*M, reserve_alignment);
 214 #endif
 215 
 216   // First try to reserve the space at the specified SharedBaseAddress.
 217   _shared_rs = ReservedSpace(cds_total, reserve_alignment, large_pages, shared_base);
 218   if (_shared_rs.is_reserved()) {
 219     assert(shared_base == 0 || _shared_rs.base() == shared_base, "should match");
 220   } else {
 221     // Get a mmap region anywhere if the SharedBaseAddress fails.
 222     _shared_rs = ReservedSpace(cds_total, reserve_alignment, large_pages);
 223   }
 224   if (!_shared_rs.is_reserved()) {
 225     vm_exit_during_initialization("Unable to reserve memory for shared space",
 226                                   err_msg(SIZE_FORMAT " bytes.", cds_total));
 227   }
 228 
 229 #ifdef _LP64
 230   // During dump time, we allocate 4GB (UnscaledClassSpaceMax) of space and split it up:
 231   // + The upper 1 GB is used as the "temporary compressed class space" -- preload_classes()
 232   //   will store Klasses into this space.
 233   // + The lower 3 GB is used for the archive -- when preload_classes() is done,
 234   //   ArchiveCompactor will copy the class metadata into this space, first the RW parts,
 235   //   then the RO parts.
 236 
 237   assert(UseCompressedOops && UseCompressedClassPointers,
 238       "UseCompressedOops and UseCompressedClassPointers must be set");
 239 
 240   size_t max_archive_size = align_size_down(cds_total * 3 / 4, reserve_alignment);
 241   ReservedSpace tmp_class_space = _shared_rs.last_part(max_archive_size);
 242   CompressedClassSpaceSize = align_size_down(tmp_class_space.size(), reserve_alignment);
 243   _shared_rs = _shared_rs.first_part(max_archive_size);
 244 
 245   // Set up compress class pointers.
 246   Universe::set_narrow_klass_base((address)_shared_rs.base());
 247   if (UseAOT || cds_total > UnscaledClassSpaceMax) {
 248     // AOT forces narrow_klass_shift=LogKlassAlignmentInBytes
 249     Universe::set_narrow_klass_shift(LogKlassAlignmentInBytes);
 250   } else {
 251     Universe::set_narrow_klass_shift(0);
 252   }
 253 
 254   Metaspace::initialize_class_space(tmp_class_space);
 255   tty->print_cr("narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
 256                 p2i(Universe::narrow_klass_base()), Universe::narrow_klass_shift());
 257 
 258   tty->print_cr("Allocated temporary class space: " SIZE_FORMAT " bytes at " PTR_FORMAT,
 259                 CompressedClassSpaceSize, p2i(tmp_class_space.base()));
 260 #endif
 261 
 262   // Start with 0 committed bytes. The memory will be committed as needed by
 263   // MetaspaceShared::commit_shared_space_to().
 264   if (!_shared_vs.initialize(_shared_rs, 0)) {
 265     vm_exit_during_initialization("Unable to allocate memory for shared space");
 266   }
 267 
 268   _mc_region.init(&_shared_rs);
 269   tty->print_cr("Allocated shared space: " SIZE_FORMAT " bytes at " PTR_FORMAT,
 270                 _shared_rs.size(), p2i(_shared_rs.base()));
 271 }
 272 
 273 void MetaspaceShared::commit_shared_space_to(char* newtop) {
 274   assert(DumpSharedSpaces, "dump-time only");
 275   char* base = _shared_rs.base();
 276   size_t need_committed_size = newtop - base;
 277   size_t has_committed_size = _shared_vs.committed_size();
 278   if (need_committed_size < has_committed_size) {
 279     return;
 280   }
 281 
 282   size_t min_bytes = need_committed_size - has_committed_size;
 283   size_t preferred_bytes = 1 * M;
 284   size_t uncommitted = _shared_vs.reserved_size() - has_committed_size;
 285 
 286   size_t commit = MAX2(min_bytes, preferred_bytes);
 287   assert(commit <= uncommitted, "sanity");
 288 
 289   bool result = _shared_vs.expand_by(commit, false);
 290   assert(result, "Failed to commit memory");
 291 
 292   log_info(cds)("Expanding shared spaces by %7d bytes [total %8d bytes ending at %p]",
 293                 int(commit), int(_shared_vs.actual_committed_size()), _shared_vs.high());
 294 }
 295 
 296 // Read/write a data stream for restoring/preserving metadata pointers and
 297 // miscellaneous data from/to the shared archive file.
 298 
 299 void MetaspaceShared::serialize(SerializeClosure* soc) {
 300   int tag = 0;
 301   soc->do_tag(--tag);
 302 
 303   // Verify the sizes of various metadata in the system.
 304   soc->do_tag(sizeof(Method));
 305   soc->do_tag(sizeof(ConstMethod));
 306   soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
 307   soc->do_tag(sizeof(ConstantPool));
 308   soc->do_tag(sizeof(ConstantPoolCache));
 309   soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
 310   soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
 311   soc->do_tag(sizeof(Symbol));
 312 
 313   // Dump/restore miscellaneous metadata.
 314   Universe::serialize(soc, true);
 315   soc->do_tag(--tag);
 316 
 317   // Dump/restore references to commonly used names and signatures.
 318   vmSymbols::serialize(soc);
 319   soc->do_tag(--tag);
 320 
 321   // Dump/restore the symbol and string tables
 322   SymbolTable::serialize(soc);
 323   StringTable::serialize(soc);
 324   soc->do_tag(--tag);
 325 
 326   soc->do_tag(666);
 327 }
 328 
 329 address MetaspaceShared::cds_i2i_entry_code_buffers(size_t total_size) {
 330   if (DumpSharedSpaces) {
 331     if (_cds_i2i_entry_code_buffers == NULL) {
 332       _cds_i2i_entry_code_buffers = (address)misc_code_space_alloc(total_size);
 333       _cds_i2i_entry_code_buffers_size = total_size;
 334     }
 335   } else if (UseSharedSpaces) {
 336     assert(_cds_i2i_entry_code_buffers != NULL, "must already been initialized");
 337   } else {
 338     return NULL;
 339   }
 340 
 341   assert(_cds_i2i_entry_code_buffers_size == total_size, "must not change");
 342   return _cds_i2i_entry_code_buffers;
 343 }
 344 
 345 // CDS code for dumping shared archive.
 346 
 347 // Global object for holding classes that have been loaded.  Since this
 348 // is run at a safepoint just before exit, this is the entire set of classes.
 349 static GrowableArray<Klass*>* _global_klass_objects;
 350 class CollectClassesClosure : public KlassClosure {
 351   void do_klass(Klass* k) {
 352     if (!(k->is_instance_klass() && InstanceKlass::cast(k)->is_in_error_state())) {
 353       _global_klass_objects->append_if_missing(k);
 354     }
 355   }
 356 };
 357 
 358 static void remove_unshareable_in_classes() {
 359   for (int i = 0; i < _global_klass_objects->length(); i++) {
 360     Klass* k = _global_klass_objects->at(i);
 361     k->remove_unshareable_info();
 362   }
 363 }
 364 
 365 static void rewrite_nofast_bytecode(Method* method) {
 366   RawBytecodeStream bcs(method);
 367   while (!bcs.is_last_bytecode()) {
 368     Bytecodes::Code opcode = bcs.raw_next();
 369     switch (opcode) {
 370     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
 371     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;
 372     case Bytecodes::_aload_0:       *bcs.bcp() = Bytecodes::_nofast_aload_0;       break;
 373     case Bytecodes::_iload: {
 374       if (!bcs.is_wide()) {
 375         *bcs.bcp() = Bytecodes::_nofast_iload;
 376       }
 377       break;
 378     }
 379     default: break;
 380     }
 381   }
 382 }
 383 
 384 // Walk all methods in the class list to ensure that they won't be modified at
 385 // run time. This includes:
 386 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified
 387 //     at run time by RewriteBytecodes/RewriteFrequentPairs
 388 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.
 389 static void rewrite_nofast_bytecodes_and_calculate_fingerprints() {
 390   for (int i = 0; i < _global_klass_objects->length(); i++) {
 391     Klass* k = _global_klass_objects->at(i);
 392     if (k->is_instance_klass()) {
 393       InstanceKlass* ik = InstanceKlass::cast(k);
 394       for (int i = 0; i < ik->methods()->length(); i++) {
 395         Method* m = ik->methods()->at(i);
 396         rewrite_nofast_bytecode(m);
 397         Fingerprinter fp(m);
 398         // The side effect of this call sets method's fingerprint field.
 399         fp.fingerprint();
 400       }
 401     }
 402   }
 403 }
 404 
 405 static void relocate_cached_class_file() {
 406   for (int i = 0; i < _global_klass_objects->length(); i++) {
 407     Klass* k = _global_klass_objects->at(i);
 408     if (k->is_instance_klass()) {
 409       InstanceKlass* ik = InstanceKlass::cast(k);
 410       JvmtiCachedClassFileData* p = ik->get_archived_class_data();
 411       if (p != NULL) {
 412         int size = offset_of(JvmtiCachedClassFileData, data) + p->length;
 413         JvmtiCachedClassFileData* q = (JvmtiCachedClassFileData*)_od_region.allocate(size);
 414         q->length = p->length;
 415         memcpy(q->data, p->data, p->length);
 416         ik->set_archived_class_data(q);
 417       }
 418     }
 419   }
 420 }
 421 
 422 // Objects of the Metadata types (such as Klass and ConstantPool) have C++ vtables.
 423 // (In GCC this is the field <Type>::_vptr, i.e., first word in the object.)
 424 //
 425 // Addresses of the vtables and the methods may be different across JVM runs,
 426 // if libjvm.so is dynamically loaded at a different base address.
 427 //
 428 // To ensure that the Metadata objects in the CDS archive always have the correct vtable:
 429 //
 430 // + at dump time:  we redirect the _vptr to point to our own vtables inside
 431 //                  the CDS image
 432 // + at run time:   we clone the actual contents of the vtables from libjvm.so
 433 //                  into our own tables.
 434 
 435 // Currently, the archive contain ONLY the following types of objects that have C++ vtables.
 436 #define CPP_VTABLE_PATCH_TYPES_DO(f) \
 437   f(ConstantPool) \
 438   f(InstanceKlass) \
 439   f(InstanceClassLoaderKlass) \
 440   f(InstanceMirrorKlass) \
 441   f(InstanceRefKlass) \
 442   f(Method) \
 443   f(ObjArrayKlass) \
 444   f(TypeArrayKlass)
 445 
 446 class CppVtableInfo {
 447   intptr_t _vtable_size;
 448   intptr_t _cloned_vtable[1];
 449 public:
 450   static int num_slots(int vtable_size) {
 451     return 1 + vtable_size; // Need to add the space occupied by _vtable_size;
 452   }
 453   int vtable_size()           { return int(uintx(_vtable_size)); }
 454   void set_vtable_size(int n) { _vtable_size = intptr_t(n); }
 455   intptr_t* cloned_vtable()   { return &_cloned_vtable[0]; }
 456   void zero()                 { memset(_cloned_vtable, 0, sizeof(intptr_t) * vtable_size()); }
 457   // Returns the address of the next CppVtableInfo that can be placed immediately after this CppVtableInfo
 458   static size_t byte_size(int vtable_size) {
 459     CppVtableInfo i;
 460     return pointer_delta(&i._cloned_vtable[vtable_size], &i, sizeof(u1));
 461   }
 462 };
 463 
 464 template <class T> class CppVtableCloner : public T {
 465   static intptr_t* vtable_of(Metadata& m) {
 466     return *((intptr_t**)&m);
 467   }
 468   static CppVtableInfo* _info;
 469 
 470   static int get_vtable_length(const char* name);
 471 
 472 public:
 473   // Allocate and initialize the C++ vtable, starting from top, but do not go past end.
 474   static intptr_t* allocate(const char* name);
 475 
 476   // Clone the vtable to ...
 477   static intptr_t* clone_vtable(const char* name, CppVtableInfo* info);
 478 
 479   static void zero_vtable_clone() {
 480     assert(DumpSharedSpaces, "dump-time only");
 481     _info->zero();
 482   }
 483 
 484   // Switch the vtable pointer to point to the cloned vtable.
 485   static void patch(Metadata* obj) {
 486     assert(DumpSharedSpaces, "dump-time only");
 487     *(void**)obj = (void*)(_info->cloned_vtable());
 488   }
 489 
 490   static bool is_valid_shared_object(const T* obj) {
 491     intptr_t* vptr = *(intptr_t**)obj;
 492     return vptr == _info->cloned_vtable();
 493   }
 494 };
 495 
 496 template <class T> CppVtableInfo* CppVtableCloner<T>::_info = NULL;
 497 
 498 template <class T>
 499 intptr_t* CppVtableCloner<T>::allocate(const char* name) {
 500   assert(is_ptr_aligned(_md_region.top(), sizeof(intptr_t)), "bad alignment");
 501   int n = get_vtable_length(name);
 502   _info = (CppVtableInfo*)_md_region.allocate(CppVtableInfo::byte_size(n), sizeof(intptr_t));
 503   _info->set_vtable_size(n);
 504 
 505   intptr_t* p = clone_vtable(name, _info);
 506   assert((char*)p == _md_region.top(), "must be");
 507 
 508   return p;
 509 }
 510 
 511 template <class T>
 512 intptr_t* CppVtableCloner<T>::clone_vtable(const char* name, CppVtableInfo* info) {
 513   if (!DumpSharedSpaces) {
 514     assert(_info == 0, "_info is initialized only at dump time");
 515     _info = info; // Remember it -- it will be used by MetaspaceShared::is_valid_shared_method()
 516   }
 517   T tmp; // Allocate temporary dummy metadata object to get to the original vtable.
 518   int n = info->vtable_size();
 519   intptr_t* srcvtable = vtable_of(tmp);
 520   intptr_t* dstvtable = info->cloned_vtable();
 521 
 522   // We already checked (and, if necessary, adjusted n) when the vtables were allocated, so we are
 523   // safe to do memcpy.
 524   log_debug(cds, vtables)("Copying %3d vtable entries for %s", n, name);
 525   memcpy(dstvtable, srcvtable, sizeof(intptr_t) * n);
 526   return dstvtable + n;
 527 }
 528 
 529 // To determine the size of the vtable for each type, we use the following
 530 // trick by declaring 2 subclasses:
 531 //
 532 //   class CppVtableTesterA: public InstanceKlass {virtual int   last_virtual_method() {return 1;}    };
 533 //   class CppVtableTesterB: public InstanceKlass {virtual void* last_virtual_method() {return NULL}; };
 534 //
 535 // CppVtableTesterA and CppVtableTesterB's vtables have the following properties:
 536 // - Their size (N+1) is exactly one more than the size of InstanceKlass's vtable (N)
 537 // - The first N entries have are exactly the same as in InstanceKlass's vtable.
 538 // - Their last entry is different.
 539 //
 540 // So to determine the value of N, we just walk CppVtableTesterA and CppVtableTesterB's tables
 541 // and find the first entry that's different.
 542 //
 543 // This works on all C++ compilers supported by Oracle, but you may need to tweak it for more
 544 // esoteric compilers.
 545 
 546 template <class T> class CppVtableTesterB: public T {
 547 public:
 548   virtual int last_virtual_method() {return 1;}
 549 };
 550 
 551 template <class T> class CppVtableTesterA : public T {
 552 public:
 553   virtual void* last_virtual_method() {
 554     // Make this different than CppVtableTesterB::last_virtual_method so the C++
 555     // compiler/linker won't alias the two functions.
 556     return NULL;
 557   }
 558 };
 559 
 560 template <class T>
 561 int CppVtableCloner<T>::get_vtable_length(const char* name) {
 562   CppVtableTesterA<T> a;
 563   CppVtableTesterB<T> b;
 564 
 565   intptr_t* avtable = vtable_of(a);
 566   intptr_t* bvtable = vtable_of(b);
 567 
 568   // Start at slot 1, because slot 0 may be RTTI (on Solaris/Sparc)
 569   int vtable_len = 1;
 570   for (; ; vtable_len++) {
 571     if (avtable[vtable_len] != bvtable[vtable_len]) {
 572       break;
 573     }
 574   }
 575   log_debug(cds, vtables)("Found   %3d vtable entries for %s", vtable_len, name);
 576 
 577   return vtable_len;
 578 }
 579 
 580 #define ALLOC_CPP_VTABLE_CLONE(c) \
 581   CppVtableCloner<c>::allocate(#c);
 582 
 583 #define CLONE_CPP_VTABLE(c) \
 584   p = CppVtableCloner<c>::clone_vtable(#c, (CppVtableInfo*)p);
 585 
 586 #define ZERO_CPP_VTABLE(c) \
 587  CppVtableCloner<c>::zero_vtable_clone();
 588 
 589 // This can be called at both dump time and run time.
 590 intptr_t* MetaspaceShared::clone_cpp_vtables(intptr_t* p) {
 591   assert(DumpSharedSpaces || UseSharedSpaces, "sanity");
 592   CPP_VTABLE_PATCH_TYPES_DO(CLONE_CPP_VTABLE);
 593   return p;
 594 }
 595 
 596 void MetaspaceShared::zero_cpp_vtable_clones_for_writing() {
 597   assert(DumpSharedSpaces, "dump-time only");
 598   CPP_VTABLE_PATCH_TYPES_DO(ZERO_CPP_VTABLE);
 599 }
 600 
 601 // Allocate and initialize the C++ vtables, starting from top, but do not go past end.
 602 void MetaspaceShared::allocate_cpp_vtable_clones() {
 603   assert(DumpSharedSpaces, "dump-time only");
 604   // Layout (each slot is a intptr_t):
 605   //   [number of slots in the first vtable = n1]
 606   //   [ <n1> slots for the first vtable]
 607   //   [number of slots in the first second = n2]
 608   //   [ <n2> slots for the second vtable]
 609   //   ...
 610   // The order of the vtables is the same as the CPP_VTAB_PATCH_TYPES_DO macro.
 611   CPP_VTABLE_PATCH_TYPES_DO(ALLOC_CPP_VTABLE_CLONE);
 612 }
 613 
 614 // Switch the vtable pointer to point to the cloned vtable. We assume the
 615 // vtable pointer is in first slot in object.
 616 void MetaspaceShared::patch_cpp_vtable_pointers() {
 617   int n = _global_klass_objects->length();
 618   for (int i = 0; i < n; i++) {
 619     Klass* obj = _global_klass_objects->at(i);
 620     if (obj->is_instance_klass()) {
 621       InstanceKlass* ik = InstanceKlass::cast(obj);
 622       if (ik->is_class_loader_instance_klass()) {
 623         CppVtableCloner<InstanceClassLoaderKlass>::patch(ik);
 624       } else if (ik->is_reference_instance_klass()) {
 625         CppVtableCloner<InstanceRefKlass>::patch(ik);
 626       } else if (ik->is_mirror_instance_klass()) {
 627         CppVtableCloner<InstanceMirrorKlass>::patch(ik);
 628       } else {
 629         CppVtableCloner<InstanceKlass>::patch(ik);
 630       }
 631       ConstantPool* cp = ik->constants();
 632       CppVtableCloner<ConstantPool>::patch(cp);
 633       for (int j = 0; j < ik->methods()->length(); j++) {
 634         Method* m = ik->methods()->at(j);
 635         CppVtableCloner<Method>::patch(m);
 636         assert(CppVtableCloner<Method>::is_valid_shared_object(m), "must be");
 637       }
 638     } else if (obj->is_objArray_klass()) {
 639       CppVtableCloner<ObjArrayKlass>::patch(obj);
 640     } else {
 641       assert(obj->is_typeArray_klass(), "sanity");
 642       CppVtableCloner<TypeArrayKlass>::patch(obj);
 643     }
 644   }
 645 }
 646 
 647 bool MetaspaceShared::is_valid_shared_method(const Method* m) {
 648   assert(is_in_shared_space(m), "must be");
 649   return CppVtableCloner<Method>::is_valid_shared_object(m);
 650 }
 651 
 652 // Closure for serializing initialization data out to a data area to be
 653 // written to the shared file.
 654 
 655 class WriteClosure : public SerializeClosure {
 656 private:
 657   DumpRegion* _dump_region;
 658 
 659 public:
 660   WriteClosure(DumpRegion* r) {
 661     _dump_region = r;
 662   }
 663 
 664   void do_ptr(void** p) {
 665     _dump_region->append_intptr_t((intptr_t)*p);
 666   }
 667 
 668   void do_u4(u4* p) {
 669     void* ptr = (void*)(uintx(*p));
 670     do_ptr(&ptr);
 671   }
 672 
 673   void do_tag(int tag) {
 674     _dump_region->append_intptr_t((intptr_t)tag);
 675   }
 676 
 677   void do_region(u_char* start, size_t size) {
 678     assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
 679     assert(size % sizeof(intptr_t) == 0, "bad size");
 680     do_tag((int)size);
 681     while (size > 0) {
 682       _dump_region->append_intptr_t(*(intptr_t*)start);
 683       start += sizeof(intptr_t);
 684       size -= sizeof(intptr_t);
 685     }
 686   }
 687 
 688   bool reading() const { return false; }
 689 };
 690 
 691 // This is for dumping detailed statistics for the allocations
 692 // in the shared spaces.
 693 class DumpAllocStats : public ResourceObj {
 694 public:
 695 
 696   // Here's poor man's enum inheritance
 697 #define SHAREDSPACE_OBJ_TYPES_DO(f) \
 698   METASPACE_OBJ_TYPES_DO(f) \
 699   f(SymbolHashentry) \
 700   f(SymbolBucket) \
 701   f(StringHashentry) \
 702   f(StringBucket) \
 703   f(Other)
 704 
 705   enum Type {
 706     // Types are MetaspaceObj::ClassType, MetaspaceObj::SymbolType, etc
 707     SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_DECLARE)
 708     _number_of_types
 709   };
 710 
 711   static const char * type_name(Type type) {
 712     switch(type) {
 713     SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_NAME_CASE)
 714     default:
 715       ShouldNotReachHere();
 716       return NULL;
 717     }
 718   }
 719 
 720 public:
 721   enum { RO = 0, RW = 1 };
 722 
 723   int _counts[2][_number_of_types];
 724   int _bytes [2][_number_of_types];
 725 
 726   DumpAllocStats() {
 727     memset(_counts, 0, sizeof(_counts));
 728     memset(_bytes,  0, sizeof(_bytes));
 729   };
 730 
 731   void record(MetaspaceObj::Type type, int byte_size, bool read_only) {
 732     assert(int(type) >= 0 && type < MetaspaceObj::_number_of_types, "sanity");
 733     int which = (read_only) ? RO : RW;
 734     _counts[which][type] ++;
 735     _bytes [which][type] += byte_size;
 736   }
 737 
 738   void print_stats(int ro_all, int rw_all, int mc_all, int md_all);
 739 };
 740 
 741 void DumpAllocStats::print_stats(int ro_all, int rw_all, int mc_all, int md_all) {
 742   // Calculate size of data that was not allocated by Metaspace::allocate()
 743   MetaspaceSharedStats *stats = MetaspaceShared::stats();
 744 
 745   // symbols
 746   _counts[RO][SymbolHashentryType] = stats->symbol.hashentry_count;
 747   _bytes [RO][SymbolHashentryType] = stats->symbol.hashentry_bytes;
 748 
 749   _counts[RO][SymbolBucketType] = stats->symbol.bucket_count;
 750   _bytes [RO][SymbolBucketType] = stats->symbol.bucket_bytes;
 751 
 752   // strings
 753   _counts[RO][StringHashentryType] = stats->string.hashentry_count;
 754   _bytes [RO][StringHashentryType] = stats->string.hashentry_bytes;
 755 
 756   _counts[RO][StringBucketType] = stats->string.bucket_count;
 757   _bytes [RO][StringBucketType] = stats->string.bucket_bytes;
 758 
 759   // TODO: count things like dictionary, vtable, etc
 760   _bytes[RW][OtherType] += mc_all + md_all;
 761   rw_all += mc_all + md_all; // mc/md are mapped Read/Write
 762 
 763   // prevent divide-by-zero
 764   if (ro_all < 1) {
 765     ro_all = 1;
 766   }
 767   if (rw_all < 1) {
 768     rw_all = 1;
 769   }
 770 
 771   int all_ro_count = 0;
 772   int all_ro_bytes = 0;
 773   int all_rw_count = 0;
 774   int all_rw_bytes = 0;
 775 
 776 // To make fmt_stats be a syntactic constant (for format warnings), use #define.
 777 #define fmt_stats "%-20s: %8d %10d %5.1f | %8d %10d %5.1f | %8d %10d %5.1f"
 778   const char *sep = "--------------------+---------------------------+---------------------------+--------------------------";
 779   const char *hdr = "                        ro_cnt   ro_bytes     % |   rw_cnt   rw_bytes     % |  all_cnt  all_bytes     %";
 780 
 781   ResourceMark rm;
 782   LogMessage(cds) msg;
 783   stringStream info_stream;
 784 
 785   info_stream.print_cr("Detailed metadata info (rw includes md and mc):");
 786   info_stream.print_cr("%s", hdr);
 787   info_stream.print_cr("%s", sep);
 788   for (int type = 0; type < int(_number_of_types); type ++) {
 789     const char *name = type_name((Type)type);
 790     int ro_count = _counts[RO][type];
 791     int ro_bytes = _bytes [RO][type];
 792     int rw_count = _counts[RW][type];
 793     int rw_bytes = _bytes [RW][type];
 794     int count = ro_count + rw_count;
 795     int bytes = ro_bytes + rw_bytes;
 796 
 797     double ro_perc = 100.0 * double(ro_bytes) / double(ro_all);
 798     double rw_perc = 100.0 * double(rw_bytes) / double(rw_all);
 799     double perc    = 100.0 * double(bytes)    / double(ro_all + rw_all);
 800 
 801     info_stream.print_cr(fmt_stats, name,
 802                          ro_count, ro_bytes, ro_perc,
 803                          rw_count, rw_bytes, rw_perc,
 804                          count, bytes, perc);
 805 
 806     all_ro_count += ro_count;
 807     all_ro_bytes += ro_bytes;
 808     all_rw_count += rw_count;
 809     all_rw_bytes += rw_bytes;
 810   }
 811 
 812   int all_count = all_ro_count + all_rw_count;
 813   int all_bytes = all_ro_bytes + all_rw_bytes;
 814 
 815   double all_ro_perc = 100.0 * double(all_ro_bytes) / double(ro_all);
 816   double all_rw_perc = 100.0 * double(all_rw_bytes) / double(rw_all);
 817   double all_perc    = 100.0 * double(all_bytes)    / double(ro_all + rw_all);
 818 
 819   info_stream.print_cr("%s", sep);
 820   info_stream.print_cr(fmt_stats, "Total",
 821                        all_ro_count, all_ro_bytes, all_ro_perc,
 822                        all_rw_count, all_rw_bytes, all_rw_perc,
 823                        all_count, all_bytes, all_perc);
 824 
 825 //assert(all_ro_bytes == ro_all, "everything should have been counted");
 826   assert(all_rw_bytes == rw_all, "everything should have been counted");
 827 
 828   msg.info("%s", info_stream.as_string());
 829 #undef fmt_stats
 830 }
 831 
 832 // Populate the shared space.
 833 
 834 class VM_PopulateDumpSharedSpace: public VM_Operation {
 835 private:
 836   GrowableArray<MemRegion> *_string_regions;
 837 
 838   void dump_string_and_symbols();
 839   char* dump_read_only_tables();
 840 public:
 841 
 842   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
 843   void doit();   // outline because gdb sucks
 844   static void write_region(FileMapInfo* mapinfo, int region, DumpRegion* space, bool read_only,  bool allow_exec);
 845 }; // class VM_PopulateDumpSharedSpace
 846 
 847 class SortedSymbolClosure: public SymbolClosure {
 848   GrowableArray<Symbol*> _symbols;
 849   virtual void do_symbol(Symbol** sym) {
 850     assert((*sym)->is_permanent(), "archived symbols must be permanent");
 851     _symbols.append(*sym);
 852   }
 853   static int compare_symbols_by_address(Symbol** a, Symbol** b) {
 854     if (a[0] < b[0]) {
 855       return -1;
 856     } else if (a[0] == b[0]) {
 857       return 0;
 858     } else {
 859       return 1;
 860     }
 861   }
 862 
 863 public:
 864   SortedSymbolClosure() {
 865     SymbolTable::symbols_do(this);
 866     _symbols.sort(compare_symbols_by_address);
 867   }
 868   GrowableArray<Symbol*>* get_sorted_symbols() {
 869     return &_symbols;
 870   }
 871 };
 872 
 873 // ArchiveCompactor --
 874 //
 875 // This class is the central piece of shared archive compaction -- all metaspace data are
 876 // initially allocated outside of the shared regions. ArchiveCompactor copies the
 877 // metaspace data into their final location in the shared regions.
 878 
 879 class ArchiveCompactor : AllStatic {
 880   static DumpAllocStats* _alloc_stats;
 881   static SortedSymbolClosure* _ssc;
 882 
 883   static unsigned my_hash(const address& a) {
 884     return primitive_hash<address>(a);
 885   }
 886   static bool my_equals(const address& a0, const address& a1) {
 887     return primitive_equals<address>(a0, a1);
 888   }
 889   typedef ResourceHashtable<
 890       address, address,
 891       ArchiveCompactor::my_hash,   // solaris compiler doesn't like: primitive_hash<address>
 892       ArchiveCompactor::my_equals, // solaris compiler doesn't like: primitive_equals<address>
 893       16384, ResourceObj::C_HEAP> MyTable;
 894   static MyTable* _new_loc_table;
 895 
 896 public:
 897   static void initialize() {
 898     _alloc_stats = new(ResourceObj::C_HEAP, mtInternal)DumpAllocStats;
 899     _new_loc_table = new(ResourceObj::C_HEAP, mtInternal)MyTable;
 900   }
 901   static DumpAllocStats* alloc_stats() {
 902     return _alloc_stats;
 903   }
 904 
 905   static void allocate(MetaspaceClosure::Ref* ref, bool read_only) {
 906     address obj = ref->obj();
 907     int bytes = ref->size() * BytesPerWord;
 908     char* p;
 909     size_t alignment = BytesPerWord;    
 910     if (read_only) {
 911       p = _ro_region.allocate(bytes, alignment);
 912     } else {
 913       p = _rw_region.allocate(bytes, alignment);
 914     }
 915     memcpy(p, obj, bytes);
 916     bool isnew = _new_loc_table->put(obj, (address)p);
 917     assert(isnew, "must be");
 918     log_trace(cds)("Copy: " PTR_FORMAT " ==> " PTR_FORMAT " %d", p2i(obj), p2i(p), bytes);
 919 
 920     _alloc_stats->record(ref->msotype(), bytes, read_only);
 921     if (ref->msotype() == MetaspaceObj::SymbolType) {
 922       uintx delta = MetaspaceShared::object_delta(p);
 923       if (delta > MAX_SHARED_DELTA) {
 924         // This is just a sanity check and should not appear in any real world usage. This
 925         // happens only if you allocate more than 2GB of Symbols and would require
 926         // millions of shared classes.
 927         vm_exit_during_initialization("Too many Symbols in the CDS archive",
 928                                       "Please reduce the number of shared classes.");
 929       }
 930     }
 931   }
 932 
 933   static address get_new_loc(MetaspaceClosure::Ref* ref) {
 934     address* pp = _new_loc_table->get(ref->obj());
 935     assert(pp != NULL, "must be");
 936     return *pp;
 937   }
 938 
 939 private:
 940   // Makes a shallow copy of visited MetaspaceObj's
 941   class ShallowCopier: public UniqueMetaspaceClosure {
 942     bool _read_only;
 943   public:
 944     ShallowCopier(bool read_only) : _read_only(read_only) {}
 945 
 946     virtual void do_unique_ref(Ref* ref, bool read_only) {
 947       if (read_only == _read_only) {
 948         allocate(ref, read_only);
 949       }
 950     }
 951   };
 952 
 953   // Relocate embedded pointers within a MetaspaceObj's shallow copy
 954   class ShallowCopyEmbeddedRefRelocator: public UniqueMetaspaceClosure {
 955   public:
 956     virtual void do_unique_ref(Ref* ref, bool read_only) {
 957       address new_loc = get_new_loc(ref);
 958       RefRelocator refer;
 959       ref->metaspace_pointers_do_at(&refer, new_loc);
 960     }
 961   };
 962 
 963   // Relocate a reference to point to its shallow copy
 964   class RefRelocator: public MetaspaceClosure {
 965   public:
 966     virtual bool do_ref(Ref* ref, bool read_only) {
 967       if (ref->not_null()) {
 968         ref->update(get_new_loc(ref));
 969       }
 970       return false; // Do not recurse.
 971     }
 972   };
 973 
 974 #ifdef ASSERT
 975   class IsRefInArchiveChecker: public MetaspaceClosure {
 976   public:
 977     virtual bool do_ref(Ref* ref, bool read_only) {
 978       if (ref->not_null()) {
 979         char* obj = (char*)ref->obj();
 980         assert(_ro_region.contains(obj) || _rw_region.contains(obj),
 981                "must be relocated to point to CDS archive");
 982       }
 983       return false; // Do not recurse.
 984     }
 985   };
 986 #endif
 987 
 988 public:
 989   static void copy_and_compact() {
 990     // We should no longer allocate anything from the metaspace, so that
 991     // we can have a stable set of MetaspaceObjs to work with.
 992     Metaspace::freeze();
 993 
 994     ResourceMark rm;
 995     SortedSymbolClosure the_ssc; // StackObj
 996     _ssc = &the_ssc;
 997 
 998     tty->print_cr("Scanning all metaspace objects ... ");
 999     {
1000       // allocate and shallow-copy RW objects, immediately following the MC region
1001       tty->print_cr("Allocating RW objects ... ");
1002       _mc_region.pack(&_rw_region);
1003 
1004       ResourceMark rm;
1005       ShallowCopier rw_copier(false);
1006       iterate_roots(&rw_copier);
1007     }
1008     {
1009       // allocate and shallow-copy of RO object, immediately following the RW region
1010       tty->print_cr("Allocating RO objects ... ");
1011       _rw_region.pack(&_ro_region);
1012 
1013       ResourceMark rm;
1014       ShallowCopier ro_copier(true);
1015       iterate_roots(&ro_copier);
1016     }
1017     {
1018       tty->print_cr("Relocating embedded pointers ... ");
1019       ResourceMark rm;
1020       ShallowCopyEmbeddedRefRelocator emb_reloc;
1021       iterate_roots(&emb_reloc);
1022     }
1023     {
1024       tty->print_cr("Relocating external roots ... ");
1025       ResourceMark rm;
1026       RefRelocator ext_reloc;
1027       iterate_roots(&ext_reloc);
1028     }
1029 
1030 #ifdef ASSERT
1031     {
1032       tty->print_cr("Verifying external roots ... ");
1033       ResourceMark rm;
1034       IsRefInArchiveChecker checker;
1035       iterate_roots(&checker);
1036     }
1037 #endif
1038 
1039 
1040     // cleanup
1041     _ssc = NULL;
1042   }
1043 
1044   // We must relocate the System::_well_known_klasses only after we have copied the
1045   // strings in during dump_string_and_symbols(): during the copy, we operate on old
1046   // String objects which assert that their klass is the old
1047   // SystemDictionary::String_klass().
1048   static void relocate_well_known_klasses() {
1049     {
1050       tty->print_cr("Relocating _well_known_klasses[] ... ");
1051       ResourceMark rm;
1052       RefRelocator ext_reloc;
1053       SystemDictionary::well_known_klasses_do(&ext_reloc);
1054     }
1055     // NOTE: after this point, we shouldn't have any globals that can reach the old
1056     // objects.
1057 
1058     // We cannot use any of the objects in the heap anymore (except for the objects
1059     // in the CDS shared string regions) because their headers no longer point to
1060     // valid Klasses.
1061   }
1062 
1063   static void iterate_roots(MetaspaceClosure* it) {
1064     GrowableArray<Symbol*>* symbols = _ssc->get_sorted_symbols();
1065     for (int i=0; i<symbols->length(); i++) {
1066       it->push(symbols->adr_at(i));
1067     }
1068     if (_global_klass_objects != NULL) {
1069       // Need to fix up the pointers
1070       for (int i = 0; i < _global_klass_objects->length(); i++) {
1071         // NOTE -- this requires that the vtable is NOT yet patched, or else we are hosed.
1072         it->push(_global_klass_objects->adr_at(i));
1073       }
1074     }
1075     FileMapInfo::metaspace_pointers_do(it);
1076     SystemDictionary::classes_do(it);
1077     Universe::metaspace_pointers_do(it);
1078     SymbolTable::metaspace_pointers_do(it);
1079     vmSymbols::metaspace_pointers_do(it);
1080   }
1081 
1082   static Klass* get_relocated_klass(Klass* orig_klass) {
1083     address* pp = _new_loc_table->get((address)orig_klass);
1084     assert(pp != NULL, "must be");
1085     Klass* klass = (Klass*)(*pp);
1086     assert(klass->is_klass(), "must be");
1087     return klass;
1088   }
1089 };
1090 
1091 DumpAllocStats* ArchiveCompactor::_alloc_stats;
1092 SortedSymbolClosure* ArchiveCompactor::_ssc;
1093 ArchiveCompactor::MyTable* ArchiveCompactor::_new_loc_table;
1094 
1095 void VM_PopulateDumpSharedSpace::write_region(FileMapInfo* mapinfo, int region_idx,
1096                                               DumpRegion* dump_region, bool read_only,  bool allow_exec) {
1097   mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);
1098 }
1099 
1100 void VM_PopulateDumpSharedSpace::dump_string_and_symbols() {
1101   tty->print_cr("Dumping string and symbol tables ...");
1102 
1103   NOT_PRODUCT(SymbolTable::verify());
1104   NOT_PRODUCT(StringTable::verify());
1105   SymbolTable::write_to_archive();
1106 
1107   // The string space has maximum two regions. See FileMapInfo::write_string_regions() for details.
1108   _string_regions = new GrowableArray<MemRegion>(2);
1109   size_t shared_string_bytes = 0;
1110   StringTable::write_to_archive(_string_regions, &shared_string_bytes);
1111   char* st_base = _string_regions->is_empty() ? NULL : (char*)_string_regions->first().start();
1112   char* st_top = st_base + shared_string_bytes;
1113   _st_region.init(st_base, st_top, st_top);
1114   _st_region.pack();
1115 }
1116 
1117 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
1118   // Reorder the system dictionary. Moving the symbols affects
1119   // how the hash table indices are calculated.
1120   SystemDictionary::reorder_dictionary_for_sharing();
1121   NOT_PRODUCT(SystemDictionary::verify();)
1122 
1123   size_t buckets_bytes = SystemDictionary::count_bytes_for_buckets();
1124   char* buckets_top = _ro_region.allocate(buckets_bytes, sizeof(intptr_t));
1125   SystemDictionary::copy_buckets(buckets_top, _ro_region.top());
1126 
1127   size_t table_bytes = SystemDictionary::count_bytes_for_table();
1128   char* table_top = _ro_region.allocate(table_bytes, sizeof(intptr_t));
1129   SystemDictionary::copy_table(table_top, _ro_region.top());
1130 
1131   // Write the other data to the output array.
1132   WriteClosure wc(&_ro_region);
1133   MetaspaceShared::serialize(&wc);
1134 
1135   return buckets_top;
1136 }
1137 
1138 void VM_PopulateDumpSharedSpace::doit() {
1139   Thread* THREAD = VMThread::vm_thread();
1140 
1141   NOT_PRODUCT(SystemDictionary::verify();)
1142   // The following guarantee is meant to ensure that no loader constraints
1143   // exist yet, since the constraints table is not shared.  This becomes
1144   // more important now that we don't re-initialize vtables/itables for
1145   // shared classes at runtime, where constraints were previously created.
1146   guarantee(SystemDictionary::constraints()->number_of_entries() == 0,
1147             "loader constraints are not saved");
1148   guarantee(SystemDictionary::placeholders()->number_of_entries() == 0,
1149           "placeholders are not saved");
1150   // Revisit and implement this if we prelink method handle call sites:
1151   guarantee(SystemDictionary::invoke_method_table() == NULL ||
1152             SystemDictionary::invoke_method_table()->number_of_entries() == 0,
1153             "invoke method table is not saved");
1154 
1155   // At this point, many classes have been loaded.
1156   // Gather systemDictionary classes in a global array and do everything to
1157   // that so we don't have to walk the SystemDictionary again.
1158   _global_klass_objects = new GrowableArray<Klass*>(1000);
1159   CollectClassesClosure collect_classes;
1160   ClassLoaderDataGraph::loaded_classes_do(&collect_classes);
1161 
1162   tty->print_cr("Number of classes %d", _global_klass_objects->length());
1163   {
1164     int num_type_array = 0, num_obj_array = 0, num_inst = 0;
1165     for (int i = 0; i < _global_klass_objects->length(); i++) {
1166       Klass* k = _global_klass_objects->at(i);
1167       if (k->is_instance_klass()) {
1168         num_inst ++;
1169       } else if (k->is_objArray_klass()) {
1170         num_obj_array ++;
1171       } else {
1172         assert(k->is_typeArray_klass(), "sanity");
1173         num_type_array ++;
1174       }
1175     }
1176     tty->print_cr("    instance classes   = %5d", num_inst);
1177     tty->print_cr("    obj array classes  = %5d", num_obj_array);
1178     tty->print_cr("    type array classes = %5d", num_type_array);
1179   }
1180 
1181 
1182   // Ensure the ConstMethods won't be modified at run-time
1183   tty->print("Updating ConstMethods ... ");
1184   rewrite_nofast_bytecodes_and_calculate_fingerprints();
1185   tty->print_cr("done. ");
1186 
1187   // Remove all references outside the metadata
1188   tty->print("Removing unshareable information ... ");
1189   remove_unshareable_in_classes();
1190   tty->print_cr("done. ");
1191 
1192   ArchiveCompactor::initialize();
1193   ArchiveCompactor::copy_and_compact();
1194 
1195   dump_string_and_symbols();
1196   ArchiveCompactor::relocate_well_known_klasses();
1197 
1198   char* read_only_tables_start = dump_read_only_tables();
1199   _ro_region.pack(&_md_region);
1200 
1201   char* vtbl_list = _md_region.top();
1202   MetaspaceShared::allocate_cpp_vtable_clones();
1203   _md_region.pack(&_od_region);
1204 
1205   // Relocate the archived class file data into the od region
1206   relocate_cached_class_file();
1207   _od_region.pack();
1208 
1209   // The 5 core spaces are allocated consecutively mc->rw->ro->md->od, so there total size
1210   // is just the spaces between the two ends.
1211   size_t core_spaces_size = _od_region.end() - _mc_region.base();
1212   assert(core_spaces_size == (size_t)align_size_up(core_spaces_size, Metaspace::reserve_alignment()),
1213          "should already be aligned");
1214 
1215   // Print statistics of all the regions
1216   const size_t total_reserved = _ro_region.reserved() + _rw_region.reserved() +
1217                                 _mc_region.reserved() + _md_region.reserved() +
1218                                 _st_region.reserved() + _od_region.reserved();
1219   const size_t total_bytes = _ro_region.used() + _rw_region.used() +
1220                              _mc_region.used() + _md_region.used() +
1221                              _st_region.used() + _od_region.used();
1222   const double total_u_perc = total_bytes / double(total_reserved) * 100.0;
1223 
1224   _mc_region.print(total_reserved);
1225   _rw_region.print(total_reserved);
1226   _ro_region.print(total_reserved);
1227   _md_region.print(total_reserved);
1228   _st_region.print(total_reserved);
1229   _od_region.print(total_reserved);
1230 
1231   tty->print_cr("total   : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]",
1232                  total_bytes, total_reserved, total_u_perc);
1233 
1234   // During patching, some virtual methods may be called, so at this point
1235   // the vtables must contain valid methods (as filled in by CppVtableCloner::allocate).
1236   MetaspaceShared::patch_cpp_vtable_pointers();
1237 
1238   // The vtable clones contain addresses of the current process.
1239   // We don't want to write these addresses into the archive.
1240   MetaspaceShared::zero_cpp_vtable_clones_for_writing();
1241 
1242   // Create and write the archive file that maps the shared spaces.
1243 
1244   FileMapInfo* mapinfo = new FileMapInfo();
1245   mapinfo->populate_header(os::vm_allocation_granularity());
1246   mapinfo->set_read_only_tables_start(read_only_tables_start);
1247   mapinfo->set_misc_data_patching_start(vtbl_list);
1248   mapinfo->set_cds_i2i_entry_code_buffers(MetaspaceShared::cds_i2i_entry_code_buffers());
1249   mapinfo->set_cds_i2i_entry_code_buffers_size(MetaspaceShared::cds_i2i_entry_code_buffers_size());
1250   mapinfo->set_core_spaces_size(core_spaces_size);
1251 
1252   for (int pass=1; pass<=2; pass++) {
1253     if (pass == 1) {
1254       // The first pass doesn't actually write the data to disk. All it
1255       // does is to update the fields in the mapinfo->_header.
1256     } else {
1257       // After the first pass, the contents of mapinfo->_header are finalized,
1258       // so we can compute the header's CRC, and write the contents of the header
1259       // and the regions into disk.
1260       mapinfo->open_for_write();
1261       mapinfo->set_header_crc(mapinfo->compute_header_crc());
1262     }
1263     mapinfo->write_header();
1264 
1265     // NOTE: md contains the trampoline code for method entries, which are patched at run time,
1266     // so it needs to be read/write.
1267     write_region(mapinfo, MetaspaceShared::mc, &_mc_region, /*read_only=*/false,/*allow_exec=*/true);
1268     write_region(mapinfo, MetaspaceShared::rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);
1269     write_region(mapinfo, MetaspaceShared::ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);
1270     write_region(mapinfo, MetaspaceShared::md, &_md_region, /*read_only=*/false,/*allow_exec=*/false);
1271     write_region(mapinfo, MetaspaceShared::od, &_od_region, /*read_only=*/true, /*allow_exec=*/false);
1272     mapinfo->write_string_regions(_string_regions);
1273   }
1274 
1275   mapinfo->close();
1276 
1277   // Restore the vtable in case we invoke any virtual methods.
1278   MetaspaceShared::clone_cpp_vtables((intptr_t*)vtbl_list);
1279 
1280   if (log_is_enabled(Info, cds)) {
1281     ArchiveCompactor::alloc_stats()->print_stats(int(_ro_region.used()), int(_rw_region.used()),
1282                                                  int(_mc_region.used()), int(_md_region.used()));
1283   }
1284 }
1285 
1286 // Update a Java object to point its Klass* to the new location after
1287 // shared archive has been compacted.
1288 void MetaspaceShared::relocate_klass_ptr(oop o) {
1289   assert(DumpSharedSpaces, "sanity");
1290   Klass* k = ArchiveCompactor::get_relocated_klass(o->klass());
1291   o->set_klass(k);
1292 }
1293 
1294 class LinkSharedClassesClosure : public KlassClosure {
1295   Thread* THREAD;
1296   bool    _made_progress;
1297  public:
1298   LinkSharedClassesClosure(Thread* thread) : THREAD(thread), _made_progress(false) {}
1299 
1300   void reset()               { _made_progress = false; }
1301   bool made_progress() const { return _made_progress; }
1302 
1303   void do_klass(Klass* k) {
1304     if (k->is_instance_klass()) {
1305       InstanceKlass* ik = InstanceKlass::cast(k);
1306       // Link the class to cause the bytecodes to be rewritten and the
1307       // cpcache to be created. Class verification is done according
1308       // to -Xverify setting.
1309       _made_progress |= MetaspaceShared::try_link_class(ik, THREAD);
1310       guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1311     }
1312   }
1313 };
1314 
1315 class CheckSharedClassesClosure : public KlassClosure {
1316   bool    _made_progress;
1317  public:
1318   CheckSharedClassesClosure() : _made_progress(false) {}
1319 
1320   void reset()               { _made_progress = false; }
1321   bool made_progress() const { return _made_progress; }
1322   void do_klass(Klass* k) {
1323     if (k->is_instance_klass() && InstanceKlass::cast(k)->check_sharing_error_state()) {
1324       _made_progress = true;
1325     }
1326   }
1327 };
1328 
1329 void MetaspaceShared::check_shared_class_loader_type(Klass* k) {
1330   if (k->is_instance_klass()) {
1331     InstanceKlass* ik = InstanceKlass::cast(k);
1332     u2 loader_type = ik->loader_type();
1333     ResourceMark rm;
1334     guarantee(loader_type != 0,
1335               "Class loader type is not set for this class %s", ik->name()->as_C_string());
1336   }
1337 }
1338 
1339 void MetaspaceShared::link_and_cleanup_shared_classes(TRAPS) {
1340   // We need to iterate because verification may cause additional classes
1341   // to be loaded.
1342   LinkSharedClassesClosure link_closure(THREAD);
1343   do {
1344     link_closure.reset();
1345     ClassLoaderDataGraph::loaded_classes_do(&link_closure);
1346     guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1347   } while (link_closure.made_progress());
1348 
1349   if (_has_error_classes) {
1350     // Mark all classes whose super class or interfaces failed verification.
1351     CheckSharedClassesClosure check_closure;
1352     do {
1353       // Not completely sure if we need to do this iteratively. Anyway,
1354       // we should come here only if there are unverifiable classes, which
1355       // shouldn't happen in normal cases. So better safe than sorry.
1356       check_closure.reset();
1357       ClassLoaderDataGraph::loaded_classes_do(&check_closure);
1358     } while (check_closure.made_progress());
1359 
1360     if (IgnoreUnverifiableClassesDuringDump) {
1361       // This is useful when running JCK or SQE tests. You should not
1362       // enable this when running real apps.
1363       SystemDictionary::remove_classes_in_error_state();
1364     } else {
1365       tty->print_cr("Please remove the unverifiable classes from your class list and try again");
1366       exit(1);
1367     }
1368   }
1369 
1370   // Copy the verification constraints from C_HEAP-alloced GrowableArrays to RO-alloced
1371   // Arrays
1372   SystemDictionaryShared::finalize_verification_constraints();
1373 }
1374 
1375 void MetaspaceShared::prepare_for_dumping() {
1376   Arguments::check_unsupported_dumping_properties();
1377   ClassLoader::initialize_shared_path();
1378   FileMapInfo::allocate_classpath_entry_table();
1379 }
1380 
1381 // Preload classes from a list, populate the shared spaces and dump to a
1382 // file.
1383 void MetaspaceShared::preload_and_dump(TRAPS) {
1384   { TraceTime timer("Dump Shared Spaces", TRACETIME_LOG(Info, startuptime));
1385     ResourceMark rm;
1386     char class_list_path_str[JVM_MAXPATHLEN];
1387     // Preload classes to be shared.
1388     // Should use some os:: method rather than fopen() here. aB.
1389     const char* class_list_path;
1390     if (SharedClassListFile == NULL) {
1391       // Construct the path to the class list (in jre/lib)
1392       // Walk up two directories from the location of the VM and
1393       // optionally tack on "lib" (depending on platform)
1394       os::jvm_path(class_list_path_str, sizeof(class_list_path_str));
1395       for (int i = 0; i < 3; i++) {
1396         char *end = strrchr(class_list_path_str, *os::file_separator());
1397         if (end != NULL) *end = '\0';
1398       }
1399       int class_list_path_len = (int)strlen(class_list_path_str);
1400       if (class_list_path_len >= 3) {
1401         if (strcmp(class_list_path_str + class_list_path_len - 3, "lib") != 0) {
1402           if (class_list_path_len < JVM_MAXPATHLEN - 4) {
1403             jio_snprintf(class_list_path_str + class_list_path_len,
1404                          sizeof(class_list_path_str) - class_list_path_len,
1405                          "%slib", os::file_separator());
1406             class_list_path_len += 4;
1407           }
1408         }
1409       }
1410       if (class_list_path_len < JVM_MAXPATHLEN - 10) {
1411         jio_snprintf(class_list_path_str + class_list_path_len,
1412                      sizeof(class_list_path_str) - class_list_path_len,
1413                      "%sclasslist", os::file_separator());
1414       }
1415       class_list_path = class_list_path_str;
1416     } else {
1417       class_list_path = SharedClassListFile;
1418     }
1419 
1420     tty->print_cr("Loading classes to share ...");
1421     _has_error_classes = false;
1422     int class_count = preload_classes(class_list_path, THREAD);
1423     if (ExtraSharedClassListFile) {
1424       class_count += preload_classes(ExtraSharedClassListFile, THREAD);
1425     }
1426     tty->print_cr("Loading classes to share: done.");
1427 
1428     log_info(cds)("Shared spaces: preloaded %d classes", class_count);
1429 
1430     // Rewrite and link classes
1431     tty->print_cr("Rewriting and linking classes ...");
1432 
1433     // Link any classes which got missed. This would happen if we have loaded classes that
1434     // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
1435     // fails verification, all other interfaces that were not specified in the classlist but
1436     // are implemented by K are not verified.
1437     link_and_cleanup_shared_classes(CATCH);
1438     tty->print_cr("Rewriting and linking classes: done");
1439 
1440     VM_PopulateDumpSharedSpace op;
1441     VMThread::execute(&op);
1442   }
1443 
1444   if (PrintSystemDictionaryAtExit) {
1445     SystemDictionary::print();
1446   }
1447 
1448   // Since various initialization steps have been undone by this process,
1449   // it is not reasonable to continue running a java process.
1450   exit(0);
1451 }
1452 
1453 
1454 int MetaspaceShared::preload_classes(const char* class_list_path, TRAPS) {
1455   ClassListParser parser(class_list_path);
1456   int class_count = 0;
1457 
1458     while (parser.parse_one_line()) {
1459       Klass* klass = ClassLoaderExt::load_one_class(&parser, THREAD);
1460 
1461       CLEAR_PENDING_EXCEPTION;
1462       if (klass != NULL) {
1463         if (log_is_enabled(Trace, cds)) {
1464           ResourceMark rm;
1465           log_trace(cds)("Shared spaces preloaded: %s", klass->external_name());
1466         }
1467 
1468         InstanceKlass* ik = InstanceKlass::cast(klass);
1469 
1470         // Link the class to cause the bytecodes to be rewritten and the
1471         // cpcache to be created. The linking is done as soon as classes
1472         // are loaded in order that the related data structures (klass and
1473         // cpCache) are located together.
1474         try_link_class(ik, THREAD);
1475         guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1476 
1477         class_count++;
1478       }
1479     }
1480 
1481   return class_count;
1482 }
1483 
1484 // Returns true if the class's status has changed
1485 bool MetaspaceShared::try_link_class(InstanceKlass* ik, TRAPS) {
1486   assert(DumpSharedSpaces, "should only be called during dumping");
1487   if (ik->init_state() < InstanceKlass::linked) {
1488     bool saved = BytecodeVerificationLocal;
1489     if (!(ik->is_shared_boot_class())) {
1490       // The verification decision is based on BytecodeVerificationRemote
1491       // for non-system classes. Since we are using the NULL classloader
1492       // to load non-system classes during dumping, we need to temporarily
1493       // change BytecodeVerificationLocal to be the same as
1494       // BytecodeVerificationRemote. Note this can cause the parent system
1495       // classes also being verified. The extra overhead is acceptable during
1496       // dumping.
1497       BytecodeVerificationLocal = BytecodeVerificationRemote;
1498     }
1499     ik->link_class(THREAD);
1500     if (HAS_PENDING_EXCEPTION) {
1501       ResourceMark rm;
1502       tty->print_cr("Preload Warning: Verification failed for %s",
1503                     ik->external_name());
1504       CLEAR_PENDING_EXCEPTION;
1505       ik->set_in_error_state();
1506       _has_error_classes = true;
1507     }
1508     BytecodeVerificationLocal = saved;
1509     return true;
1510   } else {
1511     return false;
1512   }
1513 }
1514 
1515 // Closure for serializing initialization data in from a data area
1516 // (ptr_array) read from the shared file.
1517 
1518 class ReadClosure : public SerializeClosure {
1519 private:
1520   intptr_t** _ptr_array;
1521 
1522   inline intptr_t nextPtr() {
1523     return *(*_ptr_array)++;
1524   }
1525 
1526 public:
1527   ReadClosure(intptr_t** ptr_array) { _ptr_array = ptr_array; }
1528 
1529   void do_ptr(void** p) {
1530     assert(*p == NULL, "initializing previous initialized pointer.");
1531     intptr_t obj = nextPtr();
1532     assert((intptr_t)obj >= 0 || (intptr_t)obj < -100,
1533            "hit tag while initializing ptrs.");
1534     *p = (void*)obj;
1535   }
1536 
1537   void do_u4(u4* p) {
1538     intptr_t obj = nextPtr();
1539     *p = (u4)(uintx(obj));
1540   }
1541 
1542   void do_tag(int tag) {
1543     int old_tag;
1544     old_tag = (int)(intptr_t)nextPtr();
1545     // do_int(&old_tag);
1546     assert(tag == old_tag, "old tag doesn't match");
1547     FileMapInfo::assert_mark(tag == old_tag);
1548   }
1549 
1550   void do_region(u_char* start, size_t size) {
1551     assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
1552     assert(size % sizeof(intptr_t) == 0, "bad size");
1553     do_tag((int)size);
1554     while (size > 0) {
1555       *(intptr_t*)start = nextPtr();
1556       start += sizeof(intptr_t);
1557       size -= sizeof(intptr_t);
1558     }
1559   }
1560 
1561   bool reading() const { return true; }
1562 };
1563 
1564 // Return true if given address is in the mapped shared space.
1565 bool MetaspaceShared::is_in_shared_space(const void* p) {
1566   return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_space(p);
1567 }
1568 
1569 // Return true if given address is in the misc data region
1570 bool MetaspaceShared::is_in_shared_region(const void* p, int idx) {
1571   return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx);
1572 }
1573 
1574 bool MetaspaceShared::is_in_trampoline_frame(address addr) {
1575   if (UseSharedSpaces && is_in_shared_region(addr, MetaspaceShared::mc)) {
1576     return true;
1577   }
1578   return false;
1579 }
1580 
1581 void MetaspaceShared::print_shared_spaces() {
1582   if (UseSharedSpaces) {
1583     FileMapInfo::current_info()->print_shared_spaces();
1584   }
1585 }
1586 
1587 
1588 // Map shared spaces at requested addresses and return if succeeded.
1589 bool MetaspaceShared::map_shared_spaces(FileMapInfo* mapinfo) {
1590   size_t image_alignment = mapinfo->alignment();
1591 
1592 #ifndef _WINDOWS
1593   // Map in the shared memory and then map the regions on top of it.
1594   // On Windows, don't map the memory here because it will cause the
1595   // mappings of the regions to fail.
1596   ReservedSpace shared_rs = mapinfo->reserve_shared_memory();
1597   if (!shared_rs.is_reserved()) return false;
1598 #endif
1599 
1600   assert(!DumpSharedSpaces, "Should not be called with DumpSharedSpaces");
1601 
1602   char* _ro_base = NULL;
1603   char* _rw_base = NULL;
1604   char* _mc_base = NULL;
1605   char* _md_base = NULL;
1606   char* _od_base = NULL;
1607 
1608   // Map each shared region
1609   if ((_mc_base = mapinfo->map_region(mc)) != NULL &&
1610       mapinfo->verify_region_checksum(mc) &&
1611       (_rw_base = mapinfo->map_region(rw)) != NULL &&
1612       mapinfo->verify_region_checksum(rw) &&
1613       (_ro_base = mapinfo->map_region(ro)) != NULL &&
1614       mapinfo->verify_region_checksum(ro) &&
1615       (_md_base = mapinfo->map_region(md)) != NULL &&
1616       mapinfo->verify_region_checksum(md) &&
1617       (_od_base = mapinfo->map_region(od)) != NULL &&
1618       mapinfo->verify_region_checksum(od) &&
1619       (image_alignment == (size_t)os::vm_allocation_granularity()) &&
1620       mapinfo->validate_classpath_entry_table()) {
1621     // Success (no need to do anything)
1622     return true;
1623   } else {
1624     // If there was a failure in mapping any of the spaces, unmap the ones
1625     // that succeeded
1626     if (_ro_base != NULL) mapinfo->unmap_region(ro);
1627     if (_rw_base != NULL) mapinfo->unmap_region(rw);
1628     if (_mc_base != NULL) mapinfo->unmap_region(mc);
1629     if (_md_base != NULL) mapinfo->unmap_region(md);
1630     if (_od_base != NULL) mapinfo->unmap_region(od);
1631 #ifndef _WINDOWS
1632     // Release the entire mapped region
1633     shared_rs.release();
1634 #endif
1635     // If -Xshare:on is specified, print out the error message and exit VM,
1636     // otherwise, set UseSharedSpaces to false and continue.
1637     if (RequireSharedSpaces || PrintSharedArchiveAndExit) {
1638       vm_exit_during_initialization("Unable to use shared archive.", "Failed map_region for using -Xshare:on.");
1639     } else {
1640       FLAG_SET_DEFAULT(UseSharedSpaces, false);
1641     }
1642     return false;
1643   }
1644 }
1645 
1646 // Read the miscellaneous data from the shared file, and
1647 // serialize it out to its various destinations.
1648 
1649 void MetaspaceShared::initialize_shared_spaces() {
1650   FileMapInfo *mapinfo = FileMapInfo::current_info();
1651   _cds_i2i_entry_code_buffers = mapinfo->cds_i2i_entry_code_buffers();
1652   _cds_i2i_entry_code_buffers_size = mapinfo->cds_i2i_entry_code_buffers_size();
1653   _core_spaces_size = mapinfo->core_spaces_size();
1654   char* buffer = mapinfo->misc_data_patching_start();
1655   clone_cpp_vtables((intptr_t*)buffer);
1656 
1657   // The rest of the data is now stored in the RW region
1658   buffer = mapinfo->read_only_tables_start();
1659   int sharedDictionaryLen = *(intptr_t*)buffer;
1660   buffer += sizeof(intptr_t);
1661   int number_of_entries = *(intptr_t*)buffer;
1662   buffer += sizeof(intptr_t);
1663   SystemDictionary::set_shared_dictionary((HashtableBucket<mtClass>*)buffer,
1664                                           sharedDictionaryLen,
1665                                           number_of_entries);
1666   buffer += sharedDictionaryLen;
1667 
1668   // The following data are the linked list elements
1669   // (HashtableEntry objects) for the shared dictionary table.
1670 
1671   int len = *(intptr_t*)buffer;     // skip over shared dictionary entries
1672   buffer += sizeof(intptr_t);
1673   buffer += len;
1674 
1675   // Verify various attributes of the archive, plus initialize the
1676   // shared string/symbol tables
1677   intptr_t* array = (intptr_t*)buffer;
1678   ReadClosure rc(&array);
1679   serialize(&rc);
1680 
1681   // Initialize the run-time symbol table.
1682   SymbolTable::create_table();
1683 
1684   // Close the mapinfo file
1685   mapinfo->close();
1686 
1687   if (PrintSharedArchiveAndExit) {
1688     if (PrintSharedDictionary) {
1689       tty->print_cr("\nShared classes:\n");
1690       SystemDictionary::print_shared(false);
1691     }
1692     if (_archive_loading_failed) {
1693       tty->print_cr("archive is invalid");
1694       vm_exit(1);
1695     } else {
1696       tty->print_cr("archive is valid");
1697       vm_exit(0);
1698     }
1699   }
1700 }
1701 
1702 void MetaspaceShared::fixup_shared_string_regions() {
1703   FileMapInfo *mapinfo = FileMapInfo::current_info();
1704   mapinfo->fixup_string_regions();
1705 }
1706 
1707 // JVM/TI RedefineClasses() support:
1708 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1709   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1710 
1711   if (UseSharedSpaces) {
1712     // remap the shared readonly space to shared readwrite, private
1713     FileMapInfo* mapinfo = FileMapInfo::current_info();
1714     if (!mapinfo->remap_shared_readonly_as_readwrite()) {
1715       return false;
1716     }
1717     _remapped_readwrite = true;
1718   }
1719   return true;
1720 }
1721 
1722 void MetaspaceShared::report_out_of_space(const char* name, size_t needed_bytes) {
1723   // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space.
1724   // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes
1725   // or so.
1726   _mc_region.print_out_of_space_msg(name, needed_bytes);
1727   _rw_region.print_out_of_space_msg(name, needed_bytes);
1728   _ro_region.print_out_of_space_msg(name, needed_bytes);
1729   _md_region.print_out_of_space_msg(name, needed_bytes);
1730   _st_region.print_out_of_space_msg(name, needed_bytes);
1731   _od_region.print_out_of_space_msg(name, needed_bytes);
1732 
1733   vm_exit_during_initialization(err_msg("Unable to allocate from '%s' region", name),
1734                                 "Please reduce the number of shared classes.");
1735 }