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