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