1 /*
   2  * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "classfile/classLoaderDataGraph.hpp"
  28 #include "classfile/classListParser.hpp"
  29 #include "classfile/classLoaderExt.hpp"
  30 #include "classfile/dictionary.hpp"
  31 #include "classfile/loaderConstraints.hpp"
  32 #include "classfile/javaClasses.inline.hpp"
  33 #include "classfile/placeholders.hpp"
  34 #include "classfile/symbolTable.hpp"
  35 #include "classfile/stringTable.hpp"
  36 #include "classfile/systemDictionary.hpp"
  37 #include "classfile/systemDictionaryShared.hpp"
  38 #include "code/codeCache.hpp"
  39 #include "gc/shared/softRefPolicy.hpp"
  40 #include "interpreter/bytecodeStream.hpp"
  41 #include "interpreter/bytecodes.hpp"
  42 #include "logging/log.hpp"
  43 #include "logging/logMessage.hpp"
  44 #include "memory/archiveUtils.inline.hpp"
  45 #include "memory/dynamicArchive.hpp"
  46 #include "memory/filemap.hpp"
  47 #include "memory/heapShared.inline.hpp"
  48 #include "memory/metaspace.hpp"
  49 #include "memory/metaspaceClosure.hpp"
  50 #include "memory/metaspaceShared.hpp"
  51 #include "memory/resourceArea.hpp"
  52 #include "memory/universe.hpp"
  53 #include "oops/compressedOops.inline.hpp"
  54 #include "oops/instanceClassLoaderKlass.hpp"
  55 #include "oops/instanceMirrorKlass.hpp"
  56 #include "oops/instanceRefKlass.hpp"
  57 #include "oops/methodData.hpp"
  58 #include "oops/objArrayKlass.hpp"
  59 #include "oops/objArrayOop.hpp"
  60 #include "oops/oop.inline.hpp"
  61 #include "oops/typeArrayKlass.hpp"
  62 #include "prims/jvmtiRedefineClasses.hpp"
  63 #include "runtime/handles.inline.hpp"
  64 #include "runtime/os.hpp"
  65 #include "runtime/safepointVerifiers.hpp"
  66 #include "runtime/signature.hpp"
  67 #include "runtime/timerTrace.hpp"
  68 #include "runtime/vmThread.hpp"
  69 #include "runtime/vmOperations.hpp"
  70 #include "utilities/align.hpp"
  71 #include "utilities/bitMap.inline.hpp"
  72 #include "utilities/defaultStream.hpp"
  73 #include "utilities/hashtable.inline.hpp"
  74 #if INCLUDE_G1GC
  75 #include "gc/g1/g1CollectedHeap.hpp"
  76 #endif
  77 
  78 ReservedSpace MetaspaceShared::_shared_rs;
  79 VirtualSpace MetaspaceShared::_shared_vs;
  80 MetaspaceSharedStats MetaspaceShared::_stats;
  81 bool MetaspaceShared::_has_error_classes;
  82 bool MetaspaceShared::_archive_loading_failed = false;
  83 bool MetaspaceShared::_remapped_readwrite = false;
  84 address MetaspaceShared::_i2i_entry_code_buffers = NULL;
  85 size_t MetaspaceShared::_i2i_entry_code_buffers_size = 0;
  86 void* MetaspaceShared::_shared_metaspace_static_top = NULL;
  87 intx MetaspaceShared::_relocation_delta;
  88 
  89 // The CDS archive is divided into the following regions:
  90 //     mc  - misc code (the method entry trampolines, c++ vtables)
  91 //     rw  - read-write metadata
  92 //     ro  - read-only metadata and read-only tables
  93 //
  94 //     ca0 - closed archive heap space #0
  95 //     ca1 - closed archive heap space #1 (may be empty)
  96 //     oa0 - open archive heap space #0
  97 //     oa1 - open archive heap space #1 (may be empty)
  98 //
  99 // The mc, rw, and ro regions are linearly allocated, starting from
 100 // SharedBaseAddress, in the order of mc->rw->ro. The size of these 3 regions
 101 // are page-aligned, and there's no gap between any consecutive regions.
 102 //
 103 // These 3 regions are populated in the following steps:
 104 // [1] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
 105 //     temporarily allocated outside of the shared regions. Only the method entry
 106 //     trampolines are written into the mc region.
 107 // [2] C++ vtables are copied into the mc region.
 108 // [3] ArchiveCompactor copies RW metadata into the rw region.
 109 // [4] ArchiveCompactor copies RO metadata into the ro region.
 110 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
 111 //     are copied into the ro region as read-only tables.
 112 //
 113 // The s0/s1 and oa0/oa1 regions are populated inside HeapShared::archive_java_heap_objects.
 114 // Their layout is independent of the other 4 regions.
 115 
 116 char* DumpRegion::expand_top_to(char* newtop) {
 117   assert(is_allocatable(), "must be initialized and not packed");
 118   assert(newtop >= _top, "must not grow backwards");
 119   if (newtop > _end) {
 120     MetaspaceShared::report_out_of_space(_name, newtop - _top);
 121     ShouldNotReachHere();
 122   }
 123   uintx delta;
 124   if (DynamicDumpSharedSpaces) {
 125     delta = DynamicArchive::object_delta_uintx(newtop);
 126   } else {
 127     delta = MetaspaceShared::object_delta_uintx(newtop);
 128   }
 129   if (delta > MAX_SHARED_DELTA) {
 130     // This is just a sanity check and should not appear in any real world usage. This
 131     // happens only if you allocate more than 2GB of shared objects and would require
 132     // millions of shared classes.
 133     vm_exit_during_initialization("Out of memory in the CDS archive",
 134                                   "Please reduce the number of shared classes.");
 135   }
 136 
 137   MetaspaceShared::commit_shared_space_to(newtop);
 138   _top = newtop;
 139   return _top;
 140 }
 141 
 142 char* DumpRegion::allocate(size_t num_bytes, size_t alignment) {
 143   char* p = (char*)align_up(_top, alignment);
 144   char* newtop = p + align_up(num_bytes, alignment);
 145   expand_top_to(newtop);
 146   memset(p, 0, newtop - p);
 147   return p;
 148 }
 149 
 150 void DumpRegion::append_intptr_t(intptr_t n, bool need_to_mark) {
 151   assert(is_aligned(_top, sizeof(intptr_t)), "bad alignment");
 152   intptr_t *p = (intptr_t*)_top;
 153   char* newtop = _top + sizeof(intptr_t);
 154   expand_top_to(newtop);
 155   *p = n;
 156   if (need_to_mark) {
 157     ArchivePtrMarker::mark_pointer(p);
 158   }
 159 }
 160 
 161 void DumpRegion::print(size_t total_bytes) const {
 162   log_debug(cds)("%-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()),
 164                  p2i(_base + MetaspaceShared::final_delta()));
 165 }
 166 
 167 void DumpRegion::print_out_of_space_msg(const char* failing_region, size_t needed_bytes) {
 168   log_error(cds)("[%-8s] " PTR_FORMAT " - " PTR_FORMAT " capacity =%9d, allocated =%9d",
 169                  _name, p2i(_base), p2i(_top), int(_end - _base), int(_top - _base));
 170   if (strcmp(_name, failing_region) == 0) {
 171     log_error(cds)(" required = %d", int(needed_bytes));
 172   }
 173 }
 174 
 175 void DumpRegion::pack(DumpRegion* next) {
 176   assert(!is_packed(), "sanity");
 177   _end = (char*)align_up(_top, Metaspace::reserve_alignment());
 178   _is_packed = true;
 179   if (next != NULL) {
 180     next->_base = next->_top = this->_end;
 181     next->_end = MetaspaceShared::shared_rs()->end();
 182   }
 183 }
 184 
 185 static DumpRegion _mc_region("mc"), _ro_region("ro"), _rw_region("rw");
 186 static size_t _total_closed_archive_region_size = 0, _total_open_archive_region_size = 0;
 187 
 188 void MetaspaceShared::init_shared_dump_space(DumpRegion* first_space, address first_space_bottom) {
 189   // Start with 0 committed bytes. The memory will be committed as needed by
 190   // MetaspaceShared::commit_shared_space_to().
 191   if (!_shared_vs.initialize(_shared_rs, 0)) {
 192     fatal("Unable to allocate memory for shared space");
 193   }
 194   first_space->init(&_shared_rs, (char*)first_space_bottom);
 195 }
 196 
 197 DumpRegion* MetaspaceShared::misc_code_dump_space() {
 198   return &_mc_region;
 199 }
 200 
 201 DumpRegion* MetaspaceShared::read_write_dump_space() {
 202   return &_rw_region;
 203 }
 204 
 205 DumpRegion* MetaspaceShared::read_only_dump_space() {
 206   return &_ro_region;
 207 }
 208 
 209 void MetaspaceShared::pack_dump_space(DumpRegion* current, DumpRegion* next,
 210                                       ReservedSpace* rs) {
 211   current->pack(next);
 212 }
 213 
 214 char* MetaspaceShared::misc_code_space_alloc(size_t num_bytes) {
 215   return _mc_region.allocate(num_bytes);
 216 }
 217 
 218 char* MetaspaceShared::read_only_space_alloc(size_t num_bytes) {
 219   return _ro_region.allocate(num_bytes);
 220 }
 221 
 222 // When reserving an address range using ReservedSpace, we need an alignment that satisfies both:
 223 // os::vm_allocation_granularity() -- so that we can sub-divide this range into multiple mmap regions,
 224 //                                    while keeping the first range at offset 0 of this range.
 225 // Metaspace::reserve_alignment()  -- so we can pass the region to
 226 //                                    Metaspace::allocate_metaspace_compressed_klass_ptrs.
 227 size_t MetaspaceShared::reserved_space_alignment() {
 228   size_t os_align = os::vm_allocation_granularity();
 229   size_t ms_align = Metaspace::reserve_alignment();
 230   if (os_align >= ms_align) {
 231     assert(os_align % ms_align == 0, "must be a multiple");
 232     return os_align;
 233   } else {
 234     assert(ms_align % os_align == 0, "must be a multiple");
 235     return ms_align;
 236   }
 237 }
 238 
 239 ReservedSpace MetaspaceShared::reserve_shared_space(size_t size, char* requested_address) {
 240   return Metaspace::reserve_space(size, reserved_space_alignment(),
 241                                   requested_address, requested_address != NULL);
 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 = reserved_space_alignment();
 247   char* shared_base = (char*)align_up((char*)SharedBaseAddress, reserve_alignment);
 248 
 249 #ifdef _LP64
 250   // On 64-bit VM, the heap and class space layout will be the same as if
 251   // you're running in -Xshare:on mode:
 252   //
 253   //                              +-- SharedBaseAddress (default = 0x800000000)
 254   //                              v
 255   // +-..---------+---------+ ... +----+----+----+--------------------+
 256   // |    Heap    | Archive |     | MC | RW | RO |    class space     |
 257   // +-..---------+---------+ ... +----+----+----+--------------------+
 258   // |<--   MaxHeapSize  -->|     |<-- UnscaledClassSpaceMax = 4GB -->|
 259   //
 260   const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
 261   const size_t cds_total = align_down(UnscaledClassSpaceMax, reserve_alignment);
 262 #else
 263   // We don't support archives larger than 256MB on 32-bit due to limited virtual address space.
 264   size_t cds_total = align_down(256*M, reserve_alignment);
 265 #endif
 266 
 267   bool use_requested_base = true;
 268   if (ArchiveRelocationMode == 1) {
 269     log_info(cds)("ArchiveRelocationMode == 1: always allocate class space at an alternative address");
 270     use_requested_base = false;
 271   }
 272 
 273   // First try to reserve the space at the specified SharedBaseAddress.
 274   assert(!_shared_rs.is_reserved(), "must be");
 275   if (use_requested_base) {
 276     _shared_rs = reserve_shared_space(cds_total, shared_base);
 277   }
 278   if (_shared_rs.is_reserved()) {
 279     assert(shared_base == 0 || _shared_rs.base() == shared_base, "should match");
 280   } else {
 281     // Get a mmap region anywhere if the SharedBaseAddress fails.
 282     _shared_rs = reserve_shared_space(cds_total);
 283   }
 284   if (!_shared_rs.is_reserved()) {
 285     vm_exit_during_initialization("Unable to reserve memory for shared space",
 286                                   err_msg(SIZE_FORMAT " bytes.", cds_total));
 287   }
 288 
 289 #ifdef _LP64
 290   // During dump time, we allocate 4GB (UnscaledClassSpaceMax) of space and split it up:
 291   // + The upper 1 GB is used as the "temporary compressed class space" -- preload_classes()
 292   //   will store Klasses into this space.
 293   // + The lower 3 GB is used for the archive -- when preload_classes() is done,
 294   //   ArchiveCompactor will copy the class metadata into this space, first the RW parts,
 295   //   then the RO parts.
 296 
 297   size_t max_archive_size = align_down(cds_total * 3 / 4, reserve_alignment);
 298   ReservedSpace tmp_class_space = _shared_rs.last_part(max_archive_size);
 299   CompressedClassSpaceSize = align_down(tmp_class_space.size(), reserve_alignment);
 300   _shared_rs = _shared_rs.first_part(max_archive_size);
 301 
 302   if (UseCompressedClassPointers) {
 303     // Set up compress class pointers.
 304     CompressedKlassPointers::set_base((address)_shared_rs.base());
 305     // Set narrow_klass_shift to be LogKlassAlignmentInBytes. This is consistent
 306     // with AOT.
 307     CompressedKlassPointers::set_shift(LogKlassAlignmentInBytes);
 308     // Set the range of klass addresses to 4GB.
 309     CompressedKlassPointers::set_range(cds_total);
 310     Metaspace::initialize_class_space(tmp_class_space);
 311   }
 312   log_info(cds)("narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
 313                 p2i(CompressedKlassPointers::base()), CompressedKlassPointers::shift());
 314 
 315   log_info(cds)("Allocated temporary class space: " SIZE_FORMAT " bytes at " PTR_FORMAT,
 316                 CompressedClassSpaceSize, p2i(tmp_class_space.base()));
 317 #endif
 318 
 319   init_shared_dump_space(&_mc_region);
 320   SharedBaseAddress = (size_t)_shared_rs.base();
 321   log_info(cds)("Allocated shared space: " SIZE_FORMAT " bytes at " PTR_FORMAT,
 322                 _shared_rs.size(), p2i(_shared_rs.base()));
 323 }
 324 
 325 // Called by universe_post_init()
 326 void MetaspaceShared::post_initialize(TRAPS) {
 327   if (UseSharedSpaces) {
 328     int size = FileMapInfo::get_number_of_shared_paths();
 329     if (size > 0) {
 330       SystemDictionaryShared::allocate_shared_data_arrays(size, THREAD);
 331       if (!DynamicDumpSharedSpaces) {
 332         FileMapInfo* info;
 333         if (FileMapInfo::dynamic_info() == NULL) {
 334           info = FileMapInfo::current_info();
 335         } else {
 336           info = FileMapInfo::dynamic_info();
 337         }
 338         ClassLoaderExt::init_paths_start_index(info->app_class_paths_start_index());
 339         ClassLoaderExt::init_app_module_paths_start_index(info->app_module_paths_start_index());
 340       }
 341     }
 342   }
 343 }
 344 
 345 static GrowableArray<Handle>* _extra_interned_strings = NULL;
 346 
 347 void MetaspaceShared::read_extra_data(const char* filename, TRAPS) {
 348   _extra_interned_strings = new (ResourceObj::C_HEAP, mtInternal)GrowableArray<Handle>(10000, true);
 349 
 350   HashtableTextDump reader(filename);
 351   reader.check_version("VERSION: 1.0");
 352 
 353   while (reader.remain() > 0) {
 354     int utf8_length;
 355     int prefix_type = reader.scan_prefix(&utf8_length);
 356     ResourceMark rm(THREAD);
 357     if (utf8_length == 0x7fffffff) {
 358       // buf_len will overflown 32-bit value.
 359       vm_exit_during_initialization(err_msg("string length too large: %d", utf8_length));
 360     }
 361     int buf_len = utf8_length+1;
 362     char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len);
 363     reader.get_utf8(utf8_buffer, utf8_length);
 364     utf8_buffer[utf8_length] = '\0';
 365 
 366     if (prefix_type == HashtableTextDump::SymbolPrefix) {
 367       SymbolTable::new_permanent_symbol(utf8_buffer);
 368     } else{
 369       assert(prefix_type == HashtableTextDump::StringPrefix, "Sanity");
 370       oop s = StringTable::intern(utf8_buffer, THREAD);
 371 
 372       if (HAS_PENDING_EXCEPTION) {
 373         log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d",
 374                                reader.last_line_no(), utf8_length);
 375         CLEAR_PENDING_EXCEPTION;
 376       } else {
 377 #if INCLUDE_G1GC
 378         if (UseG1GC) {
 379           typeArrayOop body = java_lang_String::value(s);
 380           const HeapRegion* hr = G1CollectedHeap::heap()->heap_region_containing(body);
 381           if (hr->is_humongous()) {
 382             // Don't keep it alive, so it will be GC'ed before we dump the strings, in order
 383             // to maximize free heap space and minimize fragmentation.
 384             log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d",
 385                                 reader.last_line_no(), utf8_length);
 386             continue;
 387           }
 388         }
 389 #endif
 390         // Interned strings are GC'ed if there are no references to it, so let's
 391         // add a reference to keep this string alive.
 392         assert(s != NULL, "must succeed");
 393         Handle h(THREAD, s);
 394         _extra_interned_strings->append(h);
 395       }
 396     }
 397   }
 398 }
 399 
 400 void MetaspaceShared::commit_shared_space_to(char* newtop) {
 401   Arguments::assert_is_dumping_archive();
 402   char* base = _shared_rs.base();
 403   size_t need_committed_size = newtop - base;
 404   size_t has_committed_size = _shared_vs.committed_size();
 405   if (need_committed_size < has_committed_size) {
 406     return;
 407   }
 408 
 409   size_t min_bytes = need_committed_size - has_committed_size;
 410   size_t preferred_bytes = 1 * M;
 411   size_t uncommitted = _shared_vs.reserved_size() - has_committed_size;
 412 
 413   size_t commit =MAX2(min_bytes, preferred_bytes);
 414   commit = MIN2(commit, uncommitted);
 415   assert(commit <= uncommitted, "sanity");
 416 
 417   bool result = _shared_vs.expand_by(commit, false);
 418   ArchivePtrMarker::expand_ptr_end((address*)_shared_vs.high());
 419 
 420   if (!result) {
 421     vm_exit_during_initialization(err_msg("Failed to expand shared space to " SIZE_FORMAT " bytes",
 422                                           need_committed_size));
 423   }
 424 
 425   log_debug(cds)("Expanding shared spaces by " SIZE_FORMAT_W(7) " bytes [total " SIZE_FORMAT_W(9)  " bytes ending at %p]",
 426                  commit, _shared_vs.actual_committed_size(), _shared_vs.high());
 427 }
 428 
 429 void MetaspaceShared::initialize_ptr_marker(CHeapBitMap* ptrmap) {
 430   ArchivePtrMarker::initialize(ptrmap, (address*)_shared_vs.low(), (address*)_shared_vs.high());
 431 }
 432 
 433 // Read/write a data stream for restoring/preserving metadata pointers and
 434 // miscellaneous data from/to the shared archive file.
 435 
 436 void MetaspaceShared::serialize(SerializeClosure* soc) {
 437   int tag = 0;
 438   soc->do_tag(--tag);
 439 
 440   // Verify the sizes of various metadata in the system.
 441   soc->do_tag(sizeof(Method));
 442   soc->do_tag(sizeof(ConstMethod));
 443   soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
 444   soc->do_tag(sizeof(ConstantPool));
 445   soc->do_tag(sizeof(ConstantPoolCache));
 446   soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
 447   soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
 448   soc->do_tag(sizeof(Symbol));
 449 
 450   // Dump/restore miscellaneous metadata.
 451   JavaClasses::serialize_offsets(soc);
 452   Universe::serialize(soc);
 453   soc->do_tag(--tag);
 454 
 455   // Dump/restore references to commonly used names and signatures.
 456   vmSymbols::serialize(soc);
 457   soc->do_tag(--tag);
 458 
 459   // Dump/restore the symbol/string/subgraph_info tables
 460   SymbolTable::serialize_shared_table_header(soc);
 461   StringTable::serialize_shared_table_header(soc);
 462   HeapShared::serialize_subgraph_info_table_header(soc);
 463   SystemDictionaryShared::serialize_dictionary_headers(soc);
 464 
 465   InstanceMirrorKlass::serialize_offsets(soc);
 466 
 467   // Dump/restore well known classes (pointers)
 468   SystemDictionaryShared::serialize_well_known_klasses(soc);
 469   soc->do_tag(--tag);
 470 
 471   serialize_cloned_cpp_vtptrs(soc);
 472   soc->do_tag(--tag);
 473 
 474   soc->do_tag(666);
 475 }
 476 
 477 address MetaspaceShared::i2i_entry_code_buffers(size_t total_size) {
 478   if (DumpSharedSpaces) {
 479     if (_i2i_entry_code_buffers == NULL) {
 480       _i2i_entry_code_buffers = (address)misc_code_space_alloc(total_size);
 481       _i2i_entry_code_buffers_size = total_size;
 482     }
 483   } else if (UseSharedSpaces) {
 484     assert(_i2i_entry_code_buffers != NULL, "must already been initialized");
 485   } else {
 486     return NULL;
 487   }
 488 
 489   assert(_i2i_entry_code_buffers_size == total_size, "must not change");
 490   return _i2i_entry_code_buffers;
 491 }
 492 
 493 uintx MetaspaceShared::object_delta_uintx(void* obj) {
 494   Arguments::assert_is_dumping_archive();
 495   if (DumpSharedSpaces) {
 496     assert(shared_rs()->contains(obj), "must be");
 497   } else {
 498     assert(is_in_shared_metaspace(obj) || DynamicArchive::is_in_target_space(obj), "must be");
 499   }
 500   address base_address = address(SharedBaseAddress);
 501   uintx deltax = address(obj) - base_address;
 502   return deltax;
 503 }
 504 
 505 // Global object for holding classes that have been loaded.  Since this
 506 // is run at a safepoint just before exit, this is the entire set of classes.
 507 static GrowableArray<Klass*>* _global_klass_objects;
 508 
 509 GrowableArray<Klass*>* MetaspaceShared::collected_klasses() {
 510   return _global_klass_objects;
 511 }
 512 
 513 static void collect_array_classes(Klass* k) {
 514   _global_klass_objects->append_if_missing(k);
 515   if (k->is_array_klass()) {
 516     // Add in the array classes too
 517     ArrayKlass* ak = ArrayKlass::cast(k);
 518     Klass* h = ak->higher_dimension();
 519     if (h != NULL) {
 520       h->array_klasses_do(collect_array_classes);
 521     }
 522   }
 523 }
 524 
 525 class CollectClassesClosure : public KlassClosure {
 526   void do_klass(Klass* k) {
 527     if (k->is_instance_klass() &&
 528         SystemDictionaryShared::is_excluded_class(InstanceKlass::cast(k))) {
 529       // Don't add to the _global_klass_objects
 530     } else {
 531       _global_klass_objects->append_if_missing(k);
 532     }
 533     if (k->is_array_klass()) {
 534       // Add in the array classes too
 535       ArrayKlass* ak = ArrayKlass::cast(k);
 536       Klass* h = ak->higher_dimension();
 537       if (h != NULL) {
 538         h->array_klasses_do(collect_array_classes);
 539       }
 540     }
 541   }
 542 };
 543 
 544 static void remove_unshareable_in_classes() {
 545   for (int i = 0; i < _global_klass_objects->length(); i++) {
 546     Klass* k = _global_klass_objects->at(i);
 547     if (!k->is_objArray_klass()) {
 548       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
 549       // on their array classes.
 550       assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be");
 551       k->remove_unshareable_info();
 552     }
 553   }
 554 }
 555 
 556 static void remove_java_mirror_in_classes() {
 557   for (int i = 0; i < _global_klass_objects->length(); i++) {
 558     Klass* k = _global_klass_objects->at(i);
 559     if (!k->is_objArray_klass()) {
 560       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
 561       // on their array classes.
 562       assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be");
 563       k->remove_java_mirror();
 564     }
 565   }
 566 }
 567 
 568 static void clear_basic_type_mirrors() {
 569   assert(!HeapShared::is_heap_object_archiving_allowed(), "Sanity");
 570   Universe::set_int_mirror(NULL);
 571   Universe::set_float_mirror(NULL);
 572   Universe::set_double_mirror(NULL);
 573   Universe::set_byte_mirror(NULL);
 574   Universe::set_bool_mirror(NULL);
 575   Universe::set_char_mirror(NULL);
 576   Universe::set_long_mirror(NULL);
 577   Universe::set_short_mirror(NULL);
 578   Universe::set_void_mirror(NULL);
 579 }
 580 
 581 static void rewrite_nofast_bytecode(const methodHandle& method) {
 582   BytecodeStream bcs(method);
 583   while (!bcs.is_last_bytecode()) {
 584     Bytecodes::Code opcode = bcs.next();
 585     switch (opcode) {
 586     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
 587     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;
 588     case Bytecodes::_aload_0:       *bcs.bcp() = Bytecodes::_nofast_aload_0;       break;
 589     case Bytecodes::_iload: {
 590       if (!bcs.is_wide()) {
 591         *bcs.bcp() = Bytecodes::_nofast_iload;
 592       }
 593       break;
 594     }
 595     default: break;
 596     }
 597   }
 598 }
 599 
 600 // Walk all methods in the class list to ensure that they won't be modified at
 601 // run time. This includes:
 602 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified
 603 //     at run time by RewriteBytecodes/RewriteFrequentPairs
 604 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.
 605 static void rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread) {
 606   for (int i = 0; i < _global_klass_objects->length(); i++) {
 607     Klass* k = _global_klass_objects->at(i);
 608     if (k->is_instance_klass()) {
 609       InstanceKlass* ik = InstanceKlass::cast(k);
 610       MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(thread, ik);
 611     }
 612   }
 613 }
 614 
 615 void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) {
 616   for (int i = 0; i < ik->methods()->length(); i++) {
 617     methodHandle m(thread, ik->methods()->at(i));
 618     rewrite_nofast_bytecode(m);
 619     Fingerprinter fp(m);
 620     // The side effect of this call sets method's fingerprint field.
 621     fp.fingerprint();
 622   }
 623 }
 624 
 625 // Objects of the Metadata types (such as Klass and ConstantPool) have C++ vtables.
 626 // (In GCC this is the field <Type>::_vptr, i.e., first word in the object.)
 627 //
 628 // Addresses of the vtables and the methods may be different across JVM runs,
 629 // if libjvm.so is dynamically loaded at a different base address.
 630 //
 631 // To ensure that the Metadata objects in the CDS archive always have the correct vtable:
 632 //
 633 // + at dump time:  we redirect the _vptr to point to our own vtables inside
 634 //                  the CDS image
 635 // + at run time:   we clone the actual contents of the vtables from libjvm.so
 636 //                  into our own tables.
 637 
 638 // Currently, the archive contain ONLY the following types of objects that have C++ vtables.
 639 #define CPP_VTABLE_PATCH_TYPES_DO(f) \
 640   f(ConstantPool) \
 641   f(InstanceKlass) \
 642   f(InstanceClassLoaderKlass) \
 643   f(InstanceMirrorKlass) \
 644   f(InstanceRefKlass) \
 645   f(Method) \
 646   f(ObjArrayKlass) \
 647   f(TypeArrayKlass)
 648 
 649 class CppVtableInfo {
 650   intptr_t _vtable_size;
 651   intptr_t _cloned_vtable[1];
 652 public:
 653   static int num_slots(int vtable_size) {
 654     return 1 + vtable_size; // Need to add the space occupied by _vtable_size;
 655   }
 656   int vtable_size()           { return int(uintx(_vtable_size)); }
 657   void set_vtable_size(int n) { _vtable_size = intptr_t(n); }
 658   intptr_t* cloned_vtable()   { return &_cloned_vtable[0]; }
 659   void zero()                 { memset(_cloned_vtable, 0, sizeof(intptr_t) * vtable_size()); }
 660   // Returns the address of the next CppVtableInfo that can be placed immediately after this CppVtableInfo
 661   static size_t byte_size(int vtable_size) {
 662     CppVtableInfo i;
 663     return pointer_delta(&i._cloned_vtable[vtable_size], &i, sizeof(u1));
 664   }
 665 };
 666 
 667 template <class T> class CppVtableCloner : public T {
 668   static intptr_t* vtable_of(Metadata& m) {
 669     return *((intptr_t**)&m);
 670   }
 671   static CppVtableInfo* _info;
 672 
 673   static int get_vtable_length(const char* name);
 674 
 675 public:
 676   // Allocate and initialize the C++ vtable, starting from top, but do not go past end.
 677   static intptr_t* allocate(const char* name);
 678 
 679   // Clone the vtable to ...
 680   static intptr_t* clone_vtable(const char* name, CppVtableInfo* info);
 681 
 682   static void zero_vtable_clone() {
 683     assert(DumpSharedSpaces, "dump-time only");
 684     _info->zero();
 685   }
 686 
 687   static bool is_valid_shared_object(const T* obj) {
 688     intptr_t* vptr = *(intptr_t**)obj;
 689     return vptr == _info->cloned_vtable();
 690   }
 691 };
 692 
 693 template <class T> CppVtableInfo* CppVtableCloner<T>::_info = NULL;
 694 
 695 template <class T>
 696 intptr_t* CppVtableCloner<T>::allocate(const char* name) {
 697   assert(is_aligned(_mc_region.top(), sizeof(intptr_t)), "bad alignment");
 698   int n = get_vtable_length(name);
 699   _info = (CppVtableInfo*)_mc_region.allocate(CppVtableInfo::byte_size(n), sizeof(intptr_t));
 700   _info->set_vtable_size(n);
 701 
 702   intptr_t* p = clone_vtable(name, _info);
 703   assert((char*)p == _mc_region.top(), "must be");
 704 
 705   return _info->cloned_vtable();
 706 }
 707 
 708 template <class T>
 709 intptr_t* CppVtableCloner<T>::clone_vtable(const char* name, CppVtableInfo* info) {
 710   if (!DumpSharedSpaces) {
 711     assert(_info == 0, "_info is initialized only at dump time");
 712     _info = info; // Remember it -- it will be used by MetaspaceShared::is_valid_shared_method()
 713   }
 714   T tmp; // Allocate temporary dummy metadata object to get to the original vtable.
 715   int n = info->vtable_size();
 716   intptr_t* srcvtable = vtable_of(tmp);
 717   intptr_t* dstvtable = info->cloned_vtable();
 718 
 719   // We already checked (and, if necessary, adjusted n) when the vtables were allocated, so we are
 720   // safe to do memcpy.
 721   log_debug(cds, vtables)("Copying %3d vtable entries for %s", n, name);
 722   memcpy(dstvtable, srcvtable, sizeof(intptr_t) * n);
 723   return dstvtable + n;
 724 }
 725 
 726 // To determine the size of the vtable for each type, we use the following
 727 // trick by declaring 2 subclasses:
 728 //
 729 //   class CppVtableTesterA: public InstanceKlass {virtual int   last_virtual_method() {return 1;}    };
 730 //   class CppVtableTesterB: public InstanceKlass {virtual void* last_virtual_method() {return NULL}; };
 731 //
 732 // CppVtableTesterA and CppVtableTesterB's vtables have the following properties:
 733 // - Their size (N+1) is exactly one more than the size of InstanceKlass's vtable (N)
 734 // - The first N entries have are exactly the same as in InstanceKlass's vtable.
 735 // - Their last entry is different.
 736 //
 737 // So to determine the value of N, we just walk CppVtableTesterA and CppVtableTesterB's tables
 738 // and find the first entry that's different.
 739 //
 740 // This works on all C++ compilers supported by Oracle, but you may need to tweak it for more
 741 // esoteric compilers.
 742 
 743 template <class T> class CppVtableTesterB: public T {
 744 public:
 745   virtual int last_virtual_method() {return 1;}
 746 };
 747 
 748 template <class T> class CppVtableTesterA : public T {
 749 public:
 750   virtual void* last_virtual_method() {
 751     // Make this different than CppVtableTesterB::last_virtual_method so the C++
 752     // compiler/linker won't alias the two functions.
 753     return NULL;
 754   }
 755 };
 756 
 757 template <class T>
 758 int CppVtableCloner<T>::get_vtable_length(const char* name) {
 759   CppVtableTesterA<T> a;
 760   CppVtableTesterB<T> b;
 761 
 762   intptr_t* avtable = vtable_of(a);
 763   intptr_t* bvtable = vtable_of(b);
 764 
 765   // Start at slot 1, because slot 0 may be RTTI (on Solaris/Sparc)
 766   int vtable_len = 1;
 767   for (; ; vtable_len++) {
 768     if (avtable[vtable_len] != bvtable[vtable_len]) {
 769       break;
 770     }
 771   }
 772   log_debug(cds, vtables)("Found   %3d vtable entries for %s", vtable_len, name);
 773 
 774   return vtable_len;
 775 }
 776 
 777 #define ALLOC_CPP_VTABLE_CLONE(c) \
 778   _cloned_cpp_vtptrs[c##_Kind] = CppVtableCloner<c>::allocate(#c); \
 779   ArchivePtrMarker::mark_pointer(&_cloned_cpp_vtptrs[c##_Kind]);
 780 
 781 #define CLONE_CPP_VTABLE(c) \
 782   p = CppVtableCloner<c>::clone_vtable(#c, (CppVtableInfo*)p);
 783 
 784 #define ZERO_CPP_VTABLE(c) \
 785  CppVtableCloner<c>::zero_vtable_clone();
 786 
 787 //------------------------------ for DynamicDumpSharedSpaces - start
 788 #define DECLARE_CLONED_VTABLE_KIND(c) c ## _Kind,
 789 
 790 enum {
 791   // E.g., ConstantPool_Kind == 0, InstanceKlass == 1, etc.
 792   CPP_VTABLE_PATCH_TYPES_DO(DECLARE_CLONED_VTABLE_KIND)
 793   _num_cloned_vtable_kinds
 794 };
 795 
 796 // This is the index of all the cloned vtables. E.g., for
 797 //     ConstantPool* cp = ....; // an archived constant pool
 798 //     InstanceKlass* ik = ....;// an archived class
 799 // the following holds true:
 800 //     _cloned_cpp_vtptrs[ConstantPool_Kind]  == ((intptr_t**)cp)[0]
 801 //     _cloned_cpp_vtptrs[InstanceKlass_Kind] == ((intptr_t**)ik)[0]
 802 static intptr_t** _cloned_cpp_vtptrs = NULL;
 803 
 804 void MetaspaceShared::allocate_cloned_cpp_vtptrs() {
 805   assert(DumpSharedSpaces, "must");
 806   size_t vtptrs_bytes = _num_cloned_vtable_kinds * sizeof(intptr_t*);
 807   _cloned_cpp_vtptrs = (intptr_t**)_mc_region.allocate(vtptrs_bytes, sizeof(intptr_t*));
 808 }
 809 
 810 void MetaspaceShared::serialize_cloned_cpp_vtptrs(SerializeClosure* soc) {
 811   soc->do_ptr((void**)&_cloned_cpp_vtptrs);
 812 }
 813 
 814 intptr_t* MetaspaceShared::fix_cpp_vtable_for_dynamic_archive(MetaspaceObj::Type msotype, address obj) {
 815   Arguments::assert_is_dumping_archive();
 816   int kind = -1;
 817   switch (msotype) {
 818   case MetaspaceObj::SymbolType:
 819   case MetaspaceObj::TypeArrayU1Type:
 820   case MetaspaceObj::TypeArrayU2Type:
 821   case MetaspaceObj::TypeArrayU4Type:
 822   case MetaspaceObj::TypeArrayU8Type:
 823   case MetaspaceObj::TypeArrayOtherType:
 824   case MetaspaceObj::ConstMethodType:
 825   case MetaspaceObj::ConstantPoolCacheType:
 826   case MetaspaceObj::AnnotationsType:
 827   case MetaspaceObj::MethodCountersType:
 828   case MetaspaceObj::RecordComponentType:
 829     // These have no vtables.
 830     break;
 831   case MetaspaceObj::ClassType:
 832     {
 833       Klass* k = (Klass*)obj;
 834       assert(k->is_klass(), "must be");
 835       if (k->is_instance_klass()) {
 836         InstanceKlass* ik = InstanceKlass::cast(k);
 837         if (ik->is_class_loader_instance_klass()) {
 838           kind = InstanceClassLoaderKlass_Kind;
 839         } else if (ik->is_reference_instance_klass()) {
 840           kind = InstanceRefKlass_Kind;
 841         } else if (ik->is_mirror_instance_klass()) {
 842           kind = InstanceMirrorKlass_Kind;
 843         } else {
 844           kind = InstanceKlass_Kind;
 845         }
 846       } else if (k->is_typeArray_klass()) {
 847         kind = TypeArrayKlass_Kind;
 848       } else {
 849         assert(k->is_objArray_klass(), "must be");
 850         kind = ObjArrayKlass_Kind;
 851       }
 852     }
 853     break;
 854 
 855   case MetaspaceObj::MethodType:
 856     {
 857       Method* m = (Method*)obj;
 858       assert(m->is_method(), "must be");
 859       kind = Method_Kind;
 860     }
 861     break;
 862 
 863   case MetaspaceObj::MethodDataType:
 864     // We don't archive MethodData <-- should have been removed in removed_unsharable_info
 865     ShouldNotReachHere();
 866     break;
 867 
 868   case MetaspaceObj::ConstantPoolType:
 869     {
 870       ConstantPool *cp = (ConstantPool*)obj;
 871       assert(cp->is_constantPool(), "must be");
 872       kind = ConstantPool_Kind;
 873     }
 874     break;
 875 
 876   default:
 877     ShouldNotReachHere();
 878   }
 879 
 880   if (kind >= 0) {
 881     assert(kind < _num_cloned_vtable_kinds, "must be");
 882     return _cloned_cpp_vtptrs[kind];
 883   } else {
 884     return NULL;
 885   }
 886 }
 887 
 888 //------------------------------ for DynamicDumpSharedSpaces - end
 889 
 890 // This can be called at both dump time and run time:
 891 // - clone the contents of the c++ vtables into the space
 892 //   allocated by allocate_cpp_vtable_clones()
 893 void MetaspaceShared::clone_cpp_vtables(intptr_t* p) {
 894   assert(DumpSharedSpaces || UseSharedSpaces, "sanity");
 895   CPP_VTABLE_PATCH_TYPES_DO(CLONE_CPP_VTABLE);
 896 }
 897 
 898 void MetaspaceShared::zero_cpp_vtable_clones_for_writing() {
 899   assert(DumpSharedSpaces, "dump-time only");
 900   CPP_VTABLE_PATCH_TYPES_DO(ZERO_CPP_VTABLE);
 901 }
 902 
 903 // Allocate and initialize the C++ vtables, starting from top, but do not go past end.
 904 char* MetaspaceShared::allocate_cpp_vtable_clones() {
 905   char* cloned_vtables = _mc_region.top(); // This is the beginning of all the cloned vtables
 906 
 907   assert(DumpSharedSpaces, "dump-time only");
 908   // Layout (each slot is a intptr_t):
 909   //   [number of slots in the first vtable = n1]
 910   //   [ <n1> slots for the first vtable]
 911   //   [number of slots in the first second = n2]
 912   //   [ <n2> slots for the second vtable]
 913   //   ...
 914   // The order of the vtables is the same as the CPP_VTAB_PATCH_TYPES_DO macro.
 915   CPP_VTABLE_PATCH_TYPES_DO(ALLOC_CPP_VTABLE_CLONE);
 916 
 917   return cloned_vtables;
 918 }
 919 
 920 bool MetaspaceShared::is_valid_shared_method(const Method* m) {
 921   assert(is_in_shared_metaspace(m), "must be");
 922   return CppVtableCloner<Method>::is_valid_shared_object(m);
 923 }
 924 
 925 void WriteClosure::do_oop(oop* o) {
 926   if (*o == NULL) {
 927     _dump_region->append_intptr_t(0);
 928   } else {
 929     assert(HeapShared::is_heap_object_archiving_allowed(),
 930            "Archiving heap object is not allowed");
 931     _dump_region->append_intptr_t(
 932       (intptr_t)CompressedOops::encode_not_null(*o));
 933   }
 934 }
 935 
 936 void WriteClosure::do_region(u_char* start, size_t size) {
 937   assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
 938   assert(size % sizeof(intptr_t) == 0, "bad size");
 939   do_tag((int)size);
 940   while (size > 0) {
 941     _dump_region->append_intptr_t(*(intptr_t*)start, true);
 942     start += sizeof(intptr_t);
 943     size -= sizeof(intptr_t);
 944   }
 945 }
 946 
 947 // This is for dumping detailed statistics for the allocations
 948 // in the shared spaces.
 949 class DumpAllocStats : public ResourceObj {
 950 public:
 951 
 952   // Here's poor man's enum inheritance
 953 #define SHAREDSPACE_OBJ_TYPES_DO(f) \
 954   METASPACE_OBJ_TYPES_DO(f) \
 955   f(SymbolHashentry) \
 956   f(SymbolBucket) \
 957   f(StringHashentry) \
 958   f(StringBucket) \
 959   f(Other)
 960 
 961   enum Type {
 962     // Types are MetaspaceObj::ClassType, MetaspaceObj::SymbolType, etc
 963     SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_DECLARE)
 964     _number_of_types
 965   };
 966 
 967   static const char * type_name(Type type) {
 968     switch(type) {
 969     SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_NAME_CASE)
 970     default:
 971       ShouldNotReachHere();
 972       return NULL;
 973     }
 974   }
 975 
 976 public:
 977   enum { RO = 0, RW = 1 };
 978 
 979   int _counts[2][_number_of_types];
 980   int _bytes [2][_number_of_types];
 981 
 982   DumpAllocStats() {
 983     memset(_counts, 0, sizeof(_counts));
 984     memset(_bytes,  0, sizeof(_bytes));
 985   };
 986 
 987   void record(MetaspaceObj::Type type, int byte_size, bool read_only) {
 988     assert(int(type) >= 0 && type < MetaspaceObj::_number_of_types, "sanity");
 989     int which = (read_only) ? RO : RW;
 990     _counts[which][type] ++;
 991     _bytes [which][type] += byte_size;
 992   }
 993 
 994   void record_other_type(int byte_size, bool read_only) {
 995     int which = (read_only) ? RO : RW;
 996     _bytes [which][OtherType] += byte_size;
 997   }
 998   void print_stats(int ro_all, int rw_all, int mc_all);
 999 };
1000 
1001 void DumpAllocStats::print_stats(int ro_all, int rw_all, int mc_all) {
1002   // Calculate size of data that was not allocated by Metaspace::allocate()
1003   MetaspaceSharedStats *stats = MetaspaceShared::stats();
1004 
1005   // symbols
1006   _counts[RO][SymbolHashentryType] = stats->symbol.hashentry_count;
1007   _bytes [RO][SymbolHashentryType] = stats->symbol.hashentry_bytes;
1008 
1009   _counts[RO][SymbolBucketType] = stats->symbol.bucket_count;
1010   _bytes [RO][SymbolBucketType] = stats->symbol.bucket_bytes;
1011 
1012   // strings
1013   _counts[RO][StringHashentryType] = stats->string.hashentry_count;
1014   _bytes [RO][StringHashentryType] = stats->string.hashentry_bytes;
1015 
1016   _counts[RO][StringBucketType] = stats->string.bucket_count;
1017   _bytes [RO][StringBucketType] = stats->string.bucket_bytes;
1018 
1019   // TODO: count things like dictionary, vtable, etc
1020   _bytes[RW][OtherType] += mc_all;
1021   rw_all += mc_all; // mc is mapped Read/Write
1022 
1023   // prevent divide-by-zero
1024   if (ro_all < 1) {
1025     ro_all = 1;
1026   }
1027   if (rw_all < 1) {
1028     rw_all = 1;
1029   }
1030 
1031   int all_ro_count = 0;
1032   int all_ro_bytes = 0;
1033   int all_rw_count = 0;
1034   int all_rw_bytes = 0;
1035 
1036 // To make fmt_stats be a syntactic constant (for format warnings), use #define.
1037 #define fmt_stats "%-20s: %8d %10d %5.1f | %8d %10d %5.1f | %8d %10d %5.1f"
1038   const char *sep = "--------------------+---------------------------+---------------------------+--------------------------";
1039   const char *hdr = "                        ro_cnt   ro_bytes     % |   rw_cnt   rw_bytes     % |  all_cnt  all_bytes     %";
1040 
1041   LogMessage(cds) msg;
1042 
1043   msg.debug("Detailed metadata info (excluding st regions; rw stats include mc regions):");
1044   msg.debug("%s", hdr);
1045   msg.debug("%s", sep);
1046   for (int type = 0; type < int(_number_of_types); type ++) {
1047     const char *name = type_name((Type)type);
1048     int ro_count = _counts[RO][type];
1049     int ro_bytes = _bytes [RO][type];
1050     int rw_count = _counts[RW][type];
1051     int rw_bytes = _bytes [RW][type];
1052     int count = ro_count + rw_count;
1053     int bytes = ro_bytes + rw_bytes;
1054 
1055     double ro_perc = percent_of(ro_bytes, ro_all);
1056     double rw_perc = percent_of(rw_bytes, rw_all);
1057     double perc    = percent_of(bytes, ro_all + rw_all);
1058 
1059     msg.debug(fmt_stats, name,
1060                          ro_count, ro_bytes, ro_perc,
1061                          rw_count, rw_bytes, rw_perc,
1062                          count, bytes, perc);
1063 
1064     all_ro_count += ro_count;
1065     all_ro_bytes += ro_bytes;
1066     all_rw_count += rw_count;
1067     all_rw_bytes += rw_bytes;
1068   }
1069 
1070   int all_count = all_ro_count + all_rw_count;
1071   int all_bytes = all_ro_bytes + all_rw_bytes;
1072 
1073   double all_ro_perc = percent_of(all_ro_bytes, ro_all);
1074   double all_rw_perc = percent_of(all_rw_bytes, rw_all);
1075   double all_perc    = percent_of(all_bytes, ro_all + rw_all);
1076 
1077   msg.debug("%s", sep);
1078   msg.debug(fmt_stats, "Total",
1079                        all_ro_count, all_ro_bytes, all_ro_perc,
1080                        all_rw_count, all_rw_bytes, all_rw_perc,
1081                        all_count, all_bytes, all_perc);
1082 
1083   assert(all_ro_bytes == ro_all, "everything should have been counted");
1084   assert(all_rw_bytes == rw_all, "everything should have been counted");
1085 
1086 #undef fmt_stats
1087 }
1088 
1089 // Populate the shared space.
1090 
1091 class VM_PopulateDumpSharedSpace: public VM_Operation {
1092 private:
1093   GrowableArray<MemRegion> *_closed_archive_heap_regions;
1094   GrowableArray<MemRegion> *_open_archive_heap_regions;
1095 
1096   GrowableArray<ArchiveHeapOopmapInfo> *_closed_archive_heap_oopmaps;
1097   GrowableArray<ArchiveHeapOopmapInfo> *_open_archive_heap_oopmaps;
1098 
1099   void dump_java_heap_objects() NOT_CDS_JAVA_HEAP_RETURN;
1100   void dump_archive_heap_oopmaps() NOT_CDS_JAVA_HEAP_RETURN;
1101   void dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
1102                                  GrowableArray<ArchiveHeapOopmapInfo>* oopmaps);
1103   void dump_symbols();
1104   char* dump_read_only_tables();
1105   void print_class_stats();
1106   void print_region_stats();
1107   void print_bitmap_region_stats(size_t size, size_t total_size);
1108   void print_heap_region_stats(GrowableArray<MemRegion> *heap_mem,
1109                                const char *name, size_t total_size);
1110   void relocate_to_default_base_address(CHeapBitMap* ptrmap);
1111 
1112 public:
1113 
1114   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
1115   void doit();   // outline because gdb sucks
1116   bool allow_nested_vm_operations() const { return true; }
1117 }; // class VM_PopulateDumpSharedSpace
1118 
1119 class SortedSymbolClosure: public SymbolClosure {
1120   GrowableArray<Symbol*> _symbols;
1121   virtual void do_symbol(Symbol** sym) {
1122     assert((*sym)->is_permanent(), "archived symbols must be permanent");
1123     _symbols.append(*sym);
1124   }
1125   static int compare_symbols_by_address(Symbol** a, Symbol** b) {
1126     if (a[0] < b[0]) {
1127       return -1;
1128     } else if (a[0] == b[0]) {
1129       return 0;
1130     } else {
1131       return 1;
1132     }
1133   }
1134 
1135 public:
1136   SortedSymbolClosure() {
1137     SymbolTable::symbols_do(this);
1138     _symbols.sort(compare_symbols_by_address);
1139   }
1140   GrowableArray<Symbol*>* get_sorted_symbols() {
1141     return &_symbols;
1142   }
1143 };
1144 
1145 // ArchiveCompactor --
1146 //
1147 // This class is the central piece of shared archive compaction -- all metaspace data are
1148 // initially allocated outside of the shared regions. ArchiveCompactor copies the
1149 // metaspace data into their final location in the shared regions.
1150 
1151 class ArchiveCompactor : AllStatic {
1152   static const int INITIAL_TABLE_SIZE = 8087;
1153   static const int MAX_TABLE_SIZE     = 1000000;
1154 
1155   static DumpAllocStats* _alloc_stats;
1156   static SortedSymbolClosure* _ssc;
1157 
1158   typedef KVHashtable<address, address, mtInternal> RelocationTable;
1159   static RelocationTable* _new_loc_table;
1160 
1161 public:
1162   static void initialize() {
1163     _alloc_stats = new(ResourceObj::C_HEAP, mtInternal)DumpAllocStats;
1164     _new_loc_table = new RelocationTable(INITIAL_TABLE_SIZE);
1165   }
1166   static DumpAllocStats* alloc_stats() {
1167     return _alloc_stats;
1168   }
1169 
1170   // Use this when you allocate space with MetaspaceShare::read_only_space_alloc()
1171   // outside of ArchiveCompactor::allocate(). These are usually for misc tables
1172   // that are allocated in the RO space.
1173   class OtherROAllocMark {
1174     char* _oldtop;
1175   public:
1176     OtherROAllocMark() {
1177       _oldtop = _ro_region.top();
1178     }
1179     ~OtherROAllocMark() {
1180       char* newtop = _ro_region.top();
1181       ArchiveCompactor::alloc_stats()->record_other_type(int(newtop - _oldtop), true);
1182     }
1183   };
1184 
1185   static void allocate(MetaspaceClosure::Ref* ref, bool read_only) {
1186     address obj = ref->obj();
1187     int bytes = ref->size() * BytesPerWord;
1188     char* p;
1189     size_t alignment = BytesPerWord;
1190     char* oldtop;
1191     char* newtop;
1192 
1193     if (read_only) {
1194       oldtop = _ro_region.top();
1195       p = _ro_region.allocate(bytes, alignment);
1196       newtop = _ro_region.top();
1197     } else {
1198       oldtop = _rw_region.top();
1199       if (ref->msotype() == MetaspaceObj::ClassType) {
1200         // Save a pointer immediate in front of an InstanceKlass, so
1201         // we can do a quick lookup from InstanceKlass* -> RunTimeSharedClassInfo*
1202         // without building another hashtable. See RunTimeSharedClassInfo::get_for()
1203         // in systemDictionaryShared.cpp.
1204         Klass* klass = (Klass*)obj;
1205         if (klass->is_instance_klass()) {
1206           SystemDictionaryShared::validate_before_archiving(InstanceKlass::cast(klass));
1207           _rw_region.allocate(sizeof(address), BytesPerWord);
1208         }
1209       }
1210       p = _rw_region.allocate(bytes, alignment);
1211       newtop = _rw_region.top();
1212     }
1213     memcpy(p, obj, bytes);
1214 
1215     intptr_t* cloned_vtable = MetaspaceShared::fix_cpp_vtable_for_dynamic_archive(ref->msotype(), (address)p);
1216     if (cloned_vtable != NULL) {
1217       *(address*)p = (address)cloned_vtable;
1218       ArchivePtrMarker::mark_pointer((address*)p);
1219     }
1220 
1221     assert(_new_loc_table->lookup(obj) == NULL, "each object can be relocated at most once");
1222     _new_loc_table->add(obj, (address)p);
1223     log_trace(cds)("Copy: " PTR_FORMAT " ==> " PTR_FORMAT " %d", p2i(obj), p2i(p), bytes);
1224     if (_new_loc_table->maybe_grow(MAX_TABLE_SIZE)) {
1225       log_info(cds, hashtables)("Expanded _new_loc_table to %d", _new_loc_table->table_size());
1226     }
1227     _alloc_stats->record(ref->msotype(), int(newtop - oldtop), read_only);
1228   }
1229 
1230   static address get_new_loc(MetaspaceClosure::Ref* ref) {
1231     address* pp = _new_loc_table->lookup(ref->obj());
1232     assert(pp != NULL, "must be");
1233     return *pp;
1234   }
1235 
1236 private:
1237   // Makes a shallow copy of visited MetaspaceObj's
1238   class ShallowCopier: public UniqueMetaspaceClosure {
1239     bool _read_only;
1240   public:
1241     ShallowCopier(bool read_only) : _read_only(read_only) {}
1242 
1243     virtual bool do_unique_ref(Ref* ref, bool read_only) {
1244       if (read_only == _read_only) {
1245         allocate(ref, read_only);
1246       }
1247       return true; // recurse into ref.obj()
1248     }
1249   };
1250 
1251   // Relocate embedded pointers within a MetaspaceObj's shallow copy
1252   class ShallowCopyEmbeddedRefRelocator: public UniqueMetaspaceClosure {
1253   public:
1254     virtual bool do_unique_ref(Ref* ref, bool read_only) {
1255       address new_loc = get_new_loc(ref);
1256       RefRelocator refer;
1257       ref->metaspace_pointers_do_at(&refer, new_loc);
1258       return true; // recurse into ref.obj()
1259     }
1260     virtual void push_special(SpecialRef type, Ref* ref, intptr_t* p) {
1261       assert(type == _method_entry_ref, "only special type allowed for now");
1262       address obj = ref->obj();
1263       address new_obj = get_new_loc(ref);
1264       size_t offset = pointer_delta(p, obj,  sizeof(u1));
1265       intptr_t* new_p = (intptr_t*)(new_obj + offset);
1266       assert(*p == *new_p, "must be a copy");
1267       ArchivePtrMarker::mark_pointer((address*)new_p);
1268     }
1269   };
1270 
1271   // Relocate a reference to point to its shallow copy
1272   class RefRelocator: public MetaspaceClosure {
1273   public:
1274     virtual bool do_ref(Ref* ref, bool read_only) {
1275       if (ref->not_null()) {
1276         ref->update(get_new_loc(ref));
1277         ArchivePtrMarker::mark_pointer(ref->addr());
1278       }
1279       return false; // Do not recurse.
1280     }
1281   };
1282 
1283 #ifdef ASSERT
1284   class IsRefInArchiveChecker: public MetaspaceClosure {
1285   public:
1286     virtual bool do_ref(Ref* ref, bool read_only) {
1287       if (ref->not_null()) {
1288         char* obj = (char*)ref->obj();
1289         assert(_ro_region.contains(obj) || _rw_region.contains(obj),
1290                "must be relocated to point to CDS archive");
1291       }
1292       return false; // Do not recurse.
1293     }
1294   };
1295 #endif
1296 
1297 public:
1298   static void copy_and_compact() {
1299     ResourceMark rm;
1300     SortedSymbolClosure the_ssc; // StackObj
1301     _ssc = &the_ssc;
1302 
1303     log_info(cds)("Scanning all metaspace objects ... ");
1304     {
1305       // allocate and shallow-copy RW objects, immediately following the MC region
1306       log_info(cds)("Allocating RW objects ... ");
1307       _mc_region.pack(&_rw_region);
1308 
1309       ResourceMark rm;
1310       ShallowCopier rw_copier(false);
1311       iterate_roots(&rw_copier);
1312     }
1313     {
1314       // allocate and shallow-copy of RO object, immediately following the RW region
1315       log_info(cds)("Allocating RO objects ... ");
1316       _rw_region.pack(&_ro_region);
1317 
1318       ResourceMark rm;
1319       ShallowCopier ro_copier(true);
1320       iterate_roots(&ro_copier);
1321     }
1322     {
1323       log_info(cds)("Relocating embedded pointers ... ");
1324       ResourceMark rm;
1325       ShallowCopyEmbeddedRefRelocator emb_reloc;
1326       iterate_roots(&emb_reloc);
1327     }
1328     {
1329       log_info(cds)("Relocating external roots ... ");
1330       ResourceMark rm;
1331       RefRelocator ext_reloc;
1332       iterate_roots(&ext_reloc);
1333     }
1334 
1335 #ifdef ASSERT
1336     {
1337       log_info(cds)("Verifying external roots ... ");
1338       ResourceMark rm;
1339       IsRefInArchiveChecker checker;
1340       iterate_roots(&checker);
1341     }
1342 #endif
1343 
1344 
1345     // cleanup
1346     _ssc = NULL;
1347   }
1348 
1349   // We must relocate the System::_well_known_klasses only after we have copied the
1350   // java objects in during dump_java_heap_objects(): during the object copy, we operate on
1351   // old objects which assert that their klass is the original klass.
1352   static void relocate_well_known_klasses() {
1353     {
1354       log_info(cds)("Relocating SystemDictionary::_well_known_klasses[] ... ");
1355       ResourceMark rm;
1356       RefRelocator ext_reloc;
1357       SystemDictionary::well_known_klasses_do(&ext_reloc);
1358     }
1359     // NOTE: after this point, we shouldn't have any globals that can reach the old
1360     // objects.
1361 
1362     // We cannot use any of the objects in the heap anymore (except for the
1363     // shared strings) because their headers no longer point to valid Klasses.
1364   }
1365 
1366   static void iterate_roots(MetaspaceClosure* it) {
1367     GrowableArray<Symbol*>* symbols = _ssc->get_sorted_symbols();
1368     for (int i=0; i<symbols->length(); i++) {
1369       it->push(symbols->adr_at(i));
1370     }
1371     if (_global_klass_objects != NULL) {
1372       // Need to fix up the pointers
1373       for (int i = 0; i < _global_klass_objects->length(); i++) {
1374         // NOTE -- this requires that the vtable is NOT yet patched, or else we are hosed.
1375         it->push(_global_klass_objects->adr_at(i));
1376       }
1377     }
1378     FileMapInfo::metaspace_pointers_do(it);
1379     SystemDictionaryShared::dumptime_classes_do(it);
1380     Universe::metaspace_pointers_do(it);
1381     SymbolTable::metaspace_pointers_do(it);
1382     vmSymbols::metaspace_pointers_do(it);
1383 
1384     it->finish();
1385   }
1386 
1387   static Klass* get_relocated_klass(Klass* orig_klass) {
1388     assert(DumpSharedSpaces, "dump time only");
1389     address* pp = _new_loc_table->lookup((address)orig_klass);
1390     assert(pp != NULL, "must be");
1391     Klass* klass = (Klass*)(*pp);
1392     assert(klass->is_klass(), "must be");
1393     return klass;
1394   }
1395 };
1396 
1397 DumpAllocStats* ArchiveCompactor::_alloc_stats;
1398 SortedSymbolClosure* ArchiveCompactor::_ssc;
1399 ArchiveCompactor::RelocationTable* ArchiveCompactor::_new_loc_table;
1400 
1401 void VM_PopulateDumpSharedSpace::dump_symbols() {
1402   log_info(cds)("Dumping symbol table ...");
1403 
1404   NOT_PRODUCT(SymbolTable::verify());
1405   SymbolTable::write_to_archive();
1406 }
1407 
1408 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
1409   ArchiveCompactor::OtherROAllocMark mark;
1410 
1411   log_info(cds)("Removing java_mirror ... ");
1412   if (!HeapShared::is_heap_object_archiving_allowed()) {
1413     clear_basic_type_mirrors();
1414   }
1415   remove_java_mirror_in_classes();
1416   log_info(cds)("done. ");
1417 
1418   SystemDictionaryShared::write_to_archive();
1419 
1420   // Write the other data to the output array.
1421   char* start = _ro_region.top();
1422   WriteClosure wc(&_ro_region);
1423   MetaspaceShared::serialize(&wc);
1424 
1425   // Write the bitmaps for patching the archive heap regions
1426   dump_archive_heap_oopmaps();
1427 
1428   return start;
1429 }
1430 
1431 void VM_PopulateDumpSharedSpace::print_class_stats() {
1432   log_info(cds)("Number of classes %d", _global_klass_objects->length());
1433   {
1434     int num_type_array = 0, num_obj_array = 0, num_inst = 0;
1435     for (int i = 0; i < _global_klass_objects->length(); i++) {
1436       Klass* k = _global_klass_objects->at(i);
1437       if (k->is_instance_klass()) {
1438         num_inst ++;
1439       } else if (k->is_objArray_klass()) {
1440         num_obj_array ++;
1441       } else {
1442         assert(k->is_typeArray_klass(), "sanity");
1443         num_type_array ++;
1444       }
1445     }
1446     log_info(cds)("    instance classes   = %5d", num_inst);
1447     log_info(cds)("    obj array classes  = %5d", num_obj_array);
1448     log_info(cds)("    type array classes = %5d", num_type_array);
1449   }
1450 }
1451 
1452 void VM_PopulateDumpSharedSpace::relocate_to_default_base_address(CHeapBitMap* ptrmap) {
1453   intx addr_delta = MetaspaceShared::final_delta();
1454   if (addr_delta == 0) {
1455     ArchivePtrMarker::compact((address)SharedBaseAddress, (address)_ro_region.top());
1456   } else {
1457     // We are not able to reserve space at Arguments::default_SharedBaseAddress() (due to ASLR).
1458     // This means that the current content of the archive is based on a random
1459     // address. Let's relocate all the pointers, so that it can be mapped to
1460     // Arguments::default_SharedBaseAddress() without runtime relocation.
1461     //
1462     // Note: both the base and dynamic archive are written with
1463     // FileMapHeader::_shared_base_address == Arguments::default_SharedBaseAddress()
1464 
1465     // Patch all pointers that are marked by ptrmap within this region,
1466     // where we have just dumped all the metaspace data.
1467     address patch_base = (address)SharedBaseAddress;
1468     address patch_end  = (address)_ro_region.top();
1469     size_t size = patch_end - patch_base;
1470 
1471     // the current value of the pointers to be patched must be within this
1472     // range (i.e., must point to valid metaspace objects)
1473     address valid_old_base = patch_base;
1474     address valid_old_end  = patch_end;
1475 
1476     // after patching, the pointers must point inside this range
1477     // (the requested location of the archive, as mapped at runtime).
1478     address valid_new_base = (address)Arguments::default_SharedBaseAddress();
1479     address valid_new_end  = valid_new_base + size;
1480 
1481     log_debug(cds)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT " ] to "
1482                    "[" INTPTR_FORMAT " - " INTPTR_FORMAT " ]", p2i(patch_base), p2i(patch_end),
1483                    p2i(valid_new_base), p2i(valid_new_end));
1484 
1485     SharedDataRelocator<true> patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end,
1486                                       valid_new_base, valid_new_end, addr_delta, ptrmap);
1487     ptrmap->iterate(&patcher);
1488     ArchivePtrMarker::compact(patcher.max_non_null_offset());
1489   }
1490 }
1491 
1492 void VM_PopulateDumpSharedSpace::doit() {
1493   CHeapBitMap ptrmap;
1494   MetaspaceShared::initialize_ptr_marker(&ptrmap);
1495 
1496   // We should no longer allocate anything from the metaspace, so that:
1497   //
1498   // (1) Metaspace::allocate might trigger GC if we have run out of
1499   //     committed metaspace, but we can't GC because we're running
1500   //     in the VM thread.
1501   // (2) ArchiveCompactor needs to work with a stable set of MetaspaceObjs.
1502   Metaspace::freeze();
1503   DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
1504 
1505   Thread* THREAD = VMThread::vm_thread();
1506 
1507   FileMapInfo::check_nonempty_dir_in_shared_path_table();
1508 
1509   NOT_PRODUCT(SystemDictionary::verify();)
1510   // The following guarantee is meant to ensure that no loader constraints
1511   // exist yet, since the constraints table is not shared.  This becomes
1512   // more important now that we don't re-initialize vtables/itables for
1513   // shared classes at runtime, where constraints were previously created.
1514   guarantee(SystemDictionary::constraints()->number_of_entries() == 0,
1515             "loader constraints are not saved");
1516   guarantee(SystemDictionary::placeholders()->number_of_entries() == 0,
1517           "placeholders are not saved");
1518 
1519   // At this point, many classes have been loaded.
1520   // Gather systemDictionary classes in a global array and do everything to
1521   // that so we don't have to walk the SystemDictionary again.
1522   SystemDictionaryShared::check_excluded_classes();
1523   _global_klass_objects = new GrowableArray<Klass*>(1000);
1524   CollectClassesClosure collect_classes;
1525   ClassLoaderDataGraph::loaded_classes_do(&collect_classes);
1526 
1527   print_class_stats();
1528 
1529   // Ensure the ConstMethods won't be modified at run-time
1530   log_info(cds)("Updating ConstMethods ... ");
1531   rewrite_nofast_bytecodes_and_calculate_fingerprints(THREAD);
1532   log_info(cds)("done. ");
1533 
1534   // Remove all references outside the metadata
1535   log_info(cds)("Removing unshareable information ... ");
1536   remove_unshareable_in_classes();
1537   log_info(cds)("done. ");
1538 
1539   MetaspaceShared::allocate_cloned_cpp_vtptrs();
1540   char* cloned_vtables = _mc_region.top();
1541   MetaspaceShared::allocate_cpp_vtable_clones();
1542 
1543   ArchiveCompactor::initialize();
1544   ArchiveCompactor::copy_and_compact();
1545 
1546   dump_symbols();
1547 
1548   // Dump supported java heap objects
1549   _closed_archive_heap_regions = NULL;
1550   _open_archive_heap_regions = NULL;
1551   dump_java_heap_objects();
1552 
1553   ArchiveCompactor::relocate_well_known_klasses();
1554 
1555   char* serialized_data = dump_read_only_tables();
1556   _ro_region.pack();
1557 
1558   // The vtable clones contain addresses of the current process.
1559   // We don't want to write these addresses into the archive.
1560   MetaspaceShared::zero_cpp_vtable_clones_for_writing();
1561 
1562   // relocate the data so that it can be mapped to Arguments::default_SharedBaseAddress()
1563   // without runtime relocation.
1564   relocate_to_default_base_address(&ptrmap);
1565 
1566   // Create and write the archive file that maps the shared spaces.
1567 
1568   FileMapInfo* mapinfo = new FileMapInfo(true);
1569   mapinfo->populate_header(os::vm_allocation_granularity());
1570   mapinfo->set_serialized_data(serialized_data);
1571   mapinfo->set_cloned_vtables(cloned_vtables);
1572   mapinfo->set_i2i_entry_code_buffers(MetaspaceShared::i2i_entry_code_buffers(),
1573                                       MetaspaceShared::i2i_entry_code_buffers_size());
1574   mapinfo->open_for_write();
1575   MetaspaceShared::write_core_archive_regions(mapinfo);
1576   _total_closed_archive_region_size = mapinfo->write_archive_heap_regions(
1577                                         _closed_archive_heap_regions,
1578                                         _closed_archive_heap_oopmaps,
1579                                         MetaspaceShared::first_closed_archive_heap_region,
1580                                         MetaspaceShared::max_closed_archive_heap_region);
1581   _total_open_archive_region_size = mapinfo->write_archive_heap_regions(
1582                                         _open_archive_heap_regions,
1583                                         _open_archive_heap_oopmaps,
1584                                         MetaspaceShared::first_open_archive_heap_region,
1585                                         MetaspaceShared::max_open_archive_heap_region);
1586 
1587   mapinfo->set_final_requested_base((char*)Arguments::default_SharedBaseAddress());
1588   mapinfo->set_header_crc(mapinfo->compute_header_crc());
1589   mapinfo->write_header();
1590   mapinfo->close();
1591 
1592   print_region_stats();
1593 
1594   if (log_is_enabled(Info, cds)) {
1595     ArchiveCompactor::alloc_stats()->print_stats(int(_ro_region.used()), int(_rw_region.used()),
1596                                                  int(_mc_region.used()));
1597   }
1598 
1599   if (PrintSystemDictionaryAtExit) {
1600     SystemDictionary::print();
1601   }
1602 
1603   if (AllowArchivingWithJavaAgent) {
1604     warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1605             "for testing purposes only and should not be used in a production environment");
1606   }
1607 
1608   // There may be other pending VM operations that operate on the InstanceKlasses,
1609   // which will fail because InstanceKlasses::remove_unshareable_info()
1610   // has been called. Forget these operations and exit the VM directly.
1611   vm_direct_exit(0);
1612 }
1613 
1614 void VM_PopulateDumpSharedSpace::print_region_stats() {
1615   // Print statistics of all the regions
1616   const size_t bitmap_used = ArchivePtrMarker::ptrmap()->size_in_bytes();
1617   const size_t bitmap_reserved = align_up(bitmap_used, Metaspace::reserve_alignment());
1618   const size_t total_reserved = _ro_region.reserved()  + _rw_region.reserved() +
1619                                 _mc_region.reserved()  +
1620                                 bitmap_reserved +
1621                                 _total_closed_archive_region_size +
1622                                 _total_open_archive_region_size;
1623   const size_t total_bytes = _ro_region.used()  + _rw_region.used() +
1624                              _mc_region.used()  +
1625                              bitmap_used +
1626                              _total_closed_archive_region_size +
1627                              _total_open_archive_region_size;
1628   const double total_u_perc = percent_of(total_bytes, total_reserved);
1629 
1630   _mc_region.print(total_reserved);
1631   _rw_region.print(total_reserved);
1632   _ro_region.print(total_reserved);
1633   print_bitmap_region_stats(bitmap_reserved, total_reserved);
1634   print_heap_region_stats(_closed_archive_heap_regions, "ca", total_reserved);
1635   print_heap_region_stats(_open_archive_heap_regions, "oa", total_reserved);
1636 
1637   log_debug(cds)("total    : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]",
1638                  total_bytes, total_reserved, total_u_perc);
1639 }
1640 
1641 void VM_PopulateDumpSharedSpace::print_bitmap_region_stats(size_t size, size_t total_size) {
1642   log_debug(cds)("bm  space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used] at " INTPTR_FORMAT,
1643                  size, size/double(total_size)*100.0, size, p2i(NULL));
1644 }
1645 
1646 void VM_PopulateDumpSharedSpace::print_heap_region_stats(GrowableArray<MemRegion> *heap_mem,
1647                                                          const char *name, size_t total_size) {
1648   int arr_len = heap_mem == NULL ? 0 : heap_mem->length();
1649   for (int i = 0; i < arr_len; i++) {
1650       char* start = (char*)heap_mem->at(i).start();
1651       size_t size = heap_mem->at(i).byte_size();
1652       char* top = start + size;
1653       log_debug(cds)("%s%d space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used] at " INTPTR_FORMAT,
1654                      name, i, size, size/double(total_size)*100.0, size, p2i(start));
1655 
1656   }
1657 }
1658 
1659 void MetaspaceShared::write_core_archive_regions(FileMapInfo* mapinfo) {
1660   // Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with
1661   // MetaspaceShared::n_regions (internal to hotspot).
1662   assert(NUM_CDS_REGIONS == MetaspaceShared::n_regions, "sanity");
1663 
1664   // mc contains the trampoline code for method entries, which are patched at run time,
1665   // so it needs to be read/write.
1666   write_region(mapinfo, mc, &_mc_region, /*read_only=*/false,/*allow_exec=*/true);
1667   write_region(mapinfo, rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);
1668   write_region(mapinfo, ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);
1669   mapinfo->write_bitmap_region(ArchivePtrMarker::ptrmap());
1670 }
1671 
1672 void MetaspaceShared::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only,  bool allow_exec) {
1673   mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);
1674 }
1675 
1676 // Update a Java object to point its Klass* to the new location after
1677 // shared archive has been compacted.
1678 void MetaspaceShared::relocate_klass_ptr(oop o) {
1679   assert(DumpSharedSpaces, "sanity");
1680   Klass* k = ArchiveCompactor::get_relocated_klass(o->klass());
1681   o->set_klass(k);
1682 }
1683 
1684 Klass* MetaspaceShared::get_relocated_klass(Klass *k, bool is_final) {
1685   assert(DumpSharedSpaces, "sanity");
1686   k = ArchiveCompactor::get_relocated_klass(k);
1687   if (is_final) {
1688     k = (Klass*)(address(k) + final_delta());
1689   }
1690   return k;
1691 }
1692 
1693 class LinkSharedClassesClosure : public KlassClosure {
1694   bool _is_static;
1695   Thread* THREAD;
1696   bool    _made_progress;
1697  public:
1698   LinkSharedClassesClosure(bool is_static, Thread* thread) : _is_static(is_static), THREAD(thread), _made_progress(false) {}
1699 
1700   void reset()               { _made_progress = false; }
1701   bool made_progress() const { return _made_progress; }
1702 
1703   void do_klass(Klass* k) {
1704     if (k->is_instance_klass()) {
1705       InstanceKlass* ik = InstanceKlass::cast(k);
1706       // For dynamic CDS dump, only link classes loaded by the builtin class loaders.
1707       bool do_linking = _is_static ? true : ik->loader_type() != 0;
1708       if (do_linking) {
1709         // Link the class to cause the bytecodes to be rewritten and the
1710         // cpcache to be created. Class verification is done according
1711         // to -Xverify setting.
1712         _made_progress |= MetaspaceShared::try_link_class(ik, THREAD);
1713         guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1714 
1715         ik->constants()->resolve_class_constants(THREAD);
1716       }
1717     }
1718   }
1719 };
1720 
1721 void MetaspaceShared::link_and_cleanup_shared_classes(bool is_static, TRAPS) {
1722   // We need to iterate because verification may cause additional classes
1723   // to be loaded.
1724   LinkSharedClassesClosure link_closure(is_static, THREAD);
1725   do {
1726     link_closure.reset();
1727     ClassLoaderDataGraph::unlocked_loaded_classes_do(&link_closure);
1728     guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1729   } while (link_closure.made_progress());
1730 }
1731 
1732 void MetaspaceShared::prepare_for_dumping() {
1733   Arguments::check_unsupported_dumping_properties();
1734   ClassLoader::initialize_shared_path();
1735 }
1736 
1737 // Preload classes from a list, populate the shared spaces and dump to a
1738 // file.
1739 void MetaspaceShared::preload_and_dump(TRAPS) {
1740   { TraceTime timer("Dump Shared Spaces", TRACETIME_LOG(Info, startuptime));
1741     ResourceMark rm(THREAD);
1742     char class_list_path_str[JVM_MAXPATHLEN];
1743     // Preload classes to be shared.
1744     const char* class_list_path;
1745     if (SharedClassListFile == NULL) {
1746       // Construct the path to the class list (in jre/lib)
1747       // Walk up two directories from the location of the VM and
1748       // optionally tack on "lib" (depending on platform)
1749       os::jvm_path(class_list_path_str, sizeof(class_list_path_str));
1750       for (int i = 0; i < 3; i++) {
1751         char *end = strrchr(class_list_path_str, *os::file_separator());
1752         if (end != NULL) *end = '\0';
1753       }
1754       int class_list_path_len = (int)strlen(class_list_path_str);
1755       if (class_list_path_len >= 3) {
1756         if (strcmp(class_list_path_str + class_list_path_len - 3, "lib") != 0) {
1757           if (class_list_path_len < JVM_MAXPATHLEN - 4) {
1758             jio_snprintf(class_list_path_str + class_list_path_len,
1759                          sizeof(class_list_path_str) - class_list_path_len,
1760                          "%slib", os::file_separator());
1761             class_list_path_len += 4;
1762           }
1763         }
1764       }
1765       if (class_list_path_len < JVM_MAXPATHLEN - 10) {
1766         jio_snprintf(class_list_path_str + class_list_path_len,
1767                      sizeof(class_list_path_str) - class_list_path_len,
1768                      "%sclasslist", os::file_separator());
1769       }
1770       class_list_path = class_list_path_str;
1771     } else {
1772       class_list_path = SharedClassListFile;
1773     }
1774 
1775     log_info(cds)("Loading classes to share ...");
1776     _has_error_classes = false;
1777     int class_count = preload_classes(class_list_path, THREAD);
1778     if (ExtraSharedClassListFile) {
1779       class_count += preload_classes(ExtraSharedClassListFile, THREAD);
1780     }
1781     log_info(cds)("Loading classes to share: done.");
1782 
1783     log_info(cds)("Shared spaces: preloaded %d classes", class_count);
1784 
1785     if (SharedArchiveConfigFile) {
1786       log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
1787       read_extra_data(SharedArchiveConfigFile, THREAD);
1788     }
1789     log_info(cds)("Reading extra data: done.");
1790 
1791     HeapShared::init_subgraph_entry_fields(THREAD);
1792 
1793     // Rewrite and link classes
1794     log_info(cds)("Rewriting and linking classes ...");
1795 
1796     // Link any classes which got missed. This would happen if we have loaded classes that
1797     // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
1798     // fails verification, all other interfaces that were not specified in the classlist but
1799     // are implemented by K are not verified.
1800     link_and_cleanup_shared_classes(true, CATCH);
1801     log_info(cds)("Rewriting and linking classes: done");
1802 
1803     if (HeapShared::is_heap_object_archiving_allowed()) {
1804       // Avoid fragmentation while archiving heap objects.
1805       Universe::heap()->soft_ref_policy()->set_should_clear_all_soft_refs(true);
1806       Universe::heap()->collect(GCCause::_archive_time_gc);
1807       Universe::heap()->soft_ref_policy()->set_should_clear_all_soft_refs(false);
1808     }
1809 
1810     VM_PopulateDumpSharedSpace op;
1811     VMThread::execute(&op);
1812   }
1813 }
1814 
1815 
1816 int MetaspaceShared::preload_classes(const char* class_list_path, TRAPS) {
1817   ClassListParser parser(class_list_path);
1818   int class_count = 0;
1819 
1820   while (parser.parse_one_line()) {
1821     Klass* klass = parser.load_current_class(THREAD);
1822     if (HAS_PENDING_EXCEPTION) {
1823       if (klass == NULL &&
1824           (PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_ClassNotFoundException())) {
1825         // print a warning only when the pending exception is class not found
1826         log_warning(cds)("Preload Warning: Cannot find %s", parser.current_class_name());
1827       }
1828       CLEAR_PENDING_EXCEPTION;
1829     }
1830     if (klass != NULL) {
1831       if (log_is_enabled(Trace, cds)) {
1832         ResourceMark rm(THREAD);
1833         log_trace(cds)("Shared spaces preloaded: %s", klass->external_name());
1834       }
1835 
1836       if (klass->is_instance_klass()) {
1837         InstanceKlass* ik = InstanceKlass::cast(klass);
1838 
1839         // Link the class to cause the bytecodes to be rewritten and the
1840         // cpcache to be created. The linking is done as soon as classes
1841         // are loaded in order that the related data structures (klass and
1842         // cpCache) are located together.
1843         try_link_class(ik, THREAD);
1844         guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1845       }
1846 
1847       class_count++;
1848     }
1849   }
1850 
1851   return class_count;
1852 }
1853 
1854 // Returns true if the class's status has changed
1855 bool MetaspaceShared::try_link_class(InstanceKlass* ik, TRAPS) {
1856   Arguments::assert_is_dumping_archive();
1857   if (ik->init_state() < InstanceKlass::linked &&
1858       !SystemDictionaryShared::has_class_failed_verification(ik)) {
1859     bool saved = BytecodeVerificationLocal;
1860     if (ik->loader_type() == 0 && ik->class_loader() == NULL) {
1861       // The verification decision is based on BytecodeVerificationRemote
1862       // for non-system classes. Since we are using the NULL classloader
1863       // to load non-system classes for customized class loaders during dumping,
1864       // we need to temporarily change BytecodeVerificationLocal to be the same as
1865       // BytecodeVerificationRemote. Note this can cause the parent system
1866       // classes also being verified. The extra overhead is acceptable during
1867       // dumping.
1868       BytecodeVerificationLocal = BytecodeVerificationRemote;
1869     }
1870     ik->link_class(THREAD);
1871     if (HAS_PENDING_EXCEPTION) {
1872       ResourceMark rm(THREAD);
1873       log_warning(cds)("Preload Warning: Verification failed for %s",
1874                     ik->external_name());
1875       CLEAR_PENDING_EXCEPTION;
1876       SystemDictionaryShared::set_class_has_failed_verification(ik);
1877       _has_error_classes = true;
1878     }
1879     BytecodeVerificationLocal = saved;
1880     return true;
1881   } else {
1882     return false;
1883   }
1884 }
1885 
1886 #if INCLUDE_CDS_JAVA_HEAP
1887 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() {
1888   // The closed and open archive heap space has maximum two regions.
1889   // See FileMapInfo::write_archive_heap_regions() for details.
1890   _closed_archive_heap_regions = new GrowableArray<MemRegion>(2);
1891   _open_archive_heap_regions = new GrowableArray<MemRegion>(2);
1892   HeapShared::archive_java_heap_objects(_closed_archive_heap_regions,
1893                                         _open_archive_heap_regions);
1894   ArchiveCompactor::OtherROAllocMark mark;
1895   HeapShared::write_subgraph_info_table();
1896 }
1897 
1898 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps() {
1899   if (HeapShared::is_heap_object_archiving_allowed()) {
1900     _closed_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
1901     dump_archive_heap_oopmaps(_closed_archive_heap_regions, _closed_archive_heap_oopmaps);
1902 
1903     _open_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
1904     dump_archive_heap_oopmaps(_open_archive_heap_regions, _open_archive_heap_oopmaps);
1905   }
1906 }
1907 
1908 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
1909                                                            GrowableArray<ArchiveHeapOopmapInfo>* oopmaps) {
1910   for (int i=0; i<regions->length(); i++) {
1911     ResourceBitMap oopmap = HeapShared::calculate_oopmap(regions->at(i));
1912     size_t size_in_bits = oopmap.size();
1913     size_t size_in_bytes = oopmap.size_in_bytes();
1914     uintptr_t* buffer = (uintptr_t*)_ro_region.allocate(size_in_bytes, sizeof(intptr_t));
1915     oopmap.write_to(buffer, size_in_bytes);
1916     log_info(cds, heap)("Oopmap = " INTPTR_FORMAT " (" SIZE_FORMAT_W(6) " bytes) for heap region "
1917                         INTPTR_FORMAT " (" SIZE_FORMAT_W(8) " bytes)",
1918                         p2i(buffer), size_in_bytes,
1919                         p2i(regions->at(i).start()), regions->at(i).byte_size());
1920 
1921     ArchiveHeapOopmapInfo info;
1922     info._oopmap = (address)buffer;
1923     info._oopmap_size_in_bits = size_in_bits;
1924     oopmaps->append(info);
1925   }
1926 }
1927 #endif // INCLUDE_CDS_JAVA_HEAP
1928 
1929 void ReadClosure::do_ptr(void** p) {
1930   assert(*p == NULL, "initializing previous initialized pointer.");
1931   intptr_t obj = nextPtr();
1932   assert((intptr_t)obj >= 0 || (intptr_t)obj < -100,
1933          "hit tag while initializing ptrs.");
1934   *p = (void*)obj;
1935 }
1936 
1937 void ReadClosure::do_u4(u4* p) {
1938   intptr_t obj = nextPtr();
1939   *p = (u4)(uintx(obj));
1940 }
1941 
1942 void ReadClosure::do_bool(bool* p) {
1943   intptr_t obj = nextPtr();
1944   *p = (bool)(uintx(obj));
1945 }
1946 
1947 void ReadClosure::do_tag(int tag) {
1948   int old_tag;
1949   old_tag = (int)(intptr_t)nextPtr();
1950   // do_int(&old_tag);
1951   assert(tag == old_tag, "old tag doesn't match");
1952   FileMapInfo::assert_mark(tag == old_tag);
1953 }
1954 
1955 void ReadClosure::do_oop(oop *p) {
1956   narrowOop o = (narrowOop)nextPtr();
1957   if (o == 0 || !HeapShared::open_archive_heap_region_mapped()) {
1958     p = NULL;
1959   } else {
1960     assert(HeapShared::is_heap_object_archiving_allowed(),
1961            "Archived heap object is not allowed");
1962     assert(HeapShared::open_archive_heap_region_mapped(),
1963            "Open archive heap region is not mapped");
1964     *p = HeapShared::decode_from_archive(o);
1965   }
1966 }
1967 
1968 void ReadClosure::do_region(u_char* start, size_t size) {
1969   assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
1970   assert(size % sizeof(intptr_t) == 0, "bad size");
1971   do_tag((int)size);
1972   while (size > 0) {
1973     *(intptr_t*)start = nextPtr();
1974     start += sizeof(intptr_t);
1975     size -= sizeof(intptr_t);
1976   }
1977 }
1978 
1979 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
1980   assert(base <= static_top && static_top <= top, "must be");
1981   _shared_metaspace_static_top = static_top;
1982   MetaspaceObj::set_shared_metaspace_range(base, top);
1983 }
1984 
1985 // Return true if given address is in the misc data region
1986 bool MetaspaceShared::is_in_shared_region(const void* p, int idx) {
1987   return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx);
1988 }
1989 
1990 bool MetaspaceShared::is_in_trampoline_frame(address addr) {
1991   if (UseSharedSpaces && is_in_shared_region(addr, MetaspaceShared::mc)) {
1992     return true;
1993   }
1994   return false;
1995 }
1996 
1997 bool MetaspaceShared::is_shared_dynamic(void* p) {
1998   if ((p < MetaspaceObj::shared_metaspace_top()) &&
1999       (p >= _shared_metaspace_static_top)) {
2000     return true;
2001   } else {
2002     return false;
2003   }
2004 }
2005 
2006 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
2007   assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");
2008   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
2009   FileMapInfo* static_mapinfo = open_static_archive();
2010   FileMapInfo* dynamic_mapinfo = NULL;
2011 
2012   if (static_mapinfo != NULL) {
2013     dynamic_mapinfo = open_dynamic_archive();
2014 
2015     // First try to map at the requested address
2016     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
2017     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
2018       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
2019       // by the OS.
2020       log_info(cds)("Try to map archive(s) at an alternative address");
2021       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
2022     }
2023   }
2024 
2025   if (result == MAP_ARCHIVE_SUCCESS) {
2026     bool dynamic_mapped = (dynamic_mapinfo != NULL && dynamic_mapinfo->is_mapped());
2027     char* cds_base = static_mapinfo->mapped_base();
2028     char* cds_end =  dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
2029     set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
2030     _relocation_delta = static_mapinfo->relocation_delta();
2031     if (dynamic_mapped) {
2032       FileMapInfo::set_shared_path_table(dynamic_mapinfo);
2033     } else {
2034       FileMapInfo::set_shared_path_table(static_mapinfo);
2035     }
2036   } else {
2037     set_shared_metaspace_range(NULL, NULL, NULL);
2038     UseSharedSpaces = false;
2039     FileMapInfo::fail_continue("Unable to map shared spaces");
2040     if (PrintSharedArchiveAndExit) {
2041       vm_exit_during_initialization("Unable to use shared archive.");
2042     }
2043   }
2044 
2045   if (static_mapinfo != NULL && !static_mapinfo->is_mapped()) {
2046     delete static_mapinfo;
2047   }
2048   if (dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped()) {
2049     delete dynamic_mapinfo;
2050   }
2051 }
2052 
2053 FileMapInfo* MetaspaceShared::open_static_archive() {
2054   FileMapInfo* mapinfo = new FileMapInfo(true);
2055   if (!mapinfo->initialize()) {
2056     delete(mapinfo);
2057     return NULL;
2058   }
2059   return mapinfo;
2060 }
2061 
2062 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
2063   if (DynamicDumpSharedSpaces) {
2064     return NULL;
2065   }
2066   if (Arguments::GetSharedDynamicArchivePath() == NULL) {
2067     return NULL;
2068   }
2069 
2070   FileMapInfo* mapinfo = new FileMapInfo(false);
2071   if (!mapinfo->initialize()) {
2072     delete(mapinfo);
2073     return NULL;
2074   }
2075   return mapinfo;
2076 }
2077 
2078 // use_requested_addr:
2079 //  true  = map at FileMapHeader::_requested_base_address
2080 //  false = map at an alternative address picked by OS.
2081 MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,
2082                                                bool use_requested_addr) {
2083   PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
2084       // For product build only -- this is for benchmarking the cost of doing relocation.
2085       // For debug builds, the check is done in FileMapInfo::map_regions for better test coverage.
2086       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
2087       return MAP_ARCHIVE_MMAP_FAILURE;
2088     });
2089 
2090   if (ArchiveRelocationMode == 2 && !use_requested_addr) {
2091     log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");
2092     return MAP_ARCHIVE_MMAP_FAILURE;
2093   };
2094 
2095   if (dynamic_mapinfo != NULL) {
2096     // Ensure that the OS won't be able to allocate new memory spaces between the two
2097     // archives, or else it would mess up the simple comparision in MetaspaceObj::is_shared().
2098     assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");
2099   }
2100 
2101   ReservedSpace main_rs, archive_space_rs, class_space_rs;
2102   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
2103   char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo, dynamic_mapinfo,
2104                                                                  use_requested_addr, main_rs, archive_space_rs,
2105                                                                  class_space_rs);
2106   if (mapped_base_address == NULL) {
2107     result = MAP_ARCHIVE_MMAP_FAILURE;
2108   } else {
2109     log_debug(cds)("Reserved archive_space_rs     [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
2110                    p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size());
2111     log_debug(cds)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
2112                    p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());
2113     MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);
2114     MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?
2115                                      map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;
2116 
2117     DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
2118       // This is for simulating mmap failures at the requested address. In debug builds, we do it
2119       // here (after all archives have possibly been mapped), so we can thoroughly test the code for
2120       // failure handling (releasing all allocated resource, etc).
2121       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
2122       if (static_result == MAP_ARCHIVE_SUCCESS) {
2123         static_result = MAP_ARCHIVE_MMAP_FAILURE;
2124       }
2125       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
2126         dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;
2127       }
2128     });
2129 
2130     if (static_result == MAP_ARCHIVE_SUCCESS) {
2131       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
2132         result = MAP_ARCHIVE_SUCCESS;
2133       } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {
2134         assert(dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped(), "must have failed");
2135         // No need to retry mapping the dynamic archive again, as it will never succeed
2136         // (bad file, etc) -- just keep the base archive.
2137         log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",
2138                                   dynamic_mapinfo->full_path());
2139         result = MAP_ARCHIVE_SUCCESS;
2140         // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no
2141         // easy API to do that right now.
2142       } else {
2143         result = MAP_ARCHIVE_MMAP_FAILURE;
2144       }
2145     } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {
2146       result = MAP_ARCHIVE_OTHER_FAILURE;
2147     } else {
2148       result = MAP_ARCHIVE_MMAP_FAILURE;
2149     }
2150   }
2151 
2152   if (result == MAP_ARCHIVE_SUCCESS) {
2153     if (!main_rs.is_reserved() && class_space_rs.is_reserved()) {
2154       MemTracker::record_virtual_memory_type((address)class_space_rs.base(), mtClass);
2155     }
2156     SharedBaseAddress = (size_t)mapped_base_address;
2157     LP64_ONLY({
2158         if (Metaspace::using_class_space()) {
2159           assert(class_space_rs.is_reserved(), "must be");
2160           char* cds_base = static_mapinfo->mapped_base();
2161           Metaspace::allocate_metaspace_compressed_klass_ptrs(class_space_rs, NULL, (address)cds_base);
2162           // map_heap_regions() compares the current narrow oop and klass encodings
2163           // with the archived ones, so it must be done after all encodings are determined.
2164           static_mapinfo->map_heap_regions();
2165           CompressedKlassPointers::set_range(CompressedClassSpaceSize);
2166         }
2167       });
2168   } else {
2169     unmap_archive(static_mapinfo);
2170     unmap_archive(dynamic_mapinfo);
2171     release_reserved_spaces(main_rs, archive_space_rs, class_space_rs);
2172   }
2173 
2174   return result;
2175 }
2176 
2177 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,
2178                                                           FileMapInfo* dynamic_mapinfo,
2179                                                           bool use_requested_addr,
2180                                                           ReservedSpace& main_rs,
2181                                                           ReservedSpace& archive_space_rs,
2182                                                           ReservedSpace& class_space_rs) {
2183   const bool use_klass_space = NOT_LP64(false) LP64_ONLY(Metaspace::using_class_space());
2184   const size_t class_space_size = NOT_LP64(0) LP64_ONLY(Metaspace::compressed_class_space_size());
2185 
2186   if (use_klass_space) {
2187     assert(class_space_size > 0, "CompressedClassSpaceSize must have been validated");
2188   }
2189   if (use_requested_addr && !is_aligned(static_mapinfo->requested_base_address(), reserved_space_alignment())) {
2190     return NULL;
2191   }
2192 
2193   // Size and requested location of the archive_space_rs (for both static and dynamic archives)
2194   size_t base_offset = static_mapinfo->mapping_base_offset();
2195   size_t end_offset  = (dynamic_mapinfo == NULL) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();
2196   assert(base_offset == 0, "must be");
2197   assert(is_aligned(end_offset,  os::vm_allocation_granularity()), "must be");
2198   assert(is_aligned(base_offset, os::vm_allocation_granularity()), "must be");
2199 
2200   // In case reserved_space_alignment() != os::vm_allocation_granularity()
2201   assert((size_t)os::vm_allocation_granularity() <= reserved_space_alignment(), "must be");
2202   end_offset = align_up(end_offset, reserved_space_alignment());
2203 
2204   size_t archive_space_size = end_offset - base_offset;
2205 
2206   // Special handling for Windows because it cannot mmap into a reserved space:
2207   //    use_requested_addr: We just map each region individually, and give up if any one of them fails.
2208   //   !use_requested_addr: We reserve the space first, and then os::read in all the regions (instead of mmap).
2209   //                        We're going to patch all the pointers anyway so there's no benefit for mmap.
2210 
2211   if (use_requested_addr) {
2212     char* archive_space_base = static_mapinfo->requested_base_address() + base_offset;
2213     char* archive_space_end  = archive_space_base + archive_space_size;
2214     if (!MetaspaceShared::use_windows_memory_mapping()) {
2215       archive_space_rs = reserve_shared_space(archive_space_size, archive_space_base);
2216       if (!archive_space_rs.is_reserved()) {
2217         return NULL;
2218       }
2219     }
2220     if (use_klass_space) {
2221       // Make sure we can map the klass space immediately following the archive_space space
2222       // Don't call reserve_shared_space here as that may try to enforce platform-specific
2223       // alignment rules which only apply to the archive base address
2224       char* class_space_base = archive_space_end;
2225       class_space_rs = ReservedSpace(class_space_size, reserved_space_alignment(),
2226                                      false /* large_pages */, class_space_base);
2227       if (!class_space_rs.is_reserved()) {
2228         return NULL;
2229       }
2230     }
2231     return static_mapinfo->requested_base_address();
2232   } else {
2233     if (use_klass_space) {
2234       main_rs = reserve_shared_space(archive_space_size + class_space_size);
2235       if (main_rs.is_reserved()) {
2236         archive_space_rs = main_rs.first_part(archive_space_size, reserved_space_alignment(), /*split=*/true);
2237         class_space_rs = main_rs.last_part(archive_space_size);
2238       }
2239     } else {
2240       main_rs = reserve_shared_space(archive_space_size);
2241       archive_space_rs = main_rs;
2242     }
2243     if (archive_space_rs.is_reserved()) {
2244       return archive_space_rs.base();
2245     } else {
2246       return NULL;
2247     }
2248   }
2249 }
2250 
2251 void MetaspaceShared::release_reserved_spaces(ReservedSpace& main_rs,
2252                                               ReservedSpace& archive_space_rs,
2253                                               ReservedSpace& class_space_rs) {
2254   if (main_rs.is_reserved()) {
2255     assert(main_rs.contains(archive_space_rs.base()), "must be");
2256     assert(main_rs.contains(class_space_rs.base()), "must be");
2257     log_debug(cds)("Released shared space (archive+classes) " INTPTR_FORMAT, p2i(main_rs.base()));
2258     main_rs.release();
2259   } else {
2260     if (archive_space_rs.is_reserved()) {
2261       log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
2262       archive_space_rs.release();
2263     }
2264     if (class_space_rs.is_reserved()) {
2265       log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
2266       class_space_rs.release();
2267     }
2268   }
2269 }
2270 
2271 static int archive_regions[]  = {MetaspaceShared::mc,
2272                                  MetaspaceShared::rw,
2273                                  MetaspaceShared::ro};
2274 static int archive_regions_count  = 3;
2275 
2276 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
2277   assert(UseSharedSpaces, "must be runtime");
2278   if (mapinfo == NULL) {
2279     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
2280   }
2281 
2282   mapinfo->set_is_mapped(false);
2283 
2284   if (mapinfo->alignment() != (size_t)os::vm_allocation_granularity()) {
2285     log_error(cds)("Unable to map CDS archive -- os::vm_allocation_granularity() expected: " SIZE_FORMAT
2286                    " actual: %d", mapinfo->alignment(), os::vm_allocation_granularity());
2287     return MAP_ARCHIVE_OTHER_FAILURE;
2288   }
2289 
2290   MapArchiveResult result =
2291     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
2292 
2293   if (result != MAP_ARCHIVE_SUCCESS) {
2294     unmap_archive(mapinfo);
2295     return result;
2296   }
2297 
2298   if (mapinfo->is_static()) {
2299     if (!mapinfo->validate_shared_path_table()) {
2300       unmap_archive(mapinfo);
2301       return MAP_ARCHIVE_OTHER_FAILURE;
2302     }
2303   } else {
2304     if (!DynamicArchive::validate(mapinfo)) {
2305       unmap_archive(mapinfo);
2306       return MAP_ARCHIVE_OTHER_FAILURE;
2307     }
2308   }
2309 
2310   mapinfo->set_is_mapped(true);
2311   return MAP_ARCHIVE_SUCCESS;
2312 }
2313 
2314 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) {
2315   assert(UseSharedSpaces, "must be runtime");
2316   if (mapinfo != NULL) {
2317     mapinfo->unmap_regions(archive_regions, archive_regions_count);
2318     mapinfo->set_is_mapped(false);
2319   }
2320 }
2321 
2322 // Read the miscellaneous data from the shared file, and
2323 // serialize it out to its various destinations.
2324 
2325 void MetaspaceShared::initialize_shared_spaces() {
2326   FileMapInfo *static_mapinfo = FileMapInfo::current_info();
2327   _i2i_entry_code_buffers = static_mapinfo->i2i_entry_code_buffers();
2328   _i2i_entry_code_buffers_size = static_mapinfo->i2i_entry_code_buffers_size();
2329   char* buffer = static_mapinfo->cloned_vtables();
2330   clone_cpp_vtables((intptr_t*)buffer);
2331 
2332   // Verify various attributes of the archive, plus initialize the
2333   // shared string/symbol tables
2334   buffer = static_mapinfo->serialized_data();
2335   intptr_t* array = (intptr_t*)buffer;
2336   ReadClosure rc(&array);
2337   serialize(&rc);
2338 
2339   // Initialize the run-time symbol table.
2340   SymbolTable::create_table();
2341 
2342   static_mapinfo->patch_archived_heap_embedded_pointers();
2343 
2344   // Close the mapinfo file
2345   static_mapinfo->close();
2346 
2347   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
2348   if (dynamic_mapinfo != NULL) {
2349     intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
2350     ReadClosure rc(&buffer);
2351     SymbolTable::serialize_shared_table_header(&rc, false);
2352     SystemDictionaryShared::serialize_dictionary_headers(&rc, false);
2353     dynamic_mapinfo->close();
2354   }
2355 
2356   if (PrintSharedArchiveAndExit) {
2357     if (PrintSharedDictionary) {
2358       tty->print_cr("\nShared classes:\n");
2359       SystemDictionaryShared::print_on(tty);
2360     }
2361     if (FileMapInfo::current_info() == NULL || _archive_loading_failed) {
2362       tty->print_cr("archive is invalid");
2363       vm_exit(1);
2364     } else {
2365       tty->print_cr("archive is valid");
2366       vm_exit(0);
2367     }
2368   }
2369 }
2370 
2371 // JVM/TI RedefineClasses() support:
2372 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
2373   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2374 
2375   if (UseSharedSpaces) {
2376     // remap the shared readonly space to shared readwrite, private
2377     FileMapInfo* mapinfo = FileMapInfo::current_info();
2378     if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2379       return false;
2380     }
2381     if (FileMapInfo::dynamic_info() != NULL) {
2382       mapinfo = FileMapInfo::dynamic_info();
2383       if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2384         return false;
2385       }
2386     }
2387     _remapped_readwrite = true;
2388   }
2389   return true;
2390 }
2391 
2392 void MetaspaceShared::report_out_of_space(const char* name, size_t needed_bytes) {
2393   // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space.
2394   // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes
2395   // or so.
2396   _mc_region.print_out_of_space_msg(name, needed_bytes);
2397   _rw_region.print_out_of_space_msg(name, needed_bytes);
2398   _ro_region.print_out_of_space_msg(name, needed_bytes);
2399 
2400   vm_exit_during_initialization(err_msg("Unable to allocate from '%s' region", name),
2401                                 "Please reduce the number of shared classes.");
2402 }
2403 
2404 // This is used to relocate the pointers so that the archive can be mapped at
2405 // Arguments::default_SharedBaseAddress() without runtime relocation.
2406 intx MetaspaceShared::final_delta() {
2407   return intx(Arguments::default_SharedBaseAddress())  // We want the archive to be mapped to here at runtime
2408        - intx(SharedBaseAddress);                      // .. but the archive is mapped at here at dump time
2409 }