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