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