1 /*
   2  * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classListParser.hpp"
  27 #include "classfile/classLoaderExt.hpp"
  28 #include "classfile/dictionary.hpp"
  29 #include "classfile/loaderConstraints.hpp"
  30 #include "classfile/placeholders.hpp"
  31 #include "classfile/sharedClassUtil.hpp"
  32 #include "classfile/symbolTable.hpp"
  33 #include "classfile/systemDictionary.hpp"
  34 #include "code/codeCache.hpp"
  35 #include "gc/shared/gcLocker.hpp"
  36 #include "interpreter/bytecodeStream.hpp"
  37 #include "interpreter/bytecodes.hpp"
  38 #include "memory/filemap.hpp"
  39 #include "memory/metaspace.hpp"
  40 #include "memory/metaspaceShared.hpp"

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