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