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