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