1 /*
   2  * Copyright (c) 2012, 2016, 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 "classfile/classListParser.hpp"
  27 #include "classfile/classLoaderExt.hpp"
  28 #include "classfile/dictionary.hpp"
  29 #include "classfile/loaderConstraints.hpp"
  30 #include "classfile/placeholders.hpp"
  31 #include "classfile/sharedClassUtil.hpp"
  32 #include "classfile/symbolTable.hpp"
  33 #include "classfile/systemDictionary.hpp"
  34 #include "classfile/systemDictionaryShared.hpp"
  35 #include "code/codeCache.hpp"
  36 #include "gc/shared/gcLocker.hpp"
  37 #include "interpreter/bytecodeStream.hpp"
  38 #include "interpreter/bytecodes.hpp"
  39 #include "memory/filemap.hpp"
  40 #include "memory/metaspace.hpp"
  41 #include "memory/metaspaceShared.hpp"
  42 #include "memory/resourceArea.hpp"
  43 #include "oops/objArrayOop.hpp"
  44 #include "oops/oop.inline.hpp"
  45 #include "runtime/timerTrace.hpp"
  46 #include "runtime/os.hpp"
  47 #include "runtime/signature.hpp"
  48 #include "runtime/vmThread.hpp"
  49 #include "runtime/vm_operations.hpp"
  50 #include "utilities/defaultStream.hpp"
  51 #include "utilities/hashtable.inline.hpp"
  52 
  53 int MetaspaceShared::_max_alignment = 0;
  54 
  55 ReservedSpace* MetaspaceShared::_shared_rs = NULL;
  56 
  57 MetaspaceSharedStats MetaspaceShared::_stats;
  58 
  59 bool MetaspaceShared::_link_classes_made_progress;
  60 bool MetaspaceShared::_check_classes_made_progress;
  61 bool MetaspaceShared::_has_error_classes;
  62 bool MetaspaceShared::_archive_loading_failed = false;
  63 bool MetaspaceShared::_remapped_readwrite = false;
  64 address MetaspaceShared::_cds_i2i_entry_code_buffers = NULL;
  65 size_t MetaspaceShared::_cds_i2i_entry_code_buffers_size = 0;
  66 SharedMiscRegion MetaspaceShared::_mc;
  67 SharedMiscRegion MetaspaceShared::_md;
  68 SharedMiscRegion MetaspaceShared::_od;
  69 
  70 void SharedMiscRegion::initialize(ReservedSpace rs, size_t committed_byte_size,  SharedSpaceType space_type) {
  71   _vs.initialize(rs, committed_byte_size);
  72   _alloc_top = _vs.low();
  73   _space_type = space_type;
  74 }
  75 
  76 // NOT thread-safe, but this is called during dump time in single-threaded mode.
  77 char* SharedMiscRegion::alloc(size_t num_bytes) {
  78   assert(DumpSharedSpaces, "dump time only");
  79   size_t alignment = sizeof(char*);
  80   num_bytes = align_size_up(num_bytes, alignment);
  81   _alloc_top = (char*)align_ptr_up(_alloc_top, alignment);
  82   if (_alloc_top + num_bytes > _vs.high()) {
  83     report_out_of_shared_space(_space_type);
  84   }
  85 
  86   char* p = _alloc_top;
  87   _alloc_top += num_bytes;
  88 
  89   memset(p, 0, num_bytes);
  90   return p;
  91 }
  92 
  93 void MetaspaceShared::initialize_shared_rs(ReservedSpace* rs) {
  94   assert(DumpSharedSpaces, "dump time only");
  95   _shared_rs = rs;
  96 
  97   size_t core_spaces_size = FileMapInfo::core_spaces_size();
  98   size_t metadata_size = SharedReadOnlySize + SharedReadWriteSize;
  99 
 100   // Split into the core and optional sections
 101   ReservedSpace core_data = _shared_rs->first_part(core_spaces_size);
 102   ReservedSpace optional_data = _shared_rs->last_part(core_spaces_size);
 103 
 104   // The RO/RW and the misc sections
 105   ReservedSpace shared_ro_rw = core_data.first_part(metadata_size);
 106   ReservedSpace misc_section = core_data.last_part(metadata_size);
 107 
 108   // Now split the misc code and misc data sections.
 109   ReservedSpace md_rs   = misc_section.first_part(SharedMiscDataSize);
 110   ReservedSpace mc_rs   = misc_section.last_part(SharedMiscDataSize);
 111 
 112   _md.initialize(md_rs, SharedMiscDataSize, SharedMiscData);
 113   _mc.initialize(mc_rs, SharedMiscCodeSize, SharedMiscCode);
 114   _od.initialize(optional_data, metadata_size, SharedOptional);
 115 }
 116 
 117 // Read/write a data stream for restoring/preserving metadata pointers and
 118 // miscellaneous data from/to the shared archive file.
 119 
 120 void MetaspaceShared::serialize(SerializeClosure* soc, GrowableArray<MemRegion> *string_space,
 121                                 size_t* space_size) {
 122   int tag = 0;
 123   soc->do_tag(--tag);
 124 
 125   // Verify the sizes of various metadata in the system.
 126   soc->do_tag(sizeof(Method));
 127   soc->do_tag(sizeof(ConstMethod));
 128   soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
 129   soc->do_tag(sizeof(ConstantPool));
 130   soc->do_tag(sizeof(ConstantPoolCache));
 131   soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
 132   soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
 133   soc->do_tag(sizeof(Symbol));
 134 
 135   // Dump/restore miscellaneous metadata.
 136   Universe::serialize(soc, true);
 137   soc->do_tag(--tag);
 138 
 139   // Dump/restore references to commonly used names and signatures.
 140   vmSymbols::serialize(soc);
 141   soc->do_tag(--tag);
 142 
 143   // Dump/restore the symbol and string tables
 144   SymbolTable::serialize(soc);
 145   StringTable::serialize(soc, string_space, space_size);
 146   soc->do_tag(--tag);
 147 
 148   soc->do_tag(666);
 149 }
 150 
 151 address MetaspaceShared::cds_i2i_entry_code_buffers(size_t total_size) {
 152   if (DumpSharedSpaces) {
 153     if (_cds_i2i_entry_code_buffers == NULL) {
 154       _cds_i2i_entry_code_buffers = (address)misc_data_space_alloc(total_size);
 155       _cds_i2i_entry_code_buffers_size = total_size;
 156     }
 157   } else if (UseSharedSpaces) {
 158     assert(_cds_i2i_entry_code_buffers != NULL, "must already been initialized");
 159   } else {
 160     return NULL;
 161   }
 162 
 163   assert(_cds_i2i_entry_code_buffers_size == total_size, "must not change");
 164   return _cds_i2i_entry_code_buffers;
 165 }
 166 
 167 // CDS code for dumping shared archive.
 168 
 169 // Global object for holding classes that have been loaded.  Since this
 170 // is run at a safepoint just before exit, this is the entire set of classes.
 171 static GrowableArray<Klass*>* _global_klass_objects;
 172 static void collect_classes(Klass* k) {
 173   _global_klass_objects->append_if_missing(k);
 174   if (k->is_instance_klass()) {
 175     // Add in the array classes too
 176     InstanceKlass* ik = InstanceKlass::cast(k);
 177     ik->array_klasses_do(collect_classes);
 178   }
 179 }
 180 
 181 static void collect_classes2(Klass* k, ClassLoaderData* class_data) {
 182   collect_classes(k);
 183 }
 184 
 185 static void remove_unshareable_in_classes() {
 186   for (int i = 0; i < _global_klass_objects->length(); i++) {
 187     Klass* k = _global_klass_objects->at(i);
 188     k->remove_unshareable_info();
 189   }
 190 }
 191 
 192 static void rewrite_nofast_bytecode(Method* method) {
 193   RawBytecodeStream bcs(method);
 194   while (!bcs.is_last_bytecode()) {
 195     Bytecodes::Code opcode = bcs.raw_next();
 196     switch (opcode) {
 197     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
 198     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;
 199     case Bytecodes::_aload_0:       *bcs.bcp() = Bytecodes::_nofast_aload_0;       break;
 200     case Bytecodes::_iload: {
 201       if (!bcs.is_wide()) {
 202         *bcs.bcp() = Bytecodes::_nofast_iload;
 203       }
 204       break;
 205     }
 206     default: break;
 207     }
 208   }
 209 }
 210 
 211 // Walk all methods in the class list to ensure that they won't be modified at
 212 // run time. This includes:
 213 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified
 214 //     at run time by RewriteBytecodes/RewriteFrequentPairs
 215 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.
 216 static void rewrite_nofast_bytecodes_and_calculate_fingerprints() {
 217   for (int i = 0; i < _global_klass_objects->length(); i++) {
 218     Klass* k = _global_klass_objects->at(i);
 219     if (k->is_instance_klass()) {
 220       InstanceKlass* ik = InstanceKlass::cast(k);
 221       for (int i = 0; i < ik->methods()->length(); i++) {
 222         Method* m = ik->methods()->at(i);
 223         rewrite_nofast_bytecode(m);
 224         Fingerprinter fp(m);
 225         // The side effect of this call sets method's fingerprint field.
 226         fp.fingerprint();
 227       }
 228     }
 229   }
 230 }
 231 
 232 // Patch C++ vtable pointer in metadata.
 233 
 234 // Klass and other metadata objects contain references to c++ vtables in the
 235 // JVM library.
 236 // Fix them to point to our constructed vtables.  However, don't iterate
 237 // across the space while doing this, as that causes the vtables to be
 238 // patched, undoing our useful work.  Instead, iterate to make a list,
 239 // then use the list to do the fixing.
 240 //
 241 // Our constructed vtables:
 242 // Dump time:
 243 //  1. init_self_patching_vtbl_list: table of pointers to current virtual method addrs
 244 //  2. generate_vtable_methods: create jump table, appended to above vtbl_list
 245 //  3. patch_klass_vtables: for Klass list, patch the vtable entry in klass and
 246 //     associated metadata to point to jump table rather than to current vtbl
 247 // Table layout: NOTE FIXED SIZE
 248 //   1. vtbl pointers
 249 //   2. #Klass X #virtual methods per Klass
 250 //   1 entry for each, in the order:
 251 //   Klass1:method1 entry, Klass1:method2 entry, ... Klass1:method<num_virtuals> entry
 252 //   Klass2:method1 entry, Klass2:method2 entry, ... Klass2:method<num_virtuals> entry
 253 //   ...
 254 //   Klass<vtbl_list_size>:method1 entry, Klass<vtbl_list_size>:method2 entry,
 255 //       ... Klass<vtbl_list_size>:method<num_virtuals> entry
 256 //  Sample entry: (Sparc):
 257 //   save(sp, -256, sp)
 258 //   ba,pt common_code
 259 //   mov XXX, %L0       %L0 gets: Klass index <<8 + method index (note: max method index 255)
 260 //
 261 // Restore time:
 262 //   1. initialize_shared_space: reserve space for table
 263 //   2. init_self_patching_vtbl_list: update pointers to NEW virtual method addrs in text
 264 //
 265 // Execution time:
 266 //   First virtual method call for any object of these metadata types:
 267 //   1. object->klass
 268 //   2. vtable entry for that klass points to the jump table entries
 269 //   3. branches to common_code with %O0/klass, %L0: Klass index <<8 + method index
 270 //   4. common_code:
 271 //      Get address of new vtbl pointer for this Klass from updated table
 272 //      Update new vtbl pointer in the Klass: future virtual calls go direct
 273 //      Jump to method, using new vtbl pointer and method index
 274 
 275 
 276 static void* find_matching_vtbl_ptr(void** vtbl_list, void* new_vtable_start, void* obj) {
 277   void* old_vtbl_ptr = *(void**)obj;
 278   for (int i = 0; i < MetaspaceShared::vtbl_list_size; i++) {
 279     if (vtbl_list[i] == old_vtbl_ptr) {
 280       return (void**)new_vtable_start + i * MetaspaceShared::num_virtuals;
 281     }
 282   }
 283   ShouldNotReachHere();
 284   return NULL;
 285 }
 286 
 287 // Assumes the vtable is in first slot in object.
 288 static void patch_klass_vtables(void** vtbl_list, void* new_vtable_start) {
 289   int n = _global_klass_objects->length();
 290   for (int i = 0; i < n; i++) {
 291     Klass* obj = _global_klass_objects->at(i);
 292     // Note is_instance_klass() is a virtual call in debug.  After patching vtables
 293     // all virtual calls on the dummy vtables will restore the original!
 294     if (obj->is_instance_klass()) {
 295       InstanceKlass* ik = InstanceKlass::cast(obj);
 296       *(void**)ik = find_matching_vtbl_ptr(vtbl_list, new_vtable_start, ik);
 297       ConstantPool* cp = ik->constants();
 298       *(void**)cp = find_matching_vtbl_ptr(vtbl_list, new_vtable_start, cp);
 299       for (int j = 0; j < ik->methods()->length(); j++) {
 300         Method* m = ik->methods()->at(j);
 301         *(void**)m = find_matching_vtbl_ptr(vtbl_list, new_vtable_start, m);
 302       }
 303     } else {
 304       // Array klasses
 305       Klass* k = obj;
 306       *(void**)k = find_matching_vtbl_ptr(vtbl_list, new_vtable_start, k);
 307     }
 308   }
 309 }
 310 
 311 // Closure for serializing initialization data out to a data area to be
 312 // written to the shared file.
 313 
 314 class WriteClosure : public SerializeClosure {
 315 private:
 316   intptr_t* top;
 317   char* end;
 318 
 319   inline void check_space() {
 320     if ((char*)top + sizeof(intptr_t) > end) {
 321       report_out_of_shared_space(SharedMiscData);
 322     }
 323   }
 324 
 325 public:
 326   WriteClosure(char* md_top, char* md_end) {
 327     top = (intptr_t*)md_top;
 328     end = md_end;
 329   }
 330 
 331   char* get_top() { return (char*)top; }
 332 
 333   void do_ptr(void** p) {
 334     check_space();
 335     *top = (intptr_t)*p;
 336     ++top;
 337   }
 338 
 339   void do_u4(u4* p) {
 340     void* ptr = (void*)(uintx(*p));
 341     do_ptr(&ptr);
 342   }
 343 
 344   void do_tag(int tag) {
 345     check_space();
 346     *top = (intptr_t)tag;
 347     ++top;
 348   }
 349 
 350   void do_region(u_char* start, size_t size) {
 351     if ((char*)top + size > end) {
 352       report_out_of_shared_space(SharedMiscData);
 353     }
 354     assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
 355     assert(size % sizeof(intptr_t) == 0, "bad size");
 356     do_tag((int)size);
 357     while (size > 0) {
 358       *top = *(intptr_t*)start;
 359       ++top;
 360       start += sizeof(intptr_t);
 361       size -= sizeof(intptr_t);
 362     }
 363   }
 364 
 365   bool reading() const { return false; }
 366 };
 367 
 368 // This is for dumping detailed statistics for the allocations
 369 // in the shared spaces.
 370 class DumpAllocClosure : public Metaspace::AllocRecordClosure {
 371 public:
 372 
 373   // Here's poor man's enum inheritance
 374 #define SHAREDSPACE_OBJ_TYPES_DO(f) \
 375   METASPACE_OBJ_TYPES_DO(f) \
 376   f(SymbolHashentry) \
 377   f(SymbolBucket) \
 378   f(StringHashentry) \
 379   f(StringBucket) \
 380   f(Other)
 381 
 382 #define SHAREDSPACE_OBJ_TYPE_DECLARE(name) name ## Type,
 383 #define SHAREDSPACE_OBJ_TYPE_NAME_CASE(name) case name ## Type: return #name;
 384 
 385   enum Type {
 386     // Types are MetaspaceObj::ClassType, MetaspaceObj::SymbolType, etc
 387     SHAREDSPACE_OBJ_TYPES_DO(SHAREDSPACE_OBJ_TYPE_DECLARE)
 388     _number_of_types
 389   };
 390 
 391   static const char * type_name(Type type) {
 392     switch(type) {
 393     SHAREDSPACE_OBJ_TYPES_DO(SHAREDSPACE_OBJ_TYPE_NAME_CASE)
 394     default:
 395       ShouldNotReachHere();
 396       return NULL;
 397     }
 398   }
 399 
 400 public:
 401   enum {
 402     RO = 0,
 403     RW = 1
 404   };
 405 
 406   int _counts[2][_number_of_types];
 407   int _bytes [2][_number_of_types];
 408   int _which;
 409 
 410   DumpAllocClosure() {
 411     memset(_counts, 0, sizeof(_counts));
 412     memset(_bytes,  0, sizeof(_bytes));
 413   };
 414 
 415   void iterate_metaspace(Metaspace* space, int which) {
 416     assert(which == RO || which == RW, "sanity");
 417     _which = which;
 418     space->iterate(this);
 419   }
 420 
 421   virtual void doit(address ptr, MetaspaceObj::Type type, int byte_size) {
 422     assert(int(type) >= 0 && type < MetaspaceObj::_number_of_types, "sanity");
 423     _counts[_which][type] ++;
 424     _bytes [_which][type] += byte_size;
 425   }
 426 
 427   void dump_stats(int ro_all, int rw_all, int md_all, int mc_all);
 428 };
 429 
 430 void DumpAllocClosure::dump_stats(int ro_all, int rw_all, int md_all, int mc_all) {
 431   rw_all += (md_all + mc_all); // md and mc are all mapped Read/Write
 432   int other_bytes = md_all + mc_all;
 433 
 434   // Calculate size of data that was not allocated by Metaspace::allocate()
 435   MetaspaceSharedStats *stats = MetaspaceShared::stats();
 436 
 437   // symbols
 438   _counts[RO][SymbolHashentryType] = stats->symbol.hashentry_count;
 439   _bytes [RO][SymbolHashentryType] = stats->symbol.hashentry_bytes;
 440   _bytes [RO][TypeArrayU4Type]    -= stats->symbol.hashentry_bytes;
 441 
 442   _counts[RO][SymbolBucketType] = stats->symbol.bucket_count;
 443   _bytes [RO][SymbolBucketType] = stats->symbol.bucket_bytes;
 444   _bytes [RO][TypeArrayU4Type] -= stats->symbol.bucket_bytes;
 445 
 446   // strings
 447   _counts[RO][StringHashentryType] = stats->string.hashentry_count;
 448   _bytes [RO][StringHashentryType] = stats->string.hashentry_bytes;
 449   _bytes [RO][TypeArrayU4Type]    -= stats->string.hashentry_bytes;
 450 
 451   _counts[RO][StringBucketType] = stats->string.bucket_count;
 452   _bytes [RO][StringBucketType] = stats->string.bucket_bytes;
 453   _bytes [RO][TypeArrayU4Type] -= stats->string.bucket_bytes;
 454 
 455   // TODO: count things like dictionary, vtable, etc
 456   _bytes[RW][OtherType] =  other_bytes;
 457 
 458   // prevent divide-by-zero
 459   if (ro_all < 1) {
 460     ro_all = 1;
 461   }
 462   if (rw_all < 1) {
 463     rw_all = 1;
 464   }
 465 
 466   int all_ro_count = 0;
 467   int all_ro_bytes = 0;
 468   int all_rw_count = 0;
 469   int all_rw_bytes = 0;
 470 
 471 // To make fmt_stats be a syntactic constant (for format warnings), use #define.
 472 #define fmt_stats "%-20s: %8d %10d %5.1f | %8d %10d %5.1f | %8d %10d %5.1f"
 473   const char *sep = "--------------------+---------------------------+---------------------------+--------------------------";
 474   const char *hdr = "                        ro_cnt   ro_bytes     % |   rw_cnt   rw_bytes     % |  all_cnt  all_bytes     %";
 475 
 476   tty->print_cr("Detailed metadata info (rw includes md and mc):");
 477   tty->print_cr("%s", hdr);
 478   tty->print_cr("%s", sep);
 479   for (int type = 0; type < int(_number_of_types); type ++) {
 480     const char *name = type_name((Type)type);
 481     int ro_count = _counts[RO][type];
 482     int ro_bytes = _bytes [RO][type];
 483     int rw_count = _counts[RW][type];
 484     int rw_bytes = _bytes [RW][type];
 485     int count = ro_count + rw_count;
 486     int bytes = ro_bytes + rw_bytes;
 487 
 488     double ro_perc = 100.0 * double(ro_bytes) / double(ro_all);
 489     double rw_perc = 100.0 * double(rw_bytes) / double(rw_all);
 490     double perc    = 100.0 * double(bytes)    / double(ro_all + rw_all);
 491 
 492     tty->print_cr(fmt_stats, name,
 493                   ro_count, ro_bytes, ro_perc,
 494                   rw_count, rw_bytes, rw_perc,
 495                   count, bytes, perc);
 496 
 497     all_ro_count += ro_count;
 498     all_ro_bytes += ro_bytes;
 499     all_rw_count += rw_count;
 500     all_rw_bytes += rw_bytes;
 501   }
 502 
 503   int all_count = all_ro_count + all_rw_count;
 504   int all_bytes = all_ro_bytes + all_rw_bytes;
 505 
 506   double all_ro_perc = 100.0 * double(all_ro_bytes) / double(ro_all);
 507   double all_rw_perc = 100.0 * double(all_rw_bytes) / double(rw_all);
 508   double all_perc    = 100.0 * double(all_bytes)    / double(ro_all + rw_all);
 509 
 510   tty->print_cr("%s", sep);
 511   tty->print_cr(fmt_stats, "Total",
 512                 all_ro_count, all_ro_bytes, all_ro_perc,
 513                 all_rw_count, all_rw_bytes, all_rw_perc,
 514                 all_count, all_bytes, all_perc);
 515 
 516   assert(all_ro_bytes == ro_all, "everything should have been counted");
 517   assert(all_rw_bytes == rw_all, "everything should have been counted");
 518 #undef fmt_stats
 519 }
 520 
 521 // Populate the shared space.
 522 
 523 class VM_PopulateDumpSharedSpace: public VM_Operation {
 524 private:
 525   ClassLoaderData* _loader_data;
 526   GrowableArray<Klass*> *_class_promote_order;
 527   VirtualSpace _md_vs;
 528   VirtualSpace _mc_vs;
 529   VirtualSpace _od_vs;
 530   GrowableArray<MemRegion> *_string_regions;
 531 
 532 public:
 533   VM_PopulateDumpSharedSpace(ClassLoaderData* loader_data,
 534                              GrowableArray<Klass*> *class_promote_order) :
 535     _loader_data(loader_data) {
 536     _class_promote_order = class_promote_order;
 537   }
 538 
 539   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
 540   void doit();   // outline because gdb sucks
 541 
 542 private:
 543   void handle_misc_data_space_failure(bool success) {
 544     if (!success) {
 545       report_out_of_shared_space(SharedMiscData);
 546     }
 547   }
 548 }; // class VM_PopulateDumpSharedSpace
 549 
 550 void VM_PopulateDumpSharedSpace::doit() {
 551   Thread* THREAD = VMThread::vm_thread();
 552   NOT_PRODUCT(SystemDictionary::verify();)
 553   // The following guarantee is meant to ensure that no loader constraints
 554   // exist yet, since the constraints table is not shared.  This becomes
 555   // more important now that we don't re-initialize vtables/itables for
 556   // shared classes at runtime, where constraints were previously created.
 557   guarantee(SystemDictionary::constraints()->number_of_entries() == 0,
 558             "loader constraints are not saved");
 559   guarantee(SystemDictionary::placeholders()->number_of_entries() == 0,
 560           "placeholders are not saved");
 561   // Revisit and implement this if we prelink method handle call sites:
 562   guarantee(SystemDictionary::invoke_method_table() == NULL ||
 563             SystemDictionary::invoke_method_table()->number_of_entries() == 0,
 564             "invoke method table is not saved");
 565 
 566   // At this point, many classes have been loaded.
 567   // Gather systemDictionary classes in a global array and do everything to
 568   // that so we don't have to walk the SystemDictionary again.
 569   _global_klass_objects = new GrowableArray<Klass*>(1000);
 570   Universe::basic_type_classes_do(collect_classes);
 571 
 572   // Need to call SystemDictionary::classes_do(void f(Klass*, ClassLoaderData*))
 573   // as we may have some classes with NULL ClassLoaderData* in the dictionary. Other
 574   // variants of SystemDictionary::classes_do will skip those classes.
 575   SystemDictionary::classes_do(collect_classes2);
 576 
 577   tty->print_cr("Number of classes %d", _global_klass_objects->length());
 578   {
 579     int num_type_array = 0, num_obj_array = 0, num_inst = 0;
 580     for (int i = 0; i < _global_klass_objects->length(); i++) {
 581       Klass* k = _global_klass_objects->at(i);
 582       if (k->is_instance_klass()) {
 583         num_inst ++;
 584       } else if (k->is_objArray_klass()) {
 585         num_obj_array ++;
 586       } else {
 587         assert(k->is_typeArray_klass(), "sanity");
 588         num_type_array ++;
 589       }
 590     }
 591     tty->print_cr("    instance classes   = %5d", num_inst);
 592     tty->print_cr("    obj array classes  = %5d", num_obj_array);
 593     tty->print_cr("    type array classes = %5d", num_type_array);
 594   }
 595 
 596 
 597   // Ensure the ConstMethods won't be modified at run-time
 598   tty->print("Updating ConstMethods ... ");
 599   rewrite_nofast_bytecodes_and_calculate_fingerprints();
 600   tty->print_cr("done. ");
 601 
 602   // Remove all references outside the metadata
 603   tty->print("Removing unshareable information ... ");
 604   remove_unshareable_in_classes();
 605   tty->print_cr("done. ");
 606 
 607   // Set up the misc data, misc code and optional data segments.
 608   _md_vs = *MetaspaceShared::misc_data_region()->virtual_space();
 609   _mc_vs = *MetaspaceShared::misc_code_region()->virtual_space();
 610   _od_vs = *MetaspaceShared::optional_data_region()->virtual_space();
 611   char* md_low = _md_vs.low();
 612   char* md_top = MetaspaceShared::misc_data_region()->alloc_top();
 613   char* md_end = _md_vs.high();
 614   char* mc_low = _mc_vs.low();
 615   char* mc_top = MetaspaceShared::misc_code_region()->alloc_top();
 616   char* mc_end = _mc_vs.high();
 617   char* od_low = _od_vs.low();
 618   char* od_top = MetaspaceShared::optional_data_region()->alloc_top();
 619   char* od_end = _od_vs.high();
 620 
 621   // Reserve space for the list of Klass*s whose vtables are used
 622   // for patching others as needed.
 623 
 624   void** vtbl_list = (void**)md_top;
 625   int vtbl_list_size = MetaspaceShared::vtbl_list_size;
 626   Universe::init_self_patching_vtbl_list(vtbl_list, vtbl_list_size);
 627 
 628   md_top += vtbl_list_size * sizeof(void*);
 629   void* vtable = md_top;
 630 
 631   // Reserve space for a new dummy vtable for klass objects in the
 632   // heap.  Generate self-patching vtable entries.
 633 
 634   MetaspaceShared::generate_vtable_methods(vtbl_list, &vtable,
 635                                      &md_top, md_end,
 636                                      &mc_top, mc_end);
 637 
 638   guarantee(md_top <= md_end, "Insufficient space for vtables.");
 639 
 640   // Reorder the system dictionary.  (Moving the symbols affects
 641   // how the hash table indices are calculated.)
 642   // Not doing this either.
 643 
 644   SystemDictionary::reorder_dictionary();
 645   NOT_PRODUCT(SystemDictionary::verify();)
 646   SystemDictionary::reverse();
 647   SystemDictionary::copy_buckets(&md_top, md_end);
 648 
 649   SystemDictionary::copy_table(&md_top, md_end);
 650 
 651   // Write the other data to the output array.
 652   // SymbolTable, StringTable and extra information for system dictionary
 653   NOT_PRODUCT(SymbolTable::verify());
 654   NOT_PRODUCT(StringTable::verify());
 655   size_t ss_bytes = 0;
 656   char* ss_low;
 657   // The string space has maximum two regions. See FileMapInfo::write_string_regions() for details.
 658   _string_regions = new GrowableArray<MemRegion>(2);
 659 
 660   WriteClosure wc(md_top, md_end);
 661   MetaspaceShared::serialize(&wc, _string_regions, &ss_bytes);
 662   md_top = wc.get_top();
 663   ss_low = _string_regions->is_empty() ? NULL : (char*)_string_regions->first().start();
 664 
 665   // Print shared spaces all the time
 666   Metaspace* ro_space = _loader_data->ro_metaspace();
 667   Metaspace* rw_space = _loader_data->rw_metaspace();
 668 
 669   // Allocated size of each space (may not be all occupied)
 670   const size_t ro_alloced = ro_space->capacity_bytes_slow(Metaspace::NonClassType);
 671   const size_t rw_alloced = rw_space->capacity_bytes_slow(Metaspace::NonClassType);
 672   const size_t md_alloced = md_end-md_low;
 673   const size_t mc_alloced = mc_end-mc_low;
 674   const size_t od_alloced = od_end-od_low;
 675   const size_t total_alloced = ro_alloced + rw_alloced + md_alloced + mc_alloced
 676                              + ss_bytes + od_alloced;
 677 
 678   // Occupied size of each space.
 679   const size_t ro_bytes = ro_space->used_bytes_slow(Metaspace::NonClassType);
 680   const size_t rw_bytes = rw_space->used_bytes_slow(Metaspace::NonClassType);
 681   const size_t md_bytes = size_t(md_top - md_low);
 682   const size_t mc_bytes = size_t(mc_top - mc_low);
 683   const size_t od_bytes = size_t(od_top - od_low);
 684 
 685   // Percent of total size
 686   const size_t total_bytes = ro_bytes + rw_bytes + md_bytes + mc_bytes + ss_bytes + od_bytes;
 687   const double ro_t_perc = ro_bytes / double(total_bytes) * 100.0;
 688   const double rw_t_perc = rw_bytes / double(total_bytes) * 100.0;
 689   const double md_t_perc = md_bytes / double(total_bytes) * 100.0;
 690   const double mc_t_perc = mc_bytes / double(total_bytes) * 100.0;
 691   const double ss_t_perc = ss_bytes / double(total_bytes) * 100.0;
 692   const double od_t_perc = od_bytes / double(total_bytes) * 100.0;
 693 
 694   // Percent of fullness of each space
 695   const double ro_u_perc = ro_bytes / double(ro_alloced) * 100.0;
 696   const double rw_u_perc = rw_bytes / double(rw_alloced) * 100.0;
 697   const double md_u_perc = md_bytes / double(md_alloced) * 100.0;
 698   const double mc_u_perc = mc_bytes / double(mc_alloced) * 100.0;
 699   const double od_u_perc = od_bytes / double(od_alloced) * 100.0;
 700   const double total_u_perc = total_bytes / double(total_alloced) * 100.0;
 701 
 702 #define fmt_space "%s space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used] at " INTPTR_FORMAT
 703   tty->print_cr(fmt_space, "ro", ro_bytes, ro_t_perc, ro_alloced, ro_u_perc, p2i(ro_space->bottom()));
 704   tty->print_cr(fmt_space, "rw", rw_bytes, rw_t_perc, rw_alloced, rw_u_perc, p2i(rw_space->bottom()));
 705   tty->print_cr(fmt_space, "md", md_bytes, md_t_perc, md_alloced, md_u_perc, p2i(md_low));
 706   tty->print_cr(fmt_space, "mc", mc_bytes, mc_t_perc, mc_alloced, mc_u_perc, p2i(mc_low));
 707   tty->print_cr(fmt_space, "st", ss_bytes, ss_t_perc, ss_bytes,   100.0,     p2i(ss_low));
 708   tty->print_cr(fmt_space, "od", od_bytes, od_t_perc, od_alloced, od_u_perc, p2i(od_low));
 709   tty->print_cr("total   : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]",
 710                  total_bytes, total_alloced, total_u_perc);
 711 
 712   // Update the vtable pointers in all of the Klass objects in the
 713   // heap. They should point to newly generated vtable.
 714   patch_klass_vtables(vtbl_list, vtable);
 715 
 716   // dunno what this is for.
 717   char* saved_vtbl = (char*)os::malloc(vtbl_list_size * sizeof(void*), mtClass);
 718   memmove(saved_vtbl, vtbl_list, vtbl_list_size * sizeof(void*));
 719   memset(vtbl_list, 0, vtbl_list_size * sizeof(void*));
 720 
 721   // Create and write the archive file that maps the shared spaces.
 722 
 723   FileMapInfo* mapinfo = new FileMapInfo();
 724   mapinfo->populate_header(MetaspaceShared::max_alignment());
 725   mapinfo->set_misc_data_patching_start((char*)vtbl_list);
 726   mapinfo->set_cds_i2i_entry_code_buffers(MetaspaceShared::cds_i2i_entry_code_buffers());
 727   mapinfo->set_cds_i2i_entry_code_buffers_size(MetaspaceShared::cds_i2i_entry_code_buffers_size());
 728 
 729   for (int pass=1; pass<=2; pass++) {
 730     if (pass == 1) {
 731       // The first pass doesn't actually write the data to disk. All it
 732       // does is to update the fields in the mapinfo->_header.
 733     } else {
 734       // After the first pass, the contents of mapinfo->_header are finalized,
 735       // so we can compute the header's CRC, and write the contents of the header
 736       // and the regions into disk.
 737       mapinfo->open_for_write();
 738       mapinfo->set_header_crc(mapinfo->compute_header_crc());
 739     }
 740     mapinfo->write_header();
 741     mapinfo->write_space(MetaspaceShared::ro, _loader_data->ro_metaspace(), true);
 742     mapinfo->write_space(MetaspaceShared::rw, _loader_data->rw_metaspace(), false);
 743     mapinfo->write_region(MetaspaceShared::md, _md_vs.low(),
 744                           pointer_delta(md_top, _md_vs.low(), sizeof(char)),
 745                           SharedMiscDataSize,
 746                           false, true);
 747     mapinfo->write_region(MetaspaceShared::mc, _mc_vs.low(),
 748                           pointer_delta(mc_top, _mc_vs.low(), sizeof(char)),
 749                           SharedMiscCodeSize,
 750                           true, true);
 751     mapinfo->write_string_regions(_string_regions);
 752     mapinfo->write_region(MetaspaceShared::od, _od_vs.low(),
 753                           pointer_delta(od_top, _od_vs.low(), sizeof(char)),
 754                           pointer_delta(od_end, _od_vs.low(), sizeof(char)),
 755                           true, false);
 756   }
 757 
 758   mapinfo->close();
 759 
 760   memmove(vtbl_list, saved_vtbl, vtbl_list_size * sizeof(void*));
 761   os::free(saved_vtbl);
 762 
 763   if (PrintSharedSpaces) {
 764     DumpAllocClosure dac;
 765     dac.iterate_metaspace(_loader_data->ro_metaspace(), DumpAllocClosure::RO);
 766     dac.iterate_metaspace(_loader_data->rw_metaspace(), DumpAllocClosure::RW);
 767 
 768     dac.dump_stats(int(ro_bytes), int(rw_bytes), int(md_bytes), int(mc_bytes));
 769   }
 770 #undef fmt_space
 771 }
 772 
 773 
 774 void MetaspaceShared::link_one_shared_class(Klass* k, TRAPS) {
 775   if (k->is_instance_klass()) {
 776     InstanceKlass* ik = InstanceKlass::cast(k);
 777     // Link the class to cause the bytecodes to be rewritten and the
 778     // cpcache to be created. Class verification is done according
 779     // to -Xverify setting.
 780     _link_classes_made_progress |= try_link_class(ik, THREAD);
 781     guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
 782   }
 783 }
 784 
 785 void MetaspaceShared::check_one_shared_class(Klass* k) {
 786   if (k->is_instance_klass() && InstanceKlass::cast(k)->check_sharing_error_state()) {
 787     _check_classes_made_progress = true;
 788   }
 789 }
 790 
 791 void MetaspaceShared::check_shared_class_loader_type(Klass* k) {
 792   if (k->is_instance_klass()) {
 793     InstanceKlass* ik = InstanceKlass::cast(k);
 794     u2 loader_type = ik->loader_type();
 795     ResourceMark rm;
 796     guarantee(loader_type != 0,
 797               "Class loader type is not set for this class %s", ik->name()->as_C_string());
 798   }
 799 }
 800 
 801 void MetaspaceShared::link_and_cleanup_shared_classes(TRAPS) {
 802   // We need to iterate because verification may cause additional classes
 803   // to be loaded.
 804   do {
 805     _link_classes_made_progress = false;
 806     SystemDictionary::classes_do(link_one_shared_class, THREAD);
 807     guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
 808   } while (_link_classes_made_progress);
 809 
 810   if (_has_error_classes) {
 811     // Mark all classes whose super class or interfaces failed verification.
 812     do {
 813       // Not completely sure if we need to do this iteratively. Anyway,
 814       // we should come here only if there are unverifiable classes, which
 815       // shouldn't happen in normal cases. So better safe than sorry.
 816       _check_classes_made_progress = false;
 817       SystemDictionary::classes_do(check_one_shared_class);
 818     } while (_check_classes_made_progress);
 819 
 820     if (IgnoreUnverifiableClassesDuringDump) {
 821       // This is useful when running JCK or SQE tests. You should not
 822       // enable this when running real apps.
 823       SystemDictionary::remove_classes_in_error_state();
 824     } else {
 825       tty->print_cr("Please remove the unverifiable classes from your class list and try again");
 826       exit(1);
 827     }
 828   }
 829 
 830   // Copy the verification constraints from C_HEAP-alloced GrowableArrays to RO-alloced
 831   // Arrays
 832   SystemDictionaryShared::finalize_verification_constraints();
 833 }
 834 
 835 void MetaspaceShared::prepare_for_dumping() {
 836   Arguments::check_unsupported_dumping_properties();
 837   ClassLoader::initialize_shared_path();
 838   FileMapInfo::allocate_classpath_entry_table();
 839 }
 840 
 841 // Preload classes from a list, populate the shared spaces and dump to a
 842 // file.
 843 void MetaspaceShared::preload_and_dump(TRAPS) {
 844   { TraceTime timer("Dump Shared Spaces", TRACETIME_LOG(Info, startuptime));
 845     ResourceMark rm;
 846     char class_list_path_str[JVM_MAXPATHLEN];
 847 
 848     tty->print_cr("Allocated shared space: " SIZE_FORMAT " bytes at " PTR_FORMAT,
 849                   MetaspaceShared::shared_rs()->size(),
 850                   p2i(MetaspaceShared::shared_rs()->base()));
 851 
 852     // Preload classes to be shared.
 853     // Should use some os:: method rather than fopen() here. aB.
 854     const char* class_list_path;
 855     if (SharedClassListFile == NULL) {
 856       // Construct the path to the class list (in jre/lib)
 857       // Walk up two directories from the location of the VM and
 858       // optionally tack on "lib" (depending on platform)
 859       os::jvm_path(class_list_path_str, sizeof(class_list_path_str));
 860       for (int i = 0; i < 3; i++) {
 861         char *end = strrchr(class_list_path_str, *os::file_separator());
 862         if (end != NULL) *end = '\0';
 863       }
 864       int class_list_path_len = (int)strlen(class_list_path_str);
 865       if (class_list_path_len >= 3) {
 866         if (strcmp(class_list_path_str + class_list_path_len - 3, "lib") != 0) {
 867           if (class_list_path_len < JVM_MAXPATHLEN - 4) {
 868             jio_snprintf(class_list_path_str + class_list_path_len,
 869                          sizeof(class_list_path_str) - class_list_path_len,
 870                          "%slib", os::file_separator());
 871             class_list_path_len += 4;
 872           }
 873         }
 874       }
 875       if (class_list_path_len < JVM_MAXPATHLEN - 10) {
 876         jio_snprintf(class_list_path_str + class_list_path_len,
 877                      sizeof(class_list_path_str) - class_list_path_len,
 878                      "%sclasslist", os::file_separator());
 879       }
 880       class_list_path = class_list_path_str;
 881     } else {
 882       class_list_path = SharedClassListFile;
 883     }
 884 
 885     int class_count = 0;
 886     GrowableArray<Klass*>* class_promote_order = new GrowableArray<Klass*>();
 887 
 888     // sun.io.Converters
 889     static const char obj_array_sig[] = "[[Ljava/lang/Object;";
 890     SymbolTable::new_permanent_symbol(obj_array_sig, THREAD);
 891 
 892     // java.util.HashMap
 893     static const char map_entry_array_sig[] = "[Ljava/util/Map$Entry;";
 894     SymbolTable::new_permanent_symbol(map_entry_array_sig, THREAD);
 895 
 896     // Need to allocate the op here:
 897     // op.misc_data_space_alloc() will be called during preload_and_dump().
 898     ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 899     VM_PopulateDumpSharedSpace op(loader_data, class_promote_order);
 900 
 901     tty->print_cr("Loading classes to share ...");
 902     _has_error_classes = false;
 903     class_count += preload_and_dump(class_list_path, class_promote_order,
 904                                     THREAD);
 905     if (ExtraSharedClassListFile) {
 906       class_count += preload_and_dump(ExtraSharedClassListFile, class_promote_order,
 907                                       THREAD);
 908     }
 909     tty->print_cr("Loading classes to share: done.");
 910 
 911     if (PrintSharedSpaces) {
 912       tty->print_cr("Shared spaces: preloaded %d classes", class_count);
 913     }
 914 
 915     // Rewrite and link classes
 916     tty->print_cr("Rewriting and linking classes ...");
 917 
 918     // Link any classes which got missed. This would happen if we have loaded classes that
 919     // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
 920     // fails verification, all other interfaces that were not specified in the classlist but
 921     // are implemented by K are not verified.
 922     link_and_cleanup_shared_classes(CATCH);
 923     tty->print_cr("Rewriting and linking classes: done");
 924 
 925     VMThread::execute(&op);
 926   }
 927   // Since various initialization steps have been undone by this process,
 928   // it is not reasonable to continue running a java process.
 929   exit(0);
 930 }
 931 
 932 
 933 int MetaspaceShared::preload_and_dump(const char* class_list_path,
 934                                       GrowableArray<Klass*>* class_promote_order,
 935                                       TRAPS) {
 936   ClassListParser parser(class_list_path);
 937   int class_count = 0;
 938 
 939     while (parser.parse_one_line()) {
 940       Klass* klass = ClassLoaderExt::load_one_class(&parser, THREAD);
 941 
 942       CLEAR_PENDING_EXCEPTION;
 943       if (klass != NULL) {
 944         if (PrintSharedSpaces && Verbose && WizardMode) {
 945           ResourceMark rm;
 946           tty->print_cr("Shared spaces preloaded: %s", klass->external_name());
 947         }
 948 
 949         InstanceKlass* ik = InstanceKlass::cast(klass);
 950 
 951         // Should be class load order as per -Xlog:class+preorder
 952         class_promote_order->append(ik);
 953 
 954         // Link the class to cause the bytecodes to be rewritten and the
 955         // cpcache to be created. The linking is done as soon as classes
 956         // are loaded in order that the related data structures (klass and
 957         // cpCache) are located together.
 958         try_link_class(ik, THREAD);
 959         guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
 960 
 961         class_count++;
 962       }
 963     }
 964 
 965   return class_count;
 966 }
 967 
 968 // Returns true if the class's status has changed
 969 bool MetaspaceShared::try_link_class(InstanceKlass* ik, TRAPS) {
 970   assert(DumpSharedSpaces, "should only be called during dumping");
 971   if (ik->init_state() < InstanceKlass::linked) {
 972     bool saved = BytecodeVerificationLocal;
 973     if (!(ik->is_shared_boot_class())) {
 974       // The verification decision is based on BytecodeVerificationRemote
 975       // for non-system classes. Since we are using the NULL classloader
 976       // to load non-system classes during dumping, we need to temporarily
 977       // change BytecodeVerificationLocal to be the same as
 978       // BytecodeVerificationRemote. Note this can cause the parent system
 979       // classes also being verified. The extra overhead is acceptable during
 980       // dumping.
 981       BytecodeVerificationLocal = BytecodeVerificationRemote;
 982     }
 983     ik->link_class(THREAD);
 984     if (HAS_PENDING_EXCEPTION) {
 985       ResourceMark rm;
 986       tty->print_cr("Preload Warning: Verification failed for %s",
 987                     ik->external_name());
 988       CLEAR_PENDING_EXCEPTION;
 989       ik->set_in_error_state();
 990       _has_error_classes = true;
 991     }
 992     BytecodeVerificationLocal = saved;
 993     return true;
 994   } else {
 995     return false;
 996   }
 997 }
 998 
 999 // Closure for serializing initialization data in from a data area
1000 // (ptr_array) read from the shared file.
1001 
1002 class ReadClosure : public SerializeClosure {
1003 private:
1004   intptr_t** _ptr_array;
1005 
1006   inline intptr_t nextPtr() {
1007     return *(*_ptr_array)++;
1008   }
1009 
1010 public:
1011   ReadClosure(intptr_t** ptr_array) { _ptr_array = ptr_array; }
1012 
1013   void do_ptr(void** p) {
1014     assert(*p == NULL, "initializing previous initialized pointer.");
1015     intptr_t obj = nextPtr();
1016     assert((intptr_t)obj >= 0 || (intptr_t)obj < -100,
1017            "hit tag while initializing ptrs.");
1018     *p = (void*)obj;
1019   }
1020 
1021   void do_u4(u4* p) {
1022     intptr_t obj = nextPtr();
1023     *p = (u4)(uintx(obj));
1024   }
1025 
1026   void do_tag(int tag) {
1027     int old_tag;
1028     old_tag = (int)(intptr_t)nextPtr();
1029     // do_int(&old_tag);
1030     assert(tag == old_tag, "old tag doesn't match");
1031     FileMapInfo::assert_mark(tag == old_tag);
1032   }
1033 
1034   void do_region(u_char* start, size_t size) {
1035     assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
1036     assert(size % sizeof(intptr_t) == 0, "bad size");
1037     do_tag((int)size);
1038     while (size > 0) {
1039       *(intptr_t*)start = nextPtr();
1040       start += sizeof(intptr_t);
1041       size -= sizeof(intptr_t);
1042     }
1043   }
1044 
1045   bool reading() const { return true; }
1046 };
1047 
1048 // Return true if given address is in the mapped shared space.
1049 bool MetaspaceShared::is_in_shared_space(const void* p) {
1050   return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_space(p);
1051 }
1052 
1053 // Return true if given address is in the misc data region
1054 bool MetaspaceShared::is_in_shared_region(const void* p, int idx) {
1055   return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx);
1056 }
1057 
1058 bool MetaspaceShared::is_string_region(int idx) {
1059   return (idx >= MetaspaceShared::first_string &&
1060           idx < MetaspaceShared::first_string + MetaspaceShared::max_strings);
1061 }
1062 
1063 void MetaspaceShared::print_shared_spaces() {
1064   if (UseSharedSpaces) {
1065     FileMapInfo::current_info()->print_shared_spaces();
1066   }
1067 }
1068 
1069 
1070 // Map shared spaces at requested addresses and return if succeeded.
1071 bool MetaspaceShared::map_shared_spaces(FileMapInfo* mapinfo) {
1072   size_t image_alignment = mapinfo->alignment();
1073 
1074 #ifndef _WINDOWS
1075   // Map in the shared memory and then map the regions on top of it.
1076   // On Windows, don't map the memory here because it will cause the
1077   // mappings of the regions to fail.
1078   ReservedSpace shared_rs = mapinfo->reserve_shared_memory();
1079   if (!shared_rs.is_reserved()) return false;
1080 #endif
1081 
1082   assert(!DumpSharedSpaces, "Should not be called with DumpSharedSpaces");
1083 
1084   char* _ro_base = NULL;
1085   char* _rw_base = NULL;
1086   char* _md_base = NULL;
1087   char* _mc_base = NULL;
1088   char* _od_base = NULL;
1089 
1090   // Map each shared region
1091   if ((_ro_base = mapinfo->map_region(ro)) != NULL &&
1092       mapinfo->verify_region_checksum(ro) &&
1093       (_rw_base = mapinfo->map_region(rw)) != NULL &&
1094       mapinfo->verify_region_checksum(rw) &&
1095       (_md_base = mapinfo->map_region(md)) != NULL &&
1096       mapinfo->verify_region_checksum(md) &&
1097       (_mc_base = mapinfo->map_region(mc)) != NULL &&
1098       mapinfo->verify_region_checksum(mc) &&
1099       (_od_base = mapinfo->map_region(od)) != NULL &&
1100       mapinfo->verify_region_checksum(od) &&
1101       (image_alignment == (size_t)max_alignment()) &&
1102       mapinfo->validate_classpath_entry_table()) {
1103     // Success (no need to do anything)
1104     return true;
1105   } else {
1106     // If there was a failure in mapping any of the spaces, unmap the ones
1107     // that succeeded
1108     if (_ro_base != NULL) mapinfo->unmap_region(ro);
1109     if (_rw_base != NULL) mapinfo->unmap_region(rw);
1110     if (_md_base != NULL) mapinfo->unmap_region(md);
1111     if (_mc_base != NULL) mapinfo->unmap_region(mc);
1112     if (_od_base != NULL) mapinfo->unmap_region(od);
1113 #ifndef _WINDOWS
1114     // Release the entire mapped region
1115     shared_rs.release();
1116 #endif
1117     // If -Xshare:on is specified, print out the error message and exit VM,
1118     // otherwise, set UseSharedSpaces to false and continue.
1119     if (RequireSharedSpaces || PrintSharedArchiveAndExit) {
1120       vm_exit_during_initialization("Unable to use shared archive.", "Failed map_region for using -Xshare:on.");
1121     } else {
1122       FLAG_SET_DEFAULT(UseSharedSpaces, false);
1123     }
1124     return false;
1125   }
1126 }
1127 
1128 // Read the miscellaneous data from the shared file, and
1129 // serialize it out to its various destinations.
1130 
1131 void MetaspaceShared::initialize_shared_spaces() {
1132   FileMapInfo *mapinfo = FileMapInfo::current_info();
1133   _cds_i2i_entry_code_buffers = mapinfo->cds_i2i_entry_code_buffers();
1134   _cds_i2i_entry_code_buffers_size = mapinfo->cds_i2i_entry_code_buffers_size();
1135   char* buffer = mapinfo->misc_data_patching_start();
1136 
1137   // Skip over (reserve space for) a list of addresses of C++ vtables
1138   // for Klass objects.  They get filled in later.
1139 
1140   void** vtbl_list = (void**)buffer;
1141   buffer += MetaspaceShared::vtbl_list_size * sizeof(void*);
1142   Universe::init_self_patching_vtbl_list(vtbl_list, vtbl_list_size);
1143 
1144   // Skip over (reserve space for) dummy C++ vtables Klass objects.
1145   // They are used as is.
1146 
1147   intptr_t vtable_size = *(intptr_t*)buffer;
1148   buffer += sizeof(intptr_t);
1149   buffer += vtable_size;
1150 
1151   int sharedDictionaryLen = *(intptr_t*)buffer;
1152   buffer += sizeof(intptr_t);
1153   int number_of_entries = *(intptr_t*)buffer;
1154   buffer += sizeof(intptr_t);
1155   SystemDictionary::set_shared_dictionary((HashtableBucket<mtClass>*)buffer,
1156                                           sharedDictionaryLen,
1157                                           number_of_entries);
1158   buffer += sharedDictionaryLen;
1159 
1160   // The following data in the shared misc data region are the linked
1161   // list elements (HashtableEntry objects) for the shared dictionary
1162   // table.
1163 
1164   int len = *(intptr_t*)buffer;     // skip over shared dictionary entries
1165   buffer += sizeof(intptr_t);
1166   buffer += len;
1167 
1168   // Verify various attributes of the archive, plus initialize the
1169   // shared string/symbol tables
1170   intptr_t* array = (intptr_t*)buffer;
1171   ReadClosure rc(&array);
1172   serialize(&rc, NULL, NULL);
1173 
1174   // Initialize the run-time symbol table.
1175   SymbolTable::create_table();
1176 
1177   // Close the mapinfo file
1178   mapinfo->close();
1179 
1180   if (PrintSharedArchiveAndExit) {
1181     if (PrintSharedDictionary) {
1182       tty->print_cr("\nShared classes:\n");
1183       SystemDictionary::print_shared(false);
1184     }
1185     if (_archive_loading_failed) {
1186       tty->print_cr("archive is invalid");
1187       vm_exit(1);
1188     } else {
1189       tty->print_cr("archive is valid");
1190       vm_exit(0);
1191     }
1192   }
1193 }
1194 
1195 void MetaspaceShared::fixup_shared_string_regions() {
1196   FileMapInfo *mapinfo = FileMapInfo::current_info();
1197   mapinfo->fixup_string_regions();
1198 }
1199 
1200 // JVM/TI RedefineClasses() support:
1201 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1202   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1203 
1204   if (UseSharedSpaces) {
1205     // remap the shared readonly space to shared readwrite, private
1206     FileMapInfo* mapinfo = FileMapInfo::current_info();
1207     if (!mapinfo->remap_shared_readonly_as_readwrite()) {
1208       return false;
1209     }
1210     _remapped_readwrite = true;
1211   }
1212   return true;
1213 }
1214 
1215 int MetaspaceShared::count_class(const char* classlist_file) {
1216   if (classlist_file == NULL) {
1217     return 0;
1218   }
1219   char class_name[256];
1220   int class_count = 0;
1221   FILE* file = fopen(classlist_file, "r");
1222   if (file != NULL) {
1223     while ((fgets(class_name, sizeof class_name, file)) != NULL) {
1224       if (*class_name == '#') { // comment
1225         continue;
1226       }
1227       class_count++;
1228     }
1229     fclose(file);
1230   } else {
1231     char errmsg[JVM_MAXPATHLEN];
1232     os::lasterror(errmsg, JVM_MAXPATHLEN);
1233     tty->print_cr("Loading classlist failed: %s", errmsg);
1234     exit(1);
1235   }
1236 
1237   return class_count;
1238 }
1239 
1240 // the sizes are good for typical large applications that have a lot of shared
1241 // classes
1242 void MetaspaceShared::estimate_regions_size() {
1243   int class_count = count_class(SharedClassListFile);
1244   class_count += count_class(ExtraSharedClassListFile);
1245 
1246   if (class_count > LargeThresholdClassCount) {
1247     if (class_count < HugeThresholdClassCount) {
1248       SET_ESTIMATED_SIZE(Large, ReadOnly);
1249       SET_ESTIMATED_SIZE(Large, ReadWrite);
1250       SET_ESTIMATED_SIZE(Large, MiscData);
1251       SET_ESTIMATED_SIZE(Large, MiscCode);
1252     } else {
1253       SET_ESTIMATED_SIZE(Huge,  ReadOnly);
1254       SET_ESTIMATED_SIZE(Huge,  ReadWrite);
1255       SET_ESTIMATED_SIZE(Huge,  MiscData);
1256       SET_ESTIMATED_SIZE(Huge,  MiscCode);
1257     }
1258   }
1259 }