src/share/vm/memory/metaspaceShared.cpp

Mon, 12 Aug 2019 18:30:40 +0300

author
apetushkov
date
Mon, 12 Aug 2019 18:30:40 +0300
changeset 9858
b985cbb00e68
parent 8509
cb4af293fe70
child 8604
04d83ba48607
child 9988
1b2d99958c29
permissions
-rw-r--r--

8223147: JFR Backport
8199712: Flight Recorder
8203346: JFR: Inconsistent signature of jfr_add_string_constant
8195817: JFR.stop should require name of recording
8195818: JFR.start should increase autogenerated name by one
8195819: Remove recording=x from jcmd JFR.check output
8203921: JFR thread sampling is missing fixes from JDK-8194552
8203929: Limit amount of data for JFR.dump
8203664: JFR start failure after AppCDS archive created with JFR StartFlightRecording
8003209: JFR events for network utilization
8207392: [PPC64] Implement JFR profiling
8202835: jfr/event/os/TestSystemProcess.java fails on missing events
Summary: Backport JFR from JDK11. Initial integration
Reviewed-by: neugens

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

mercurial