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