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