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