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