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