1 /* 2 * Copyright (c) 2012, 2020, 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/classLoaderDataGraph.hpp" 27 #include "classfile/classLoaderDataShared.hpp" 28 #include "classfile/classListParser.hpp" 29 #include "classfile/classLoaderExt.hpp" 30 #include "classfile/loaderConstraints.hpp" 31 #include "classfile/javaClasses.inline.hpp" 32 #include "classfile/placeholders.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 #include "interpreter/bytecodeStream.hpp" 39 #include "interpreter/bytecodes.hpp" 40 #include "logging/log.hpp" 41 #include "logging/logMessage.hpp" 42 #include "memory/archiveBuilder.hpp" 43 #include "memory/archiveUtils.inline.hpp" 44 #include "memory/dumpAllocStats.hpp" 45 #include "memory/dynamicArchive.hpp" 46 #include "memory/filemap.hpp" 47 #include "memory/heapShared.inline.hpp" 48 #include "memory/metaspace.hpp" 49 #include "memory/metaspaceClosure.hpp" 50 #include "memory/metaspaceShared.hpp" 51 #include "memory/resourceArea.hpp" 52 #include "memory/universe.hpp" 53 #include "oops/compressedOops.inline.hpp" 54 #include "oops/instanceClassLoaderKlass.hpp" 55 #include "oops/instanceMirrorKlass.hpp" 56 #include "oops/instanceRefKlass.hpp" 57 #include "oops/methodData.hpp" 58 #include "oops/objArrayKlass.hpp" 59 #include "oops/objArrayOop.hpp" 60 #include "oops/oop.inline.hpp" 61 #include "oops/typeArrayKlass.hpp" 62 #include "runtime/handles.inline.hpp" 63 #include "runtime/os.hpp" 64 #include "runtime/safepointVerifiers.hpp" 65 #include "runtime/timerTrace.hpp" 66 #include "runtime/vmThread.hpp" 67 #include "runtime/vmOperations.hpp" 68 #include "utilities/align.hpp" 69 #include "utilities/bitMap.inline.hpp" 70 #include "utilities/ostream.hpp" 71 #include "utilities/defaultStream.hpp" 72 #include "utilities/hashtable.inline.hpp" 73 #if INCLUDE_G1GC 74 #include "gc/g1/g1CollectedHeap.hpp" 75 #endif 76 77 ReservedSpace MetaspaceShared::_shared_rs; 78 VirtualSpace MetaspaceShared::_shared_vs; 79 ReservedSpace MetaspaceShared::_symbol_rs; 80 VirtualSpace MetaspaceShared::_symbol_vs; 81 MetaspaceSharedStats MetaspaceShared::_stats; 82 bool MetaspaceShared::_has_error_classes; 83 bool MetaspaceShared::_archive_loading_failed = false; 84 bool MetaspaceShared::_remapped_readwrite = false; 85 address MetaspaceShared::_i2i_entry_code_buffers = NULL; 86 size_t MetaspaceShared::_i2i_entry_code_buffers_size = 0; 87 void* MetaspaceShared::_shared_metaspace_static_top = NULL; 88 intx MetaspaceShared::_relocation_delta; 89 char* MetaspaceShared::_requested_base_address; 90 bool MetaspaceShared::_use_optimized_module_handling = true; 91 bool MetaspaceShared::_use_full_module_graph = true; 92 93 // The CDS archive is divided into the following regions: 94 // mc - misc code (the method entry trampolines, c++ vtables) 95 // rw - read-write metadata 96 // ro - read-only metadata and read-only tables 97 // 98 // ca0 - closed archive heap space #0 99 // ca1 - closed archive heap space #1 (may be empty) 100 // oa0 - open archive heap space #0 101 // oa1 - open archive heap space #1 (may be empty) 102 // 103 // The mc, rw, and ro regions are linearly allocated, starting from 104 // SharedBaseAddress, in the order of mc->rw->ro. The size of these 3 regions 105 // are page-aligned, and there's no gap between any consecutive regions. 106 // 107 // These 3 regions are populated in the following steps: 108 // [1] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are 109 // temporarily allocated outside of the shared regions. Only the method entry 110 // trampolines are written into the mc region. 111 // [2] C++ vtables are copied into the mc region. 112 // [3] ArchiveBuilder copies RW metadata into the rw region. 113 // [4] ArchiveBuilder copies RO metadata into the ro region. 114 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data 115 // are copied into the ro region as read-only tables. 116 // 117 // The s0/s1 and oa0/oa1 regions are populated inside HeapShared::archive_java_heap_objects. 118 // Their layout is independent of the other 4 regions. 119 120 static DumpRegion _mc_region("mc"), _ro_region("ro"), _rw_region("rw"), _symbol_region("symbols"); 121 static size_t _total_closed_archive_region_size = 0, _total_open_archive_region_size = 0; 122 123 void MetaspaceShared::init_shared_dump_space(DumpRegion* first_space) { 124 first_space->init(&_shared_rs, &_shared_vs); 125 } 126 127 DumpRegion* MetaspaceShared::misc_code_dump_space() { 128 return &_mc_region; 129 } 130 131 DumpRegion* MetaspaceShared::read_write_dump_space() { 132 return &_rw_region; 133 } 134 135 DumpRegion* MetaspaceShared::read_only_dump_space() { 136 return &_ro_region; 137 } 138 139 void MetaspaceShared::pack_dump_space(DumpRegion* current, DumpRegion* next, 140 ReservedSpace* rs) { 141 current->pack(next); 142 } 143 144 char* MetaspaceShared::symbol_space_alloc(size_t num_bytes) { 145 return _symbol_region.allocate(num_bytes); 146 } 147 148 char* MetaspaceShared::misc_code_space_alloc(size_t num_bytes) { 149 return _mc_region.allocate(num_bytes); 150 } 151 152 char* MetaspaceShared::read_only_space_alloc(size_t num_bytes) { 153 return _ro_region.allocate(num_bytes); 154 } 155 156 char* MetaspaceShared::read_write_space_alloc(size_t num_bytes) { 157 return _rw_region.allocate(num_bytes); 158 } 159 160 size_t MetaspaceShared::reserved_space_alignment() { return os::vm_allocation_granularity(); } 161 162 static bool shared_base_valid(char* shared_base) { 163 #ifdef _LP64 164 return CompressedKlassPointers::is_valid_base((address)shared_base); 165 #else 166 return true; 167 #endif 168 } 169 170 static bool shared_base_too_high(char* shared_base, size_t cds_total) { 171 if (SharedBaseAddress != 0 && shared_base < (char*)SharedBaseAddress) { 172 // SharedBaseAddress is very high (e.g., 0xffffffffffffff00) so 173 // align_up(SharedBaseAddress, MetaspaceShared::reserved_space_alignment()) has wrapped around. 174 return true; 175 } 176 if (max_uintx - uintx(shared_base) < uintx(cds_total)) { 177 // The end of the archive will wrap around 178 return true; 179 } 180 181 return false; 182 } 183 184 static char* compute_shared_base(size_t cds_total) { 185 char* shared_base = (char*)align_up((char*)SharedBaseAddress, MetaspaceShared::reserved_space_alignment()); 186 const char* err = NULL; 187 if (shared_base_too_high(shared_base, cds_total)) { 188 err = "too high"; 189 } else if (!shared_base_valid(shared_base)) { 190 err = "invalid for this platform"; 191 } 192 if (err) { 193 log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT, 194 p2i((void*)SharedBaseAddress), err, 195 p2i((void*)Arguments::default_SharedBaseAddress())); 196 SharedBaseAddress = Arguments::default_SharedBaseAddress(); 197 shared_base = (char*)align_up((char*)SharedBaseAddress, MetaspaceShared::reserved_space_alignment()); 198 } 199 assert(!shared_base_too_high(shared_base, cds_total) && shared_base_valid(shared_base), "Sanity"); 200 return shared_base; 201 } 202 203 void MetaspaceShared::initialize_dumptime_shared_and_meta_spaces() { 204 assert(DumpSharedSpaces, "should be called for dump time only"); 205 206 const size_t reserve_alignment = MetaspaceShared::reserved_space_alignment(); 207 208 #ifdef _LP64 209 // On 64-bit VM we reserve a 4G range and, if UseCompressedClassPointers=1, 210 // will use that to house both the archives and the ccs. See below for 211 // details. 212 const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1); 213 const size_t cds_total = align_down(UnscaledClassSpaceMax, reserve_alignment); 214 #else 215 // We don't support archives larger than 256MB on 32-bit due to limited 216 // virtual address space. 217 size_t cds_total = align_down(256*M, reserve_alignment); 218 #endif 219 220 char* shared_base = compute_shared_base(cds_total); 221 _requested_base_address = shared_base; 222 223 // Whether to use SharedBaseAddress as attach address. 224 bool use_requested_base = true; 225 226 if (shared_base == NULL) { 227 use_requested_base = false; 228 } 229 230 if (ArchiveRelocationMode == 1) { 231 log_info(cds)("ArchiveRelocationMode == 1: always allocate class space at an alternative address"); 232 use_requested_base = false; 233 } 234 235 // First try to reserve the space at the specified SharedBaseAddress. 236 assert(!_shared_rs.is_reserved(), "must be"); 237 if (use_requested_base) { 238 _shared_rs = ReservedSpace(cds_total, reserve_alignment, 239 false /* large */, (char*)shared_base); 240 if (_shared_rs.is_reserved()) { 241 assert(_shared_rs.base() == shared_base, "should match"); 242 } else { 243 log_info(cds)("dumptime space reservation: failed to map at " 244 "SharedBaseAddress " PTR_FORMAT, p2i(shared_base)); 245 } 246 } 247 if (!_shared_rs.is_reserved()) { 248 // Get a reserved space anywhere if attaching at the SharedBaseAddress 249 // fails: 250 if (UseCompressedClassPointers) { 251 // If we need to reserve class space as well, let the platform handle 252 // the reservation. 253 LP64_ONLY(_shared_rs = 254 Metaspace::reserve_address_space_for_compressed_classes(cds_total);) 255 NOT_LP64(ShouldNotReachHere();) 256 } else { 257 // anywhere is fine. 258 _shared_rs = ReservedSpace(cds_total, reserve_alignment, 259 false /* large */, (char*)NULL); 260 } 261 } 262 263 if (!_shared_rs.is_reserved()) { 264 vm_exit_during_initialization("Unable to reserve memory for shared space", 265 err_msg(SIZE_FORMAT " bytes.", cds_total)); 266 } 267 268 #ifdef _LP64 269 270 if (UseCompressedClassPointers) { 271 272 assert(CompressedKlassPointers::is_valid_base((address)_shared_rs.base()), "Sanity"); 273 274 // On 64-bit VM, if UseCompressedClassPointers=1, the compressed class space 275 // must be allocated near the cds such as that the compressed Klass pointer 276 // encoding can be used to en/decode pointers from both cds and ccs. Since 277 // Metaspace cannot do this (it knows nothing about cds), we do it for 278 // Metaspace here and pass it the space to use for ccs. 279 // 280 // We do this by reserving space for the ccs behind the archives. Note 281 // however that ccs follows a different alignment 282 // (Metaspace::reserve_alignment), so there may be a gap between ccs and 283 // cds. 284 // We use a similar layout at runtime, see reserve_address_space_for_archives(). 285 // 286 // +-- SharedBaseAddress (default = 0x800000000) 287 // v 288 // +-..---------+---------+ ... +----+----+----+--------+-----------------+ 289 // | Heap | Archive | | MC | RW | RO | [gap] | class space | 290 // +-..---------+---------+ ... +----+----+----+--------+-----------------+ 291 // |<-- MaxHeapSize -->| |<-- UnscaledClassSpaceMax = 4GB -->| 292 // 293 // Note: ccs must follow the archives, and the archives must start at the 294 // encoding base. However, the exact placement of ccs does not matter as 295 // long as it it resides in the encoding range of CompressedKlassPointers 296 // and comes after the archive. 297 // 298 // We do this by splitting up the allocated 4G into 3G of archive space, 299 // followed by 1G for the ccs: 300 // + The upper 1 GB is used as the "temporary compressed class space" 301 // -- preload_classes() will store Klasses into this space. 302 // + The lower 3 GB is used for the archive -- when preload_classes() 303 // is done, ArchiveBuilder will copy the class metadata into this 304 // space, first the RW parts, then the RO parts. 305 306 // Starting address of ccs must be aligned to Metaspace::reserve_alignment()... 307 size_t class_space_size = align_down(_shared_rs.size() / 4, Metaspace::reserve_alignment()); 308 address class_space_start = (address)align_down(_shared_rs.end() - class_space_size, Metaspace::reserve_alignment()); 309 size_t archive_size = class_space_start - (address)_shared_rs.base(); 310 311 ReservedSpace tmp_class_space = _shared_rs.last_part(archive_size); 312 _shared_rs = _shared_rs.first_part(archive_size); 313 314 // ... as does the size of ccs. 315 tmp_class_space = tmp_class_space.first_part(class_space_size); 316 CompressedClassSpaceSize = class_space_size; 317 318 // Let Metaspace initialize ccs 319 Metaspace::initialize_class_space(tmp_class_space); 320 321 // and set up CompressedKlassPointers encoding. 322 CompressedKlassPointers::initialize((address)_shared_rs.base(), cds_total); 323 324 log_info(cds)("narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d", 325 p2i(CompressedKlassPointers::base()), CompressedKlassPointers::shift()); 326 327 log_info(cds)("Allocated temporary class space: " SIZE_FORMAT " bytes at " PTR_FORMAT, 328 CompressedClassSpaceSize, p2i(tmp_class_space.base())); 329 330 assert(_shared_rs.end() == tmp_class_space.base() && 331 is_aligned(_shared_rs.base(), MetaspaceShared::reserved_space_alignment()) && 332 is_aligned(tmp_class_space.base(), Metaspace::reserve_alignment()) && 333 is_aligned(tmp_class_space.size(), Metaspace::reserve_alignment()), "Sanity"); 334 } 335 336 #endif 337 338 init_shared_dump_space(&_mc_region); 339 SharedBaseAddress = (size_t)_shared_rs.base(); 340 log_info(cds)("Allocated shared space: " SIZE_FORMAT " bytes at " PTR_FORMAT, 341 _shared_rs.size(), p2i(_shared_rs.base())); 342 343 // We don't want any valid object to be at the very bottom of the archive. 344 // See ArchivePtrMarker::mark_pointer(). 345 MetaspaceShared::misc_code_space_alloc(16); 346 347 size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M); 348 _symbol_rs = ReservedSpace(symbol_rs_size); 349 if (!_symbol_rs.is_reserved()) { 350 vm_exit_during_initialization("Unable to reserve memory for symbols", 351 err_msg(SIZE_FORMAT " bytes.", symbol_rs_size)); 352 } 353 _symbol_region.init(&_symbol_rs, &_symbol_vs); 354 } 355 356 // Called by universe_post_init() 357 void MetaspaceShared::post_initialize(TRAPS) { 358 if (UseSharedSpaces) { 359 int size = FileMapInfo::get_number_of_shared_paths(); 360 if (size > 0) { 361 SystemDictionaryShared::allocate_shared_data_arrays(size, THREAD); 362 if (!DynamicDumpSharedSpaces) { 363 FileMapInfo* info; 364 if (FileMapInfo::dynamic_info() == NULL) { 365 info = FileMapInfo::current_info(); 366 } else { 367 info = FileMapInfo::dynamic_info(); 368 } 369 ClassLoaderExt::init_paths_start_index(info->app_class_paths_start_index()); 370 ClassLoaderExt::init_app_module_paths_start_index(info->app_module_paths_start_index()); 371 } 372 } 373 } 374 } 375 376 static GrowableArrayCHeap<Handle, mtClassShared>* _extra_interned_strings = NULL; 377 378 void MetaspaceShared::read_extra_data(const char* filename, TRAPS) { 379 _extra_interned_strings = new GrowableArrayCHeap<Handle, mtClassShared>(10000); 380 381 HashtableTextDump reader(filename); 382 reader.check_version("VERSION: 1.0"); 383 384 while (reader.remain() > 0) { 385 int utf8_length; 386 int prefix_type = reader.scan_prefix(&utf8_length); 387 ResourceMark rm(THREAD); 388 if (utf8_length == 0x7fffffff) { 389 // buf_len will overflown 32-bit value. 390 vm_exit_during_initialization(err_msg("string length too large: %d", utf8_length)); 391 } 392 int buf_len = utf8_length+1; 393 char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len); 394 reader.get_utf8(utf8_buffer, utf8_length); 395 utf8_buffer[utf8_length] = '\0'; 396 397 if (prefix_type == HashtableTextDump::SymbolPrefix) { 398 SymbolTable::new_permanent_symbol(utf8_buffer); 399 } else{ 400 assert(prefix_type == HashtableTextDump::StringPrefix, "Sanity"); 401 oop s = StringTable::intern(utf8_buffer, THREAD); 402 403 if (HAS_PENDING_EXCEPTION) { 404 log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d", 405 reader.last_line_no(), utf8_length); 406 CLEAR_PENDING_EXCEPTION; 407 } else { 408 #if INCLUDE_G1GC 409 if (UseG1GC) { 410 typeArrayOop body = java_lang_String::value(s); 411 const HeapRegion* hr = G1CollectedHeap::heap()->heap_region_containing(body); 412 if (hr->is_humongous()) { 413 // Don't keep it alive, so it will be GC'ed before we dump the strings, in order 414 // to maximize free heap space and minimize fragmentation. 415 log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d", 416 reader.last_line_no(), utf8_length); 417 continue; 418 } 419 } 420 #endif 421 // Interned strings are GC'ed if there are no references to it, so let's 422 // add a reference to keep this string alive. 423 assert(s != NULL, "must succeed"); 424 Handle h(THREAD, s); 425 _extra_interned_strings->append(h); 426 } 427 } 428 } 429 } 430 431 void MetaspaceShared::commit_to(ReservedSpace* rs, VirtualSpace* vs, char* newtop) { 432 Arguments::assert_is_dumping_archive(); 433 char* base = rs->base(); 434 size_t need_committed_size = newtop - base; 435 size_t has_committed_size = vs->committed_size(); 436 if (need_committed_size < has_committed_size) { 437 return; 438 } 439 440 size_t min_bytes = need_committed_size - has_committed_size; 441 size_t preferred_bytes = 1 * M; 442 size_t uncommitted = vs->reserved_size() - has_committed_size; 443 444 size_t commit =MAX2(min_bytes, preferred_bytes); 445 commit = MIN2(commit, uncommitted); 446 assert(commit <= uncommitted, "sanity"); 447 448 bool result = vs->expand_by(commit, false); 449 if (rs == &_shared_rs) { 450 ArchivePtrMarker::expand_ptr_end((address*)vs->high()); 451 } 452 453 if (!result) { 454 vm_exit_during_initialization(err_msg("Failed to expand shared space to " SIZE_FORMAT " bytes", 455 need_committed_size)); 456 } 457 458 assert(rs == &_shared_rs || rs == &_symbol_rs, "must be"); 459 const char* which = (rs == &_shared_rs) ? "shared" : "symbol"; 460 log_debug(cds)("Expanding %s spaces by " SIZE_FORMAT_W(7) " bytes [total " SIZE_FORMAT_W(9) " bytes ending at %p]", 461 which, commit, vs->actual_committed_size(), vs->high()); 462 } 463 464 void MetaspaceShared::initialize_ptr_marker(CHeapBitMap* ptrmap) { 465 ArchivePtrMarker::initialize(ptrmap, (address*)_shared_vs.low(), (address*)_shared_vs.high()); 466 } 467 468 // Read/write a data stream for restoring/preserving metadata pointers and 469 // miscellaneous data from/to the shared archive file. 470 471 void MetaspaceShared::serialize(SerializeClosure* soc) { 472 int tag = 0; 473 soc->do_tag(--tag); 474 475 // Verify the sizes of various metadata in the system. 476 soc->do_tag(sizeof(Method)); 477 soc->do_tag(sizeof(ConstMethod)); 478 soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE)); 479 soc->do_tag(sizeof(ConstantPool)); 480 soc->do_tag(sizeof(ConstantPoolCache)); 481 soc->do_tag(objArrayOopDesc::base_offset_in_bytes()); 482 soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE)); 483 soc->do_tag(sizeof(Symbol)); 484 485 // Dump/restore miscellaneous metadata. 486 JavaClasses::serialize_offsets(soc); 487 Universe::serialize(soc); 488 soc->do_tag(--tag); 489 490 // Dump/restore references to commonly used names and signatures. 491 vmSymbols::serialize(soc); 492 soc->do_tag(--tag); 493 494 // Dump/restore the symbol/string/subgraph_info tables 495 SymbolTable::serialize_shared_table_header(soc); 496 StringTable::serialize_shared_table_header(soc); 497 HeapShared::serialize_subgraph_info_table_header(soc); 498 SystemDictionaryShared::serialize_dictionary_headers(soc); 499 500 InstanceMirrorKlass::serialize_offsets(soc); 501 502 // Dump/restore well known classes (pointers) 503 SystemDictionaryShared::serialize_well_known_klasses(soc); 504 soc->do_tag(--tag); 505 506 serialize_cloned_cpp_vtptrs(soc); 507 soc->do_tag(--tag); 508 509 CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc)); 510 511 soc->do_tag(666); 512 } 513 514 address MetaspaceShared::i2i_entry_code_buffers(size_t total_size) { 515 if (DumpSharedSpaces) { 516 if (_i2i_entry_code_buffers == NULL) { 517 _i2i_entry_code_buffers = (address)misc_code_space_alloc(total_size); 518 _i2i_entry_code_buffers_size = total_size; 519 } 520 } else if (UseSharedSpaces) { 521 assert(_i2i_entry_code_buffers != NULL, "must already been initialized"); 522 } else { 523 return NULL; 524 } 525 526 assert(_i2i_entry_code_buffers_size == total_size, "must not change"); 527 return _i2i_entry_code_buffers; 528 } 529 530 uintx MetaspaceShared::object_delta_uintx(void* obj) { 531 Arguments::assert_is_dumping_archive(); 532 if (DumpSharedSpaces) { 533 assert(shared_rs()->contains(obj), "must be"); 534 } else { 535 assert(is_in_shared_metaspace(obj) || DynamicArchive::is_in_target_space(obj), "must be"); 536 } 537 address base_address = address(SharedBaseAddress); 538 uintx deltax = address(obj) - base_address; 539 return deltax; 540 } 541 542 // Global object for holding classes that have been loaded. Since this 543 // is run at a safepoint just before exit, this is the entire set of classes. 544 static GrowableArray<Klass*>* _global_klass_objects; 545 546 GrowableArray<Klass*>* MetaspaceShared::collected_klasses() { 547 return _global_klass_objects; 548 } 549 550 static void remove_unshareable_in_classes() { 551 for (int i = 0; i < _global_klass_objects->length(); i++) { 552 Klass* k = _global_klass_objects->at(i); 553 if (!k->is_objArray_klass()) { 554 // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info 555 // on their array classes. 556 assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be"); 557 k->remove_unshareable_info(); 558 } 559 } 560 } 561 562 static void remove_java_mirror_in_classes() { 563 for (int i = 0; i < _global_klass_objects->length(); i++) { 564 Klass* k = _global_klass_objects->at(i); 565 if (!k->is_objArray_klass()) { 566 // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info 567 // on their array classes. 568 assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be"); 569 k->remove_java_mirror(); 570 } 571 } 572 } 573 574 static void rewrite_nofast_bytecode(const methodHandle& method) { 575 BytecodeStream bcs(method); 576 while (!bcs.is_last_bytecode()) { 577 Bytecodes::Code opcode = bcs.next(); 578 switch (opcode) { 579 case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break; 580 case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break; 581 case Bytecodes::_aload_0: *bcs.bcp() = Bytecodes::_nofast_aload_0; break; 582 case Bytecodes::_iload: { 583 if (!bcs.is_wide()) { 584 *bcs.bcp() = Bytecodes::_nofast_iload; 585 } 586 break; 587 } 588 default: break; 589 } 590 } 591 } 592 593 // Walk all methods in the class list to ensure that they won't be modified at 594 // run time. This includes: 595 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified 596 // at run time by RewriteBytecodes/RewriteFrequentPairs 597 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time. 598 static void rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread) { 599 for (int i = 0; i < _global_klass_objects->length(); i++) { 600 Klass* k = _global_klass_objects->at(i); 601 if (k->is_instance_klass()) { 602 InstanceKlass* ik = InstanceKlass::cast(k); 603 MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(thread, ik); 604 } 605 } 606 } 607 608 void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) { 609 for (int i = 0; i < ik->methods()->length(); i++) { 610 methodHandle m(thread, ik->methods()->at(i)); 611 rewrite_nofast_bytecode(m); 612 Fingerprinter fp(m); 613 // The side effect of this call sets method's fingerprint field. 614 fp.fingerprint(); 615 } 616 } 617 618 // Objects of the Metadata types (such as Klass and ConstantPool) have C++ vtables. 619 // (In GCC this is the field <Type>::_vptr, i.e., first word in the object.) 620 // 621 // Addresses of the vtables and the methods may be different across JVM runs, 622 // if libjvm.so is dynamically loaded at a different base address. 623 // 624 // To ensure that the Metadata objects in the CDS archive always have the correct vtable: 625 // 626 // + at dump time: we redirect the _vptr to point to our own vtables inside 627 // the CDS image 628 // + at run time: we clone the actual contents of the vtables from libjvm.so 629 // into our own tables. 630 631 // Currently, the archive contain ONLY the following types of objects that have C++ vtables. 632 #define CPP_VTABLE_PATCH_TYPES_DO(f) \ 633 f(ConstantPool) \ 634 f(InstanceKlass) \ 635 f(InstanceClassLoaderKlass) \ 636 f(InstanceMirrorKlass) \ 637 f(InstanceRefKlass) \ 638 f(Method) \ 639 f(ObjArrayKlass) \ 640 f(TypeArrayKlass) 641 642 class CppVtableInfo { 643 intptr_t _vtable_size; 644 intptr_t _cloned_vtable[1]; 645 public: 646 static int num_slots(int vtable_size) { 647 return 1 + vtable_size; // Need to add the space occupied by _vtable_size; 648 } 649 int vtable_size() { return int(uintx(_vtable_size)); } 650 void set_vtable_size(int n) { _vtable_size = intptr_t(n); } 651 intptr_t* cloned_vtable() { return &_cloned_vtable[0]; } 652 void zero() { memset(_cloned_vtable, 0, sizeof(intptr_t) * vtable_size()); } 653 // Returns the address of the next CppVtableInfo that can be placed immediately after this CppVtableInfo 654 static size_t byte_size(int vtable_size) { 655 CppVtableInfo i; 656 return pointer_delta(&i._cloned_vtable[vtable_size], &i, sizeof(u1)); 657 } 658 }; 659 660 static inline intptr_t* vtable_of(Metadata* m) { 661 return *((intptr_t**)m); 662 } 663 664 template <class T> class CppVtableCloner : public T { 665 static CppVtableInfo* _info; 666 667 static int get_vtable_length(const char* name); 668 669 public: 670 // Allocate and initialize the C++ vtable, starting from top, but do not go past end. 671 static intptr_t* allocate(const char* name); 672 673 // Clone the vtable to ... 674 static intptr_t* clone_vtable(const char* name, CppVtableInfo* info); 675 676 static void zero_vtable_clone() { 677 assert(DumpSharedSpaces, "dump-time only"); 678 _info->zero(); 679 } 680 681 static bool is_valid_shared_object(const T* obj) { 682 intptr_t* vptr = *(intptr_t**)obj; 683 return vptr == _info->cloned_vtable(); 684 } 685 686 static void init_orig_cpp_vtptr(int kind); 687 }; 688 689 template <class T> CppVtableInfo* CppVtableCloner<T>::_info = NULL; 690 691 template <class T> 692 intptr_t* CppVtableCloner<T>::allocate(const char* name) { 693 assert(is_aligned(_mc_region.top(), sizeof(intptr_t)), "bad alignment"); 694 int n = get_vtable_length(name); 695 _info = (CppVtableInfo*)_mc_region.allocate(CppVtableInfo::byte_size(n), sizeof(intptr_t)); 696 _info->set_vtable_size(n); 697 698 intptr_t* p = clone_vtable(name, _info); 699 assert((char*)p == _mc_region.top(), "must be"); 700 701 return _info->cloned_vtable(); 702 } 703 704 template <class T> 705 intptr_t* CppVtableCloner<T>::clone_vtable(const char* name, CppVtableInfo* info) { 706 if (!DumpSharedSpaces) { 707 assert(_info == 0, "_info is initialized only at dump time"); 708 _info = info; // Remember it -- it will be used by MetaspaceShared::is_valid_shared_method() 709 } 710 T tmp; // Allocate temporary dummy metadata object to get to the original vtable. 711 int n = info->vtable_size(); 712 intptr_t* srcvtable = vtable_of(&tmp); 713 intptr_t* dstvtable = info->cloned_vtable(); 714 715 // We already checked (and, if necessary, adjusted n) when the vtables were allocated, so we are 716 // safe to do memcpy. 717 log_debug(cds, vtables)("Copying %3d vtable entries for %s", n, name); 718 memcpy(dstvtable, srcvtable, sizeof(intptr_t) * n); 719 return dstvtable + n; 720 } 721 722 // To determine the size of the vtable for each type, we use the following 723 // trick by declaring 2 subclasses: 724 // 725 // class CppVtableTesterA: public InstanceKlass {virtual int last_virtual_method() {return 1;} }; 726 // class CppVtableTesterB: public InstanceKlass {virtual void* last_virtual_method() {return NULL}; }; 727 // 728 // CppVtableTesterA and CppVtableTesterB's vtables have the following properties: 729 // - Their size (N+1) is exactly one more than the size of InstanceKlass's vtable (N) 730 // - The first N entries have are exactly the same as in InstanceKlass's vtable. 731 // - Their last entry is different. 732 // 733 // So to determine the value of N, we just walk CppVtableTesterA and CppVtableTesterB's tables 734 // and find the first entry that's different. 735 // 736 // This works on all C++ compilers supported by Oracle, but you may need to tweak it for more 737 // esoteric compilers. 738 739 template <class T> class CppVtableTesterB: public T { 740 public: 741 virtual int last_virtual_method() {return 1;} 742 }; 743 744 template <class T> class CppVtableTesterA : public T { 745 public: 746 virtual void* last_virtual_method() { 747 // Make this different than CppVtableTesterB::last_virtual_method so the C++ 748 // compiler/linker won't alias the two functions. 749 return NULL; 750 } 751 }; 752 753 template <class T> 754 int CppVtableCloner<T>::get_vtable_length(const char* name) { 755 CppVtableTesterA<T> a; 756 CppVtableTesterB<T> b; 757 758 intptr_t* avtable = vtable_of(&a); 759 intptr_t* bvtable = vtable_of(&b); 760 761 // Start at slot 1, because slot 0 may be RTTI (on Solaris/Sparc) 762 int vtable_len = 1; 763 for (; ; vtable_len++) { 764 if (avtable[vtable_len] != bvtable[vtable_len]) { 765 break; 766 } 767 } 768 log_debug(cds, vtables)("Found %3d vtable entries for %s", vtable_len, name); 769 770 return vtable_len; 771 } 772 773 #define ALLOC_CPP_VTABLE_CLONE(c) \ 774 _cloned_cpp_vtptrs[c##_Kind] = CppVtableCloner<c>::allocate(#c); \ 775 ArchivePtrMarker::mark_pointer(&_cloned_cpp_vtptrs[c##_Kind]); 776 777 #define CLONE_CPP_VTABLE(c) \ 778 p = CppVtableCloner<c>::clone_vtable(#c, (CppVtableInfo*)p); 779 780 #define ZERO_CPP_VTABLE(c) \ 781 CppVtableCloner<c>::zero_vtable_clone(); 782 783 #define INIT_ORIG_CPP_VTPTRS(c) \ 784 CppVtableCloner<c>::init_orig_cpp_vtptr(c##_Kind); 785 786 #define DECLARE_CLONED_VTABLE_KIND(c) c ## _Kind, 787 788 enum ClonedVtableKind { 789 // E.g., ConstantPool_Kind == 0, InstanceKlass_Kind == 1, etc. 790 CPP_VTABLE_PATCH_TYPES_DO(DECLARE_CLONED_VTABLE_KIND) 791 _num_cloned_vtable_kinds 792 }; 793 794 // This is a map of all the original vtptrs. E.g., for 795 // ConstantPool *cp = new (...) ConstantPool(...) ; // a dynamically allocated constant pool 796 // the following holds true: 797 // _orig_cpp_vtptrs[ConstantPool_Kind] == ((intptr_t**)cp)[0] 798 static intptr_t* _orig_cpp_vtptrs[_num_cloned_vtable_kinds]; 799 static bool _orig_cpp_vtptrs_inited = false; 800 801 template <class T> 802 void CppVtableCloner<T>::init_orig_cpp_vtptr(int kind) { 803 assert(kind < _num_cloned_vtable_kinds, "sanity"); 804 T tmp; // Allocate temporary dummy metadata object to get to the original vtable. 805 intptr_t* srcvtable = vtable_of(&tmp); 806 _orig_cpp_vtptrs[kind] = srcvtable; 807 } 808 809 // This is the index of all the cloned vtables. E.g., for 810 // ConstantPool* cp = ....; // an archived constant pool 811 // InstanceKlass* ik = ....;// an archived class 812 // the following holds true: 813 // _cloned_cpp_vtptrs[ConstantPool_Kind] == ((intptr_t**)cp)[0] 814 // _cloned_cpp_vtptrs[InstanceKlass_Kind] == ((intptr_t**)ik)[0] 815 static intptr_t** _cloned_cpp_vtptrs = NULL; 816 817 void MetaspaceShared::allocate_cloned_cpp_vtptrs() { 818 assert(DumpSharedSpaces, "must"); 819 size_t vtptrs_bytes = _num_cloned_vtable_kinds * sizeof(intptr_t*); 820 _cloned_cpp_vtptrs = (intptr_t**)_mc_region.allocate(vtptrs_bytes, sizeof(intptr_t*)); 821 } 822 823 void MetaspaceShared::serialize_cloned_cpp_vtptrs(SerializeClosure* soc) { 824 soc->do_ptr((void**)&_cloned_cpp_vtptrs); 825 } 826 827 intptr_t* MetaspaceShared::get_archived_cpp_vtable(MetaspaceObj::Type msotype, address obj) { 828 if (!_orig_cpp_vtptrs_inited) { 829 CPP_VTABLE_PATCH_TYPES_DO(INIT_ORIG_CPP_VTPTRS); 830 _orig_cpp_vtptrs_inited = true; 831 } 832 833 Arguments::assert_is_dumping_archive(); 834 int kind = -1; 835 switch (msotype) { 836 case MetaspaceObj::SymbolType: 837 case MetaspaceObj::TypeArrayU1Type: 838 case MetaspaceObj::TypeArrayU2Type: 839 case MetaspaceObj::TypeArrayU4Type: 840 case MetaspaceObj::TypeArrayU8Type: 841 case MetaspaceObj::TypeArrayOtherType: 842 case MetaspaceObj::ConstMethodType: 843 case MetaspaceObj::ConstantPoolCacheType: 844 case MetaspaceObj::AnnotationsType: 845 case MetaspaceObj::MethodCountersType: 846 case MetaspaceObj::RecordComponentType: 847 // These have no vtables. 848 break; 849 case MetaspaceObj::MethodDataType: 850 // We don't archive MethodData <-- should have been removed in removed_unsharable_info 851 ShouldNotReachHere(); 852 break; 853 default: 854 for (kind = 0; kind < _num_cloned_vtable_kinds; kind ++) { 855 if (vtable_of((Metadata*)obj) == _orig_cpp_vtptrs[kind]) { 856 break; 857 } 858 } 859 if (kind >= _num_cloned_vtable_kinds) { 860 fatal("Cannot find C++ vtable for " INTPTR_FORMAT " -- you probably added" 861 " a new subtype of Klass or MetaData without updating CPP_VTABLE_PATCH_TYPES_DO", 862 p2i(obj)); 863 } 864 } 865 866 if (kind >= 0) { 867 assert(kind < _num_cloned_vtable_kinds, "must be"); 868 return _cloned_cpp_vtptrs[kind]; 869 } else { 870 return NULL; 871 } 872 } 873 874 // This can be called at both dump time and run time: 875 // - clone the contents of the c++ vtables into the space 876 // allocated by allocate_cpp_vtable_clones() 877 void MetaspaceShared::clone_cpp_vtables(intptr_t* p) { 878 assert(DumpSharedSpaces || UseSharedSpaces, "sanity"); 879 CPP_VTABLE_PATCH_TYPES_DO(CLONE_CPP_VTABLE); 880 } 881 882 void MetaspaceShared::zero_cpp_vtable_clones_for_writing() { 883 assert(DumpSharedSpaces, "dump-time only"); 884 CPP_VTABLE_PATCH_TYPES_DO(ZERO_CPP_VTABLE); 885 } 886 887 // Allocate and initialize the C++ vtables, starting from top, but do not go past end. 888 char* MetaspaceShared::allocate_cpp_vtable_clones() { 889 char* cloned_vtables = _mc_region.top(); // This is the beginning of all the cloned vtables 890 891 assert(DumpSharedSpaces, "dump-time only"); 892 // Layout (each slot is a intptr_t): 893 // [number of slots in the first vtable = n1] 894 // [ <n1> slots for the first vtable] 895 // [number of slots in the first second = n2] 896 // [ <n2> slots for the second vtable] 897 // ... 898 // The order of the vtables is the same as the CPP_VTAB_PATCH_TYPES_DO macro. 899 CPP_VTABLE_PATCH_TYPES_DO(ALLOC_CPP_VTABLE_CLONE); 900 901 return cloned_vtables; 902 } 903 904 bool MetaspaceShared::is_valid_shared_method(const Method* m) { 905 assert(is_in_shared_metaspace(m), "must be"); 906 return CppVtableCloner<Method>::is_valid_shared_object(m); 907 } 908 909 class VM_PopulateDumpSharedSpace: public VM_Operation { 910 private: 911 GrowableArray<MemRegion> *_closed_archive_heap_regions; 912 GrowableArray<MemRegion> *_open_archive_heap_regions; 913 914 GrowableArray<ArchiveHeapOopmapInfo> *_closed_archive_heap_oopmaps; 915 GrowableArray<ArchiveHeapOopmapInfo> *_open_archive_heap_oopmaps; 916 917 void dump_java_heap_objects() NOT_CDS_JAVA_HEAP_RETURN; 918 void dump_archive_heap_oopmaps() NOT_CDS_JAVA_HEAP_RETURN; 919 void dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions, 920 GrowableArray<ArchiveHeapOopmapInfo>* oopmaps); 921 void dump_symbols(); 922 char* dump_read_only_tables(); 923 void print_region_stats(FileMapInfo* map_info); 924 void print_bitmap_region_stats(size_t size, size_t total_size); 925 void print_heap_region_stats(GrowableArray<MemRegion> *heap_mem, 926 const char *name, size_t total_size); 927 void relocate_to_requested_base_address(CHeapBitMap* ptrmap); 928 929 public: 930 931 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; } 932 void doit(); // outline because gdb sucks 933 bool allow_nested_vm_operations() const { return true; } 934 }; // class VM_PopulateDumpSharedSpace 935 936 class StaticArchiveBuilder : public ArchiveBuilder { 937 public: 938 StaticArchiveBuilder(DumpRegion* rw_region, DumpRegion* ro_region) 939 : ArchiveBuilder(rw_region, ro_region) {} 940 941 virtual void iterate_roots(MetaspaceClosure* it, bool is_relocating_pointers) { 942 FileMapInfo::metaspace_pointers_do(it, false); 943 SystemDictionaryShared::dumptime_classes_do(it); 944 Universe::metaspace_pointers_do(it); 945 SymbolTable::metaspace_pointers_do(it); 946 vmSymbols::metaspace_pointers_do(it); 947 } 948 }; 949 950 void VM_PopulateDumpSharedSpace::dump_symbols() { 951 log_info(cds)("Dumping symbol table ..."); 952 953 NOT_PRODUCT(SymbolTable::verify()); 954 SymbolTable::write_to_archive(); 955 } 956 957 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() { 958 ArchiveBuilder::OtherROAllocMark mark; 959 960 log_info(cds)("Removing java_mirror ... "); 961 if (!HeapShared::is_heap_object_archiving_allowed()) { 962 Universe::clear_basic_type_mirrors(); 963 } 964 remove_java_mirror_in_classes(); 965 log_info(cds)("done. "); 966 967 SystemDictionaryShared::write_to_archive(); 968 969 // Write the other data to the output array. 970 char* start = _ro_region.top(); 971 WriteClosure wc(&_ro_region); 972 MetaspaceShared::serialize(&wc); 973 974 // Write the bitmaps for patching the archive heap regions 975 _closed_archive_heap_oopmaps = NULL; 976 _open_archive_heap_oopmaps = NULL; 977 dump_archive_heap_oopmaps(); 978 979 return start; 980 } 981 982 void VM_PopulateDumpSharedSpace::relocate_to_requested_base_address(CHeapBitMap* ptrmap) { 983 intx addr_delta = MetaspaceShared::final_delta(); 984 if (addr_delta == 0) { 985 ArchivePtrMarker::compact((address)SharedBaseAddress, (address)_ro_region.top()); 986 } else { 987 // We are not able to reserve space at MetaspaceShared::requested_base_address() (due to ASLR). 988 // This means that the current content of the archive is based on a random 989 // address. Let's relocate all the pointers, so that it can be mapped to 990 // MetaspaceShared::requested_base_address() without runtime relocation. 991 // 992 // Note: both the base and dynamic archive are written with 993 // FileMapHeader::_requested_base_address == MetaspaceShared::requested_base_address() 994 995 // Patch all pointers that are marked by ptrmap within this region, 996 // where we have just dumped all the metaspace data. 997 address patch_base = (address)SharedBaseAddress; 998 address patch_end = (address)_ro_region.top(); 999 size_t size = patch_end - patch_base; 1000 1001 // the current value of the pointers to be patched must be within this 1002 // range (i.e., must point to valid metaspace objects) 1003 address valid_old_base = patch_base; 1004 address valid_old_end = patch_end; 1005 1006 // after patching, the pointers must point inside this range 1007 // (the requested location of the archive, as mapped at runtime). 1008 address valid_new_base = (address)MetaspaceShared::requested_base_address(); 1009 address valid_new_end = valid_new_base + size; 1010 1011 log_debug(cds)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT " ] to " 1012 "[" INTPTR_FORMAT " - " INTPTR_FORMAT " ]", p2i(patch_base), p2i(patch_end), 1013 p2i(valid_new_base), p2i(valid_new_end)); 1014 1015 SharedDataRelocator<true> patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end, 1016 valid_new_base, valid_new_end, addr_delta, ptrmap); 1017 ptrmap->iterate(&patcher); 1018 ArchivePtrMarker::compact(patcher.max_non_null_offset()); 1019 } 1020 } 1021 1022 void VM_PopulateDumpSharedSpace::doit() { 1023 HeapShared::run_full_gc_in_vm_thread(); 1024 CHeapBitMap ptrmap; 1025 MetaspaceShared::initialize_ptr_marker(&ptrmap); 1026 1027 // We should no longer allocate anything from the metaspace, so that: 1028 // 1029 // (1) Metaspace::allocate might trigger GC if we have run out of 1030 // committed metaspace, but we can't GC because we're running 1031 // in the VM thread. 1032 // (2) ArchiveBuilder needs to work with a stable set of MetaspaceObjs. 1033 Metaspace::freeze(); 1034 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm); 1035 1036 Thread* THREAD = VMThread::vm_thread(); 1037 1038 FileMapInfo::check_nonempty_dir_in_shared_path_table(); 1039 1040 NOT_PRODUCT(SystemDictionary::verify();) 1041 // The following guarantee is meant to ensure that no loader constraints 1042 // exist yet, since the constraints table is not shared. This becomes 1043 // more important now that we don't re-initialize vtables/itables for 1044 // shared classes at runtime, where constraints were previously created. 1045 guarantee(SystemDictionary::constraints()->number_of_entries() == 0, 1046 "loader constraints are not saved"); 1047 guarantee(SystemDictionary::placeholders()->number_of_entries() == 0, 1048 "placeholders are not saved"); 1049 1050 // At this point, many classes have been loaded. 1051 // Gather systemDictionary classes in a global array and do everything to 1052 // that so we don't have to walk the SystemDictionary again. 1053 SystemDictionaryShared::check_excluded_classes(); 1054 1055 StaticArchiveBuilder builder(&_rw_region, &_ro_region); 1056 builder.gather_klasses_and_symbols(); 1057 _global_klass_objects = builder.klasses(); 1058 1059 // Ensure the ConstMethods won't be modified at run-time 1060 log_info(cds)("Updating ConstMethods ... "); 1061 rewrite_nofast_bytecodes_and_calculate_fingerprints(THREAD); 1062 log_info(cds)("done. "); 1063 1064 // Remove all references outside the metadata 1065 log_info(cds)("Removing unshareable information ... "); 1066 remove_unshareable_in_classes(); 1067 log_info(cds)("done. "); 1068 1069 builder.gather_source_objs(); 1070 1071 MetaspaceShared::allocate_cloned_cpp_vtptrs(); 1072 char* cloned_vtables = _mc_region.top(); 1073 MetaspaceShared::allocate_cpp_vtable_clones(); 1074 1075 { 1076 _mc_region.pack(&_rw_region); 1077 builder.dump_rw_region(); 1078 #if INCLUDE_CDS_JAVA_HEAP 1079 if (MetaspaceShared::use_full_module_graph()) { 1080 // Archive the ModuleEntry's and PackageEntry's of the 3 built-in loaders 1081 char* start = _rw_region.top(); 1082 ClassLoaderDataShared::allocate_archived_tables(); 1083 ArchiveBuilder::alloc_stats()->record_modules(_rw_region.top() - start, /*read_only*/false); 1084 } 1085 #endif 1086 } 1087 { 1088 _rw_region.pack(&_ro_region); 1089 builder.dump_ro_region(); 1090 #if INCLUDE_CDS_JAVA_HEAP 1091 if (MetaspaceShared::use_full_module_graph()) { 1092 char* start = _ro_region.top(); 1093 ClassLoaderDataShared::init_archived_tables(); 1094 ArchiveBuilder::alloc_stats()->record_modules(_ro_region.top() - start, /*read_only*/true); 1095 } 1096 #endif 1097 } 1098 builder.relocate_pointers(); 1099 1100 dump_symbols(); 1101 1102 // Dump supported java heap objects 1103 _closed_archive_heap_regions = NULL; 1104 _open_archive_heap_regions = NULL; 1105 dump_java_heap_objects(); 1106 1107 builder.relocate_well_known_klasses(); 1108 1109 char* serialized_data = dump_read_only_tables(); 1110 _ro_region.pack(); 1111 1112 // The vtable clones contain addresses of the current process. 1113 // We don't want to write these addresses into the archive. Same for i2i buffer. 1114 MetaspaceShared::zero_cpp_vtable_clones_for_writing(); 1115 memset(MetaspaceShared::i2i_entry_code_buffers(), 0, 1116 MetaspaceShared::i2i_entry_code_buffers_size()); 1117 1118 // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address() 1119 // without runtime relocation. 1120 relocate_to_requested_base_address(&ptrmap); 1121 1122 // Create and write the archive file that maps the shared spaces. 1123 1124 FileMapInfo* mapinfo = new FileMapInfo(true); 1125 mapinfo->populate_header(os::vm_allocation_granularity()); 1126 mapinfo->set_serialized_data(serialized_data); 1127 mapinfo->set_cloned_vtables(cloned_vtables); 1128 mapinfo->set_i2i_entry_code_buffers(MetaspaceShared::i2i_entry_code_buffers(), 1129 MetaspaceShared::i2i_entry_code_buffers_size()); 1130 mapinfo->open_for_write(); 1131 MetaspaceShared::write_core_archive_regions(mapinfo, _closed_archive_heap_oopmaps, _open_archive_heap_oopmaps); 1132 _total_closed_archive_region_size = mapinfo->write_archive_heap_regions( 1133 _closed_archive_heap_regions, 1134 _closed_archive_heap_oopmaps, 1135 MetaspaceShared::first_closed_archive_heap_region, 1136 MetaspaceShared::max_closed_archive_heap_region); 1137 _total_open_archive_region_size = mapinfo->write_archive_heap_regions( 1138 _open_archive_heap_regions, 1139 _open_archive_heap_oopmaps, 1140 MetaspaceShared::first_open_archive_heap_region, 1141 MetaspaceShared::max_open_archive_heap_region); 1142 1143 mapinfo->set_final_requested_base((char*)MetaspaceShared::requested_base_address()); 1144 mapinfo->set_header_crc(mapinfo->compute_header_crc()); 1145 mapinfo->write_header(); 1146 print_region_stats(mapinfo); 1147 mapinfo->close(); 1148 1149 if (log_is_enabled(Info, cds)) { 1150 builder.print_stats(int(_ro_region.used()), int(_rw_region.used()), int(_mc_region.used())); 1151 } 1152 1153 if (PrintSystemDictionaryAtExit) { 1154 SystemDictionary::print(); 1155 } 1156 1157 if (AllowArchivingWithJavaAgent) { 1158 warning("This archive was created with AllowArchivingWithJavaAgent. It should be used " 1159 "for testing purposes only and should not be used in a production environment"); 1160 } 1161 1162 // There may be other pending VM operations that operate on the InstanceKlasses, 1163 // which will fail because InstanceKlasses::remove_unshareable_info() 1164 // has been called. Forget these operations and exit the VM directly. 1165 vm_direct_exit(0); 1166 } 1167 1168 void VM_PopulateDumpSharedSpace::print_region_stats(FileMapInfo *map_info) { 1169 // Print statistics of all the regions 1170 const size_t bitmap_used = map_info->space_at(MetaspaceShared::bm)->used(); 1171 const size_t bitmap_reserved = map_info->space_at(MetaspaceShared::bm)->used_aligned(); 1172 const size_t total_reserved = _ro_region.reserved() + _rw_region.reserved() + 1173 _mc_region.reserved() + 1174 bitmap_reserved + 1175 _total_closed_archive_region_size + 1176 _total_open_archive_region_size; 1177 const size_t total_bytes = _ro_region.used() + _rw_region.used() + 1178 _mc_region.used() + 1179 bitmap_used + 1180 _total_closed_archive_region_size + 1181 _total_open_archive_region_size; 1182 const double total_u_perc = percent_of(total_bytes, total_reserved); 1183 1184 _mc_region.print(total_reserved); 1185 _rw_region.print(total_reserved); 1186 _ro_region.print(total_reserved); 1187 print_bitmap_region_stats(bitmap_used, total_reserved); 1188 print_heap_region_stats(_closed_archive_heap_regions, "ca", total_reserved); 1189 print_heap_region_stats(_open_archive_heap_regions, "oa", total_reserved); 1190 1191 log_debug(cds)("total : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]", 1192 total_bytes, total_reserved, total_u_perc); 1193 } 1194 1195 void VM_PopulateDumpSharedSpace::print_bitmap_region_stats(size_t size, size_t total_size) { 1196 log_debug(cds)("bm space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used]", 1197 size, size/double(total_size)*100.0, size); 1198 } 1199 1200 void VM_PopulateDumpSharedSpace::print_heap_region_stats(GrowableArray<MemRegion> *heap_mem, 1201 const char *name, size_t total_size) { 1202 int arr_len = heap_mem == NULL ? 0 : heap_mem->length(); 1203 for (int i = 0; i < arr_len; i++) { 1204 char* start = (char*)heap_mem->at(i).start(); 1205 size_t size = heap_mem->at(i).byte_size(); 1206 char* top = start + size; 1207 log_debug(cds)("%s%d space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used] at " INTPTR_FORMAT, 1208 name, i, size, size/double(total_size)*100.0, size, p2i(start)); 1209 1210 } 1211 } 1212 1213 void MetaspaceShared::write_core_archive_regions(FileMapInfo* mapinfo, 1214 GrowableArray<ArchiveHeapOopmapInfo>* closed_oopmaps, 1215 GrowableArray<ArchiveHeapOopmapInfo>* open_oopmaps) { 1216 // Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with 1217 // MetaspaceShared::n_regions (internal to hotspot). 1218 assert(NUM_CDS_REGIONS == MetaspaceShared::n_regions, "sanity"); 1219 1220 // mc contains the trampoline code for method entries, which are patched at run time, 1221 // so it needs to be read/write. 1222 write_region(mapinfo, mc, &_mc_region, /*read_only=*/false,/*allow_exec=*/true); 1223 write_region(mapinfo, rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false); 1224 write_region(mapinfo, ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false); 1225 mapinfo->write_bitmap_region(ArchivePtrMarker::ptrmap(), closed_oopmaps, open_oopmaps); 1226 } 1227 1228 void MetaspaceShared::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only, bool allow_exec) { 1229 mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec); 1230 } 1231 1232 // Update a Java object to point its Klass* to the new location after 1233 // shared archive has been compacted. 1234 void MetaspaceShared::relocate_klass_ptr(oop o) { 1235 assert(DumpSharedSpaces, "sanity"); 1236 Klass* k = ArchiveBuilder::get_relocated_klass(o->klass()); 1237 o->set_klass(k); 1238 } 1239 1240 Klass* MetaspaceShared::get_relocated_klass(Klass *k, bool is_final) { 1241 assert(DumpSharedSpaces, "sanity"); 1242 k = ArchiveBuilder::get_relocated_klass(k); 1243 if (is_final) { 1244 k = (Klass*)(address(k) + final_delta()); 1245 } 1246 return k; 1247 } 1248 1249 Symbol* MetaspaceShared::get_relocated_symbol(Symbol* orig_symbol) { 1250 return ArchiveBuilder::get_relocated_symbol(orig_symbol); 1251 } 1252 1253 class LinkSharedClassesClosure : public KlassClosure { 1254 Thread* THREAD; 1255 bool _made_progress; 1256 public: 1257 LinkSharedClassesClosure(Thread* thread) : THREAD(thread), _made_progress(false) {} 1258 1259 void reset() { _made_progress = false; } 1260 bool made_progress() const { return _made_progress; } 1261 1262 void do_klass(Klass* k) { 1263 if (k->is_instance_klass()) { 1264 InstanceKlass* ik = InstanceKlass::cast(k); 1265 // For dynamic CDS dump, only link classes loaded by the builtin class loaders. 1266 bool do_linking = DumpSharedSpaces ? true : !ik->is_shared_unregistered_class(); 1267 if (do_linking) { 1268 // Link the class to cause the bytecodes to be rewritten and the 1269 // cpcache to be created. Class verification is done according 1270 // to -Xverify setting. 1271 _made_progress |= MetaspaceShared::try_link_class(ik, THREAD); 1272 guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class"); 1273 1274 if (DumpSharedSpaces) { 1275 // The following function is used to resolve all Strings in the statically 1276 // dumped classes to archive all the Strings. The archive heap is not supported 1277 // for the dynamic archive. 1278 ik->constants()->resolve_class_constants(THREAD); 1279 } 1280 } 1281 } 1282 } 1283 }; 1284 1285 void MetaspaceShared::link_and_cleanup_shared_classes(TRAPS) { 1286 // We need to iterate because verification may cause additional classes 1287 // to be loaded. 1288 LinkSharedClassesClosure link_closure(THREAD); 1289 do { 1290 link_closure.reset(); 1291 ClassLoaderDataGraph::unlocked_loaded_classes_do(&link_closure); 1292 guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class"); 1293 } while (link_closure.made_progress()); 1294 } 1295 1296 void MetaspaceShared::prepare_for_dumping() { 1297 Arguments::check_unsupported_dumping_properties(); 1298 ClassLoader::initialize_shared_path(); 1299 } 1300 1301 // Preload classes from a list, populate the shared spaces and dump to a 1302 // file. 1303 void MetaspaceShared::preload_and_dump(TRAPS) { 1304 { TraceTime timer("Dump Shared Spaces", TRACETIME_LOG(Info, startuptime)); 1305 ResourceMark rm(THREAD); 1306 char class_list_path_str[JVM_MAXPATHLEN]; 1307 // Preload classes to be shared. 1308 const char* class_list_path; 1309 if (SharedClassListFile == NULL) { 1310 // Construct the path to the class list (in jre/lib) 1311 // Walk up two directories from the location of the VM and 1312 // optionally tack on "lib" (depending on platform) 1313 os::jvm_path(class_list_path_str, sizeof(class_list_path_str)); 1314 for (int i = 0; i < 3; i++) { 1315 char *end = strrchr(class_list_path_str, *os::file_separator()); 1316 if (end != NULL) *end = '\0'; 1317 } 1318 int class_list_path_len = (int)strlen(class_list_path_str); 1319 if (class_list_path_len >= 3) { 1320 if (strcmp(class_list_path_str + class_list_path_len - 3, "lib") != 0) { 1321 if (class_list_path_len < JVM_MAXPATHLEN - 4) { 1322 jio_snprintf(class_list_path_str + class_list_path_len, 1323 sizeof(class_list_path_str) - class_list_path_len, 1324 "%slib", os::file_separator()); 1325 class_list_path_len += 4; 1326 } 1327 } 1328 } 1329 if (class_list_path_len < JVM_MAXPATHLEN - 10) { 1330 jio_snprintf(class_list_path_str + class_list_path_len, 1331 sizeof(class_list_path_str) - class_list_path_len, 1332 "%sclasslist", os::file_separator()); 1333 } 1334 class_list_path = class_list_path_str; 1335 } else { 1336 class_list_path = SharedClassListFile; 1337 } 1338 1339 log_info(cds)("Loading classes to share ..."); 1340 _has_error_classes = false; 1341 int class_count = preload_classes(class_list_path, THREAD); 1342 if (ExtraSharedClassListFile) { 1343 class_count += preload_classes(ExtraSharedClassListFile, THREAD); 1344 } 1345 log_info(cds)("Loading classes to share: done."); 1346 1347 log_info(cds)("Shared spaces: preloaded %d classes", class_count); 1348 1349 if (SharedArchiveConfigFile) { 1350 log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile); 1351 read_extra_data(SharedArchiveConfigFile, THREAD); 1352 } 1353 log_info(cds)("Reading extra data: done."); 1354 1355 HeapShared::init_subgraph_entry_fields(THREAD); 1356 1357 // Rewrite and link classes 1358 log_info(cds)("Rewriting and linking classes ..."); 1359 1360 // Link any classes which got missed. This would happen if we have loaded classes that 1361 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K 1362 // fails verification, all other interfaces that were not specified in the classlist but 1363 // are implemented by K are not verified. 1364 link_and_cleanup_shared_classes(CATCH); 1365 log_info(cds)("Rewriting and linking classes: done"); 1366 1367 #if INCLUDE_CDS_JAVA_HEAP 1368 if (use_full_module_graph()) { 1369 HeapShared::reset_archived_object_states(THREAD); 1370 } 1371 #endif 1372 1373 VM_PopulateDumpSharedSpace op; 1374 MutexLocker ml(THREAD, HeapShared::is_heap_object_archiving_allowed() ? 1375 Heap_lock : NULL); // needed by HeapShared::run_gc() 1376 VMThread::execute(&op); 1377 } 1378 } 1379 1380 1381 int MetaspaceShared::preload_classes(const char* class_list_path, TRAPS) { 1382 ClassListParser parser(class_list_path); 1383 int class_count = 0; 1384 1385 while (parser.parse_one_line()) { 1386 Klass* klass = parser.load_current_class(THREAD); 1387 if (HAS_PENDING_EXCEPTION) { 1388 if (klass == NULL && 1389 (PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_ClassNotFoundException())) { 1390 // print a warning only when the pending exception is class not found 1391 log_warning(cds)("Preload Warning: Cannot find %s", parser.current_class_name()); 1392 } 1393 CLEAR_PENDING_EXCEPTION; 1394 } 1395 if (klass != NULL) { 1396 if (log_is_enabled(Trace, cds)) { 1397 ResourceMark rm(THREAD); 1398 log_trace(cds)("Shared spaces preloaded: %s", klass->external_name()); 1399 } 1400 1401 if (klass->is_instance_klass()) { 1402 InstanceKlass* ik = InstanceKlass::cast(klass); 1403 1404 // Link the class to cause the bytecodes to be rewritten and the 1405 // cpcache to be created. The linking is done as soon as classes 1406 // are loaded in order that the related data structures (klass and 1407 // cpCache) are located together. 1408 try_link_class(ik, THREAD); 1409 guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class"); 1410 } 1411 1412 class_count++; 1413 } 1414 } 1415 1416 return class_count; 1417 } 1418 1419 // Returns true if the class's status has changed 1420 bool MetaspaceShared::try_link_class(InstanceKlass* ik, TRAPS) { 1421 Arguments::assert_is_dumping_archive(); 1422 if (ik->init_state() < InstanceKlass::linked && 1423 !SystemDictionaryShared::has_class_failed_verification(ik)) { 1424 bool saved = BytecodeVerificationLocal; 1425 if (ik->is_shared_unregistered_class() && ik->class_loader() == NULL) { 1426 // The verification decision is based on BytecodeVerificationRemote 1427 // for non-system classes. Since we are using the NULL classloader 1428 // to load non-system classes for customized class loaders during dumping, 1429 // we need to temporarily change BytecodeVerificationLocal to be the same as 1430 // BytecodeVerificationRemote. Note this can cause the parent system 1431 // classes also being verified. The extra overhead is acceptable during 1432 // dumping. 1433 BytecodeVerificationLocal = BytecodeVerificationRemote; 1434 } 1435 ik->link_class(THREAD); 1436 if (HAS_PENDING_EXCEPTION) { 1437 ResourceMark rm(THREAD); 1438 log_warning(cds)("Preload Warning: Verification failed for %s", 1439 ik->external_name()); 1440 CLEAR_PENDING_EXCEPTION; 1441 SystemDictionaryShared::set_class_has_failed_verification(ik); 1442 _has_error_classes = true; 1443 } 1444 BytecodeVerificationLocal = saved; 1445 return true; 1446 } else { 1447 return false; 1448 } 1449 } 1450 1451 #if INCLUDE_CDS_JAVA_HEAP 1452 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() { 1453 // The closed and open archive heap space has maximum two regions. 1454 // See FileMapInfo::write_archive_heap_regions() for details. 1455 _closed_archive_heap_regions = new GrowableArray<MemRegion>(2); 1456 _open_archive_heap_regions = new GrowableArray<MemRegion>(2); 1457 HeapShared::archive_java_heap_objects(_closed_archive_heap_regions, 1458 _open_archive_heap_regions); 1459 ArchiveBuilder::OtherROAllocMark mark; 1460 HeapShared::write_subgraph_info_table(); 1461 } 1462 1463 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps() { 1464 if (HeapShared::is_heap_object_archiving_allowed()) { 1465 _closed_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2); 1466 dump_archive_heap_oopmaps(_closed_archive_heap_regions, _closed_archive_heap_oopmaps); 1467 1468 _open_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2); 1469 dump_archive_heap_oopmaps(_open_archive_heap_regions, _open_archive_heap_oopmaps); 1470 } 1471 } 1472 1473 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions, 1474 GrowableArray<ArchiveHeapOopmapInfo>* oopmaps) { 1475 for (int i=0; i<regions->length(); i++) { 1476 ResourceBitMap oopmap = HeapShared::calculate_oopmap(regions->at(i)); 1477 size_t size_in_bits = oopmap.size(); 1478 size_t size_in_bytes = oopmap.size_in_bytes(); 1479 uintptr_t* buffer = (uintptr_t*)NEW_C_HEAP_ARRAY(char, size_in_bytes, mtInternal); 1480 oopmap.write_to(buffer, size_in_bytes); 1481 log_info(cds, heap)("Oopmap = " INTPTR_FORMAT " (" SIZE_FORMAT_W(6) " bytes) for heap region " 1482 INTPTR_FORMAT " (" SIZE_FORMAT_W(8) " bytes)", 1483 p2i(buffer), size_in_bytes, 1484 p2i(regions->at(i).start()), regions->at(i).byte_size()); 1485 1486 ArchiveHeapOopmapInfo info; 1487 info._oopmap = (address)buffer; 1488 info._oopmap_size_in_bits = size_in_bits; 1489 info._oopmap_size_in_bytes = size_in_bytes; 1490 oopmaps->append(info); 1491 } 1492 } 1493 #endif // INCLUDE_CDS_JAVA_HEAP 1494 1495 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) { 1496 assert(base <= static_top && static_top <= top, "must be"); 1497 _shared_metaspace_static_top = static_top; 1498 MetaspaceObj::set_shared_metaspace_range(base, top); 1499 } 1500 1501 // Return true if given address is in the misc data region 1502 bool MetaspaceShared::is_in_shared_region(const void* p, int idx) { 1503 return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx); 1504 } 1505 1506 bool MetaspaceShared::is_in_trampoline_frame(address addr) { 1507 if (UseSharedSpaces && is_in_shared_region(addr, MetaspaceShared::mc)) { 1508 return true; 1509 } 1510 return false; 1511 } 1512 1513 bool MetaspaceShared::is_shared_dynamic(void* p) { 1514 if ((p < MetaspaceObj::shared_metaspace_top()) && 1515 (p >= _shared_metaspace_static_top)) { 1516 return true; 1517 } else { 1518 return false; 1519 } 1520 } 1521 1522 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() { 1523 assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled"); 1524 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE; 1525 1526 FileMapInfo* static_mapinfo = open_static_archive(); 1527 FileMapInfo* dynamic_mapinfo = NULL; 1528 1529 if (static_mapinfo != NULL) { 1530 dynamic_mapinfo = open_dynamic_archive(); 1531 1532 // First try to map at the requested address 1533 result = map_archives(static_mapinfo, dynamic_mapinfo, true); 1534 if (result == MAP_ARCHIVE_MMAP_FAILURE) { 1535 // Mapping has failed (probably due to ASLR). Let's map at an address chosen 1536 // by the OS. 1537 log_info(cds)("Try to map archive(s) at an alternative address"); 1538 result = map_archives(static_mapinfo, dynamic_mapinfo, false); 1539 } 1540 } 1541 1542 if (result == MAP_ARCHIVE_SUCCESS) { 1543 bool dynamic_mapped = (dynamic_mapinfo != NULL && dynamic_mapinfo->is_mapped()); 1544 char* cds_base = static_mapinfo->mapped_base(); 1545 char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end(); 1546 set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end); 1547 _relocation_delta = static_mapinfo->relocation_delta(); 1548 if (dynamic_mapped) { 1549 FileMapInfo::set_shared_path_table(dynamic_mapinfo); 1550 } else { 1551 FileMapInfo::set_shared_path_table(static_mapinfo); 1552 } 1553 _requested_base_address = static_mapinfo->requested_base_address(); 1554 } else { 1555 set_shared_metaspace_range(NULL, NULL, NULL); 1556 UseSharedSpaces = false; 1557 FileMapInfo::fail_continue("Unable to map shared spaces"); 1558 if (PrintSharedArchiveAndExit) { 1559 vm_exit_during_initialization("Unable to use shared archive."); 1560 } 1561 } 1562 1563 if (static_mapinfo != NULL && !static_mapinfo->is_mapped()) { 1564 delete static_mapinfo; 1565 } 1566 if (dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped()) { 1567 delete dynamic_mapinfo; 1568 } 1569 } 1570 1571 FileMapInfo* MetaspaceShared::open_static_archive() { 1572 FileMapInfo* mapinfo = new FileMapInfo(true); 1573 if (!mapinfo->initialize()) { 1574 delete(mapinfo); 1575 return NULL; 1576 } 1577 return mapinfo; 1578 } 1579 1580 FileMapInfo* MetaspaceShared::open_dynamic_archive() { 1581 if (DynamicDumpSharedSpaces) { 1582 return NULL; 1583 } 1584 if (Arguments::GetSharedDynamicArchivePath() == NULL) { 1585 return NULL; 1586 } 1587 1588 FileMapInfo* mapinfo = new FileMapInfo(false); 1589 if (!mapinfo->initialize()) { 1590 delete(mapinfo); 1591 return NULL; 1592 } 1593 return mapinfo; 1594 } 1595 1596 // use_requested_addr: 1597 // true = map at FileMapHeader::_requested_base_address 1598 // false = map at an alternative address picked by OS. 1599 MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo, 1600 bool use_requested_addr) { 1601 if (use_requested_addr && static_mapinfo->requested_base_address() == NULL) { 1602 log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address."); 1603 return MAP_ARCHIVE_MMAP_FAILURE; 1604 } 1605 1606 PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) { 1607 // For product build only -- this is for benchmarking the cost of doing relocation. 1608 // For debug builds, the check is done below, after reserving the space, for better test coverage 1609 // (see comment below). 1610 log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address"); 1611 return MAP_ARCHIVE_MMAP_FAILURE; 1612 }); 1613 1614 if (ArchiveRelocationMode == 2 && !use_requested_addr) { 1615 log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address"); 1616 return MAP_ARCHIVE_MMAP_FAILURE; 1617 }; 1618 1619 if (dynamic_mapinfo != NULL) { 1620 // Ensure that the OS won't be able to allocate new memory spaces between the two 1621 // archives, or else it would mess up the simple comparision in MetaspaceObj::is_shared(). 1622 assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap"); 1623 } 1624 1625 ReservedSpace archive_space_rs, class_space_rs; 1626 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE; 1627 char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo, dynamic_mapinfo, 1628 use_requested_addr, archive_space_rs, 1629 class_space_rs); 1630 if (mapped_base_address == NULL) { 1631 result = MAP_ARCHIVE_MMAP_FAILURE; 1632 log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr); 1633 } else { 1634 1635 #ifdef ASSERT 1636 // Some sanity checks after reserving address spaces for archives 1637 // and class space. 1638 assert(archive_space_rs.is_reserved(), "Sanity"); 1639 if (Metaspace::using_class_space()) { 1640 // Class space must closely follow the archive space. Both spaces 1641 // must be aligned correctly. 1642 assert(class_space_rs.is_reserved(), 1643 "A class space should have been reserved"); 1644 assert(class_space_rs.base() >= archive_space_rs.end(), 1645 "class space should follow the cds archive space"); 1646 assert(is_aligned(archive_space_rs.base(), 1647 MetaspaceShared::reserved_space_alignment()), 1648 "Archive space misaligned"); 1649 assert(is_aligned(class_space_rs.base(), 1650 Metaspace::reserve_alignment()), 1651 "class space misaligned"); 1652 } 1653 #endif // ASSERT 1654 1655 log_debug(cds)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes", 1656 p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size()); 1657 log_debug(cds)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes", 1658 p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size()); 1659 1660 if (MetaspaceShared::use_windows_memory_mapping()) { 1661 // We have now reserved address space for the archives, and will map in 1662 // the archive files into this space. 1663 // 1664 // Special handling for Windows: on Windows we cannot map a file view 1665 // into an existing memory mapping. So, we unmap the address range we 1666 // just reserved again, which will make it available for mapping the 1667 // archives. 1668 // Reserving this range has not been for naught however since it makes 1669 // us reasonably sure the address range is available. 1670 // 1671 // But still it may fail, since between unmapping the range and mapping 1672 // in the archive someone else may grab the address space. Therefore 1673 // there is a fallback in FileMap::map_region() where we just read in 1674 // the archive files sequentially instead of mapping it in. We couple 1675 // this with use_requested_addr, since we're going to patch all the 1676 // pointers anyway so there's no benefit to mmap. 1677 if (use_requested_addr) { 1678 log_info(cds)("Windows mmap workaround: releasing archive space."); 1679 archive_space_rs.release(); 1680 } 1681 } 1682 MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs); 1683 MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ? 1684 map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE; 1685 1686 DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) { 1687 // This is for simulating mmap failures at the requested address. In 1688 // debug builds, we do it here (after all archives have possibly been 1689 // mapped), so we can thoroughly test the code for failure handling 1690 // (releasing all allocated resource, etc). 1691 log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address"); 1692 if (static_result == MAP_ARCHIVE_SUCCESS) { 1693 static_result = MAP_ARCHIVE_MMAP_FAILURE; 1694 } 1695 if (dynamic_result == MAP_ARCHIVE_SUCCESS) { 1696 dynamic_result = MAP_ARCHIVE_MMAP_FAILURE; 1697 } 1698 }); 1699 1700 if (static_result == MAP_ARCHIVE_SUCCESS) { 1701 if (dynamic_result == MAP_ARCHIVE_SUCCESS) { 1702 result = MAP_ARCHIVE_SUCCESS; 1703 } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) { 1704 assert(dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped(), "must have failed"); 1705 // No need to retry mapping the dynamic archive again, as it will never succeed 1706 // (bad file, etc) -- just keep the base archive. 1707 log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s", 1708 dynamic_mapinfo->full_path()); 1709 result = MAP_ARCHIVE_SUCCESS; 1710 // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no 1711 // easy API to do that right now. 1712 } else { 1713 result = MAP_ARCHIVE_MMAP_FAILURE; 1714 } 1715 } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) { 1716 result = MAP_ARCHIVE_OTHER_FAILURE; 1717 } else { 1718 result = MAP_ARCHIVE_MMAP_FAILURE; 1719 } 1720 } 1721 1722 if (result == MAP_ARCHIVE_SUCCESS) { 1723 SharedBaseAddress = (size_t)mapped_base_address; 1724 LP64_ONLY({ 1725 if (Metaspace::using_class_space()) { 1726 // Set up ccs in metaspace. 1727 Metaspace::initialize_class_space(class_space_rs); 1728 1729 // Set up compressed Klass pointer encoding: the encoding range must 1730 // cover both archive and class space. 1731 address cds_base = (address)static_mapinfo->mapped_base(); 1732 address ccs_end = (address)class_space_rs.end(); 1733 CompressedKlassPointers::initialize(cds_base, ccs_end - cds_base); 1734 1735 // map_heap_regions() compares the current narrow oop and klass encodings 1736 // with the archived ones, so it must be done after all encodings are determined. 1737 static_mapinfo->map_heap_regions(); 1738 } 1739 }); 1740 log_info(cds)("optimized module handling: %s", MetaspaceShared::use_optimized_module_handling() ? "enabled" : "disabled"); 1741 log_info(cds)("full module graph: %s", MetaspaceShared::use_full_module_graph() ? "enabled" : "disabled"); 1742 } else { 1743 unmap_archive(static_mapinfo); 1744 unmap_archive(dynamic_mapinfo); 1745 release_reserved_spaces(archive_space_rs, class_space_rs); 1746 } 1747 1748 return result; 1749 } 1750 1751 1752 // This will reserve two address spaces suitable to house Klass structures, one 1753 // for the cds archives (static archive and optionally dynamic archive) and 1754 // optionally one move for ccs. 1755 // 1756 // Since both spaces must fall within the compressed class pointer encoding 1757 // range, they are allocated close to each other. 1758 // 1759 // Space for archives will be reserved first, followed by a potential gap, 1760 // followed by the space for ccs: 1761 // 1762 // +-- Base address A B End 1763 // | | | | 1764 // v v v v 1765 // +-------------+--------------+ +----------------------+ 1766 // | static arc | [dyn. arch] | [gap] | compr. class space | 1767 // +-------------+--------------+ +----------------------+ 1768 // 1769 // (The gap may result from different alignment requirements between metaspace 1770 // and CDS) 1771 // 1772 // If UseCompressedClassPointers is disabled, only one address space will be 1773 // reserved: 1774 // 1775 // +-- Base address End 1776 // | | 1777 // v v 1778 // +-------------+--------------+ 1779 // | static arc | [dyn. arch] | 1780 // +-------------+--------------+ 1781 // 1782 // Base address: If use_archive_base_addr address is true, the Base address is 1783 // determined by the address stored in the static archive. If 1784 // use_archive_base_addr address is false, this base address is determined 1785 // by the platform. 1786 // 1787 // If UseCompressedClassPointers=1, the range encompassing both spaces will be 1788 // suitable to en/decode narrow Klass pointers: the base will be valid for 1789 // encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax. 1790 // 1791 // Return: 1792 // 1793 // - On success: 1794 // - archive_space_rs will be reserved and large enough to host static and 1795 // if needed dynamic archive: [Base, A). 1796 // archive_space_rs.base and size will be aligned to CDS reserve 1797 // granularity. 1798 // - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will 1799 // be reserved. Its start address will be aligned to metaspace reserve 1800 // alignment, which may differ from CDS alignment. It will follow the cds 1801 // archive space, close enough such that narrow class pointer encoding 1802 // covers both spaces. 1803 // If UseCompressedClassPointers=0, class_space_rs remains unreserved. 1804 // - On error: NULL is returned and the spaces remain unreserved. 1805 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo, 1806 FileMapInfo* dynamic_mapinfo, 1807 bool use_archive_base_addr, 1808 ReservedSpace& archive_space_rs, 1809 ReservedSpace& class_space_rs) { 1810 1811 address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : NULL); 1812 const size_t archive_space_alignment = MetaspaceShared::reserved_space_alignment(); 1813 1814 // Size and requested location of the archive_space_rs (for both static and dynamic archives) 1815 assert(static_mapinfo->mapping_base_offset() == 0, "Must be"); 1816 size_t archive_end_offset = (dynamic_mapinfo == NULL) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset(); 1817 size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment); 1818 1819 // If a base address is given, it must have valid alignment and be suitable as encoding base. 1820 if (base_address != NULL) { 1821 assert(is_aligned(base_address, archive_space_alignment), 1822 "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address)); 1823 if (Metaspace::using_class_space()) { 1824 assert(CompressedKlassPointers::is_valid_base(base_address), 1825 "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address)); 1826 } 1827 } 1828 1829 if (!Metaspace::using_class_space()) { 1830 // Get the simple case out of the way first: 1831 // no compressed class space, simple allocation. 1832 archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment, 1833 false /* bool large */, (char*)base_address); 1834 if (archive_space_rs.is_reserved()) { 1835 assert(base_address == NULL || 1836 (address)archive_space_rs.base() == base_address, "Sanity"); 1837 // Register archive space with NMT. 1838 MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared); 1839 return archive_space_rs.base(); 1840 } 1841 return NULL; 1842 } 1843 1844 #ifdef _LP64 1845 1846 // Complex case: two spaces adjacent to each other, both to be addressable 1847 // with narrow class pointers. 1848 // We reserve the whole range spanning both spaces, then split that range up. 1849 1850 const size_t class_space_alignment = Metaspace::reserve_alignment(); 1851 1852 // To simplify matters, lets assume that metaspace alignment will always be 1853 // equal or a multiple of archive alignment. 1854 assert(is_power_of_2(class_space_alignment) && 1855 is_power_of_2(archive_space_alignment) && 1856 class_space_alignment >= archive_space_alignment, 1857 "Sanity"); 1858 1859 const size_t class_space_size = CompressedClassSpaceSize; 1860 assert(CompressedClassSpaceSize > 0 && 1861 is_aligned(CompressedClassSpaceSize, class_space_alignment), 1862 "CompressedClassSpaceSize malformed: " 1863 SIZE_FORMAT, CompressedClassSpaceSize); 1864 1865 const size_t ccs_begin_offset = align_up(base_address + archive_space_size, 1866 class_space_alignment) - base_address; 1867 const size_t gap_size = ccs_begin_offset - archive_space_size; 1868 1869 const size_t total_range_size = 1870 align_up(archive_space_size + gap_size + class_space_size, 1871 os::vm_allocation_granularity()); 1872 1873 ReservedSpace total_rs; 1874 if (base_address != NULL) { 1875 // Reserve at the given archive base address, or not at all. 1876 total_rs = ReservedSpace(total_range_size, archive_space_alignment, 1877 false /* bool large */, (char*) base_address); 1878 } else { 1879 // Reserve at any address, but leave it up to the platform to choose a good one. 1880 total_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size); 1881 } 1882 1883 if (!total_rs.is_reserved()) { 1884 return NULL; 1885 } 1886 1887 // Paranoid checks: 1888 assert(base_address == NULL || (address)total_rs.base() == base_address, 1889 "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_rs.base())); 1890 assert(is_aligned(total_rs.base(), archive_space_alignment), "Sanity"); 1891 assert(total_rs.size() == total_range_size, "Sanity"); 1892 assert(CompressedKlassPointers::is_valid_base((address)total_rs.base()), "Sanity"); 1893 1894 // Now split up the space into ccs and cds archive. For simplicity, just leave 1895 // the gap reserved at the end of the archive space. 1896 archive_space_rs = total_rs.first_part(ccs_begin_offset, 1897 (size_t)os::vm_allocation_granularity(), 1898 /*split=*/true); 1899 class_space_rs = total_rs.last_part(ccs_begin_offset); 1900 1901 assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity"); 1902 assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity"); 1903 assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity"); 1904 assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity"); 1905 1906 // NMT: fix up the space tags 1907 MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared); 1908 MemTracker::record_virtual_memory_type(class_space_rs.base(), mtClass); 1909 1910 return archive_space_rs.base(); 1911 1912 #else 1913 ShouldNotReachHere(); 1914 return NULL; 1915 #endif 1916 1917 } 1918 1919 void MetaspaceShared::release_reserved_spaces(ReservedSpace& archive_space_rs, 1920 ReservedSpace& class_space_rs) { 1921 if (archive_space_rs.is_reserved()) { 1922 log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base())); 1923 archive_space_rs.release(); 1924 } 1925 if (class_space_rs.is_reserved()) { 1926 log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base())); 1927 class_space_rs.release(); 1928 } 1929 } 1930 1931 static int archive_regions[] = {MetaspaceShared::mc, 1932 MetaspaceShared::rw, 1933 MetaspaceShared::ro}; 1934 static int archive_regions_count = 3; 1935 1936 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) { 1937 assert(UseSharedSpaces, "must be runtime"); 1938 if (mapinfo == NULL) { 1939 return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded. 1940 } 1941 1942 mapinfo->set_is_mapped(false); 1943 1944 if (mapinfo->alignment() != (size_t)os::vm_allocation_granularity()) { 1945 log_error(cds)("Unable to map CDS archive -- os::vm_allocation_granularity() expected: " SIZE_FORMAT 1946 " actual: %d", mapinfo->alignment(), os::vm_allocation_granularity()); 1947 return MAP_ARCHIVE_OTHER_FAILURE; 1948 } 1949 1950 MapArchiveResult result = 1951 mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs); 1952 1953 if (result != MAP_ARCHIVE_SUCCESS) { 1954 unmap_archive(mapinfo); 1955 return result; 1956 } 1957 1958 if (!mapinfo->validate_shared_path_table()) { 1959 unmap_archive(mapinfo); 1960 return MAP_ARCHIVE_OTHER_FAILURE; 1961 } 1962 1963 mapinfo->set_is_mapped(true); 1964 return MAP_ARCHIVE_SUCCESS; 1965 } 1966 1967 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) { 1968 assert(UseSharedSpaces, "must be runtime"); 1969 if (mapinfo != NULL) { 1970 mapinfo->unmap_regions(archive_regions, archive_regions_count); 1971 mapinfo->set_is_mapped(false); 1972 } 1973 } 1974 1975 // Read the miscellaneous data from the shared file, and 1976 // serialize it out to its various destinations. 1977 1978 void MetaspaceShared::initialize_shared_spaces() { 1979 FileMapInfo *static_mapinfo = FileMapInfo::current_info(); 1980 _i2i_entry_code_buffers = static_mapinfo->i2i_entry_code_buffers(); 1981 _i2i_entry_code_buffers_size = static_mapinfo->i2i_entry_code_buffers_size(); 1982 char* buffer = static_mapinfo->cloned_vtables(); 1983 clone_cpp_vtables((intptr_t*)buffer); 1984 1985 // Verify various attributes of the archive, plus initialize the 1986 // shared string/symbol tables 1987 buffer = static_mapinfo->serialized_data(); 1988 intptr_t* array = (intptr_t*)buffer; 1989 ReadClosure rc(&array); 1990 serialize(&rc); 1991 1992 // Initialize the run-time symbol table. 1993 SymbolTable::create_table(); 1994 1995 static_mapinfo->patch_archived_heap_embedded_pointers(); 1996 1997 // Close the mapinfo file 1998 static_mapinfo->close(); 1999 2000 static_mapinfo->unmap_region(MetaspaceShared::bm); 2001 2002 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info(); 2003 if (dynamic_mapinfo != NULL) { 2004 intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data(); 2005 ReadClosure rc(&buffer); 2006 SymbolTable::serialize_shared_table_header(&rc, false); 2007 SystemDictionaryShared::serialize_dictionary_headers(&rc, false); 2008 dynamic_mapinfo->close(); 2009 } 2010 2011 if (PrintSharedArchiveAndExit) { 2012 if (PrintSharedDictionary) { 2013 tty->print_cr("\nShared classes:\n"); 2014 SystemDictionaryShared::print_on(tty); 2015 } 2016 if (FileMapInfo::current_info() == NULL || _archive_loading_failed) { 2017 tty->print_cr("archive is invalid"); 2018 vm_exit(1); 2019 } else { 2020 tty->print_cr("archive is valid"); 2021 vm_exit(0); 2022 } 2023 } 2024 } 2025 2026 // JVM/TI RedefineClasses() support: 2027 bool MetaspaceShared::remap_shared_readonly_as_readwrite() { 2028 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 2029 2030 if (UseSharedSpaces) { 2031 // remap the shared readonly space to shared readwrite, private 2032 FileMapInfo* mapinfo = FileMapInfo::current_info(); 2033 if (!mapinfo->remap_shared_readonly_as_readwrite()) { 2034 return false; 2035 } 2036 if (FileMapInfo::dynamic_info() != NULL) { 2037 mapinfo = FileMapInfo::dynamic_info(); 2038 if (!mapinfo->remap_shared_readonly_as_readwrite()) { 2039 return false; 2040 } 2041 } 2042 _remapped_readwrite = true; 2043 } 2044 return true; 2045 } 2046 2047 void MetaspaceShared::report_out_of_space(const char* name, size_t needed_bytes) { 2048 // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space. 2049 // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes 2050 // or so. 2051 _mc_region.print_out_of_space_msg(name, needed_bytes); 2052 _rw_region.print_out_of_space_msg(name, needed_bytes); 2053 _ro_region.print_out_of_space_msg(name, needed_bytes); 2054 2055 vm_exit_during_initialization(err_msg("Unable to allocate from '%s' region", name), 2056 "Please reduce the number of shared classes."); 2057 } 2058 2059 // This is used to relocate the pointers so that the base archive can be mapped at 2060 // MetaspaceShared::requested_base_address() without runtime relocation. 2061 intx MetaspaceShared::final_delta() { 2062 return intx(MetaspaceShared::requested_base_address()) // We want the base archive to be mapped to here at runtime 2063 - intx(SharedBaseAddress); // .. but the base archive is mapped at here at dump time 2064 } 2065 2066 bool MetaspaceShared::use_full_module_graph() { 2067 bool result = _use_optimized_module_handling && _use_full_module_graph && 2068 (UseSharedSpaces || DumpSharedSpaces) && HeapShared::is_heap_object_archiving_allowed(); 2069 if (result && UseSharedSpaces) { 2070 // Classes used by the archived full module graph are loaded in JVMTI early phase. 2071 assert(!(JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()), 2072 "CDS should be disabled if early class hooks are enabled"); 2073 } 2074 return result; 2075 } 2076 2077 void MetaspaceShared::print_on(outputStream* st) { 2078 if (UseSharedSpaces || DumpSharedSpaces) { 2079 st->print("CDS archive(s) mapped at: "); 2080 address base; 2081 address top; 2082 if (UseSharedSpaces) { // Runtime 2083 base = (address)MetaspaceObj::shared_metaspace_base(); 2084 address static_top = (address)_shared_metaspace_static_top; 2085 top = (address)MetaspaceObj::shared_metaspace_top(); 2086 st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top)); 2087 } else if (DumpSharedSpaces) { // Dump Time 2088 base = (address)_shared_rs.base(); 2089 top = (address)_shared_rs.end(); 2090 st->print("[" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(top)); 2091 } 2092 st->print("size " SIZE_FORMAT ", ", top - base); 2093 st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, (int)ArchiveRelocationMode); 2094 } else { 2095 st->print("CDS disabled."); 2096 } 2097 st->cr(); 2098 }