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