1 /* 2 * Copyright (c) 2012, 2018, 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 "jvm.h" 27 #include "classfile/classListParser.hpp" 28 #include "classfile/classLoaderExt.hpp" 29 #include "classfile/dictionary.hpp" 30 #include "classfile/loaderConstraints.hpp" 31 #include "classfile/placeholders.hpp" 32 #include "classfile/sharedClassUtil.hpp" 33 #include "classfile/symbolTable.hpp" 34 #include "classfile/stringTable.hpp" 35 #include "classfile/systemDictionary.hpp" 36 #include "classfile/systemDictionaryShared.hpp" 37 #include "code/codeCache.hpp" 38 #if INCLUDE_ALL_GCS 39 #include "gc/g1/g1Allocator.inline.hpp" 40 #include "gc/g1/g1CollectedHeap.hpp" 41 #endif 42 #include "gc/shared/gcLocker.hpp" 43 #include "interpreter/bytecodeStream.hpp" 44 #include "interpreter/bytecodes.hpp" 45 #include "logging/log.hpp" 46 #include "logging/logMessage.hpp" 47 #include "memory/filemap.hpp" 48 #include "memory/metaspace.hpp" 49 #include "memory/metaspaceShared.hpp" 50 #include "memory/resourceArea.hpp" 51 #include "oops/instanceClassLoaderKlass.hpp" 52 #include "oops/instanceMirrorKlass.hpp" 53 #include "oops/instanceRefKlass.hpp" 54 #include "oops/objArrayKlass.hpp" 55 #include "oops/objArrayOop.hpp" 56 #include "oops/oop.inline.hpp" 57 #include "oops/typeArrayKlass.hpp" 58 #include "prims/jvmtiRedefineClasses.hpp" 59 #include "runtime/timerTrace.hpp" 60 #include "runtime/os.hpp" 61 #include "runtime/signature.hpp" 62 #include "runtime/vmThread.hpp" 63 #include "runtime/vm_operations.hpp" 64 #include "utilities/align.hpp" 65 #include "utilities/defaultStream.hpp" 66 #include "utilities/hashtable.inline.hpp" 67 #include "memory/metaspaceClosure.hpp" 68 69 ReservedSpace MetaspaceShared::_shared_rs; 70 VirtualSpace MetaspaceShared::_shared_vs; 71 MetaspaceSharedStats MetaspaceShared::_stats; 72 bool MetaspaceShared::_has_error_classes; 73 bool MetaspaceShared::_archive_loading_failed = false; 74 bool MetaspaceShared::_remapped_readwrite = false; 75 bool MetaspaceShared::_open_archive_heap_region_mapped = false; 76 address MetaspaceShared::_cds_i2i_entry_code_buffers = NULL; 77 size_t MetaspaceShared::_cds_i2i_entry_code_buffers_size = 0; 78 size_t MetaspaceShared::_core_spaces_size = 0; 79 80 // The CDS archive is divided into the following regions: 81 // mc - misc code (the method entry trampolines) 82 // rw - read-write metadata 83 // ro - read-only metadata and read-only tables 84 // md - misc data (the c++ vtables) 85 // od - optional data (original class files) 86 // 87 // s0 - shared strings(closed archive heap space) #0 88 // s1 - shared strings(closed archive heap space) #1 (may be empty) 89 // oa0 - open archive heap space #0 90 // oa1 - open archive heap space #1 (may be empty) 91 // 92 // The mc, rw, ro, md and od regions are linearly allocated, starting from 93 // SharedBaseAddress, in the order of mc->rw->ro->md->od. The size of these 5 regions 94 // are page-aligned, and there's no gap between any consecutive regions. 95 // 96 // These 5 regions are populated in the following steps: 97 // [1] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are 98 // temporarily allocated outside of the shared regions. Only the method entry 99 // trampolines are written into the mc region. 100 // [2] ArchiveCompactor copies RW metadata into the rw region. 101 // [3] ArchiveCompactor copies RO metadata into the ro region. 102 // [4] SymbolTable, StringTable, SystemDictionary, and a few other read-only data 103 // are copied into the ro region as read-only tables. 104 // [5] C++ vtables are copied into the md region. 105 // [6] Original class files are copied into the od region. 106 // 107 // The s0/s1 and oa0/oa1 regions are populated inside MetaspaceShared::dump_java_heap_objects. 108 // Their layout is independent of the other 5 regions. 109 110 class DumpRegion { 111 private: 112 const char* _name; 113 char* _base; 114 char* _top; 115 char* _end; 116 bool _is_packed; 117 118 char* expand_top_to(char* newtop) { 119 assert(is_allocatable(), "must be initialized and not packed"); 120 assert(newtop >= _top, "must not grow backwards"); 121 if (newtop > _end) { 122 MetaspaceShared::report_out_of_space(_name, newtop - _top); 123 ShouldNotReachHere(); 124 } 125 MetaspaceShared::commit_shared_space_to(newtop); 126 _top = newtop; 127 return _top; 128 } 129 130 public: 131 DumpRegion(const char* name) : _name(name), _base(NULL), _top(NULL), _end(NULL), _is_packed(false) {} 132 133 char* allocate(size_t num_bytes, size_t alignment=BytesPerWord) { 134 char* p = (char*)align_up(_top, alignment); 135 char* newtop = p + align_up(num_bytes, alignment); 136 expand_top_to(newtop); 137 memset(p, 0, newtop - p); 138 return p; 139 } 140 141 void append_intptr_t(intptr_t n) { 142 assert(is_aligned(_top, sizeof(intptr_t)), "bad alignment"); 143 intptr_t *p = (intptr_t*)_top; 144 char* newtop = _top + sizeof(intptr_t); 145 expand_top_to(newtop); 146 *p = n; 147 } 148 149 char* base() const { return _base; } 150 char* top() const { return _top; } 151 char* end() const { return _end; } 152 size_t reserved() const { return _end - _base; } 153 size_t used() const { return _top - _base; } 154 bool is_packed() const { return _is_packed; } 155 bool is_allocatable() const { 156 return !is_packed() && _base != NULL; 157 } 158 159 void print(size_t total_bytes) const { 160 tty->print_cr("%-3s space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used] at " INTPTR_FORMAT, 161 _name, used(), percent_of(used(), total_bytes), reserved(), percent_of(used(), reserved()), p2i(_base)); 162 } 163 void print_out_of_space_msg(const char* failing_region, size_t needed_bytes) { 164 tty->print("[%-8s] " PTR_FORMAT " - " PTR_FORMAT " capacity =%9d, allocated =%9d", 165 _name, p2i(_base), p2i(_top), int(_end - _base), int(_top - _base)); 166 if (strcmp(_name, failing_region) == 0) { 167 tty->print_cr(" required = %d", int(needed_bytes)); 168 } else { 169 tty->cr(); 170 } 171 } 172 173 void init(const ReservedSpace* rs) { 174 _base = _top = rs->base(); 175 _end = rs->end(); 176 } 177 void init(char* b, char* t, char* e) { 178 _base = b; 179 _top = t; 180 _end = e; 181 } 182 183 void pack(DumpRegion* next = NULL) { 184 assert(!is_packed(), "sanity"); 185 _end = (char*)align_up(_top, Metaspace::reserve_alignment()); 186 _is_packed = true; 187 if (next != NULL) { 188 next->_base = next->_top = this->_end; 189 next->_end = MetaspaceShared::shared_rs()->end(); 190 } 191 } 192 bool contains(char* p) { 193 return base() <= p && p < top(); 194 } 195 }; 196 197 198 DumpRegion _mc_region("mc"), _ro_region("ro"), _rw_region("rw"), _md_region("md"), _od_region("od"); 199 size_t _total_string_region_size = 0, _total_open_archive_region_size = 0; 200 201 char* MetaspaceShared::misc_code_space_alloc(size_t num_bytes) { 202 return _mc_region.allocate(num_bytes); 203 } 204 205 char* MetaspaceShared::read_only_space_alloc(size_t num_bytes) { 206 return _ro_region.allocate(num_bytes); 207 } 208 209 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() { 210 assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled"); 211 212 // If using shared space, open the file that contains the shared space 213 // and map in the memory before initializing the rest of metaspace (so 214 // the addresses don't conflict) 215 address cds_address = NULL; 216 FileMapInfo* mapinfo = new FileMapInfo(); 217 218 // Open the shared archive file, read and validate the header. If 219 // initialization fails, shared spaces [UseSharedSpaces] are 220 // disabled and the file is closed. 221 // Map in spaces now also 222 if (mapinfo->initialize() && map_shared_spaces(mapinfo)) { 223 size_t cds_total = core_spaces_size(); 224 cds_address = (address)mapinfo->header()->region_addr(0); 225 #ifdef _LP64 226 if (Metaspace::using_class_space()) { 227 char* cds_end = (char*)(cds_address + cds_total); 228 cds_end = (char *)align_up(cds_end, Metaspace::reserve_alignment()); 229 // If UseCompressedClassPointers is set then allocate the metaspace area 230 // above the heap and above the CDS area (if it exists). 231 Metaspace::allocate_metaspace_compressed_klass_ptrs(cds_end, cds_address); 232 // map_heap_regions() compares the current narrow oop and klass encodings 233 // with the archived ones, so it must be done after all encodings are determined. 234 mapinfo->map_heap_regions(); 235 } 236 #endif // _LP64 237 } else { 238 assert(!mapinfo->is_open() && !UseSharedSpaces, 239 "archive file not closed or shared spaces not disabled."); 240 } 241 } 242 243 void MetaspaceShared::initialize_dumptime_shared_and_meta_spaces() { 244 assert(DumpSharedSpaces, "should be called for dump time only"); 245 const size_t reserve_alignment = Metaspace::reserve_alignment(); 246 bool large_pages = false; // No large pages when dumping the CDS archive. 247 char* shared_base = (char*)align_up((char*)SharedBaseAddress, reserve_alignment); 248 249 #ifdef _LP64 250 // On 64-bit VM, the heap and class space layout will be the same as if 251 // you're running in -Xshare:on mode: 252 // 253 // +-- SharedBaseAddress (default = 0x800000000) 254 // v 255 // +-..---------+---------+ ... +----+----+----+----+----+---------------+ 256 // | Heap | Archive | | MC | RW | RO | MD | OD | class space | 257 // +-..---------+---------+ ... +----+----+----+----+----+---------------+ 258 // |<-- MaxHeapSize -->| |<-- UnscaledClassSpaceMax = 4GB ------->| 259 // 260 const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1); 261 const size_t cds_total = align_down(UnscaledClassSpaceMax, reserve_alignment); 262 #else 263 // We don't support archives larger than 256MB on 32-bit due to limited virtual address space. 264 size_t cds_total = align_down(256*M, reserve_alignment); 265 #endif 266 267 // First try to reserve the space at the specified SharedBaseAddress. 268 _shared_rs = ReservedSpace(cds_total, reserve_alignment, large_pages, shared_base); 269 if (_shared_rs.is_reserved()) { 270 assert(shared_base == 0 || _shared_rs.base() == shared_base, "should match"); 271 } else { 272 // Get a mmap region anywhere if the SharedBaseAddress fails. 273 _shared_rs = ReservedSpace(cds_total, reserve_alignment, large_pages); 274 } 275 if (!_shared_rs.is_reserved()) { 276 vm_exit_during_initialization("Unable to reserve memory for shared space", 277 err_msg(SIZE_FORMAT " bytes.", cds_total)); 278 } 279 280 #ifdef _LP64 281 // During dump time, we allocate 4GB (UnscaledClassSpaceMax) of space and split it up: 282 // + The upper 1 GB is used as the "temporary compressed class space" -- preload_classes() 283 // will store Klasses into this space. 284 // + The lower 3 GB is used for the archive -- when preload_classes() is done, 285 // ArchiveCompactor will copy the class metadata into this space, first the RW parts, 286 // then the RO parts. 287 288 assert(UseCompressedOops && UseCompressedClassPointers, 289 "UseCompressedOops and UseCompressedClassPointers must be set"); 290 291 size_t max_archive_size = align_down(cds_total * 3 / 4, reserve_alignment); 292 ReservedSpace tmp_class_space = _shared_rs.last_part(max_archive_size); 293 CompressedClassSpaceSize = align_down(tmp_class_space.size(), reserve_alignment); 294 _shared_rs = _shared_rs.first_part(max_archive_size); 295 296 // Set up compress class pointers. 297 Universe::set_narrow_klass_base((address)_shared_rs.base()); 298 // Set narrow_klass_shift to be LogKlassAlignmentInBytes. This is consistent 299 // with AOT. 300 Universe::set_narrow_klass_shift(LogKlassAlignmentInBytes); 301 302 Metaspace::initialize_class_space(tmp_class_space); 303 tty->print_cr("narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d", 304 p2i(Universe::narrow_klass_base()), Universe::narrow_klass_shift()); 305 306 tty->print_cr("Allocated temporary class space: " SIZE_FORMAT " bytes at " PTR_FORMAT, 307 CompressedClassSpaceSize, p2i(tmp_class_space.base())); 308 #endif 309 310 // Start with 0 committed bytes. The memory will be committed as needed by 311 // MetaspaceShared::commit_shared_space_to(). 312 if (!_shared_vs.initialize(_shared_rs, 0)) { 313 vm_exit_during_initialization("Unable to allocate memory for shared space"); 314 } 315 316 _mc_region.init(&_shared_rs); 317 tty->print_cr("Allocated shared space: " SIZE_FORMAT " bytes at " PTR_FORMAT, 318 _shared_rs.size(), p2i(_shared_rs.base())); 319 } 320 321 void MetaspaceShared::commit_shared_space_to(char* newtop) { 322 assert(DumpSharedSpaces, "dump-time only"); 323 char* base = _shared_rs.base(); 324 size_t need_committed_size = newtop - base; 325 size_t has_committed_size = _shared_vs.committed_size(); 326 if (need_committed_size < has_committed_size) { 327 return; 328 } 329 330 size_t min_bytes = need_committed_size - has_committed_size; 331 size_t preferred_bytes = 1 * M; 332 size_t uncommitted = _shared_vs.reserved_size() - has_committed_size; 333 334 size_t commit = MAX2(min_bytes, preferred_bytes); 335 assert(commit <= uncommitted, "sanity"); 336 337 bool result = _shared_vs.expand_by(commit, false); 338 if (!result) { 339 vm_exit_during_initialization(err_msg("Failed to expand shared space to " SIZE_FORMAT " bytes", 340 need_committed_size)); 341 } 342 343 log_info(cds)("Expanding shared spaces by " SIZE_FORMAT_W(7) " bytes [total " SIZE_FORMAT_W(9) " bytes ending at %p]", 344 commit, _shared_vs.actual_committed_size(), _shared_vs.high()); 345 } 346 347 // Read/write a data stream for restoring/preserving metadata pointers and 348 // miscellaneous data from/to the shared archive file. 349 350 void MetaspaceShared::serialize(SerializeClosure* soc) { 351 int tag = 0; 352 soc->do_tag(--tag); 353 354 // Verify the sizes of various metadata in the system. 355 soc->do_tag(sizeof(Method)); 356 soc->do_tag(sizeof(ConstMethod)); 357 soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE)); 358 soc->do_tag(sizeof(ConstantPool)); 359 soc->do_tag(sizeof(ConstantPoolCache)); 360 soc->do_tag(objArrayOopDesc::base_offset_in_bytes()); 361 soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE)); 362 soc->do_tag(sizeof(Symbol)); 363 364 // Dump/restore miscellaneous metadata. 365 Universe::serialize(soc, true); 366 soc->do_tag(--tag); 367 368 // Dump/restore references to commonly used names and signatures. 369 vmSymbols::serialize(soc); 370 soc->do_tag(--tag); 371 372 // Dump/restore the symbol and string tables 373 SymbolTable::serialize(soc); 374 StringTable::serialize(soc); 375 soc->do_tag(--tag); 376 377 soc->do_tag(666); 378 } 379 380 address MetaspaceShared::cds_i2i_entry_code_buffers(size_t total_size) { 381 if (DumpSharedSpaces) { 382 if (_cds_i2i_entry_code_buffers == NULL) { 383 _cds_i2i_entry_code_buffers = (address)misc_code_space_alloc(total_size); 384 _cds_i2i_entry_code_buffers_size = total_size; 385 } 386 } else if (UseSharedSpaces) { 387 assert(_cds_i2i_entry_code_buffers != NULL, "must already been initialized"); 388 } else { 389 return NULL; 390 } 391 392 assert(_cds_i2i_entry_code_buffers_size == total_size, "must not change"); 393 return _cds_i2i_entry_code_buffers; 394 } 395 396 // CDS code for dumping shared archive. 397 398 // Global object for holding classes that have been loaded. Since this 399 // is run at a safepoint just before exit, this is the entire set of classes. 400 static GrowableArray<Klass*>* _global_klass_objects; 401 402 static void collect_array_classes(Klass* k) { 403 _global_klass_objects->append_if_missing(k); 404 if (k->is_array_klass()) { 405 // Add in the array classes too 406 ArrayKlass* ak = ArrayKlass::cast(k); 407 Klass* h = ak->higher_dimension(); 408 if (h != NULL) { 409 h->array_klasses_do(collect_array_classes); 410 } 411 } 412 } 413 414 class CollectClassesClosure : public KlassClosure { 415 void do_klass(Klass* k) { 416 if (!(k->is_instance_klass() && InstanceKlass::cast(k)->is_in_error_state())) { 417 _global_klass_objects->append_if_missing(k); 418 } 419 if (k->is_array_klass()) { 420 // Add in the array classes too 421 ArrayKlass* ak = ArrayKlass::cast(k); 422 Klass* h = ak->higher_dimension(); 423 if (h != NULL) { 424 h->array_klasses_do(collect_array_classes); 425 } 426 } 427 } 428 }; 429 430 static void remove_unshareable_in_classes() { 431 for (int i = 0; i < _global_klass_objects->length(); i++) { 432 Klass* k = _global_klass_objects->at(i); 433 if (!k->is_objArray_klass()) { 434 // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info 435 // on their array classes. 436 assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be"); 437 k->remove_unshareable_info(); 438 } 439 } 440 } 441 442 static void remove_java_mirror_in_classes() { 443 for (int i = 0; i < _global_klass_objects->length(); i++) { 444 Klass* k = _global_klass_objects->at(i); 445 if (!k->is_objArray_klass()) { 446 // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info 447 // on their array classes. 448 assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be"); 449 k->remove_java_mirror(); 450 } 451 } 452 } 453 454 static void rewrite_nofast_bytecode(Method* method) { 455 BytecodeStream bcs(method); 456 while (!bcs.is_last_bytecode()) { 457 Bytecodes::Code opcode = bcs.next(); 458 switch (opcode) { 459 case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break; 460 case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break; 461 case Bytecodes::_aload_0: *bcs.bcp() = Bytecodes::_nofast_aload_0; break; 462 case Bytecodes::_iload: { 463 if (!bcs.is_wide()) { 464 *bcs.bcp() = Bytecodes::_nofast_iload; 465 } 466 break; 467 } 468 default: break; 469 } 470 } 471 } 472 473 // Walk all methods in the class list to ensure that they won't be modified at 474 // run time. This includes: 475 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified 476 // at run time by RewriteBytecodes/RewriteFrequentPairs 477 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time. 478 static void rewrite_nofast_bytecodes_and_calculate_fingerprints() { 479 for (int i = 0; i < _global_klass_objects->length(); i++) { 480 Klass* k = _global_klass_objects->at(i); 481 if (k->is_instance_klass()) { 482 InstanceKlass* ik = InstanceKlass::cast(k); 483 for (int i = 0; i < ik->methods()->length(); i++) { 484 Method* m = ik->methods()->at(i); 485 rewrite_nofast_bytecode(m); 486 Fingerprinter fp(m); 487 // The side effect of this call sets method's fingerprint field. 488 fp.fingerprint(); 489 } 490 } 491 } 492 } 493 494 static void relocate_cached_class_file() { 495 for (int i = 0; i < _global_klass_objects->length(); i++) { 496 Klass* k = _global_klass_objects->at(i); 497 if (k->is_instance_klass()) { 498 InstanceKlass* ik = InstanceKlass::cast(k); 499 JvmtiCachedClassFileData* p = ik->get_archived_class_data(); 500 if (p != NULL) { 501 int size = offset_of(JvmtiCachedClassFileData, data) + p->length; 502 JvmtiCachedClassFileData* q = (JvmtiCachedClassFileData*)_od_region.allocate(size); 503 q->length = p->length; 504 memcpy(q->data, p->data, p->length); 505 ik->set_archived_class_data(q); 506 } 507 } 508 } 509 } 510 511 NOT_PRODUCT( 512 static void assert_not_anonymous_class(InstanceKlass* k) { 513 assert(!(k->is_anonymous()), "cannot archive anonymous classes"); 514 } 515 516 // Anonymous classes are not stored inside any dictionaries. They are created by 517 // SystemDictionary::parse_stream() with a non-null host_klass. 518 static void assert_no_anonymoys_classes_in_dictionaries() { 519 ClassLoaderDataGraph::dictionary_classes_do(assert_not_anonymous_class); 520 }) 521 522 // Objects of the Metadata types (such as Klass and ConstantPool) have C++ vtables. 523 // (In GCC this is the field <Type>::_vptr, i.e., first word in the object.) 524 // 525 // Addresses of the vtables and the methods may be different across JVM runs, 526 // if libjvm.so is dynamically loaded at a different base address. 527 // 528 // To ensure that the Metadata objects in the CDS archive always have the correct vtable: 529 // 530 // + at dump time: we redirect the _vptr to point to our own vtables inside 531 // the CDS image 532 // + at run time: we clone the actual contents of the vtables from libjvm.so 533 // into our own tables. 534 535 // Currently, the archive contain ONLY the following types of objects that have C++ vtables. 536 #define CPP_VTABLE_PATCH_TYPES_DO(f) \ 537 f(ConstantPool) \ 538 f(InstanceKlass) \ 539 f(InstanceClassLoaderKlass) \ 540 f(InstanceMirrorKlass) \ 541 f(InstanceRefKlass) \ 542 f(Method) \ 543 f(ObjArrayKlass) \ 544 f(TypeArrayKlass) 545 546 class CppVtableInfo { 547 intptr_t _vtable_size; 548 intptr_t _cloned_vtable[1]; 549 public: 550 static int num_slots(int vtable_size) { 551 return 1 + vtable_size; // Need to add the space occupied by _vtable_size; 552 } 553 int vtable_size() { return int(uintx(_vtable_size)); } 554 void set_vtable_size(int n) { _vtable_size = intptr_t(n); } 555 intptr_t* cloned_vtable() { return &_cloned_vtable[0]; } 556 void zero() { memset(_cloned_vtable, 0, sizeof(intptr_t) * vtable_size()); } 557 // Returns the address of the next CppVtableInfo that can be placed immediately after this CppVtableInfo 558 static size_t byte_size(int vtable_size) { 559 CppVtableInfo i; 560 return pointer_delta(&i._cloned_vtable[vtable_size], &i, sizeof(u1)); 561 } 562 }; 563 564 template <class T> class CppVtableCloner : public T { 565 static intptr_t* vtable_of(Metadata& m) { 566 return *((intptr_t**)&m); 567 } 568 static CppVtableInfo* _info; 569 570 static int get_vtable_length(const char* name); 571 572 public: 573 // Allocate and initialize the C++ vtable, starting from top, but do not go past end. 574 static intptr_t* allocate(const char* name); 575 576 // Clone the vtable to ... 577 static intptr_t* clone_vtable(const char* name, CppVtableInfo* info); 578 579 static void zero_vtable_clone() { 580 assert(DumpSharedSpaces, "dump-time only"); 581 _info->zero(); 582 } 583 584 // Switch the vtable pointer to point to the cloned vtable. 585 static void patch(Metadata* obj) { 586 assert(DumpSharedSpaces, "dump-time only"); 587 *(void**)obj = (void*)(_info->cloned_vtable()); 588 } 589 590 static bool is_valid_shared_object(const T* obj) { 591 intptr_t* vptr = *(intptr_t**)obj; 592 return vptr == _info->cloned_vtable(); 593 } 594 }; 595 596 template <class T> CppVtableInfo* CppVtableCloner<T>::_info = NULL; 597 598 template <class T> 599 intptr_t* CppVtableCloner<T>::allocate(const char* name) { 600 assert(is_aligned(_md_region.top(), sizeof(intptr_t)), "bad alignment"); 601 int n = get_vtable_length(name); 602 _info = (CppVtableInfo*)_md_region.allocate(CppVtableInfo::byte_size(n), sizeof(intptr_t)); 603 _info->set_vtable_size(n); 604 605 intptr_t* p = clone_vtable(name, _info); 606 assert((char*)p == _md_region.top(), "must be"); 607 608 return p; 609 } 610 611 template <class T> 612 intptr_t* CppVtableCloner<T>::clone_vtable(const char* name, CppVtableInfo* info) { 613 if (!DumpSharedSpaces) { 614 assert(_info == 0, "_info is initialized only at dump time"); 615 _info = info; // Remember it -- it will be used by MetaspaceShared::is_valid_shared_method() 616 } 617 T tmp; // Allocate temporary dummy metadata object to get to the original vtable. 618 int n = info->vtable_size(); 619 intptr_t* srcvtable = vtable_of(tmp); 620 intptr_t* dstvtable = info->cloned_vtable(); 621 622 // We already checked (and, if necessary, adjusted n) when the vtables were allocated, so we are 623 // safe to do memcpy. 624 log_debug(cds, vtables)("Copying %3d vtable entries for %s", n, name); 625 memcpy(dstvtable, srcvtable, sizeof(intptr_t) * n); 626 return dstvtable + n; 627 } 628 629 // To determine the size of the vtable for each type, we use the following 630 // trick by declaring 2 subclasses: 631 // 632 // class CppVtableTesterA: public InstanceKlass {virtual int last_virtual_method() {return 1;} }; 633 // class CppVtableTesterB: public InstanceKlass {virtual void* last_virtual_method() {return NULL}; }; 634 // 635 // CppVtableTesterA and CppVtableTesterB's vtables have the following properties: 636 // - Their size (N+1) is exactly one more than the size of InstanceKlass's vtable (N) 637 // - The first N entries have are exactly the same as in InstanceKlass's vtable. 638 // - Their last entry is different. 639 // 640 // So to determine the value of N, we just walk CppVtableTesterA and CppVtableTesterB's tables 641 // and find the first entry that's different. 642 // 643 // This works on all C++ compilers supported by Oracle, but you may need to tweak it for more 644 // esoteric compilers. 645 646 template <class T> class CppVtableTesterB: public T { 647 public: 648 virtual int last_virtual_method() {return 1;} 649 }; 650 651 template <class T> class CppVtableTesterA : public T { 652 public: 653 virtual void* last_virtual_method() { 654 // Make this different than CppVtableTesterB::last_virtual_method so the C++ 655 // compiler/linker won't alias the two functions. 656 return NULL; 657 } 658 }; 659 660 template <class T> 661 int CppVtableCloner<T>::get_vtable_length(const char* name) { 662 CppVtableTesterA<T> a; 663 CppVtableTesterB<T> b; 664 665 intptr_t* avtable = vtable_of(a); 666 intptr_t* bvtable = vtable_of(b); 667 668 // Start at slot 1, because slot 0 may be RTTI (on Solaris/Sparc) 669 int vtable_len = 1; 670 for (; ; vtable_len++) { 671 if (avtable[vtable_len] != bvtable[vtable_len]) { 672 break; 673 } 674 } 675 log_debug(cds, vtables)("Found %3d vtable entries for %s", vtable_len, name); 676 677 return vtable_len; 678 } 679 680 #define ALLOC_CPP_VTABLE_CLONE(c) \ 681 CppVtableCloner<c>::allocate(#c); 682 683 #define CLONE_CPP_VTABLE(c) \ 684 p = CppVtableCloner<c>::clone_vtable(#c, (CppVtableInfo*)p); 685 686 #define ZERO_CPP_VTABLE(c) \ 687 CppVtableCloner<c>::zero_vtable_clone(); 688 689 // This can be called at both dump time and run time. 690 intptr_t* MetaspaceShared::clone_cpp_vtables(intptr_t* p) { 691 assert(DumpSharedSpaces || UseSharedSpaces, "sanity"); 692 CPP_VTABLE_PATCH_TYPES_DO(CLONE_CPP_VTABLE); 693 return p; 694 } 695 696 void MetaspaceShared::zero_cpp_vtable_clones_for_writing() { 697 assert(DumpSharedSpaces, "dump-time only"); 698 CPP_VTABLE_PATCH_TYPES_DO(ZERO_CPP_VTABLE); 699 } 700 701 // Allocate and initialize the C++ vtables, starting from top, but do not go past end. 702 void MetaspaceShared::allocate_cpp_vtable_clones() { 703 assert(DumpSharedSpaces, "dump-time only"); 704 // Layout (each slot is a intptr_t): 705 // [number of slots in the first vtable = n1] 706 // [ <n1> slots for the first vtable] 707 // [number of slots in the first second = n2] 708 // [ <n2> slots for the second vtable] 709 // ... 710 // The order of the vtables is the same as the CPP_VTAB_PATCH_TYPES_DO macro. 711 CPP_VTABLE_PATCH_TYPES_DO(ALLOC_CPP_VTABLE_CLONE); 712 } 713 714 // Switch the vtable pointer to point to the cloned vtable. We assume the 715 // vtable pointer is in first slot in object. 716 void MetaspaceShared::patch_cpp_vtable_pointers() { 717 int n = _global_klass_objects->length(); 718 for (int i = 0; i < n; i++) { 719 Klass* obj = _global_klass_objects->at(i); 720 if (obj->is_instance_klass()) { 721 InstanceKlass* ik = InstanceKlass::cast(obj); 722 if (ik->is_class_loader_instance_klass()) { 723 CppVtableCloner<InstanceClassLoaderKlass>::patch(ik); 724 } else if (ik->is_reference_instance_klass()) { 725 CppVtableCloner<InstanceRefKlass>::patch(ik); 726 } else if (ik->is_mirror_instance_klass()) { 727 CppVtableCloner<InstanceMirrorKlass>::patch(ik); 728 } else { 729 CppVtableCloner<InstanceKlass>::patch(ik); 730 } 731 ConstantPool* cp = ik->constants(); 732 CppVtableCloner<ConstantPool>::patch(cp); 733 for (int j = 0; j < ik->methods()->length(); j++) { 734 Method* m = ik->methods()->at(j); 735 CppVtableCloner<Method>::patch(m); 736 assert(CppVtableCloner<Method>::is_valid_shared_object(m), "must be"); 737 } 738 } else if (obj->is_objArray_klass()) { 739 CppVtableCloner<ObjArrayKlass>::patch(obj); 740 } else { 741 assert(obj->is_typeArray_klass(), "sanity"); 742 CppVtableCloner<TypeArrayKlass>::patch(obj); 743 } 744 } 745 } 746 747 bool MetaspaceShared::is_valid_shared_method(const Method* m) { 748 assert(is_in_shared_metaspace(m), "must be"); 749 return CppVtableCloner<Method>::is_valid_shared_object(m); 750 } 751 752 // Closure for serializing initialization data out to a data area to be 753 // written to the shared file. 754 755 class WriteClosure : public SerializeClosure { 756 private: 757 DumpRegion* _dump_region; 758 759 public: 760 WriteClosure(DumpRegion* r) { 761 _dump_region = r; 762 } 763 764 void do_ptr(void** p) { 765 _dump_region->append_intptr_t((intptr_t)*p); 766 } 767 768 void do_u4(u4* p) { 769 void* ptr = (void*)(uintx(*p)); 770 do_ptr(&ptr); 771 } 772 773 void do_tag(int tag) { 774 _dump_region->append_intptr_t((intptr_t)tag); 775 } 776 777 void do_region(u_char* start, size_t size) { 778 assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment"); 779 assert(size % sizeof(intptr_t) == 0, "bad size"); 780 do_tag((int)size); 781 while (size > 0) { 782 _dump_region->append_intptr_t(*(intptr_t*)start); 783 start += sizeof(intptr_t); 784 size -= sizeof(intptr_t); 785 } 786 } 787 788 bool reading() const { return false; } 789 }; 790 791 // This is for dumping detailed statistics for the allocations 792 // in the shared spaces. 793 class DumpAllocStats : public ResourceObj { 794 public: 795 796 // Here's poor man's enum inheritance 797 #define SHAREDSPACE_OBJ_TYPES_DO(f) \ 798 METASPACE_OBJ_TYPES_DO(f) \ 799 f(SymbolHashentry) \ 800 f(SymbolBucket) \ 801 f(StringHashentry) \ 802 f(StringBucket) \ 803 f(Other) 804 805 enum Type { 806 // Types are MetaspaceObj::ClassType, MetaspaceObj::SymbolType, etc 807 SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_DECLARE) 808 _number_of_types 809 }; 810 811 static const char * type_name(Type type) { 812 switch(type) { 813 SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_NAME_CASE) 814 default: 815 ShouldNotReachHere(); 816 return NULL; 817 } 818 } 819 820 public: 821 enum { RO = 0, RW = 1 }; 822 823 int _counts[2][_number_of_types]; 824 int _bytes [2][_number_of_types]; 825 826 DumpAllocStats() { 827 memset(_counts, 0, sizeof(_counts)); 828 memset(_bytes, 0, sizeof(_bytes)); 829 }; 830 831 void record(MetaspaceObj::Type type, int byte_size, bool read_only) { 832 assert(int(type) >= 0 && type < MetaspaceObj::_number_of_types, "sanity"); 833 int which = (read_only) ? RO : RW; 834 _counts[which][type] ++; 835 _bytes [which][type] += byte_size; 836 } 837 838 void record_other_type(int byte_size, bool read_only) { 839 int which = (read_only) ? RO : RW; 840 _bytes [which][OtherType] += byte_size; 841 } 842 void print_stats(int ro_all, int rw_all, int mc_all, int md_all); 843 }; 844 845 void DumpAllocStats::print_stats(int ro_all, int rw_all, int mc_all, int md_all) { 846 // Calculate size of data that was not allocated by Metaspace::allocate() 847 MetaspaceSharedStats *stats = MetaspaceShared::stats(); 848 849 // symbols 850 _counts[RO][SymbolHashentryType] = stats->symbol.hashentry_count; 851 _bytes [RO][SymbolHashentryType] = stats->symbol.hashentry_bytes; 852 853 _counts[RO][SymbolBucketType] = stats->symbol.bucket_count; 854 _bytes [RO][SymbolBucketType] = stats->symbol.bucket_bytes; 855 856 // strings 857 _counts[RO][StringHashentryType] = stats->string.hashentry_count; 858 _bytes [RO][StringHashentryType] = stats->string.hashentry_bytes; 859 860 _counts[RO][StringBucketType] = stats->string.bucket_count; 861 _bytes [RO][StringBucketType] = stats->string.bucket_bytes; 862 863 // TODO: count things like dictionary, vtable, etc 864 _bytes[RW][OtherType] += mc_all + md_all; 865 rw_all += mc_all + md_all; // mc/md are mapped Read/Write 866 867 // prevent divide-by-zero 868 if (ro_all < 1) { 869 ro_all = 1; 870 } 871 if (rw_all < 1) { 872 rw_all = 1; 873 } 874 875 int all_ro_count = 0; 876 int all_ro_bytes = 0; 877 int all_rw_count = 0; 878 int all_rw_bytes = 0; 879 880 // To make fmt_stats be a syntactic constant (for format warnings), use #define. 881 #define fmt_stats "%-20s: %8d %10d %5.1f | %8d %10d %5.1f | %8d %10d %5.1f" 882 const char *sep = "--------------------+---------------------------+---------------------------+--------------------------"; 883 const char *hdr = " ro_cnt ro_bytes % | rw_cnt rw_bytes % | all_cnt all_bytes %"; 884 885 LogMessage(cds) msg; 886 887 msg.info("Detailed metadata info (excluding od/st regions; rw stats include md/mc regions):"); 888 msg.info("%s", hdr); 889 msg.info("%s", sep); 890 for (int type = 0; type < int(_number_of_types); type ++) { 891 const char *name = type_name((Type)type); 892 int ro_count = _counts[RO][type]; 893 int ro_bytes = _bytes [RO][type]; 894 int rw_count = _counts[RW][type]; 895 int rw_bytes = _bytes [RW][type]; 896 int count = ro_count + rw_count; 897 int bytes = ro_bytes + rw_bytes; 898 899 double ro_perc = percent_of(ro_bytes, ro_all); 900 double rw_perc = percent_of(rw_bytes, rw_all); 901 double perc = percent_of(bytes, ro_all + rw_all); 902 903 msg.info(fmt_stats, name, 904 ro_count, ro_bytes, ro_perc, 905 rw_count, rw_bytes, rw_perc, 906 count, bytes, perc); 907 908 all_ro_count += ro_count; 909 all_ro_bytes += ro_bytes; 910 all_rw_count += rw_count; 911 all_rw_bytes += rw_bytes; 912 } 913 914 int all_count = all_ro_count + all_rw_count; 915 int all_bytes = all_ro_bytes + all_rw_bytes; 916 917 double all_ro_perc = percent_of(all_ro_bytes, ro_all); 918 double all_rw_perc = percent_of(all_rw_bytes, rw_all); 919 double all_perc = percent_of(all_bytes, ro_all + rw_all); 920 921 msg.info("%s", sep); 922 msg.info(fmt_stats, "Total", 923 all_ro_count, all_ro_bytes, all_ro_perc, 924 all_rw_count, all_rw_bytes, all_rw_perc, 925 all_count, all_bytes, all_perc); 926 927 assert(all_ro_bytes == ro_all, "everything should have been counted"); 928 assert(all_rw_bytes == rw_all, "everything should have been counted"); 929 930 #undef fmt_stats 931 } 932 933 // Populate the shared space. 934 935 class VM_PopulateDumpSharedSpace: public VM_Operation { 936 private: 937 GrowableArray<MemRegion> *_string_regions; 938 GrowableArray<MemRegion> *_open_archive_heap_regions; 939 940 void dump_java_heap_objects() NOT_CDS_JAVA_HEAP_RETURN; 941 void dump_symbols(); 942 char* dump_read_only_tables(); 943 void print_region_stats(); 944 void print_heap_region_stats(GrowableArray<MemRegion> *heap_mem, 945 const char *name, const size_t total_size); 946 public: 947 948 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; } 949 void doit(); // outline because gdb sucks 950 static void write_region(FileMapInfo* mapinfo, int region, DumpRegion* space, bool read_only, bool allow_exec); 951 }; // class VM_PopulateDumpSharedSpace 952 953 class SortedSymbolClosure: public SymbolClosure { 954 GrowableArray<Symbol*> _symbols; 955 virtual void do_symbol(Symbol** sym) { 956 assert((*sym)->is_permanent(), "archived symbols must be permanent"); 957 _symbols.append(*sym); 958 } 959 static int compare_symbols_by_address(Symbol** a, Symbol** b) { 960 if (a[0] < b[0]) { 961 return -1; 962 } else if (a[0] == b[0]) { 963 return 0; 964 } else { 965 return 1; 966 } 967 } 968 969 public: 970 SortedSymbolClosure() { 971 SymbolTable::symbols_do(this); 972 _symbols.sort(compare_symbols_by_address); 973 } 974 GrowableArray<Symbol*>* get_sorted_symbols() { 975 return &_symbols; 976 } 977 }; 978 979 // ArchiveCompactor -- 980 // 981 // This class is the central piece of shared archive compaction -- all metaspace data are 982 // initially allocated outside of the shared regions. ArchiveCompactor copies the 983 // metaspace data into their final location in the shared regions. 984 985 class ArchiveCompactor : AllStatic { 986 static DumpAllocStats* _alloc_stats; 987 static SortedSymbolClosure* _ssc; 988 989 static unsigned my_hash(const address& a) { 990 return primitive_hash<address>(a); 991 } 992 static bool my_equals(const address& a0, const address& a1) { 993 return primitive_equals<address>(a0, a1); 994 } 995 typedef ResourceHashtable< 996 address, address, 997 ArchiveCompactor::my_hash, // solaris compiler doesn't like: primitive_hash<address> 998 ArchiveCompactor::my_equals, // solaris compiler doesn't like: primitive_equals<address> 999 16384, ResourceObj::C_HEAP> RelocationTable; 1000 static RelocationTable* _new_loc_table; 1001 1002 public: 1003 static void initialize() { 1004 _alloc_stats = new(ResourceObj::C_HEAP, mtInternal)DumpAllocStats; 1005 _new_loc_table = new(ResourceObj::C_HEAP, mtInternal)RelocationTable; 1006 } 1007 static DumpAllocStats* alloc_stats() { 1008 return _alloc_stats; 1009 } 1010 1011 static void allocate(MetaspaceClosure::Ref* ref, bool read_only) { 1012 address obj = ref->obj(); 1013 int bytes = ref->size() * BytesPerWord; 1014 char* p; 1015 size_t alignment = BytesPerWord; 1016 char* oldtop; 1017 char* newtop; 1018 1019 if (read_only) { 1020 oldtop = _ro_region.top(); 1021 p = _ro_region.allocate(bytes, alignment); 1022 newtop = _ro_region.top(); 1023 } else { 1024 oldtop = _rw_region.top(); 1025 p = _rw_region.allocate(bytes, alignment); 1026 newtop = _rw_region.top(); 1027 } 1028 memcpy(p, obj, bytes); 1029 bool isnew = _new_loc_table->put(obj, (address)p); 1030 log_trace(cds)("Copy: " PTR_FORMAT " ==> " PTR_FORMAT " %d", p2i(obj), p2i(p), bytes); 1031 assert(isnew, "must be"); 1032 1033 _alloc_stats->record(ref->msotype(), int(newtop - oldtop), read_only); 1034 if (ref->msotype() == MetaspaceObj::SymbolType) { 1035 uintx delta = MetaspaceShared::object_delta(p); 1036 if (delta > MAX_SHARED_DELTA) { 1037 // This is just a sanity check and should not appear in any real world usage. This 1038 // happens only if you allocate more than 2GB of Symbols and would require 1039 // millions of shared classes. 1040 vm_exit_during_initialization("Too many Symbols in the CDS archive", 1041 "Please reduce the number of shared classes."); 1042 } 1043 } 1044 } 1045 1046 static address get_new_loc(MetaspaceClosure::Ref* ref) { 1047 address* pp = _new_loc_table->get(ref->obj()); 1048 assert(pp != NULL, "must be"); 1049 return *pp; 1050 } 1051 1052 private: 1053 // Makes a shallow copy of visited MetaspaceObj's 1054 class ShallowCopier: public UniqueMetaspaceClosure { 1055 bool _read_only; 1056 public: 1057 ShallowCopier(bool read_only) : _read_only(read_only) {} 1058 1059 virtual void do_unique_ref(Ref* ref, bool read_only) { 1060 if (read_only == _read_only) { 1061 allocate(ref, read_only); 1062 } 1063 } 1064 }; 1065 1066 // Relocate embedded pointers within a MetaspaceObj's shallow copy 1067 class ShallowCopyEmbeddedRefRelocator: public UniqueMetaspaceClosure { 1068 public: 1069 virtual void do_unique_ref(Ref* ref, bool read_only) { 1070 address new_loc = get_new_loc(ref); 1071 RefRelocator refer; 1072 ref->metaspace_pointers_do_at(&refer, new_loc); 1073 } 1074 }; 1075 1076 // Relocate a reference to point to its shallow copy 1077 class RefRelocator: public MetaspaceClosure { 1078 public: 1079 virtual bool do_ref(Ref* ref, bool read_only) { 1080 if (ref->not_null()) { 1081 ref->update(get_new_loc(ref)); 1082 } 1083 return false; // Do not recurse. 1084 } 1085 }; 1086 1087 #ifdef ASSERT 1088 class IsRefInArchiveChecker: public MetaspaceClosure { 1089 public: 1090 virtual bool do_ref(Ref* ref, bool read_only) { 1091 if (ref->not_null()) { 1092 char* obj = (char*)ref->obj(); 1093 assert(_ro_region.contains(obj) || _rw_region.contains(obj), 1094 "must be relocated to point to CDS archive"); 1095 } 1096 return false; // Do not recurse. 1097 } 1098 }; 1099 #endif 1100 1101 public: 1102 static void copy_and_compact() { 1103 // We should no longer allocate anything from the metaspace, so that 1104 // we can have a stable set of MetaspaceObjs to work with. 1105 Metaspace::freeze(); 1106 1107 ResourceMark rm; 1108 SortedSymbolClosure the_ssc; // StackObj 1109 _ssc = &the_ssc; 1110 1111 tty->print_cr("Scanning all metaspace objects ... "); 1112 { 1113 // allocate and shallow-copy RW objects, immediately following the MC region 1114 tty->print_cr("Allocating RW objects ... "); 1115 _mc_region.pack(&_rw_region); 1116 1117 ResourceMark rm; 1118 ShallowCopier rw_copier(false); 1119 iterate_roots(&rw_copier); 1120 } 1121 { 1122 // allocate and shallow-copy of RO object, immediately following the RW region 1123 tty->print_cr("Allocating RO objects ... "); 1124 _rw_region.pack(&_ro_region); 1125 1126 ResourceMark rm; 1127 ShallowCopier ro_copier(true); 1128 iterate_roots(&ro_copier); 1129 } 1130 { 1131 tty->print_cr("Relocating embedded pointers ... "); 1132 ResourceMark rm; 1133 ShallowCopyEmbeddedRefRelocator emb_reloc; 1134 iterate_roots(&emb_reloc); 1135 } 1136 { 1137 tty->print_cr("Relocating external roots ... "); 1138 ResourceMark rm; 1139 RefRelocator ext_reloc; 1140 iterate_roots(&ext_reloc); 1141 } 1142 1143 #ifdef ASSERT 1144 { 1145 tty->print_cr("Verifying external roots ... "); 1146 ResourceMark rm; 1147 IsRefInArchiveChecker checker; 1148 iterate_roots(&checker); 1149 } 1150 #endif 1151 1152 1153 // cleanup 1154 _ssc = NULL; 1155 } 1156 1157 // We must relocate the System::_well_known_klasses only after we have copied the 1158 // java objects in during dump_java_heap_objects(): during the object copy, we operate on 1159 // old objects which assert that their klass is the original klass. 1160 static void relocate_well_known_klasses() { 1161 { 1162 tty->print_cr("Relocating SystemDictionary::_well_known_klasses[] ... "); 1163 ResourceMark rm; 1164 RefRelocator ext_reloc; 1165 SystemDictionary::well_known_klasses_do(&ext_reloc); 1166 } 1167 // NOTE: after this point, we shouldn't have any globals that can reach the old 1168 // objects. 1169 1170 // We cannot use any of the objects in the heap anymore (except for the objects 1171 // in the CDS shared string regions) because their headers no longer point to 1172 // valid Klasses. 1173 } 1174 1175 static void iterate_roots(MetaspaceClosure* it) { 1176 GrowableArray<Symbol*>* symbols = _ssc->get_sorted_symbols(); 1177 for (int i=0; i<symbols->length(); i++) { 1178 it->push(symbols->adr_at(i)); 1179 } 1180 if (_global_klass_objects != NULL) { 1181 // Need to fix up the pointers 1182 for (int i = 0; i < _global_klass_objects->length(); i++) { 1183 // NOTE -- this requires that the vtable is NOT yet patched, or else we are hosed. 1184 it->push(_global_klass_objects->adr_at(i)); 1185 } 1186 } 1187 FileMapInfo::metaspace_pointers_do(it); 1188 SystemDictionary::classes_do(it); 1189 Universe::metaspace_pointers_do(it); 1190 SymbolTable::metaspace_pointers_do(it); 1191 vmSymbols::metaspace_pointers_do(it); 1192 } 1193 1194 static Klass* get_relocated_klass(Klass* orig_klass) { 1195 address* pp = _new_loc_table->get((address)orig_klass); 1196 assert(pp != NULL, "must be"); 1197 Klass* klass = (Klass*)(*pp); 1198 assert(klass->is_klass(), "must be"); 1199 return klass; 1200 } 1201 }; 1202 1203 DumpAllocStats* ArchiveCompactor::_alloc_stats; 1204 SortedSymbolClosure* ArchiveCompactor::_ssc; 1205 ArchiveCompactor::RelocationTable* ArchiveCompactor::_new_loc_table; 1206 1207 void VM_PopulateDumpSharedSpace::write_region(FileMapInfo* mapinfo, int region_idx, 1208 DumpRegion* dump_region, bool read_only, bool allow_exec) { 1209 mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec); 1210 } 1211 1212 void VM_PopulateDumpSharedSpace::dump_symbols() { 1213 tty->print_cr("Dumping symbol table ..."); 1214 1215 NOT_PRODUCT(SymbolTable::verify()); 1216 SymbolTable::write_to_archive(); 1217 } 1218 1219 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() { 1220 char* oldtop = _ro_region.top(); 1221 // Reorder the system dictionary. Moving the symbols affects 1222 // how the hash table indices are calculated. 1223 SystemDictionary::reorder_dictionary_for_sharing(); 1224 tty->print("Removing java_mirror ... "); 1225 remove_java_mirror_in_classes(); 1226 tty->print_cr("done. "); 1227 NOT_PRODUCT(SystemDictionary::verify();) 1228 1229 size_t buckets_bytes = SystemDictionary::count_bytes_for_buckets(); 1230 char* buckets_top = _ro_region.allocate(buckets_bytes, sizeof(intptr_t)); 1231 SystemDictionary::copy_buckets(buckets_top, _ro_region.top()); 1232 1233 size_t table_bytes = SystemDictionary::count_bytes_for_table(); 1234 char* table_top = _ro_region.allocate(table_bytes, sizeof(intptr_t)); 1235 SystemDictionary::copy_table(table_top, _ro_region.top()); 1236 1237 // Write the other data to the output array. 1238 WriteClosure wc(&_ro_region); 1239 MetaspaceShared::serialize(&wc); 1240 1241 char* newtop = _ro_region.top(); 1242 ArchiveCompactor::alloc_stats()->record_other_type(int(newtop - oldtop), true); 1243 return buckets_top; 1244 } 1245 1246 void VM_PopulateDumpSharedSpace::doit() { 1247 Thread* THREAD = VMThread::vm_thread(); 1248 1249 NOT_PRODUCT(SystemDictionary::verify();) 1250 // The following guarantee is meant to ensure that no loader constraints 1251 // exist yet, since the constraints table is not shared. This becomes 1252 // more important now that we don't re-initialize vtables/itables for 1253 // shared classes at runtime, where constraints were previously created. 1254 guarantee(SystemDictionary::constraints()->number_of_entries() == 0, 1255 "loader constraints are not saved"); 1256 guarantee(SystemDictionary::placeholders()->number_of_entries() == 0, 1257 "placeholders are not saved"); 1258 // Revisit and implement this if we prelink method handle call sites: 1259 guarantee(SystemDictionary::invoke_method_table() == NULL || 1260 SystemDictionary::invoke_method_table()->number_of_entries() == 0, 1261 "invoke method table is not saved"); 1262 1263 // At this point, many classes have been loaded. 1264 // Gather systemDictionary classes in a global array and do everything to 1265 // that so we don't have to walk the SystemDictionary again. 1266 _global_klass_objects = new GrowableArray<Klass*>(1000); 1267 CollectClassesClosure collect_classes; 1268 ClassLoaderDataGraph::loaded_classes_do(&collect_classes); 1269 1270 tty->print_cr("Number of classes %d", _global_klass_objects->length()); 1271 { 1272 int num_type_array = 0, num_obj_array = 0, num_inst = 0; 1273 for (int i = 0; i < _global_klass_objects->length(); i++) { 1274 Klass* k = _global_klass_objects->at(i); 1275 if (k->is_instance_klass()) { 1276 num_inst ++; 1277 } else if (k->is_objArray_klass()) { 1278 num_obj_array ++; 1279 } else { 1280 assert(k->is_typeArray_klass(), "sanity"); 1281 num_type_array ++; 1282 } 1283 } 1284 tty->print_cr(" instance classes = %5d", num_inst); 1285 tty->print_cr(" obj array classes = %5d", num_obj_array); 1286 tty->print_cr(" type array classes = %5d", num_type_array); 1287 } 1288 1289 // Ensure the ConstMethods won't be modified at run-time 1290 tty->print("Updating ConstMethods ... "); 1291 rewrite_nofast_bytecodes_and_calculate_fingerprints(); 1292 tty->print_cr("done. "); 1293 1294 // Move classes from platform/system dictionaries into the boot dictionary 1295 SystemDictionary::combine_shared_dictionaries(); 1296 1297 // Remove all references outside the metadata 1298 tty->print("Removing unshareable information ... "); 1299 remove_unshareable_in_classes(); 1300 tty->print_cr("done. "); 1301 1302 // We don't support archiving anonymous classes. Verify that they are not stored in 1303 // the any dictionaries. 1304 NOT_PRODUCT(assert_no_anonymoys_classes_in_dictionaries()); 1305 1306 SystemDictionaryShared::finalize_verification_constraints(); 1307 1308 ArchiveCompactor::initialize(); 1309 ArchiveCompactor::copy_and_compact(); 1310 1311 dump_symbols(); 1312 1313 // Dump supported java heap objects 1314 _string_regions = NULL; 1315 _open_archive_heap_regions = NULL; 1316 dump_java_heap_objects(); 1317 1318 ArchiveCompactor::relocate_well_known_klasses(); 1319 1320 char* read_only_tables_start = dump_read_only_tables(); 1321 _ro_region.pack(&_md_region); 1322 1323 char* vtbl_list = _md_region.top(); 1324 MetaspaceShared::allocate_cpp_vtable_clones(); 1325 _md_region.pack(&_od_region); 1326 1327 // Relocate the archived class file data into the od region 1328 relocate_cached_class_file(); 1329 _od_region.pack(); 1330 1331 // The 5 core spaces are allocated consecutively mc->rw->ro->md->od, so there total size 1332 // is just the spaces between the two ends. 1333 size_t core_spaces_size = _od_region.end() - _mc_region.base(); 1334 assert(core_spaces_size == (size_t)align_up(core_spaces_size, Metaspace::reserve_alignment()), 1335 "should already be aligned"); 1336 1337 // During patching, some virtual methods may be called, so at this point 1338 // the vtables must contain valid methods (as filled in by CppVtableCloner::allocate). 1339 MetaspaceShared::patch_cpp_vtable_pointers(); 1340 1341 // The vtable clones contain addresses of the current process. 1342 // We don't want to write these addresses into the archive. 1343 MetaspaceShared::zero_cpp_vtable_clones_for_writing(); 1344 1345 // Create and write the archive file that maps the shared spaces. 1346 1347 FileMapInfo* mapinfo = new FileMapInfo(); 1348 mapinfo->populate_header(os::vm_allocation_granularity()); 1349 mapinfo->set_read_only_tables_start(read_only_tables_start); 1350 mapinfo->set_misc_data_patching_start(vtbl_list); 1351 mapinfo->set_cds_i2i_entry_code_buffers(MetaspaceShared::cds_i2i_entry_code_buffers()); 1352 mapinfo->set_cds_i2i_entry_code_buffers_size(MetaspaceShared::cds_i2i_entry_code_buffers_size()); 1353 mapinfo->set_core_spaces_size(core_spaces_size); 1354 1355 for (int pass=1; pass<=2; pass++) { 1356 if (pass == 1) { 1357 // The first pass doesn't actually write the data to disk. All it 1358 // does is to update the fields in the mapinfo->_header. 1359 } else { 1360 // After the first pass, the contents of mapinfo->_header are finalized, 1361 // so we can compute the header's CRC, and write the contents of the header 1362 // and the regions into disk. 1363 mapinfo->open_for_write(); 1364 mapinfo->set_header_crc(mapinfo->compute_header_crc()); 1365 } 1366 mapinfo->write_header(); 1367 1368 // NOTE: md contains the trampoline code for method entries, which are patched at run time, 1369 // so it needs to be read/write. 1370 write_region(mapinfo, MetaspaceShared::mc, &_mc_region, /*read_only=*/false,/*allow_exec=*/true); 1371 write_region(mapinfo, MetaspaceShared::rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false); 1372 write_region(mapinfo, MetaspaceShared::ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false); 1373 write_region(mapinfo, MetaspaceShared::md, &_md_region, /*read_only=*/false,/*allow_exec=*/false); 1374 write_region(mapinfo, MetaspaceShared::od, &_od_region, /*read_only=*/true, /*allow_exec=*/false); 1375 1376 _total_string_region_size = mapinfo->write_archive_heap_regions( 1377 _string_regions, 1378 MetaspaceShared::first_string, 1379 MetaspaceShared::max_strings); 1380 _total_open_archive_region_size = mapinfo->write_archive_heap_regions( 1381 _open_archive_heap_regions, 1382 MetaspaceShared::first_open_archive_heap_region, 1383 MetaspaceShared::max_open_archive_heap_region); 1384 } 1385 1386 mapinfo->close(); 1387 1388 // Restore the vtable in case we invoke any virtual methods. 1389 MetaspaceShared::clone_cpp_vtables((intptr_t*)vtbl_list); 1390 1391 print_region_stats(); 1392 1393 if (log_is_enabled(Info, cds)) { 1394 ArchiveCompactor::alloc_stats()->print_stats(int(_ro_region.used()), int(_rw_region.used()), 1395 int(_mc_region.used()), int(_md_region.used())); 1396 } 1397 1398 if (PrintSystemDictionaryAtExit) { 1399 SystemDictionary::print(); 1400 } 1401 // There may be other pending VM operations that operate on the InstanceKlasses, 1402 // which will fail because InstanceKlasses::remove_unshareable_info() 1403 // has been called. Forget these operations and exit the VM directly. 1404 vm_direct_exit(0); 1405 } 1406 1407 void VM_PopulateDumpSharedSpace::print_region_stats() { 1408 // Print statistics of all the regions 1409 const size_t total_reserved = _ro_region.reserved() + _rw_region.reserved() + 1410 _mc_region.reserved() + _md_region.reserved() + 1411 _od_region.reserved() + 1412 _total_string_region_size + 1413 _total_open_archive_region_size; 1414 const size_t total_bytes = _ro_region.used() + _rw_region.used() + 1415 _mc_region.used() + _md_region.used() + 1416 _od_region.used() + 1417 _total_string_region_size + 1418 _total_open_archive_region_size; 1419 const double total_u_perc = percent_of(total_bytes, total_reserved); 1420 1421 _mc_region.print(total_reserved); 1422 _rw_region.print(total_reserved); 1423 _ro_region.print(total_reserved); 1424 _md_region.print(total_reserved); 1425 _od_region.print(total_reserved); 1426 print_heap_region_stats(_string_regions, "st", total_reserved); 1427 print_heap_region_stats(_open_archive_heap_regions, "oa", total_reserved); 1428 1429 tty->print_cr("total : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]", 1430 total_bytes, total_reserved, total_u_perc); 1431 } 1432 1433 void VM_PopulateDumpSharedSpace::print_heap_region_stats(GrowableArray<MemRegion> *heap_mem, 1434 const char *name, const size_t total_size) { 1435 int arr_len = heap_mem == NULL ? 0 : heap_mem->length(); 1436 for (int i = 0; i < arr_len; i++) { 1437 char* start = (char*)heap_mem->at(i).start(); 1438 size_t size = heap_mem->at(i).byte_size(); 1439 char* top = start + size; 1440 tty->print_cr("%s%d space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used] at " INTPTR_FORMAT, 1441 name, i, size, size/double(total_size)*100.0, size, p2i(start)); 1442 1443 } 1444 } 1445 1446 // Update a Java object to point its Klass* to the new location after 1447 // shared archive has been compacted. 1448 void MetaspaceShared::relocate_klass_ptr(oop o) { 1449 assert(DumpSharedSpaces, "sanity"); 1450 Klass* k = ArchiveCompactor::get_relocated_klass(o->klass()); 1451 o->set_klass(k); 1452 } 1453 1454 class LinkSharedClassesClosure : public KlassClosure { 1455 Thread* THREAD; 1456 bool _made_progress; 1457 public: 1458 LinkSharedClassesClosure(Thread* thread) : THREAD(thread), _made_progress(false) {} 1459 1460 void reset() { _made_progress = false; } 1461 bool made_progress() const { return _made_progress; } 1462 1463 void do_klass(Klass* k) { 1464 if (k->is_instance_klass()) { 1465 InstanceKlass* ik = InstanceKlass::cast(k); 1466 // Link the class to cause the bytecodes to be rewritten and the 1467 // cpcache to be created. Class verification is done according 1468 // to -Xverify setting. 1469 _made_progress |= MetaspaceShared::try_link_class(ik, THREAD); 1470 guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class"); 1471 1472 ik->constants()->resolve_class_constants(THREAD); 1473 } 1474 } 1475 }; 1476 1477 class CheckSharedClassesClosure : public KlassClosure { 1478 bool _made_progress; 1479 public: 1480 CheckSharedClassesClosure() : _made_progress(false) {} 1481 1482 void reset() { _made_progress = false; } 1483 bool made_progress() const { return _made_progress; } 1484 void do_klass(Klass* k) { 1485 if (k->is_instance_klass() && InstanceKlass::cast(k)->check_sharing_error_state()) { 1486 _made_progress = true; 1487 } 1488 } 1489 }; 1490 1491 void MetaspaceShared::check_shared_class_loader_type(Klass* k) { 1492 if (k->is_instance_klass()) { 1493 InstanceKlass* ik = InstanceKlass::cast(k); 1494 u2 loader_type = ik->loader_type(); 1495 ResourceMark rm; 1496 guarantee(loader_type != 0, 1497 "Class loader type is not set for this class %s", ik->name()->as_C_string()); 1498 } 1499 } 1500 1501 void MetaspaceShared::link_and_cleanup_shared_classes(TRAPS) { 1502 // We need to iterate because verification may cause additional classes 1503 // to be loaded. 1504 LinkSharedClassesClosure link_closure(THREAD); 1505 do { 1506 link_closure.reset(); 1507 ClassLoaderDataGraph::loaded_classes_do(&link_closure); 1508 guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class"); 1509 } while (link_closure.made_progress()); 1510 1511 if (_has_error_classes) { 1512 // Mark all classes whose super class or interfaces failed verification. 1513 CheckSharedClassesClosure check_closure; 1514 do { 1515 // Not completely sure if we need to do this iteratively. Anyway, 1516 // we should come here only if there are unverifiable classes, which 1517 // shouldn't happen in normal cases. So better safe than sorry. 1518 check_closure.reset(); 1519 ClassLoaderDataGraph::loaded_classes_do(&check_closure); 1520 } while (check_closure.made_progress()); 1521 1522 if (IgnoreUnverifiableClassesDuringDump) { 1523 // This is useful when running JCK or SQE tests. You should not 1524 // enable this when running real apps. 1525 SystemDictionary::remove_classes_in_error_state(); 1526 } else { 1527 tty->print_cr("Please remove the unverifiable classes from your class list and try again"); 1528 exit(1); 1529 } 1530 } 1531 } 1532 1533 void MetaspaceShared::prepare_for_dumping() { 1534 Arguments::check_unsupported_dumping_properties(); 1535 ClassLoader::initialize_shared_path(); 1536 FileMapInfo::allocate_classpath_entry_table(); 1537 } 1538 1539 // Preload classes from a list, populate the shared spaces and dump to a 1540 // file. 1541 void MetaspaceShared::preload_and_dump(TRAPS) { 1542 { TraceTime timer("Dump Shared Spaces", TRACETIME_LOG(Info, startuptime)); 1543 ResourceMark rm; 1544 char class_list_path_str[JVM_MAXPATHLEN]; 1545 // Preload classes to be shared. 1546 // Should use some os:: method rather than fopen() here. aB. 1547 const char* class_list_path; 1548 if (SharedClassListFile == NULL) { 1549 // Construct the path to the class list (in jre/lib) 1550 // Walk up two directories from the location of the VM and 1551 // optionally tack on "lib" (depending on platform) 1552 os::jvm_path(class_list_path_str, sizeof(class_list_path_str)); 1553 for (int i = 0; i < 3; i++) { 1554 char *end = strrchr(class_list_path_str, *os::file_separator()); 1555 if (end != NULL) *end = '\0'; 1556 } 1557 int class_list_path_len = (int)strlen(class_list_path_str); 1558 if (class_list_path_len >= 3) { 1559 if (strcmp(class_list_path_str + class_list_path_len - 3, "lib") != 0) { 1560 if (class_list_path_len < JVM_MAXPATHLEN - 4) { 1561 jio_snprintf(class_list_path_str + class_list_path_len, 1562 sizeof(class_list_path_str) - class_list_path_len, 1563 "%slib", os::file_separator()); 1564 class_list_path_len += 4; 1565 } 1566 } 1567 } 1568 if (class_list_path_len < JVM_MAXPATHLEN - 10) { 1569 jio_snprintf(class_list_path_str + class_list_path_len, 1570 sizeof(class_list_path_str) - class_list_path_len, 1571 "%sclasslist", os::file_separator()); 1572 } 1573 class_list_path = class_list_path_str; 1574 } else { 1575 class_list_path = SharedClassListFile; 1576 } 1577 1578 tty->print_cr("Loading classes to share ..."); 1579 _has_error_classes = false; 1580 int class_count = preload_classes(class_list_path, THREAD); 1581 if (ExtraSharedClassListFile) { 1582 class_count += preload_classes(ExtraSharedClassListFile, THREAD); 1583 } 1584 tty->print_cr("Loading classes to share: done."); 1585 1586 log_info(cds)("Shared spaces: preloaded %d classes", class_count); 1587 1588 // Rewrite and link classes 1589 tty->print_cr("Rewriting and linking classes ..."); 1590 1591 // Link any classes which got missed. This would happen if we have loaded classes that 1592 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K 1593 // fails verification, all other interfaces that were not specified in the classlist but 1594 // are implemented by K are not verified. 1595 link_and_cleanup_shared_classes(CATCH); 1596 tty->print_cr("Rewriting and linking classes: done"); 1597 1598 SystemDictionary::clear_invoke_method_table(); 1599 1600 VM_PopulateDumpSharedSpace op; 1601 VMThread::execute(&op); 1602 } 1603 } 1604 1605 1606 int MetaspaceShared::preload_classes(const char* class_list_path, TRAPS) { 1607 ClassListParser parser(class_list_path); 1608 int class_count = 0; 1609 1610 while (parser.parse_one_line()) { 1611 Klass* klass = ClassLoaderExt::load_one_class(&parser, THREAD); 1612 if (HAS_PENDING_EXCEPTION) { 1613 if (klass == NULL && 1614 (PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_ClassNotFoundException())) { 1615 // print a warning only when the pending exception is class not found 1616 tty->print_cr("Preload Warning: Cannot find %s", parser.current_class_name()); 1617 } 1618 CLEAR_PENDING_EXCEPTION; 1619 } 1620 if (klass != NULL) { 1621 if (log_is_enabled(Trace, cds)) { 1622 ResourceMark rm; 1623 log_trace(cds)("Shared spaces preloaded: %s", klass->external_name()); 1624 } 1625 1626 if (klass->is_instance_klass()) { 1627 InstanceKlass* ik = InstanceKlass::cast(klass); 1628 1629 // Link the class to cause the bytecodes to be rewritten and the 1630 // cpcache to be created. The linking is done as soon as classes 1631 // are loaded in order that the related data structures (klass and 1632 // cpCache) are located together. 1633 try_link_class(ik, THREAD); 1634 guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class"); 1635 } 1636 1637 class_count++; 1638 } 1639 } 1640 1641 return class_count; 1642 } 1643 1644 // Returns true if the class's status has changed 1645 bool MetaspaceShared::try_link_class(InstanceKlass* ik, TRAPS) { 1646 assert(DumpSharedSpaces, "should only be called during dumping"); 1647 if (ik->init_state() < InstanceKlass::linked) { 1648 bool saved = BytecodeVerificationLocal; 1649 if (!(ik->is_shared_boot_class())) { 1650 // The verification decision is based on BytecodeVerificationRemote 1651 // for non-system classes. Since we are using the NULL classloader 1652 // to load non-system classes during dumping, we need to temporarily 1653 // change BytecodeVerificationLocal to be the same as 1654 // BytecodeVerificationRemote. Note this can cause the parent system 1655 // classes also being verified. The extra overhead is acceptable during 1656 // dumping. 1657 BytecodeVerificationLocal = BytecodeVerificationRemote; 1658 } 1659 ik->link_class(THREAD); 1660 if (HAS_PENDING_EXCEPTION) { 1661 ResourceMark rm; 1662 tty->print_cr("Preload Warning: Verification failed for %s", 1663 ik->external_name()); 1664 CLEAR_PENDING_EXCEPTION; 1665 ik->set_in_error_state(); 1666 _has_error_classes = true; 1667 } 1668 BytecodeVerificationLocal = saved; 1669 return true; 1670 } else { 1671 return false; 1672 } 1673 } 1674 1675 #if INCLUDE_CDS_JAVA_HEAP 1676 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() { 1677 if (!MetaspaceShared::is_heap_object_archiving_allowed()) { 1678 if (log_is_enabled(Info, cds)) { 1679 log_info(cds)( 1680 "Archived java heap is not supported as UseG1GC, " 1681 "UseCompressedOops and UseCompressedClassPointers are required." 1682 "Current settings: UseG1GC=%s, UseCompressedOops=%s, UseCompressedClassPointers=%s.", 1683 BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedOops), 1684 BOOL_TO_STR(UseCompressedClassPointers)); 1685 } 1686 return; 1687 } 1688 1689 { 1690 NoSafepointVerifier nsv; 1691 1692 // Cache for recording where the archived objects are copied to 1693 MetaspaceShared::create_archive_object_cache(); 1694 1695 tty->print_cr("Dumping String objects to closed archive heap region ..."); 1696 NOT_PRODUCT(StringTable::verify()); 1697 // The string space has maximum two regions. See FileMapInfo::write_archive_heap_regions() for details. 1698 _string_regions = new GrowableArray<MemRegion>(2); 1699 StringTable::write_to_archive(_string_regions); 1700 1701 tty->print_cr("Dumping objects to open archive heap region ..."); 1702 _open_archive_heap_regions = new GrowableArray<MemRegion>(2); 1703 MetaspaceShared::dump_open_archive_heap_objects(_open_archive_heap_regions); 1704 1705 MetaspaceShared::destroy_archive_object_cache(); 1706 } 1707 1708 G1HeapVerifier::verify_archive_regions(); 1709 } 1710 1711 void MetaspaceShared::dump_open_archive_heap_objects( 1712 GrowableArray<MemRegion> * open_archive) { 1713 assert(UseG1GC, "Only support G1 GC"); 1714 assert(UseCompressedOops && UseCompressedClassPointers, 1715 "Only support UseCompressedOops and UseCompressedClassPointers enabled"); 1716 1717 Thread* THREAD = Thread::current(); 1718 G1CollectedHeap::heap()->begin_archive_alloc_range(true /* open */); 1719 1720 MetaspaceShared::archive_resolved_constants(THREAD); 1721 1722 G1CollectedHeap::heap()->end_archive_alloc_range(open_archive, 1723 os::vm_allocation_granularity()); 1724 } 1725 1726 MetaspaceShared::ArchivedObjectCache* MetaspaceShared::_archive_object_cache = NULL; 1727 oop MetaspaceShared::archive_heap_object(oop obj, Thread* THREAD) { 1728 assert(DumpSharedSpaces, "dump-time only"); 1729 1730 ArchivedObjectCache* cache = MetaspaceShared::archive_object_cache(); 1731 oop* p = cache->get(obj); 1732 if (p != NULL) { 1733 // already archived 1734 return *p; 1735 } 1736 1737 int len = obj->size(); 1738 if (G1CollectedHeap::heap()->is_archive_alloc_too_large(len)) { 1739 return NULL; 1740 } 1741 1742 int hash = obj->identity_hash(); 1743 oop archived_oop = (oop)G1CollectedHeap::heap()->archive_mem_allocate(len); 1744 if (archived_oop != NULL) { 1745 Copy::aligned_disjoint_words((HeapWord*)obj, (HeapWord*)archived_oop, len); 1746 relocate_klass_ptr(archived_oop); 1747 cache->put(obj, archived_oop); 1748 } 1749 return archived_oop; 1750 } 1751 1752 void MetaspaceShared::archive_resolved_constants(Thread* THREAD) { 1753 int i; 1754 for (i = 0; i < _global_klass_objects->length(); i++) { 1755 Klass* k = _global_klass_objects->at(i); 1756 if (k->is_instance_klass()) { 1757 InstanceKlass* ik = InstanceKlass::cast(k); 1758 ik->constants()->archive_resolved_references(THREAD); 1759 } 1760 } 1761 } 1762 1763 void MetaspaceShared::fixup_mapped_heap_regions() { 1764 FileMapInfo *mapinfo = FileMapInfo::current_info(); 1765 mapinfo->fixup_mapped_heap_regions(); 1766 } 1767 #endif // INCLUDE_CDS_JAVA_HEAP 1768 1769 // Closure for serializing initialization data in from a data area 1770 // (ptr_array) read from the shared file. 1771 1772 class ReadClosure : public SerializeClosure { 1773 private: 1774 intptr_t** _ptr_array; 1775 1776 inline intptr_t nextPtr() { 1777 return *(*_ptr_array)++; 1778 } 1779 1780 public: 1781 ReadClosure(intptr_t** ptr_array) { _ptr_array = ptr_array; } 1782 1783 void do_ptr(void** p) { 1784 assert(*p == NULL, "initializing previous initialized pointer."); 1785 intptr_t obj = nextPtr(); 1786 assert((intptr_t)obj >= 0 || (intptr_t)obj < -100, 1787 "hit tag while initializing ptrs."); 1788 *p = (void*)obj; 1789 } 1790 1791 void do_u4(u4* p) { 1792 intptr_t obj = nextPtr(); 1793 *p = (u4)(uintx(obj)); 1794 } 1795 1796 void do_tag(int tag) { 1797 int old_tag; 1798 old_tag = (int)(intptr_t)nextPtr(); 1799 // do_int(&old_tag); 1800 assert(tag == old_tag, "old tag doesn't match"); 1801 FileMapInfo::assert_mark(tag == old_tag); 1802 } 1803 1804 void do_region(u_char* start, size_t size) { 1805 assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment"); 1806 assert(size % sizeof(intptr_t) == 0, "bad size"); 1807 do_tag((int)size); 1808 while (size > 0) { 1809 *(intptr_t*)start = nextPtr(); 1810 start += sizeof(intptr_t); 1811 size -= sizeof(intptr_t); 1812 } 1813 } 1814 1815 bool reading() const { return true; } 1816 }; 1817 1818 // Return true if given address is in the misc data region 1819 bool MetaspaceShared::is_in_shared_region(const void* p, int idx) { 1820 return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx); 1821 } 1822 1823 bool MetaspaceShared::is_in_trampoline_frame(address addr) { 1824 if (UseSharedSpaces && is_in_shared_region(addr, MetaspaceShared::mc)) { 1825 return true; 1826 } 1827 return false; 1828 } 1829 1830 void MetaspaceShared::print_shared_spaces() { 1831 if (UseSharedSpaces) { 1832 FileMapInfo::current_info()->print_shared_spaces(); 1833 } 1834 } 1835 1836 1837 // Map shared spaces at requested addresses and return if succeeded. 1838 bool MetaspaceShared::map_shared_spaces(FileMapInfo* mapinfo) { 1839 size_t image_alignment = mapinfo->alignment(); 1840 1841 #ifndef _WINDOWS 1842 // Map in the shared memory and then map the regions on top of it. 1843 // On Windows, don't map the memory here because it will cause the 1844 // mappings of the regions to fail. 1845 ReservedSpace shared_rs = mapinfo->reserve_shared_memory(); 1846 if (!shared_rs.is_reserved()) return false; 1847 #endif 1848 1849 assert(!DumpSharedSpaces, "Should not be called with DumpSharedSpaces"); 1850 1851 char* ro_base = NULL; char* ro_top; 1852 char* rw_base = NULL; char* rw_top; 1853 char* mc_base = NULL; char* mc_top; 1854 char* md_base = NULL; char* md_top; 1855 char* od_base = NULL; char* od_top; 1856 1857 // Map each shared region 1858 if ((mc_base = mapinfo->map_region(mc, &mc_top)) != NULL && 1859 (rw_base = mapinfo->map_region(rw, &rw_top)) != NULL && 1860 (ro_base = mapinfo->map_region(ro, &ro_top)) != NULL && 1861 (md_base = mapinfo->map_region(md, &md_top)) != NULL && 1862 (od_base = mapinfo->map_region(od, &od_top)) != NULL && 1863 (image_alignment == (size_t)os::vm_allocation_granularity()) && 1864 mapinfo->validate_classpath_entry_table()) { 1865 // Success -- set up MetaspaceObj::_shared_metaspace_{base,top} for 1866 // fast checking in MetaspaceShared::is_in_shared_metaspace() and 1867 // MetaspaceObj::is_shared(). 1868 // 1869 // We require that mc->rw->ro->md->od to be laid out consecutively, with no 1870 // gaps between them. That way, we can ensure that the OS won't be able to 1871 // allocate any new memory spaces inside _shared_metaspace_{base,top}, which 1872 // would mess up the simple comparision in MetaspaceShared::is_in_shared_metaspace(). 1873 assert(mc_base < ro_base && mc_base < rw_base && mc_base < md_base && mc_base < od_base, "must be"); 1874 assert(od_top > ro_top && od_top > rw_top && od_top > md_top && od_top > mc_top , "must be"); 1875 assert(mc_top == rw_base, "must be"); 1876 assert(rw_top == ro_base, "must be"); 1877 assert(ro_top == md_base, "must be"); 1878 assert(md_top == od_base, "must be"); 1879 1880 MetaspaceObj::_shared_metaspace_base = (void*)mc_base; 1881 MetaspaceObj::_shared_metaspace_top = (void*)od_top; 1882 return true; 1883 } else { 1884 // If there was a failure in mapping any of the spaces, unmap the ones 1885 // that succeeded 1886 if (ro_base != NULL) mapinfo->unmap_region(ro); 1887 if (rw_base != NULL) mapinfo->unmap_region(rw); 1888 if (mc_base != NULL) mapinfo->unmap_region(mc); 1889 if (md_base != NULL) mapinfo->unmap_region(md); 1890 if (od_base != NULL) mapinfo->unmap_region(od); 1891 #ifndef _WINDOWS 1892 // Release the entire mapped region 1893 shared_rs.release(); 1894 #endif 1895 // If -Xshare:on is specified, print out the error message and exit VM, 1896 // otherwise, set UseSharedSpaces to false and continue. 1897 if (RequireSharedSpaces || PrintSharedArchiveAndExit) { 1898 vm_exit_during_initialization("Unable to use shared archive.", "Failed map_region for using -Xshare:on."); 1899 } else { 1900 FLAG_SET_DEFAULT(UseSharedSpaces, false); 1901 } 1902 return false; 1903 } 1904 } 1905 1906 // Read the miscellaneous data from the shared file, and 1907 // serialize it out to its various destinations. 1908 1909 void MetaspaceShared::initialize_shared_spaces() { 1910 FileMapInfo *mapinfo = FileMapInfo::current_info(); 1911 _cds_i2i_entry_code_buffers = mapinfo->cds_i2i_entry_code_buffers(); 1912 _cds_i2i_entry_code_buffers_size = mapinfo->cds_i2i_entry_code_buffers_size(); 1913 _core_spaces_size = mapinfo->core_spaces_size(); 1914 char* buffer = mapinfo->misc_data_patching_start(); 1915 clone_cpp_vtables((intptr_t*)buffer); 1916 1917 // The rest of the data is now stored in the RW region 1918 buffer = mapinfo->read_only_tables_start(); 1919 int sharedDictionaryLen = *(intptr_t*)buffer; 1920 buffer += sizeof(intptr_t); 1921 int number_of_entries = *(intptr_t*)buffer; 1922 buffer += sizeof(intptr_t); 1923 SystemDictionary::set_shared_dictionary((HashtableBucket<mtClass>*)buffer, 1924 sharedDictionaryLen, 1925 number_of_entries); 1926 buffer += sharedDictionaryLen; 1927 1928 // The following data are the linked list elements 1929 // (HashtableEntry objects) for the shared dictionary table. 1930 1931 int len = *(intptr_t*)buffer; // skip over shared dictionary entries 1932 buffer += sizeof(intptr_t); 1933 buffer += len; 1934 1935 // Verify various attributes of the archive, plus initialize the 1936 // shared string/symbol tables 1937 intptr_t* array = (intptr_t*)buffer; 1938 ReadClosure rc(&array); 1939 serialize(&rc); 1940 1941 // Initialize the run-time symbol table. 1942 SymbolTable::create_table(); 1943 1944 // Close the mapinfo file 1945 mapinfo->close(); 1946 1947 if (PrintSharedArchiveAndExit) { 1948 if (PrintSharedDictionary) { 1949 tty->print_cr("\nShared classes:\n"); 1950 SystemDictionary::print_shared(tty); 1951 } 1952 if (_archive_loading_failed) { 1953 tty->print_cr("archive is invalid"); 1954 vm_exit(1); 1955 } else { 1956 tty->print_cr("archive is valid"); 1957 vm_exit(0); 1958 } 1959 } 1960 } 1961 1962 // JVM/TI RedefineClasses() support: 1963 bool MetaspaceShared::remap_shared_readonly_as_readwrite() { 1964 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 1965 1966 if (UseSharedSpaces) { 1967 // remap the shared readonly space to shared readwrite, private 1968 FileMapInfo* mapinfo = FileMapInfo::current_info(); 1969 if (!mapinfo->remap_shared_readonly_as_readwrite()) { 1970 return false; 1971 } 1972 _remapped_readwrite = true; 1973 } 1974 return true; 1975 } 1976 1977 void MetaspaceShared::report_out_of_space(const char* name, size_t needed_bytes) { 1978 // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space. 1979 // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes 1980 // or so. 1981 _mc_region.print_out_of_space_msg(name, needed_bytes); 1982 _rw_region.print_out_of_space_msg(name, needed_bytes); 1983 _ro_region.print_out_of_space_msg(name, needed_bytes); 1984 _md_region.print_out_of_space_msg(name, needed_bytes); 1985 _od_region.print_out_of_space_msg(name, needed_bytes); 1986 1987 vm_exit_during_initialization(err_msg("Unable to allocate from '%s' region", name), 1988 "Please reduce the number of shared classes."); 1989 }