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 "jvm.h" 27 #include "classfile/classLoaderDataGraph.hpp" 28 #include "classfile/classListParser.hpp" 29 #include "classfile/classLoaderExt.hpp" 30 #include "classfile/dictionary.hpp" 31 #include "classfile/loaderConstraints.hpp" 32 #include "classfile/javaClasses.inline.hpp" 33 #include "classfile/placeholders.hpp" 34 #include "classfile/symbolTable.hpp" 35 #include "classfile/stringTable.hpp" 36 #include "classfile/systemDictionary.hpp" 37 #include "classfile/systemDictionaryShared.hpp" 38 #include "code/codeCache.hpp" 39 #include "gc/shared/softRefPolicy.hpp" 40 #include "interpreter/bytecodeStream.hpp" 41 #include "interpreter/bytecodes.hpp" 42 #include "logging/log.hpp" 43 #include "logging/logMessage.hpp" 44 #include "memory/archiveUtils.inline.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 "prims/jvmtiRedefineClasses.hpp" 63 #include "runtime/handles.inline.hpp" 64 #include "runtime/os.hpp" 65 #include "runtime/safepointVerifiers.hpp" 66 #include "runtime/signature.hpp" 67 #include "runtime/timerTrace.hpp" 68 #include "runtime/vmThread.hpp" 69 #include "runtime/vmOperations.hpp" 70 #include "utilities/align.hpp" 71 #include "utilities/bitMap.inline.hpp" 72 #include "utilities/defaultStream.hpp" 73 #include "utilities/hashtable.inline.hpp" 74 #if INCLUDE_G1GC 75 #include "gc/g1/g1CollectedHeap.hpp" 76 #endif 77 78 ReservedSpace MetaspaceShared::_shared_rs; 79 VirtualSpace MetaspaceShared::_shared_vs; 80 MetaspaceSharedStats MetaspaceShared::_stats; 81 bool MetaspaceShared::_has_error_classes; 82 bool MetaspaceShared::_archive_loading_failed = false; 83 bool MetaspaceShared::_remapped_readwrite = false; 84 address MetaspaceShared::_i2i_entry_code_buffers = NULL; 85 size_t MetaspaceShared::_i2i_entry_code_buffers_size = 0; 86 void* MetaspaceShared::_shared_metaspace_static_top = NULL; 87 intx MetaspaceShared::_relocation_delta; 88 char* MetaspaceShared::_default_base_address; 89 90 // The CDS archive is divided into the following regions: 91 // mc - misc code (the method entry trampolines, c++ vtables) 92 // rw - read-write metadata 93 // ro - read-only metadata and read-only tables 94 // 95 // ca0 - closed archive heap space #0 96 // ca1 - closed archive heap space #1 (may be empty) 97 // oa0 - open archive heap space #0 98 // oa1 - open archive heap space #1 (may be empty) 99 // 100 // The mc, rw, and ro regions are linearly allocated, starting from 101 // SharedBaseAddress, in the order of mc->rw->ro. The size of these 3 regions 102 // are page-aligned, and there's no gap between any consecutive regions. 103 // 104 // These 3 regions are populated in the following steps: 105 // [1] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are 106 // temporarily allocated outside of the shared regions. Only the method entry 107 // trampolines are written into the mc region. 108 // [2] C++ vtables are copied into the mc region. 109 // [3] ArchiveCompactor copies RW metadata into the rw region. 110 // [4] ArchiveCompactor copies RO metadata into the ro region. 111 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data 112 // are copied into the ro region as read-only tables. 113 // 114 // The s0/s1 and oa0/oa1 regions are populated inside HeapShared::archive_java_heap_objects. 115 // Their layout is independent of the other 4 regions. 116 117 char* DumpRegion::expand_top_to(char* newtop) { 118 assert(is_allocatable(), "must be initialized and not packed"); 119 assert(newtop >= _top, "must not grow backwards"); 120 if (newtop > _end) { 121 MetaspaceShared::report_out_of_space(_name, newtop - _top); 122 ShouldNotReachHere(); 123 } 124 uintx delta; 125 if (DynamicDumpSharedSpaces) { 126 delta = DynamicArchive::object_delta_uintx(newtop); 127 } else { 128 delta = MetaspaceShared::object_delta_uintx(newtop); 129 } 130 if (delta > MAX_SHARED_DELTA) { 131 // This is just a sanity check and should not appear in any real world usage. This 132 // happens only if you allocate more than 2GB of shared objects and would require 133 // millions of shared classes. 134 vm_exit_during_initialization("Out of memory in the CDS archive", 135 "Please reduce the number of shared classes."); 136 } 137 138 MetaspaceShared::commit_shared_space_to(newtop); 139 _top = newtop; 140 return _top; 141 } 142 143 char* DumpRegion::allocate(size_t num_bytes, size_t alignment) { 144 char* p = (char*)align_up(_top, alignment); 145 char* newtop = p + align_up(num_bytes, alignment); 146 expand_top_to(newtop); 147 memset(p, 0, newtop - p); 148 return p; 149 } 150 151 void DumpRegion::append_intptr_t(intptr_t n, bool need_to_mark) { 152 assert(is_aligned(_top, sizeof(intptr_t)), "bad alignment"); 153 intptr_t *p = (intptr_t*)_top; 154 char* newtop = _top + sizeof(intptr_t); 155 expand_top_to(newtop); 156 *p = n; 157 if (need_to_mark) { 158 ArchivePtrMarker::mark_pointer(p); 159 } 160 } 161 162 void DumpRegion::print(size_t total_bytes) const { 163 log_debug(cds)("%-3s space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used] at " INTPTR_FORMAT, 164 _name, used(), percent_of(used(), total_bytes), reserved(), percent_of(used(), reserved()), 165 p2i(_base + MetaspaceShared::final_delta())); 166 } 167 168 void DumpRegion::print_out_of_space_msg(const char* failing_region, size_t needed_bytes) { 169 log_error(cds)("[%-8s] " PTR_FORMAT " - " PTR_FORMAT " capacity =%9d, allocated =%9d", 170 _name, p2i(_base), p2i(_top), int(_end - _base), int(_top - _base)); 171 if (strcmp(_name, failing_region) == 0) { 172 log_error(cds)(" required = %d", int(needed_bytes)); 173 } 174 } 175 176 void DumpRegion::pack(DumpRegion* next) { 177 assert(!is_packed(), "sanity"); 178 _end = (char*)align_up(_top, Metaspace::reserve_alignment()); 179 _is_packed = true; 180 if (next != NULL) { 181 next->_base = next->_top = this->_end; 182 next->_end = MetaspaceShared::shared_rs()->end(); 183 } 184 } 185 186 static DumpRegion _mc_region("mc"), _ro_region("ro"), _rw_region("rw"); 187 static size_t _total_closed_archive_region_size = 0, _total_open_archive_region_size = 0; 188 189 void MetaspaceShared::init_shared_dump_space(DumpRegion* first_space, address first_space_bottom) { 190 // Start with 0 committed bytes. The memory will be committed as needed by 191 // MetaspaceShared::commit_shared_space_to(). 192 if (!_shared_vs.initialize(_shared_rs, 0)) { 193 fatal("Unable to allocate memory for shared space"); 194 } 195 first_space->init(&_shared_rs, (char*)first_space_bottom); 196 } 197 198 DumpRegion* MetaspaceShared::misc_code_dump_space() { 199 return &_mc_region; 200 } 201 202 DumpRegion* MetaspaceShared::read_write_dump_space() { 203 return &_rw_region; 204 } 205 206 DumpRegion* MetaspaceShared::read_only_dump_space() { 207 return &_ro_region; 208 } 209 210 void MetaspaceShared::pack_dump_space(DumpRegion* current, DumpRegion* next, 211 ReservedSpace* rs) { 212 current->pack(next); 213 } 214 215 char* MetaspaceShared::misc_code_space_alloc(size_t num_bytes) { 216 return _mc_region.allocate(num_bytes); 217 } 218 219 char* MetaspaceShared::read_only_space_alloc(size_t num_bytes) { 220 return _ro_region.allocate(num_bytes); 221 } 222 223 // When reserving an address range using ReservedSpace, we need an alignment that satisfies both: 224 // os::vm_allocation_granularity() -- so that we can sub-divide this range into multiple mmap regions, 225 // while keeping the first range at offset 0 of this range. 226 // Metaspace::reserve_alignment() -- so we can pass the region to 227 // Metaspace::allocate_metaspace_compressed_klass_ptrs. 228 size_t MetaspaceShared::reserved_space_alignment() { 229 size_t os_align = os::vm_allocation_granularity(); 230 size_t ms_align = Metaspace::reserve_alignment(); 231 if (os_align >= ms_align) { 232 assert(os_align % ms_align == 0, "must be a multiple"); 233 return os_align; 234 } else { 235 assert(ms_align % os_align == 0, "must be a multiple"); 236 return ms_align; 237 } 238 } 239 240 ReservedSpace MetaspaceShared::reserve_shared_space(size_t size, char* requested_address) { 241 return Metaspace::reserve_space(size, reserved_space_alignment(), 242 requested_address, requested_address != NULL); 243 } 244 245 void MetaspaceShared::initialize_dumptime_shared_and_meta_spaces() { 246 assert(DumpSharedSpaces, "should be called for dump time only"); 247 const size_t reserve_alignment = reserved_space_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 | 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 char* shared_base = (char*)align_up((char*)SharedBaseAddress, reserve_alignment); 268 if ((shared_base == NULL && SharedBaseAddress != 0) // align_up has wrapped around 269 || (max_uintx - uintx(shared_base) < uintx(cds_total))) { // end of the archive will wrap around 270 log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is too high. Reverted to " INTPTR_FORMAT, 271 p2i((void*)SharedBaseAddress), 272 p2i((void*)Arguments::default_SharedBaseAddress())); 273 SharedBaseAddress = Arguments::default_SharedBaseAddress(); 274 shared_base = (char*)align_up((char*)SharedBaseAddress, reserve_alignment); 275 assert(uintx(shared_base + cds_total) > uintx(shared_base), "must not wrap around"); 276 } 277 _default_base_address = shared_base; 278 279 bool use_requested_base = true; 280 if (ArchiveRelocationMode == 1) { 281 log_info(cds)("ArchiveRelocationMode == 1: always allocate class space at an alternative address"); 282 use_requested_base = false; 283 } 284 285 // First try to reserve the space at the specified SharedBaseAddress. 286 assert(!_shared_rs.is_reserved(), "must be"); 287 if (use_requested_base) { 288 _shared_rs = reserve_shared_space(cds_total, shared_base); 289 } 290 if (_shared_rs.is_reserved()) { 291 assert(shared_base == 0 || _shared_rs.base() == shared_base, "should match"); 292 } else { 293 // Get a mmap region anywhere if the SharedBaseAddress fails. 294 _shared_rs = reserve_shared_space(cds_total); 295 } 296 if (!_shared_rs.is_reserved()) { 297 vm_exit_during_initialization("Unable to reserve memory for shared space", 298 err_msg(SIZE_FORMAT " bytes.", cds_total)); 299 } 300 301 #ifdef _LP64 302 // During dump time, we allocate 4GB (UnscaledClassSpaceMax) of space and split it up: 303 // + The upper 1 GB is used as the "temporary compressed class space" -- preload_classes() 304 // will store Klasses into this space. 305 // + The lower 3 GB is used for the archive -- when preload_classes() is done, 306 // ArchiveCompactor will copy the class metadata into this space, first the RW parts, 307 // then the RO parts. 308 309 size_t max_archive_size = align_down(cds_total * 3 / 4, reserve_alignment); 310 ReservedSpace tmp_class_space = _shared_rs.last_part(max_archive_size); 311 CompressedClassSpaceSize = align_down(tmp_class_space.size(), reserve_alignment); 312 _shared_rs = _shared_rs.first_part(max_archive_size); 313 314 if (UseCompressedClassPointers) { 315 // Set up compress class pointers. 316 CompressedKlassPointers::set_base((address)_shared_rs.base()); 317 // Set narrow_klass_shift to be LogKlassAlignmentInBytes. This is consistent 318 // with AOT. 319 CompressedKlassPointers::set_shift(LogKlassAlignmentInBytes); 320 // Set the range of klass addresses to 4GB. 321 CompressedKlassPointers::set_range(cds_total); 322 Metaspace::initialize_class_space(tmp_class_space); 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 #endif 330 331 init_shared_dump_space(&_mc_region); 332 SharedBaseAddress = (size_t)_shared_rs.base(); 333 log_info(cds)("Allocated shared space: " SIZE_FORMAT " bytes at " PTR_FORMAT, 334 _shared_rs.size(), p2i(_shared_rs.base())); 335 336 // We don't want any valid object to be at the very of the archive. 337 // See ArchivePtrMarker::mark_pointer(). 338 MetaspaceShared::misc_code_space_alloc(16); 339 } 340 341 // Called by universe_post_init() 342 void MetaspaceShared::post_initialize(TRAPS) { 343 if (UseSharedSpaces) { 344 int size = FileMapInfo::get_number_of_shared_paths(); 345 if (size > 0) { 346 SystemDictionaryShared::allocate_shared_data_arrays(size, THREAD); 347 if (!DynamicDumpSharedSpaces) { 348 FileMapInfo* info; 349 if (FileMapInfo::dynamic_info() == NULL) { 350 info = FileMapInfo::current_info(); 351 } else { 352 info = FileMapInfo::dynamic_info(); 353 } 354 ClassLoaderExt::init_paths_start_index(info->app_class_paths_start_index()); 355 ClassLoaderExt::init_app_module_paths_start_index(info->app_module_paths_start_index()); 356 } 357 } 358 } 359 } 360 361 static GrowableArray<Handle>* _extra_interned_strings = NULL; 362 363 void MetaspaceShared::read_extra_data(const char* filename, TRAPS) { 364 _extra_interned_strings = new (ResourceObj::C_HEAP, mtInternal)GrowableArray<Handle>(10000, true); 365 366 HashtableTextDump reader(filename); 367 reader.check_version("VERSION: 1.0"); 368 369 while (reader.remain() > 0) { 370 int utf8_length; 371 int prefix_type = reader.scan_prefix(&utf8_length); 372 ResourceMark rm(THREAD); 373 if (utf8_length == 0x7fffffff) { 374 // buf_len will overflown 32-bit value. 375 vm_exit_during_initialization(err_msg("string length too large: %d", utf8_length)); 376 } 377 int buf_len = utf8_length+1; 378 char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len); 379 reader.get_utf8(utf8_buffer, utf8_length); 380 utf8_buffer[utf8_length] = '\0'; 381 382 if (prefix_type == HashtableTextDump::SymbolPrefix) { 383 SymbolTable::new_permanent_symbol(utf8_buffer); 384 } else{ 385 assert(prefix_type == HashtableTextDump::StringPrefix, "Sanity"); 386 oop s = StringTable::intern(utf8_buffer, THREAD); 387 388 if (HAS_PENDING_EXCEPTION) { 389 log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d", 390 reader.last_line_no(), utf8_length); 391 CLEAR_PENDING_EXCEPTION; 392 } else { 393 #if INCLUDE_G1GC 394 if (UseG1GC) { 395 typeArrayOop body = java_lang_String::value(s); 396 const HeapRegion* hr = G1CollectedHeap::heap()->heap_region_containing(body); 397 if (hr->is_humongous()) { 398 // Don't keep it alive, so it will be GC'ed before we dump the strings, in order 399 // to maximize free heap space and minimize fragmentation. 400 log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d", 401 reader.last_line_no(), utf8_length); 402 continue; 403 } 404 } 405 #endif 406 // Interned strings are GC'ed if there are no references to it, so let's 407 // add a reference to keep this string alive. 408 assert(s != NULL, "must succeed"); 409 Handle h(THREAD, s); 410 _extra_interned_strings->append(h); 411 } 412 } 413 } 414 } 415 416 void MetaspaceShared::commit_shared_space_to(char* newtop) { 417 Arguments::assert_is_dumping_archive(); 418 char* base = _shared_rs.base(); 419 size_t need_committed_size = newtop - base; 420 size_t has_committed_size = _shared_vs.committed_size(); 421 if (need_committed_size < has_committed_size) { 422 return; 423 } 424 425 size_t min_bytes = need_committed_size - has_committed_size; 426 size_t preferred_bytes = 1 * M; 427 size_t uncommitted = _shared_vs.reserved_size() - has_committed_size; 428 429 size_t commit =MAX2(min_bytes, preferred_bytes); 430 commit = MIN2(commit, uncommitted); 431 assert(commit <= uncommitted, "sanity"); 432 433 bool result = _shared_vs.expand_by(commit, false); 434 ArchivePtrMarker::expand_ptr_end((address*)_shared_vs.high()); 435 436 if (!result) { 437 vm_exit_during_initialization(err_msg("Failed to expand shared space to " SIZE_FORMAT " bytes", 438 need_committed_size)); 439 } 440 441 log_debug(cds)("Expanding shared spaces by " SIZE_FORMAT_W(7) " bytes [total " SIZE_FORMAT_W(9) " bytes ending at %p]", 442 commit, _shared_vs.actual_committed_size(), _shared_vs.high()); 443 } 444 445 void MetaspaceShared::initialize_ptr_marker(CHeapBitMap* ptrmap) { 446 ArchivePtrMarker::initialize(ptrmap, (address*)_shared_vs.low(), (address*)_shared_vs.high()); 447 } 448 449 // Read/write a data stream for restoring/preserving metadata pointers and 450 // miscellaneous data from/to the shared archive file. 451 452 void MetaspaceShared::serialize(SerializeClosure* soc) { 453 int tag = 0; 454 soc->do_tag(--tag); 455 456 // Verify the sizes of various metadata in the system. 457 soc->do_tag(sizeof(Method)); 458 soc->do_tag(sizeof(ConstMethod)); 459 soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE)); 460 soc->do_tag(sizeof(ConstantPool)); 461 soc->do_tag(sizeof(ConstantPoolCache)); 462 soc->do_tag(objArrayOopDesc::base_offset_in_bytes()); 463 soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE)); 464 soc->do_tag(sizeof(Symbol)); 465 466 // Dump/restore miscellaneous metadata. 467 JavaClasses::serialize_offsets(soc); 468 Universe::serialize(soc); 469 soc->do_tag(--tag); 470 471 // Dump/restore references to commonly used names and signatures. 472 vmSymbols::serialize(soc); 473 soc->do_tag(--tag); 474 475 // Dump/restore the symbol/string/subgraph_info tables 476 SymbolTable::serialize_shared_table_header(soc); 477 StringTable::serialize_shared_table_header(soc); 478 HeapShared::serialize_subgraph_info_table_header(soc); 479 SystemDictionaryShared::serialize_dictionary_headers(soc); 480 481 InstanceMirrorKlass::serialize_offsets(soc); 482 483 // Dump/restore well known classes (pointers) 484 SystemDictionaryShared::serialize_well_known_klasses(soc); 485 soc->do_tag(--tag); 486 487 serialize_cloned_cpp_vtptrs(soc); 488 soc->do_tag(--tag); 489 490 soc->do_tag(666); 491 } 492 493 address MetaspaceShared::i2i_entry_code_buffers(size_t total_size) { 494 if (DumpSharedSpaces) { 495 if (_i2i_entry_code_buffers == NULL) { 496 _i2i_entry_code_buffers = (address)misc_code_space_alloc(total_size); 497 _i2i_entry_code_buffers_size = total_size; 498 } 499 } else if (UseSharedSpaces) { 500 assert(_i2i_entry_code_buffers != NULL, "must already been initialized"); 501 } else { 502 return NULL; 503 } 504 505 assert(_i2i_entry_code_buffers_size == total_size, "must not change"); 506 return _i2i_entry_code_buffers; 507 } 508 509 uintx MetaspaceShared::object_delta_uintx(void* obj) { 510 Arguments::assert_is_dumping_archive(); 511 if (DumpSharedSpaces) { 512 assert(shared_rs()->contains(obj), "must be"); 513 } else { 514 assert(is_in_shared_metaspace(obj) || DynamicArchive::is_in_target_space(obj), "must be"); 515 } 516 address base_address = address(SharedBaseAddress); 517 uintx deltax = address(obj) - base_address; 518 return deltax; 519 } 520 521 // Global object for holding classes that have been loaded. Since this 522 // is run at a safepoint just before exit, this is the entire set of classes. 523 static GrowableArray<Klass*>* _global_klass_objects; 524 525 GrowableArray<Klass*>* MetaspaceShared::collected_klasses() { 526 return _global_klass_objects; 527 } 528 529 static void collect_array_classes(Klass* k) { 530 _global_klass_objects->append_if_missing(k); 531 if (k->is_array_klass()) { 532 // Add in the array classes too 533 ArrayKlass* ak = ArrayKlass::cast(k); 534 Klass* h = ak->higher_dimension(); 535 if (h != NULL) { 536 h->array_klasses_do(collect_array_classes); 537 } 538 } 539 } 540 541 class CollectClassesClosure : public KlassClosure { 542 void do_klass(Klass* k) { 543 if (k->is_instance_klass() && 544 SystemDictionaryShared::is_excluded_class(InstanceKlass::cast(k))) { 545 // Don't add to the _global_klass_objects 546 } else { 547 _global_klass_objects->append_if_missing(k); 548 } 549 if (k->is_array_klass()) { 550 // Add in the array classes too 551 ArrayKlass* ak = ArrayKlass::cast(k); 552 Klass* h = ak->higher_dimension(); 553 if (h != NULL) { 554 h->array_klasses_do(collect_array_classes); 555 } 556 } 557 } 558 }; 559 560 static void remove_unshareable_in_classes() { 561 for (int i = 0; i < _global_klass_objects->length(); i++) { 562 Klass* k = _global_klass_objects->at(i); 563 if (!k->is_objArray_klass()) { 564 // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info 565 // on their array classes. 566 assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be"); 567 k->remove_unshareable_info(); 568 } 569 } 570 } 571 572 static void remove_java_mirror_in_classes() { 573 for (int i = 0; i < _global_klass_objects->length(); i++) { 574 Klass* k = _global_klass_objects->at(i); 575 if (!k->is_objArray_klass()) { 576 // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info 577 // on their array classes. 578 assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be"); 579 k->remove_java_mirror(); 580 } 581 } 582 } 583 584 static void clear_basic_type_mirrors() { 585 assert(!HeapShared::is_heap_object_archiving_allowed(), "Sanity"); 586 Universe::set_int_mirror(NULL); 587 Universe::set_float_mirror(NULL); 588 Universe::set_double_mirror(NULL); 589 Universe::set_byte_mirror(NULL); 590 Universe::set_bool_mirror(NULL); 591 Universe::set_char_mirror(NULL); 592 Universe::set_long_mirror(NULL); 593 Universe::set_short_mirror(NULL); 594 Universe::set_void_mirror(NULL); 595 } 596 597 static void rewrite_nofast_bytecode(const methodHandle& method) { 598 BytecodeStream bcs(method); 599 while (!bcs.is_last_bytecode()) { 600 Bytecodes::Code opcode = bcs.next(); 601 switch (opcode) { 602 case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break; 603 case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break; 604 case Bytecodes::_aload_0: *bcs.bcp() = Bytecodes::_nofast_aload_0; break; 605 case Bytecodes::_iload: { 606 if (!bcs.is_wide()) { 607 *bcs.bcp() = Bytecodes::_nofast_iload; 608 } 609 break; 610 } 611 default: break; 612 } 613 } 614 } 615 616 // Walk all methods in the class list to ensure that they won't be modified at 617 // run time. This includes: 618 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified 619 // at run time by RewriteBytecodes/RewriteFrequentPairs 620 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time. 621 static void rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread) { 622 for (int i = 0; i < _global_klass_objects->length(); i++) { 623 Klass* k = _global_klass_objects->at(i); 624 if (k->is_instance_klass()) { 625 InstanceKlass* ik = InstanceKlass::cast(k); 626 MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(thread, ik); 627 } 628 } 629 } 630 631 void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) { 632 for (int i = 0; i < ik->methods()->length(); i++) { 633 methodHandle m(thread, ik->methods()->at(i)); 634 rewrite_nofast_bytecode(m); 635 Fingerprinter fp(m); 636 // The side effect of this call sets method's fingerprint field. 637 fp.fingerprint(); 638 } 639 } 640 641 // Objects of the Metadata types (such as Klass and ConstantPool) have C++ vtables. 642 // (In GCC this is the field <Type>::_vptr, i.e., first word in the object.) 643 // 644 // Addresses of the vtables and the methods may be different across JVM runs, 645 // if libjvm.so is dynamically loaded at a different base address. 646 // 647 // To ensure that the Metadata objects in the CDS archive always have the correct vtable: 648 // 649 // + at dump time: we redirect the _vptr to point to our own vtables inside 650 // the CDS image 651 // + at run time: we clone the actual contents of the vtables from libjvm.so 652 // into our own tables. 653 654 // Currently, the archive contain ONLY the following types of objects that have C++ vtables. 655 #define CPP_VTABLE_PATCH_TYPES_DO(f) \ 656 f(ConstantPool) \ 657 f(InstanceKlass) \ 658 f(InstanceClassLoaderKlass) \ 659 f(InstanceMirrorKlass) \ 660 f(InstanceRefKlass) \ 661 f(Method) \ 662 f(ObjArrayKlass) \ 663 f(TypeArrayKlass) 664 665 class CppVtableInfo { 666 intptr_t _vtable_size; 667 intptr_t _cloned_vtable[1]; 668 public: 669 static int num_slots(int vtable_size) { 670 return 1 + vtable_size; // Need to add the space occupied by _vtable_size; 671 } 672 int vtable_size() { return int(uintx(_vtable_size)); } 673 void set_vtable_size(int n) { _vtable_size = intptr_t(n); } 674 intptr_t* cloned_vtable() { return &_cloned_vtable[0]; } 675 void zero() { memset(_cloned_vtable, 0, sizeof(intptr_t) * vtable_size()); } 676 // Returns the address of the next CppVtableInfo that can be placed immediately after this CppVtableInfo 677 static size_t byte_size(int vtable_size) { 678 CppVtableInfo i; 679 return pointer_delta(&i._cloned_vtable[vtable_size], &i, sizeof(u1)); 680 } 681 }; 682 683 template <class T> class CppVtableCloner : public T { 684 static intptr_t* vtable_of(Metadata& m) { 685 return *((intptr_t**)&m); 686 } 687 static CppVtableInfo* _info; 688 689 static int get_vtable_length(const char* name); 690 691 public: 692 // Allocate and initialize the C++ vtable, starting from top, but do not go past end. 693 static intptr_t* allocate(const char* name); 694 695 // Clone the vtable to ... 696 static intptr_t* clone_vtable(const char* name, CppVtableInfo* info); 697 698 static void zero_vtable_clone() { 699 assert(DumpSharedSpaces, "dump-time only"); 700 _info->zero(); 701 } 702 703 static bool is_valid_shared_object(const T* obj) { 704 intptr_t* vptr = *(intptr_t**)obj; 705 return vptr == _info->cloned_vtable(); 706 } 707 }; 708 709 template <class T> CppVtableInfo* CppVtableCloner<T>::_info = NULL; 710 711 template <class T> 712 intptr_t* CppVtableCloner<T>::allocate(const char* name) { 713 assert(is_aligned(_mc_region.top(), sizeof(intptr_t)), "bad alignment"); 714 int n = get_vtable_length(name); 715 _info = (CppVtableInfo*)_mc_region.allocate(CppVtableInfo::byte_size(n), sizeof(intptr_t)); 716 _info->set_vtable_size(n); 717 718 intptr_t* p = clone_vtable(name, _info); 719 assert((char*)p == _mc_region.top(), "must be"); 720 721 return _info->cloned_vtable(); 722 } 723 724 template <class T> 725 intptr_t* CppVtableCloner<T>::clone_vtable(const char* name, CppVtableInfo* info) { 726 if (!DumpSharedSpaces) { 727 assert(_info == 0, "_info is initialized only at dump time"); 728 _info = info; // Remember it -- it will be used by MetaspaceShared::is_valid_shared_method() 729 } 730 T tmp; // Allocate temporary dummy metadata object to get to the original vtable. 731 int n = info->vtable_size(); 732 intptr_t* srcvtable = vtable_of(tmp); 733 intptr_t* dstvtable = info->cloned_vtable(); 734 735 // We already checked (and, if necessary, adjusted n) when the vtables were allocated, so we are 736 // safe to do memcpy. 737 log_debug(cds, vtables)("Copying %3d vtable entries for %s", n, name); 738 memcpy(dstvtable, srcvtable, sizeof(intptr_t) * n); 739 return dstvtable + n; 740 } 741 742 // To determine the size of the vtable for each type, we use the following 743 // trick by declaring 2 subclasses: 744 // 745 // class CppVtableTesterA: public InstanceKlass {virtual int last_virtual_method() {return 1;} }; 746 // class CppVtableTesterB: public InstanceKlass {virtual void* last_virtual_method() {return NULL}; }; 747 // 748 // CppVtableTesterA and CppVtableTesterB's vtables have the following properties: 749 // - Their size (N+1) is exactly one more than the size of InstanceKlass's vtable (N) 750 // - The first N entries have are exactly the same as in InstanceKlass's vtable. 751 // - Their last entry is different. 752 // 753 // So to determine the value of N, we just walk CppVtableTesterA and CppVtableTesterB's tables 754 // and find the first entry that's different. 755 // 756 // This works on all C++ compilers supported by Oracle, but you may need to tweak it for more 757 // esoteric compilers. 758 759 template <class T> class CppVtableTesterB: public T { 760 public: 761 virtual int last_virtual_method() {return 1;} 762 }; 763 764 template <class T> class CppVtableTesterA : public T { 765 public: 766 virtual void* last_virtual_method() { 767 // Make this different than CppVtableTesterB::last_virtual_method so the C++ 768 // compiler/linker won't alias the two functions. 769 return NULL; 770 } 771 }; 772 773 template <class T> 774 int CppVtableCloner<T>::get_vtable_length(const char* name) { 775 CppVtableTesterA<T> a; 776 CppVtableTesterB<T> b; 777 778 intptr_t* avtable = vtable_of(a); 779 intptr_t* bvtable = vtable_of(b); 780 781 // Start at slot 1, because slot 0 may be RTTI (on Solaris/Sparc) 782 int vtable_len = 1; 783 for (; ; vtable_len++) { 784 if (avtable[vtable_len] != bvtable[vtable_len]) { 785 break; 786 } 787 } 788 log_debug(cds, vtables)("Found %3d vtable entries for %s", vtable_len, name); 789 790 return vtable_len; 791 } 792 793 #define ALLOC_CPP_VTABLE_CLONE(c) \ 794 _cloned_cpp_vtptrs[c##_Kind] = CppVtableCloner<c>::allocate(#c); \ 795 ArchivePtrMarker::mark_pointer(&_cloned_cpp_vtptrs[c##_Kind]); 796 797 #define CLONE_CPP_VTABLE(c) \ 798 p = CppVtableCloner<c>::clone_vtable(#c, (CppVtableInfo*)p); 799 800 #define ZERO_CPP_VTABLE(c) \ 801 CppVtableCloner<c>::zero_vtable_clone(); 802 803 //------------------------------ for DynamicDumpSharedSpaces - start 804 #define DECLARE_CLONED_VTABLE_KIND(c) c ## _Kind, 805 806 enum { 807 // E.g., ConstantPool_Kind == 0, InstanceKlass == 1, etc. 808 CPP_VTABLE_PATCH_TYPES_DO(DECLARE_CLONED_VTABLE_KIND) 809 _num_cloned_vtable_kinds 810 }; 811 812 // This is the index of all the cloned vtables. E.g., for 813 // ConstantPool* cp = ....; // an archived constant pool 814 // InstanceKlass* ik = ....;// an archived class 815 // the following holds true: 816 // _cloned_cpp_vtptrs[ConstantPool_Kind] == ((intptr_t**)cp)[0] 817 // _cloned_cpp_vtptrs[InstanceKlass_Kind] == ((intptr_t**)ik)[0] 818 static intptr_t** _cloned_cpp_vtptrs = NULL; 819 820 void MetaspaceShared::allocate_cloned_cpp_vtptrs() { 821 assert(DumpSharedSpaces, "must"); 822 size_t vtptrs_bytes = _num_cloned_vtable_kinds * sizeof(intptr_t*); 823 _cloned_cpp_vtptrs = (intptr_t**)_mc_region.allocate(vtptrs_bytes, sizeof(intptr_t*)); 824 } 825 826 void MetaspaceShared::serialize_cloned_cpp_vtptrs(SerializeClosure* soc) { 827 soc->do_ptr((void**)&_cloned_cpp_vtptrs); 828 } 829 830 intptr_t* MetaspaceShared::fix_cpp_vtable_for_dynamic_archive(MetaspaceObj::Type msotype, address obj) { 831 Arguments::assert_is_dumping_archive(); 832 int kind = -1; 833 switch (msotype) { 834 case MetaspaceObj::SymbolType: 835 case MetaspaceObj::TypeArrayU1Type: 836 case MetaspaceObj::TypeArrayU2Type: 837 case MetaspaceObj::TypeArrayU4Type: 838 case MetaspaceObj::TypeArrayU8Type: 839 case MetaspaceObj::TypeArrayOtherType: 840 case MetaspaceObj::ConstMethodType: 841 case MetaspaceObj::ConstantPoolCacheType: 842 case MetaspaceObj::AnnotationsType: 843 case MetaspaceObj::MethodCountersType: 844 case MetaspaceObj::RecordComponentType: 845 // These have no vtables. 846 break; 847 case MetaspaceObj::ClassType: 848 { 849 Klass* k = (Klass*)obj; 850 assert(k->is_klass(), "must be"); 851 if (k->is_instance_klass()) { 852 InstanceKlass* ik = InstanceKlass::cast(k); 853 if (ik->is_class_loader_instance_klass()) { 854 kind = InstanceClassLoaderKlass_Kind; 855 } else if (ik->is_reference_instance_klass()) { 856 kind = InstanceRefKlass_Kind; 857 } else if (ik->is_mirror_instance_klass()) { 858 kind = InstanceMirrorKlass_Kind; 859 } else { 860 kind = InstanceKlass_Kind; 861 } 862 } else if (k->is_typeArray_klass()) { 863 kind = TypeArrayKlass_Kind; 864 } else { 865 assert(k->is_objArray_klass(), "must be"); 866 kind = ObjArrayKlass_Kind; 867 } 868 } 869 break; 870 871 case MetaspaceObj::MethodType: 872 { 873 Method* m = (Method*)obj; 874 assert(m->is_method(), "must be"); 875 kind = Method_Kind; 876 } 877 break; 878 879 case MetaspaceObj::MethodDataType: 880 // We don't archive MethodData <-- should have been removed in removed_unsharable_info 881 ShouldNotReachHere(); 882 break; 883 884 case MetaspaceObj::ConstantPoolType: 885 { 886 ConstantPool *cp = (ConstantPool*)obj; 887 assert(cp->is_constantPool(), "must be"); 888 kind = ConstantPool_Kind; 889 } 890 break; 891 892 default: 893 ShouldNotReachHere(); 894 } 895 896 if (kind >= 0) { 897 assert(kind < _num_cloned_vtable_kinds, "must be"); 898 return _cloned_cpp_vtptrs[kind]; 899 } else { 900 return NULL; 901 } 902 } 903 904 //------------------------------ for DynamicDumpSharedSpaces - end 905 906 // This can be called at both dump time and run time: 907 // - clone the contents of the c++ vtables into the space 908 // allocated by allocate_cpp_vtable_clones() 909 void MetaspaceShared::clone_cpp_vtables(intptr_t* p) { 910 assert(DumpSharedSpaces || UseSharedSpaces, "sanity"); 911 CPP_VTABLE_PATCH_TYPES_DO(CLONE_CPP_VTABLE); 912 } 913 914 void MetaspaceShared::zero_cpp_vtable_clones_for_writing() { 915 assert(DumpSharedSpaces, "dump-time only"); 916 CPP_VTABLE_PATCH_TYPES_DO(ZERO_CPP_VTABLE); 917 } 918 919 // Allocate and initialize the C++ vtables, starting from top, but do not go past end. 920 char* MetaspaceShared::allocate_cpp_vtable_clones() { 921 char* cloned_vtables = _mc_region.top(); // This is the beginning of all the cloned vtables 922 923 assert(DumpSharedSpaces, "dump-time only"); 924 // Layout (each slot is a intptr_t): 925 // [number of slots in the first vtable = n1] 926 // [ <n1> slots for the first vtable] 927 // [number of slots in the first second = n2] 928 // [ <n2> slots for the second vtable] 929 // ... 930 // The order of the vtables is the same as the CPP_VTAB_PATCH_TYPES_DO macro. 931 CPP_VTABLE_PATCH_TYPES_DO(ALLOC_CPP_VTABLE_CLONE); 932 933 return cloned_vtables; 934 } 935 936 bool MetaspaceShared::is_valid_shared_method(const Method* m) { 937 assert(is_in_shared_metaspace(m), "must be"); 938 return CppVtableCloner<Method>::is_valid_shared_object(m); 939 } 940 941 void WriteClosure::do_oop(oop* o) { 942 if (*o == NULL) { 943 _dump_region->append_intptr_t(0); 944 } else { 945 assert(HeapShared::is_heap_object_archiving_allowed(), 946 "Archiving heap object is not allowed"); 947 _dump_region->append_intptr_t( 948 (intptr_t)CompressedOops::encode_not_null(*o)); 949 } 950 } 951 952 void WriteClosure::do_region(u_char* start, size_t size) { 953 assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment"); 954 assert(size % sizeof(intptr_t) == 0, "bad size"); 955 do_tag((int)size); 956 while (size > 0) { 957 _dump_region->append_intptr_t(*(intptr_t*)start, true); 958 start += sizeof(intptr_t); 959 size -= sizeof(intptr_t); 960 } 961 } 962 963 // This is for dumping detailed statistics for the allocations 964 // in the shared spaces. 965 class DumpAllocStats : public ResourceObj { 966 public: 967 968 // Here's poor man's enum inheritance 969 #define SHAREDSPACE_OBJ_TYPES_DO(f) \ 970 METASPACE_OBJ_TYPES_DO(f) \ 971 f(SymbolHashentry) \ 972 f(SymbolBucket) \ 973 f(StringHashentry) \ 974 f(StringBucket) \ 975 f(Other) 976 977 enum Type { 978 // Types are MetaspaceObj::ClassType, MetaspaceObj::SymbolType, etc 979 SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_DECLARE) 980 _number_of_types 981 }; 982 983 static const char * type_name(Type type) { 984 switch(type) { 985 SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_NAME_CASE) 986 default: 987 ShouldNotReachHere(); 988 return NULL; 989 } 990 } 991 992 public: 993 enum { RO = 0, RW = 1 }; 994 995 int _counts[2][_number_of_types]; 996 int _bytes [2][_number_of_types]; 997 998 DumpAllocStats() { 999 memset(_counts, 0, sizeof(_counts)); 1000 memset(_bytes, 0, sizeof(_bytes)); 1001 }; 1002 1003 void record(MetaspaceObj::Type type, int byte_size, bool read_only) { 1004 assert(int(type) >= 0 && type < MetaspaceObj::_number_of_types, "sanity"); 1005 int which = (read_only) ? RO : RW; 1006 _counts[which][type] ++; 1007 _bytes [which][type] += byte_size; 1008 } 1009 1010 void record_other_type(int byte_size, bool read_only) { 1011 int which = (read_only) ? RO : RW; 1012 _bytes [which][OtherType] += byte_size; 1013 } 1014 void print_stats(int ro_all, int rw_all, int mc_all); 1015 }; 1016 1017 void DumpAllocStats::print_stats(int ro_all, int rw_all, int mc_all) { 1018 // Calculate size of data that was not allocated by Metaspace::allocate() 1019 MetaspaceSharedStats *stats = MetaspaceShared::stats(); 1020 1021 // symbols 1022 _counts[RO][SymbolHashentryType] = stats->symbol.hashentry_count; 1023 _bytes [RO][SymbolHashentryType] = stats->symbol.hashentry_bytes; 1024 1025 _counts[RO][SymbolBucketType] = stats->symbol.bucket_count; 1026 _bytes [RO][SymbolBucketType] = stats->symbol.bucket_bytes; 1027 1028 // strings 1029 _counts[RO][StringHashentryType] = stats->string.hashentry_count; 1030 _bytes [RO][StringHashentryType] = stats->string.hashentry_bytes; 1031 1032 _counts[RO][StringBucketType] = stats->string.bucket_count; 1033 _bytes [RO][StringBucketType] = stats->string.bucket_bytes; 1034 1035 // TODO: count things like dictionary, vtable, etc 1036 _bytes[RW][OtherType] += mc_all; 1037 rw_all += mc_all; // mc is mapped Read/Write 1038 1039 // prevent divide-by-zero 1040 if (ro_all < 1) { 1041 ro_all = 1; 1042 } 1043 if (rw_all < 1) { 1044 rw_all = 1; 1045 } 1046 1047 int all_ro_count = 0; 1048 int all_ro_bytes = 0; 1049 int all_rw_count = 0; 1050 int all_rw_bytes = 0; 1051 1052 // To make fmt_stats be a syntactic constant (for format warnings), use #define. 1053 #define fmt_stats "%-20s: %8d %10d %5.1f | %8d %10d %5.1f | %8d %10d %5.1f" 1054 const char *sep = "--------------------+---------------------------+---------------------------+--------------------------"; 1055 const char *hdr = " ro_cnt ro_bytes % | rw_cnt rw_bytes % | all_cnt all_bytes %"; 1056 1057 LogMessage(cds) msg; 1058 1059 msg.debug("Detailed metadata info (excluding st regions; rw stats include mc regions):"); 1060 msg.debug("%s", hdr); 1061 msg.debug("%s", sep); 1062 for (int type = 0; type < int(_number_of_types); type ++) { 1063 const char *name = type_name((Type)type); 1064 int ro_count = _counts[RO][type]; 1065 int ro_bytes = _bytes [RO][type]; 1066 int rw_count = _counts[RW][type]; 1067 int rw_bytes = _bytes [RW][type]; 1068 int count = ro_count + rw_count; 1069 int bytes = ro_bytes + rw_bytes; 1070 1071 double ro_perc = percent_of(ro_bytes, ro_all); 1072 double rw_perc = percent_of(rw_bytes, rw_all); 1073 double perc = percent_of(bytes, ro_all + rw_all); 1074 1075 msg.debug(fmt_stats, name, 1076 ro_count, ro_bytes, ro_perc, 1077 rw_count, rw_bytes, rw_perc, 1078 count, bytes, perc); 1079 1080 all_ro_count += ro_count; 1081 all_ro_bytes += ro_bytes; 1082 all_rw_count += rw_count; 1083 all_rw_bytes += rw_bytes; 1084 } 1085 1086 int all_count = all_ro_count + all_rw_count; 1087 int all_bytes = all_ro_bytes + all_rw_bytes; 1088 1089 double all_ro_perc = percent_of(all_ro_bytes, ro_all); 1090 double all_rw_perc = percent_of(all_rw_bytes, rw_all); 1091 double all_perc = percent_of(all_bytes, ro_all + rw_all); 1092 1093 msg.debug("%s", sep); 1094 msg.debug(fmt_stats, "Total", 1095 all_ro_count, all_ro_bytes, all_ro_perc, 1096 all_rw_count, all_rw_bytes, all_rw_perc, 1097 all_count, all_bytes, all_perc); 1098 1099 assert(all_ro_bytes == ro_all, "everything should have been counted"); 1100 assert(all_rw_bytes == rw_all, "everything should have been counted"); 1101 1102 #undef fmt_stats 1103 } 1104 1105 // Populate the shared space. 1106 1107 class VM_PopulateDumpSharedSpace: public VM_Operation { 1108 private: 1109 GrowableArray<MemRegion> *_closed_archive_heap_regions; 1110 GrowableArray<MemRegion> *_open_archive_heap_regions; 1111 1112 GrowableArray<ArchiveHeapOopmapInfo> *_closed_archive_heap_oopmaps; 1113 GrowableArray<ArchiveHeapOopmapInfo> *_open_archive_heap_oopmaps; 1114 1115 void dump_java_heap_objects() NOT_CDS_JAVA_HEAP_RETURN; 1116 void dump_archive_heap_oopmaps() NOT_CDS_JAVA_HEAP_RETURN; 1117 void dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions, 1118 GrowableArray<ArchiveHeapOopmapInfo>* oopmaps); 1119 void dump_symbols(); 1120 char* dump_read_only_tables(); 1121 void print_class_stats(); 1122 void print_region_stats(FileMapInfo* map_info); 1123 void print_bitmap_region_stats(size_t size, size_t total_size); 1124 void print_heap_region_stats(GrowableArray<MemRegion> *heap_mem, 1125 const char *name, size_t total_size); 1126 void relocate_to_default_base_address(CHeapBitMap* ptrmap); 1127 1128 public: 1129 1130 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; } 1131 void doit(); // outline because gdb sucks 1132 bool allow_nested_vm_operations() const { return true; } 1133 }; // class VM_PopulateDumpSharedSpace 1134 1135 class SortedSymbolClosure: public SymbolClosure { 1136 GrowableArray<Symbol*> _symbols; 1137 virtual void do_symbol(Symbol** sym) { 1138 assert((*sym)->is_permanent(), "archived symbols must be permanent"); 1139 _symbols.append(*sym); 1140 } 1141 static int compare_symbols_by_address(Symbol** a, Symbol** b) { 1142 if (a[0] < b[0]) { 1143 return -1; 1144 } else if (a[0] == b[0]) { 1145 return 0; 1146 } else { 1147 return 1; 1148 } 1149 } 1150 1151 public: 1152 SortedSymbolClosure() { 1153 SymbolTable::symbols_do(this); 1154 _symbols.sort(compare_symbols_by_address); 1155 } 1156 GrowableArray<Symbol*>* get_sorted_symbols() { 1157 return &_symbols; 1158 } 1159 }; 1160 1161 // ArchiveCompactor -- 1162 // 1163 // This class is the central piece of shared archive compaction -- all metaspace data are 1164 // initially allocated outside of the shared regions. ArchiveCompactor copies the 1165 // metaspace data into their final location in the shared regions. 1166 1167 class ArchiveCompactor : AllStatic { 1168 static const int INITIAL_TABLE_SIZE = 8087; 1169 static const int MAX_TABLE_SIZE = 1000000; 1170 1171 static DumpAllocStats* _alloc_stats; 1172 static SortedSymbolClosure* _ssc; 1173 1174 typedef KVHashtable<address, address, mtInternal> RelocationTable; 1175 static RelocationTable* _new_loc_table; 1176 1177 public: 1178 static void initialize() { 1179 _alloc_stats = new(ResourceObj::C_HEAP, mtInternal)DumpAllocStats; 1180 _new_loc_table = new RelocationTable(INITIAL_TABLE_SIZE); 1181 } 1182 static DumpAllocStats* alloc_stats() { 1183 return _alloc_stats; 1184 } 1185 1186 // Use this when you allocate space with MetaspaceShare::read_only_space_alloc() 1187 // outside of ArchiveCompactor::allocate(). These are usually for misc tables 1188 // that are allocated in the RO space. 1189 class OtherROAllocMark { 1190 char* _oldtop; 1191 public: 1192 OtherROAllocMark() { 1193 _oldtop = _ro_region.top(); 1194 } 1195 ~OtherROAllocMark() { 1196 char* newtop = _ro_region.top(); 1197 ArchiveCompactor::alloc_stats()->record_other_type(int(newtop - _oldtop), true); 1198 } 1199 }; 1200 1201 static void allocate(MetaspaceClosure::Ref* ref, bool read_only) { 1202 address obj = ref->obj(); 1203 int bytes = ref->size() * BytesPerWord; 1204 char* p; 1205 size_t alignment = BytesPerWord; 1206 char* oldtop; 1207 char* newtop; 1208 1209 if (read_only) { 1210 oldtop = _ro_region.top(); 1211 p = _ro_region.allocate(bytes, alignment); 1212 newtop = _ro_region.top(); 1213 } else { 1214 oldtop = _rw_region.top(); 1215 if (ref->msotype() == MetaspaceObj::ClassType) { 1216 // Save a pointer immediate in front of an InstanceKlass, so 1217 // we can do a quick lookup from InstanceKlass* -> RunTimeSharedClassInfo* 1218 // without building another hashtable. See RunTimeSharedClassInfo::get_for() 1219 // in systemDictionaryShared.cpp. 1220 Klass* klass = (Klass*)obj; 1221 if (klass->is_instance_klass()) { 1222 SystemDictionaryShared::validate_before_archiving(InstanceKlass::cast(klass)); 1223 _rw_region.allocate(sizeof(address), BytesPerWord); 1224 } 1225 } 1226 p = _rw_region.allocate(bytes, alignment); 1227 newtop = _rw_region.top(); 1228 } 1229 memcpy(p, obj, bytes); 1230 1231 intptr_t* cloned_vtable = MetaspaceShared::fix_cpp_vtable_for_dynamic_archive(ref->msotype(), (address)p); 1232 if (cloned_vtable != NULL) { 1233 *(address*)p = (address)cloned_vtable; 1234 ArchivePtrMarker::mark_pointer((address*)p); 1235 } 1236 1237 assert(_new_loc_table->lookup(obj) == NULL, "each object can be relocated at most once"); 1238 _new_loc_table->add(obj, (address)p); 1239 log_trace(cds)("Copy: " PTR_FORMAT " ==> " PTR_FORMAT " %d", p2i(obj), p2i(p), bytes); 1240 if (_new_loc_table->maybe_grow(MAX_TABLE_SIZE)) { 1241 log_info(cds, hashtables)("Expanded _new_loc_table to %d", _new_loc_table->table_size()); 1242 } 1243 _alloc_stats->record(ref->msotype(), int(newtop - oldtop), read_only); 1244 } 1245 1246 static address get_new_loc(MetaspaceClosure::Ref* ref) { 1247 address* pp = _new_loc_table->lookup(ref->obj()); 1248 assert(pp != NULL, "must be"); 1249 return *pp; 1250 } 1251 1252 private: 1253 // Makes a shallow copy of visited MetaspaceObj's 1254 class ShallowCopier: public UniqueMetaspaceClosure { 1255 bool _read_only; 1256 public: 1257 ShallowCopier(bool read_only) : _read_only(read_only) {} 1258 1259 virtual bool do_unique_ref(Ref* ref, bool read_only) { 1260 if (read_only == _read_only) { 1261 allocate(ref, read_only); 1262 } 1263 return true; // recurse into ref.obj() 1264 } 1265 }; 1266 1267 // Relocate embedded pointers within a MetaspaceObj's shallow copy 1268 class ShallowCopyEmbeddedRefRelocator: public UniqueMetaspaceClosure { 1269 public: 1270 virtual bool do_unique_ref(Ref* ref, bool read_only) { 1271 address new_loc = get_new_loc(ref); 1272 RefRelocator refer; 1273 ref->metaspace_pointers_do_at(&refer, new_loc); 1274 return true; // recurse into ref.obj() 1275 } 1276 virtual void push_special(SpecialRef type, Ref* ref, intptr_t* p) { 1277 assert(type == _method_entry_ref, "only special type allowed for now"); 1278 address obj = ref->obj(); 1279 address new_obj = get_new_loc(ref); 1280 size_t offset = pointer_delta(p, obj, sizeof(u1)); 1281 intptr_t* new_p = (intptr_t*)(new_obj + offset); 1282 assert(*p == *new_p, "must be a copy"); 1283 ArchivePtrMarker::mark_pointer((address*)new_p); 1284 } 1285 }; 1286 1287 // Relocate a reference to point to its shallow copy 1288 class RefRelocator: public MetaspaceClosure { 1289 public: 1290 virtual bool do_ref(Ref* ref, bool read_only) { 1291 if (ref->not_null()) { 1292 ref->update(get_new_loc(ref)); 1293 ArchivePtrMarker::mark_pointer(ref->addr()); 1294 } 1295 return false; // Do not recurse. 1296 } 1297 }; 1298 1299 #ifdef ASSERT 1300 class IsRefInArchiveChecker: public MetaspaceClosure { 1301 public: 1302 virtual bool do_ref(Ref* ref, bool read_only) { 1303 if (ref->not_null()) { 1304 char* obj = (char*)ref->obj(); 1305 assert(_ro_region.contains(obj) || _rw_region.contains(obj), 1306 "must be relocated to point to CDS archive"); 1307 } 1308 return false; // Do not recurse. 1309 } 1310 }; 1311 #endif 1312 1313 public: 1314 static void copy_and_compact() { 1315 ResourceMark rm; 1316 SortedSymbolClosure the_ssc; // StackObj 1317 _ssc = &the_ssc; 1318 1319 log_info(cds)("Scanning all metaspace objects ... "); 1320 { 1321 // allocate and shallow-copy RW objects, immediately following the MC region 1322 log_info(cds)("Allocating RW objects ... "); 1323 _mc_region.pack(&_rw_region); 1324 1325 ResourceMark rm; 1326 ShallowCopier rw_copier(false); 1327 iterate_roots(&rw_copier); 1328 } 1329 { 1330 // allocate and shallow-copy of RO object, immediately following the RW region 1331 log_info(cds)("Allocating RO objects ... "); 1332 _rw_region.pack(&_ro_region); 1333 1334 ResourceMark rm; 1335 ShallowCopier ro_copier(true); 1336 iterate_roots(&ro_copier); 1337 } 1338 { 1339 log_info(cds)("Relocating embedded pointers ... "); 1340 ResourceMark rm; 1341 ShallowCopyEmbeddedRefRelocator emb_reloc; 1342 iterate_roots(&emb_reloc); 1343 } 1344 { 1345 log_info(cds)("Relocating external roots ... "); 1346 ResourceMark rm; 1347 RefRelocator ext_reloc; 1348 iterate_roots(&ext_reloc); 1349 } 1350 1351 #ifdef ASSERT 1352 { 1353 log_info(cds)("Verifying external roots ... "); 1354 ResourceMark rm; 1355 IsRefInArchiveChecker checker; 1356 iterate_roots(&checker); 1357 } 1358 #endif 1359 1360 1361 // cleanup 1362 _ssc = NULL; 1363 } 1364 1365 // We must relocate the System::_well_known_klasses only after we have copied the 1366 // java objects in during dump_java_heap_objects(): during the object copy, we operate on 1367 // old objects which assert that their klass is the original klass. 1368 static void relocate_well_known_klasses() { 1369 { 1370 log_info(cds)("Relocating SystemDictionary::_well_known_klasses[] ... "); 1371 ResourceMark rm; 1372 RefRelocator ext_reloc; 1373 SystemDictionary::well_known_klasses_do(&ext_reloc); 1374 } 1375 // NOTE: after this point, we shouldn't have any globals that can reach the old 1376 // objects. 1377 1378 // We cannot use any of the objects in the heap anymore (except for the 1379 // shared strings) because their headers no longer point to valid Klasses. 1380 } 1381 1382 static void iterate_roots(MetaspaceClosure* it) { 1383 GrowableArray<Symbol*>* symbols = _ssc->get_sorted_symbols(); 1384 for (int i=0; i<symbols->length(); i++) { 1385 it->push(symbols->adr_at(i)); 1386 } 1387 if (_global_klass_objects != NULL) { 1388 // Need to fix up the pointers 1389 for (int i = 0; i < _global_klass_objects->length(); i++) { 1390 // NOTE -- this requires that the vtable is NOT yet patched, or else we are hosed. 1391 it->push(_global_klass_objects->adr_at(i)); 1392 } 1393 } 1394 FileMapInfo::metaspace_pointers_do(it, false); 1395 SystemDictionaryShared::dumptime_classes_do(it); 1396 Universe::metaspace_pointers_do(it); 1397 SymbolTable::metaspace_pointers_do(it); 1398 vmSymbols::metaspace_pointers_do(it); 1399 1400 it->finish(); 1401 } 1402 1403 static Klass* get_relocated_klass(Klass* orig_klass) { 1404 assert(DumpSharedSpaces, "dump time only"); 1405 address* pp = _new_loc_table->lookup((address)orig_klass); 1406 assert(pp != NULL, "must be"); 1407 Klass* klass = (Klass*)(*pp); 1408 assert(klass->is_klass(), "must be"); 1409 return klass; 1410 } 1411 }; 1412 1413 DumpAllocStats* ArchiveCompactor::_alloc_stats; 1414 SortedSymbolClosure* ArchiveCompactor::_ssc; 1415 ArchiveCompactor::RelocationTable* ArchiveCompactor::_new_loc_table; 1416 1417 void VM_PopulateDumpSharedSpace::dump_symbols() { 1418 log_info(cds)("Dumping symbol table ..."); 1419 1420 NOT_PRODUCT(SymbolTable::verify()); 1421 SymbolTable::write_to_archive(); 1422 } 1423 1424 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() { 1425 ArchiveCompactor::OtherROAllocMark mark; 1426 1427 log_info(cds)("Removing java_mirror ... "); 1428 if (!HeapShared::is_heap_object_archiving_allowed()) { 1429 clear_basic_type_mirrors(); 1430 } 1431 remove_java_mirror_in_classes(); 1432 log_info(cds)("done. "); 1433 1434 SystemDictionaryShared::write_to_archive(); 1435 1436 // Write the other data to the output array. 1437 char* start = _ro_region.top(); 1438 WriteClosure wc(&_ro_region); 1439 MetaspaceShared::serialize(&wc); 1440 1441 // Write the bitmaps for patching the archive heap regions 1442 _closed_archive_heap_oopmaps = NULL; 1443 _open_archive_heap_oopmaps = NULL; 1444 dump_archive_heap_oopmaps(); 1445 1446 return start; 1447 } 1448 1449 void VM_PopulateDumpSharedSpace::print_class_stats() { 1450 log_info(cds)("Number of classes %d", _global_klass_objects->length()); 1451 { 1452 int num_type_array = 0, num_obj_array = 0, num_inst = 0; 1453 for (int i = 0; i < _global_klass_objects->length(); i++) { 1454 Klass* k = _global_klass_objects->at(i); 1455 if (k->is_instance_klass()) { 1456 num_inst ++; 1457 } else if (k->is_objArray_klass()) { 1458 num_obj_array ++; 1459 } else { 1460 assert(k->is_typeArray_klass(), "sanity"); 1461 num_type_array ++; 1462 } 1463 } 1464 log_info(cds)(" instance classes = %5d", num_inst); 1465 log_info(cds)(" obj array classes = %5d", num_obj_array); 1466 log_info(cds)(" type array classes = %5d", num_type_array); 1467 } 1468 } 1469 1470 void VM_PopulateDumpSharedSpace::relocate_to_default_base_address(CHeapBitMap* ptrmap) { 1471 intx addr_delta = MetaspaceShared::final_delta(); 1472 if (addr_delta == 0) { 1473 ArchivePtrMarker::compact((address)SharedBaseAddress, (address)_ro_region.top()); 1474 } else { 1475 // We are not able to reserve space at MetaspaceShared::default_base_address() (due to ASLR). 1476 // This means that the current content of the archive is based on a random 1477 // address. Let's relocate all the pointers, so that it can be mapped to 1478 // MetaspaceShared::default_base_address() without runtime relocation. 1479 // 1480 // Note: both the base and dynamic archive are written with 1481 // FileMapHeader::_shared_base_address == MetaspaceShared::default_base_address() 1482 1483 // Patch all pointers that are marked by ptrmap within this region, 1484 // where we have just dumped all the metaspace data. 1485 address patch_base = (address)SharedBaseAddress; 1486 address patch_end = (address)_ro_region.top(); 1487 size_t size = patch_end - patch_base; 1488 1489 // the current value of the pointers to be patched must be within this 1490 // range (i.e., must point to valid metaspace objects) 1491 address valid_old_base = patch_base; 1492 address valid_old_end = patch_end; 1493 1494 // after patching, the pointers must point inside this range 1495 // (the requested location of the archive, as mapped at runtime). 1496 address valid_new_base = (address)MetaspaceShared::default_base_address(); 1497 address valid_new_end = valid_new_base + size; 1498 1499 log_debug(cds)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT " ] to " 1500 "[" INTPTR_FORMAT " - " INTPTR_FORMAT " ]", p2i(patch_base), p2i(patch_end), 1501 p2i(valid_new_base), p2i(valid_new_end)); 1502 1503 SharedDataRelocator<true> patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end, 1504 valid_new_base, valid_new_end, addr_delta, ptrmap); 1505 ptrmap->iterate(&patcher); 1506 ArchivePtrMarker::compact(patcher.max_non_null_offset()); 1507 } 1508 } 1509 1510 void VM_PopulateDumpSharedSpace::doit() { 1511 CHeapBitMap ptrmap; 1512 MetaspaceShared::initialize_ptr_marker(&ptrmap); 1513 1514 // We should no longer allocate anything from the metaspace, so that: 1515 // 1516 // (1) Metaspace::allocate might trigger GC if we have run out of 1517 // committed metaspace, but we can't GC because we're running 1518 // in the VM thread. 1519 // (2) ArchiveCompactor needs to work with a stable set of MetaspaceObjs. 1520 Metaspace::freeze(); 1521 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm); 1522 1523 Thread* THREAD = VMThread::vm_thread(); 1524 1525 FileMapInfo::check_nonempty_dir_in_shared_path_table(); 1526 1527 NOT_PRODUCT(SystemDictionary::verify();) 1528 // The following guarantee is meant to ensure that no loader constraints 1529 // exist yet, since the constraints table is not shared. This becomes 1530 // more important now that we don't re-initialize vtables/itables for 1531 // shared classes at runtime, where constraints were previously created. 1532 guarantee(SystemDictionary::constraints()->number_of_entries() == 0, 1533 "loader constraints are not saved"); 1534 guarantee(SystemDictionary::placeholders()->number_of_entries() == 0, 1535 "placeholders are not saved"); 1536 1537 // At this point, many classes have been loaded. 1538 // Gather systemDictionary classes in a global array and do everything to 1539 // that so we don't have to walk the SystemDictionary again. 1540 SystemDictionaryShared::check_excluded_classes(); 1541 _global_klass_objects = new GrowableArray<Klass*>(1000); 1542 CollectClassesClosure collect_classes; 1543 ClassLoaderDataGraph::loaded_classes_do(&collect_classes); 1544 1545 print_class_stats(); 1546 1547 // Ensure the ConstMethods won't be modified at run-time 1548 log_info(cds)("Updating ConstMethods ... "); 1549 rewrite_nofast_bytecodes_and_calculate_fingerprints(THREAD); 1550 log_info(cds)("done. "); 1551 1552 // Remove all references outside the metadata 1553 log_info(cds)("Removing unshareable information ... "); 1554 remove_unshareable_in_classes(); 1555 log_info(cds)("done. "); 1556 1557 MetaspaceShared::allocate_cloned_cpp_vtptrs(); 1558 char* cloned_vtables = _mc_region.top(); 1559 MetaspaceShared::allocate_cpp_vtable_clones(); 1560 1561 ArchiveCompactor::initialize(); 1562 ArchiveCompactor::copy_and_compact(); 1563 1564 dump_symbols(); 1565 1566 // Dump supported java heap objects 1567 _closed_archive_heap_regions = NULL; 1568 _open_archive_heap_regions = NULL; 1569 dump_java_heap_objects(); 1570 1571 ArchiveCompactor::relocate_well_known_klasses(); 1572 1573 char* serialized_data = dump_read_only_tables(); 1574 _ro_region.pack(); 1575 1576 // The vtable clones contain addresses of the current process. 1577 // We don't want to write these addresses into the archive. 1578 MetaspaceShared::zero_cpp_vtable_clones_for_writing(); 1579 1580 // relocate the data so that it can be mapped to MetaspaceShared::default_base_address() 1581 // without runtime relocation. 1582 relocate_to_default_base_address(&ptrmap); 1583 1584 // Create and write the archive file that maps the shared spaces. 1585 1586 FileMapInfo* mapinfo = new FileMapInfo(true); 1587 mapinfo->populate_header(os::vm_allocation_granularity()); 1588 mapinfo->set_serialized_data(serialized_data); 1589 mapinfo->set_cloned_vtables(cloned_vtables); 1590 mapinfo->set_i2i_entry_code_buffers(MetaspaceShared::i2i_entry_code_buffers(), 1591 MetaspaceShared::i2i_entry_code_buffers_size()); 1592 mapinfo->open_for_write(); 1593 MetaspaceShared::write_core_archive_regions(mapinfo, _closed_archive_heap_oopmaps, _open_archive_heap_oopmaps); 1594 _total_closed_archive_region_size = mapinfo->write_archive_heap_regions( 1595 _closed_archive_heap_regions, 1596 _closed_archive_heap_oopmaps, 1597 MetaspaceShared::first_closed_archive_heap_region, 1598 MetaspaceShared::max_closed_archive_heap_region); 1599 _total_open_archive_region_size = mapinfo->write_archive_heap_regions( 1600 _open_archive_heap_regions, 1601 _open_archive_heap_oopmaps, 1602 MetaspaceShared::first_open_archive_heap_region, 1603 MetaspaceShared::max_open_archive_heap_region); 1604 1605 mapinfo->set_final_requested_base((char*)MetaspaceShared::default_base_address()); 1606 mapinfo->set_header_crc(mapinfo->compute_header_crc()); 1607 mapinfo->write_header(); 1608 print_region_stats(mapinfo); 1609 mapinfo->close(); 1610 1611 if (log_is_enabled(Info, cds)) { 1612 ArchiveCompactor::alloc_stats()->print_stats(int(_ro_region.used()), int(_rw_region.used()), 1613 int(_mc_region.used())); 1614 } 1615 1616 if (PrintSystemDictionaryAtExit) { 1617 SystemDictionary::print(); 1618 } 1619 1620 if (AllowArchivingWithJavaAgent) { 1621 warning("This archive was created with AllowArchivingWithJavaAgent. It should be used " 1622 "for testing purposes only and should not be used in a production environment"); 1623 } 1624 1625 // There may be other pending VM operations that operate on the InstanceKlasses, 1626 // which will fail because InstanceKlasses::remove_unshareable_info() 1627 // has been called. Forget these operations and exit the VM directly. 1628 vm_direct_exit(0); 1629 } 1630 1631 void VM_PopulateDumpSharedSpace::print_region_stats(FileMapInfo *map_info) { 1632 // Print statistics of all the regions 1633 const size_t bitmap_used = map_info->space_at(MetaspaceShared::bm)->used(); 1634 const size_t bitmap_reserved = map_info->space_at(MetaspaceShared::bm)->used_aligned(); 1635 const size_t total_reserved = _ro_region.reserved() + _rw_region.reserved() + 1636 _mc_region.reserved() + 1637 bitmap_reserved + 1638 _total_closed_archive_region_size + 1639 _total_open_archive_region_size; 1640 const size_t total_bytes = _ro_region.used() + _rw_region.used() + 1641 _mc_region.used() + 1642 bitmap_used + 1643 _total_closed_archive_region_size + 1644 _total_open_archive_region_size; 1645 const double total_u_perc = percent_of(total_bytes, total_reserved); 1646 1647 _mc_region.print(total_reserved); 1648 _rw_region.print(total_reserved); 1649 _ro_region.print(total_reserved); 1650 print_bitmap_region_stats(bitmap_reserved, total_reserved); 1651 print_heap_region_stats(_closed_archive_heap_regions, "ca", total_reserved); 1652 print_heap_region_stats(_open_archive_heap_regions, "oa", total_reserved); 1653 1654 log_debug(cds)("total : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]", 1655 total_bytes, total_reserved, total_u_perc); 1656 } 1657 1658 void VM_PopulateDumpSharedSpace::print_bitmap_region_stats(size_t size, size_t total_size) { 1659 log_debug(cds)("bm space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used] at " INTPTR_FORMAT, 1660 size, size/double(total_size)*100.0, size, p2i(NULL)); 1661 } 1662 1663 void VM_PopulateDumpSharedSpace::print_heap_region_stats(GrowableArray<MemRegion> *heap_mem, 1664 const char *name, size_t total_size) { 1665 int arr_len = heap_mem == NULL ? 0 : heap_mem->length(); 1666 for (int i = 0; i < arr_len; i++) { 1667 char* start = (char*)heap_mem->at(i).start(); 1668 size_t size = heap_mem->at(i).byte_size(); 1669 char* top = start + size; 1670 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, 1671 name, i, size, size/double(total_size)*100.0, size, p2i(start)); 1672 1673 } 1674 } 1675 1676 void MetaspaceShared::write_core_archive_regions(FileMapInfo* mapinfo, 1677 GrowableArray<ArchiveHeapOopmapInfo>* closed_oopmaps, 1678 GrowableArray<ArchiveHeapOopmapInfo>* open_oopmaps) { 1679 // Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with 1680 // MetaspaceShared::n_regions (internal to hotspot). 1681 assert(NUM_CDS_REGIONS == MetaspaceShared::n_regions, "sanity"); 1682 1683 // mc contains the trampoline code for method entries, which are patched at run time, 1684 // so it needs to be read/write. 1685 write_region(mapinfo, mc, &_mc_region, /*read_only=*/false,/*allow_exec=*/true); 1686 write_region(mapinfo, rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false); 1687 write_region(mapinfo, ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false); 1688 mapinfo->write_bitmap_region(ArchivePtrMarker::ptrmap(), closed_oopmaps, open_oopmaps); 1689 } 1690 1691 void MetaspaceShared::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only, bool allow_exec) { 1692 mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec); 1693 } 1694 1695 // Update a Java object to point its Klass* to the new location after 1696 // shared archive has been compacted. 1697 void MetaspaceShared::relocate_klass_ptr(oop o) { 1698 assert(DumpSharedSpaces, "sanity"); 1699 Klass* k = ArchiveCompactor::get_relocated_klass(o->klass()); 1700 o->set_klass(k); 1701 } 1702 1703 Klass* MetaspaceShared::get_relocated_klass(Klass *k, bool is_final) { 1704 assert(DumpSharedSpaces, "sanity"); 1705 k = ArchiveCompactor::get_relocated_klass(k); 1706 if (is_final) { 1707 k = (Klass*)(address(k) + final_delta()); 1708 } 1709 return k; 1710 } 1711 1712 class LinkSharedClassesClosure : public KlassClosure { 1713 Thread* THREAD; 1714 bool _made_progress; 1715 public: 1716 LinkSharedClassesClosure(Thread* thread) : THREAD(thread), _made_progress(false) {} 1717 1718 void reset() { _made_progress = false; } 1719 bool made_progress() const { return _made_progress; } 1720 1721 void do_klass(Klass* k) { 1722 if (k->is_instance_klass()) { 1723 InstanceKlass* ik = InstanceKlass::cast(k); 1724 // For dynamic CDS dump, only link classes loaded by the builtin class loaders. 1725 bool do_linking = DumpSharedSpaces ? true : !ik->is_shared_unregistered_class(); 1726 if (do_linking) { 1727 // Link the class to cause the bytecodes to be rewritten and the 1728 // cpcache to be created. Class verification is done according 1729 // to -Xverify setting. 1730 _made_progress |= MetaspaceShared::try_link_class(ik, THREAD); 1731 guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class"); 1732 1733 if (DumpSharedSpaces) { 1734 // The following function is used to resolve all Strings in the statically 1735 // dumped classes to archive all the Strings. The archive heap is not supported 1736 // for the dynamic archive. 1737 ik->constants()->resolve_class_constants(THREAD); 1738 } 1739 } 1740 } 1741 } 1742 }; 1743 1744 void MetaspaceShared::link_and_cleanup_shared_classes(TRAPS) { 1745 // We need to iterate because verification may cause additional classes 1746 // to be loaded. 1747 LinkSharedClassesClosure link_closure(THREAD); 1748 do { 1749 link_closure.reset(); 1750 ClassLoaderDataGraph::unlocked_loaded_classes_do(&link_closure); 1751 guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class"); 1752 } while (link_closure.made_progress()); 1753 } 1754 1755 void MetaspaceShared::prepare_for_dumping() { 1756 Arguments::check_unsupported_dumping_properties(); 1757 ClassLoader::initialize_shared_path(); 1758 } 1759 1760 // Preload classes from a list, populate the shared spaces and dump to a 1761 // file. 1762 void MetaspaceShared::preload_and_dump(TRAPS) { 1763 { TraceTime timer("Dump Shared Spaces", TRACETIME_LOG(Info, startuptime)); 1764 ResourceMark rm(THREAD); 1765 char class_list_path_str[JVM_MAXPATHLEN]; 1766 // Preload classes to be shared. 1767 const char* class_list_path; 1768 if (SharedClassListFile == NULL) { 1769 // Construct the path to the class list (in jre/lib) 1770 // Walk up two directories from the location of the VM and 1771 // optionally tack on "lib" (depending on platform) 1772 os::jvm_path(class_list_path_str, sizeof(class_list_path_str)); 1773 for (int i = 0; i < 3; i++) { 1774 char *end = strrchr(class_list_path_str, *os::file_separator()); 1775 if (end != NULL) *end = '\0'; 1776 } 1777 int class_list_path_len = (int)strlen(class_list_path_str); 1778 if (class_list_path_len >= 3) { 1779 if (strcmp(class_list_path_str + class_list_path_len - 3, "lib") != 0) { 1780 if (class_list_path_len < JVM_MAXPATHLEN - 4) { 1781 jio_snprintf(class_list_path_str + class_list_path_len, 1782 sizeof(class_list_path_str) - class_list_path_len, 1783 "%slib", os::file_separator()); 1784 class_list_path_len += 4; 1785 } 1786 } 1787 } 1788 if (class_list_path_len < JVM_MAXPATHLEN - 10) { 1789 jio_snprintf(class_list_path_str + class_list_path_len, 1790 sizeof(class_list_path_str) - class_list_path_len, 1791 "%sclasslist", os::file_separator()); 1792 } 1793 class_list_path = class_list_path_str; 1794 } else { 1795 class_list_path = SharedClassListFile; 1796 } 1797 1798 log_info(cds)("Loading classes to share ..."); 1799 _has_error_classes = false; 1800 int class_count = preload_classes(class_list_path, THREAD); 1801 if (ExtraSharedClassListFile) { 1802 class_count += preload_classes(ExtraSharedClassListFile, THREAD); 1803 } 1804 log_info(cds)("Loading classes to share: done."); 1805 1806 log_info(cds)("Shared spaces: preloaded %d classes", class_count); 1807 1808 if (SharedArchiveConfigFile) { 1809 log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile); 1810 read_extra_data(SharedArchiveConfigFile, THREAD); 1811 } 1812 log_info(cds)("Reading extra data: done."); 1813 1814 HeapShared::init_subgraph_entry_fields(THREAD); 1815 1816 // Rewrite and link classes 1817 log_info(cds)("Rewriting and linking classes ..."); 1818 1819 // Link any classes which got missed. This would happen if we have loaded classes that 1820 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K 1821 // fails verification, all other interfaces that were not specified in the classlist but 1822 // are implemented by K are not verified. 1823 link_and_cleanup_shared_classes(CATCH); 1824 log_info(cds)("Rewriting and linking classes: done"); 1825 1826 if (HeapShared::is_heap_object_archiving_allowed()) { 1827 // Avoid fragmentation while archiving heap objects. 1828 Universe::heap()->soft_ref_policy()->set_should_clear_all_soft_refs(true); 1829 Universe::heap()->collect(GCCause::_archive_time_gc); 1830 Universe::heap()->soft_ref_policy()->set_should_clear_all_soft_refs(false); 1831 } 1832 1833 VM_PopulateDumpSharedSpace op; 1834 VMThread::execute(&op); 1835 } 1836 } 1837 1838 1839 int MetaspaceShared::preload_classes(const char* class_list_path, TRAPS) { 1840 ClassListParser parser(class_list_path); 1841 int class_count = 0; 1842 1843 while (parser.parse_one_line()) { 1844 Klass* klass = parser.load_current_class(THREAD); 1845 if (HAS_PENDING_EXCEPTION) { 1846 if (klass == NULL && 1847 (PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_ClassNotFoundException())) { 1848 // print a warning only when the pending exception is class not found 1849 log_warning(cds)("Preload Warning: Cannot find %s", parser.current_class_name()); 1850 } 1851 CLEAR_PENDING_EXCEPTION; 1852 } 1853 if (klass != NULL) { 1854 if (log_is_enabled(Trace, cds)) { 1855 ResourceMark rm(THREAD); 1856 log_trace(cds)("Shared spaces preloaded: %s", klass->external_name()); 1857 } 1858 1859 if (klass->is_instance_klass()) { 1860 InstanceKlass* ik = InstanceKlass::cast(klass); 1861 1862 // Link the class to cause the bytecodes to be rewritten and the 1863 // cpcache to be created. The linking is done as soon as classes 1864 // are loaded in order that the related data structures (klass and 1865 // cpCache) are located together. 1866 try_link_class(ik, THREAD); 1867 guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class"); 1868 } 1869 1870 class_count++; 1871 } 1872 } 1873 1874 return class_count; 1875 } 1876 1877 // Returns true if the class's status has changed 1878 bool MetaspaceShared::try_link_class(InstanceKlass* ik, TRAPS) { 1879 Arguments::assert_is_dumping_archive(); 1880 if (ik->init_state() < InstanceKlass::linked && 1881 !SystemDictionaryShared::has_class_failed_verification(ik)) { 1882 bool saved = BytecodeVerificationLocal; 1883 if (ik->is_shared_unregistered_class() && ik->class_loader() == NULL) { 1884 // The verification decision is based on BytecodeVerificationRemote 1885 // for non-system classes. Since we are using the NULL classloader 1886 // to load non-system classes for customized class loaders during dumping, 1887 // we need to temporarily change BytecodeVerificationLocal to be the same as 1888 // BytecodeVerificationRemote. Note this can cause the parent system 1889 // classes also being verified. The extra overhead is acceptable during 1890 // dumping. 1891 BytecodeVerificationLocal = BytecodeVerificationRemote; 1892 } 1893 ik->link_class(THREAD); 1894 if (HAS_PENDING_EXCEPTION) { 1895 ResourceMark rm(THREAD); 1896 log_warning(cds)("Preload Warning: Verification failed for %s", 1897 ik->external_name()); 1898 CLEAR_PENDING_EXCEPTION; 1899 SystemDictionaryShared::set_class_has_failed_verification(ik); 1900 _has_error_classes = true; 1901 } 1902 BytecodeVerificationLocal = saved; 1903 return true; 1904 } else { 1905 return false; 1906 } 1907 } 1908 1909 #if INCLUDE_CDS_JAVA_HEAP 1910 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() { 1911 // The closed and open archive heap space has maximum two regions. 1912 // See FileMapInfo::write_archive_heap_regions() for details. 1913 _closed_archive_heap_regions = new GrowableArray<MemRegion>(2); 1914 _open_archive_heap_regions = new GrowableArray<MemRegion>(2); 1915 HeapShared::archive_java_heap_objects(_closed_archive_heap_regions, 1916 _open_archive_heap_regions); 1917 ArchiveCompactor::OtherROAllocMark mark; 1918 HeapShared::write_subgraph_info_table(); 1919 } 1920 1921 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps() { 1922 if (HeapShared::is_heap_object_archiving_allowed()) { 1923 _closed_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2); 1924 dump_archive_heap_oopmaps(_closed_archive_heap_regions, _closed_archive_heap_oopmaps); 1925 1926 _open_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2); 1927 dump_archive_heap_oopmaps(_open_archive_heap_regions, _open_archive_heap_oopmaps); 1928 } 1929 } 1930 1931 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions, 1932 GrowableArray<ArchiveHeapOopmapInfo>* oopmaps) { 1933 for (int i=0; i<regions->length(); i++) { 1934 ResourceBitMap oopmap = HeapShared::calculate_oopmap(regions->at(i)); 1935 size_t size_in_bits = oopmap.size(); 1936 size_t size_in_bytes = oopmap.size_in_bytes(); 1937 uintptr_t* buffer = (uintptr_t*)NEW_C_HEAP_ARRAY(char, size_in_bytes, mtInternal); 1938 oopmap.write_to(buffer, size_in_bytes); 1939 log_info(cds, heap)("Oopmap = " INTPTR_FORMAT " (" SIZE_FORMAT_W(6) " bytes) for heap region " 1940 INTPTR_FORMAT " (" SIZE_FORMAT_W(8) " bytes)", 1941 p2i(buffer), size_in_bytes, 1942 p2i(regions->at(i).start()), regions->at(i).byte_size()); 1943 1944 ArchiveHeapOopmapInfo info; 1945 info._oopmap = (address)buffer; 1946 info._oopmap_size_in_bits = size_in_bits; 1947 info._oopmap_size_in_bytes = size_in_bytes; 1948 oopmaps->append(info); 1949 } 1950 } 1951 #endif // INCLUDE_CDS_JAVA_HEAP 1952 1953 void ReadClosure::do_ptr(void** p) { 1954 assert(*p == NULL, "initializing previous initialized pointer."); 1955 intptr_t obj = nextPtr(); 1956 assert((intptr_t)obj >= 0 || (intptr_t)obj < -100, 1957 "hit tag while initializing ptrs."); 1958 *p = (void*)obj; 1959 } 1960 1961 void ReadClosure::do_u4(u4* p) { 1962 intptr_t obj = nextPtr(); 1963 *p = (u4)(uintx(obj)); 1964 } 1965 1966 void ReadClosure::do_bool(bool* p) { 1967 intptr_t obj = nextPtr(); 1968 *p = (bool)(uintx(obj)); 1969 } 1970 1971 void ReadClosure::do_tag(int tag) { 1972 int old_tag; 1973 old_tag = (int)(intptr_t)nextPtr(); 1974 // do_int(&old_tag); 1975 assert(tag == old_tag, "old tag doesn't match"); 1976 FileMapInfo::assert_mark(tag == old_tag); 1977 } 1978 1979 void ReadClosure::do_oop(oop *p) { 1980 narrowOop o = (narrowOop)nextPtr(); 1981 if (o == 0 || !HeapShared::open_archive_heap_region_mapped()) { 1982 p = NULL; 1983 } else { 1984 assert(HeapShared::is_heap_object_archiving_allowed(), 1985 "Archived heap object is not allowed"); 1986 assert(HeapShared::open_archive_heap_region_mapped(), 1987 "Open archive heap region is not mapped"); 1988 *p = HeapShared::decode_from_archive(o); 1989 } 1990 } 1991 1992 void ReadClosure::do_region(u_char* start, size_t size) { 1993 assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment"); 1994 assert(size % sizeof(intptr_t) == 0, "bad size"); 1995 do_tag((int)size); 1996 while (size > 0) { 1997 *(intptr_t*)start = nextPtr(); 1998 start += sizeof(intptr_t); 1999 size -= sizeof(intptr_t); 2000 } 2001 } 2002 2003 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) { 2004 assert(base <= static_top && static_top <= top, "must be"); 2005 _shared_metaspace_static_top = static_top; 2006 MetaspaceObj::set_shared_metaspace_range(base, top); 2007 } 2008 2009 // Return true if given address is in the misc data region 2010 bool MetaspaceShared::is_in_shared_region(const void* p, int idx) { 2011 return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx); 2012 } 2013 2014 bool MetaspaceShared::is_in_trampoline_frame(address addr) { 2015 if (UseSharedSpaces && is_in_shared_region(addr, MetaspaceShared::mc)) { 2016 return true; 2017 } 2018 return false; 2019 } 2020 2021 bool MetaspaceShared::is_shared_dynamic(void* p) { 2022 if ((p < MetaspaceObj::shared_metaspace_top()) && 2023 (p >= _shared_metaspace_static_top)) { 2024 return true; 2025 } else { 2026 return false; 2027 } 2028 } 2029 2030 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() { 2031 assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled"); 2032 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE; 2033 FileMapInfo* static_mapinfo = open_static_archive(); 2034 FileMapInfo* dynamic_mapinfo = NULL; 2035 2036 if (static_mapinfo != NULL) { 2037 dynamic_mapinfo = open_dynamic_archive(); 2038 2039 // First try to map at the requested address 2040 result = map_archives(static_mapinfo, dynamic_mapinfo, true); 2041 if (result == MAP_ARCHIVE_MMAP_FAILURE) { 2042 // Mapping has failed (probably due to ASLR). Let's map at an address chosen 2043 // by the OS. 2044 log_info(cds)("Try to map archive(s) at an alternative address"); 2045 result = map_archives(static_mapinfo, dynamic_mapinfo, false); 2046 } 2047 } 2048 2049 if (result == MAP_ARCHIVE_SUCCESS) { 2050 bool dynamic_mapped = (dynamic_mapinfo != NULL && dynamic_mapinfo->is_mapped()); 2051 char* cds_base = static_mapinfo->mapped_base(); 2052 char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end(); 2053 set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end); 2054 _relocation_delta = static_mapinfo->relocation_delta(); 2055 if (dynamic_mapped) { 2056 FileMapInfo::set_shared_path_table(dynamic_mapinfo); 2057 } else { 2058 FileMapInfo::set_shared_path_table(static_mapinfo); 2059 } 2060 _default_base_address = static_mapinfo->requested_base_address(); 2061 } else { 2062 set_shared_metaspace_range(NULL, NULL, NULL); 2063 UseSharedSpaces = false; 2064 FileMapInfo::fail_continue("Unable to map shared spaces"); 2065 if (PrintSharedArchiveAndExit) { 2066 vm_exit_during_initialization("Unable to use shared archive."); 2067 } 2068 } 2069 2070 if (static_mapinfo != NULL && !static_mapinfo->is_mapped()) { 2071 delete static_mapinfo; 2072 } 2073 if (dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped()) { 2074 delete dynamic_mapinfo; 2075 } 2076 } 2077 2078 FileMapInfo* MetaspaceShared::open_static_archive() { 2079 FileMapInfo* mapinfo = new FileMapInfo(true); 2080 if (!mapinfo->initialize()) { 2081 delete(mapinfo); 2082 return NULL; 2083 } 2084 return mapinfo; 2085 } 2086 2087 FileMapInfo* MetaspaceShared::open_dynamic_archive() { 2088 if (DynamicDumpSharedSpaces) { 2089 return NULL; 2090 } 2091 if (Arguments::GetSharedDynamicArchivePath() == NULL) { 2092 return NULL; 2093 } 2094 2095 FileMapInfo* mapinfo = new FileMapInfo(false); 2096 if (!mapinfo->initialize()) { 2097 delete(mapinfo); 2098 return NULL; 2099 } 2100 return mapinfo; 2101 } 2102 2103 // use_requested_addr: 2104 // true = map at FileMapHeader::_requested_base_address 2105 // false = map at an alternative address picked by OS. 2106 MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo, 2107 bool use_requested_addr) { 2108 if (use_requested_addr && static_mapinfo->requested_base_address() == NULL) { 2109 log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address"); 2110 return MAP_ARCHIVE_MMAP_FAILURE; 2111 } 2112 2113 PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) { 2114 // For product build only -- this is for benchmarking the cost of doing relocation. 2115 // For debug builds, the check is done in FileMapInfo::map_regions for better test coverage. 2116 log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address"); 2117 return MAP_ARCHIVE_MMAP_FAILURE; 2118 }); 2119 2120 if (ArchiveRelocationMode == 2 && !use_requested_addr) { 2121 log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address"); 2122 return MAP_ARCHIVE_MMAP_FAILURE; 2123 }; 2124 2125 if (dynamic_mapinfo != NULL) { 2126 // Ensure that the OS won't be able to allocate new memory spaces between the two 2127 // archives, or else it would mess up the simple comparision in MetaspaceObj::is_shared(). 2128 assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap"); 2129 } 2130 2131 ReservedSpace main_rs, archive_space_rs, class_space_rs; 2132 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE; 2133 char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo, dynamic_mapinfo, 2134 use_requested_addr, main_rs, archive_space_rs, 2135 class_space_rs); 2136 if (mapped_base_address == NULL) { 2137 result = MAP_ARCHIVE_MMAP_FAILURE; 2138 } else { 2139 log_debug(cds)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes", 2140 p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size()); 2141 log_debug(cds)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes", 2142 p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size()); 2143 MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs); 2144 MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ? 2145 map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE; 2146 2147 DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) { 2148 // This is for simulating mmap failures at the requested address. In debug builds, we do it 2149 // here (after all archives have possibly been mapped), so we can thoroughly test the code for 2150 // failure handling (releasing all allocated resource, etc). 2151 log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address"); 2152 if (static_result == MAP_ARCHIVE_SUCCESS) { 2153 static_result = MAP_ARCHIVE_MMAP_FAILURE; 2154 } 2155 if (dynamic_result == MAP_ARCHIVE_SUCCESS) { 2156 dynamic_result = MAP_ARCHIVE_MMAP_FAILURE; 2157 } 2158 }); 2159 2160 if (static_result == MAP_ARCHIVE_SUCCESS) { 2161 if (dynamic_result == MAP_ARCHIVE_SUCCESS) { 2162 result = MAP_ARCHIVE_SUCCESS; 2163 } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) { 2164 assert(dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped(), "must have failed"); 2165 // No need to retry mapping the dynamic archive again, as it will never succeed 2166 // (bad file, etc) -- just keep the base archive. 2167 log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s", 2168 dynamic_mapinfo->full_path()); 2169 result = MAP_ARCHIVE_SUCCESS; 2170 // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no 2171 // easy API to do that right now. 2172 } else { 2173 result = MAP_ARCHIVE_MMAP_FAILURE; 2174 } 2175 } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) { 2176 result = MAP_ARCHIVE_OTHER_FAILURE; 2177 } else { 2178 result = MAP_ARCHIVE_MMAP_FAILURE; 2179 } 2180 } 2181 2182 if (result == MAP_ARCHIVE_SUCCESS) { 2183 if (!main_rs.is_reserved() && class_space_rs.is_reserved()) { 2184 MemTracker::record_virtual_memory_type((address)class_space_rs.base(), mtClass); 2185 } 2186 SharedBaseAddress = (size_t)mapped_base_address; 2187 LP64_ONLY({ 2188 if (Metaspace::using_class_space()) { 2189 assert(class_space_rs.is_reserved(), "must be"); 2190 char* cds_base = static_mapinfo->mapped_base(); 2191 Metaspace::allocate_metaspace_compressed_klass_ptrs(class_space_rs, NULL, (address)cds_base); 2192 // map_heap_regions() compares the current narrow oop and klass encodings 2193 // with the archived ones, so it must be done after all encodings are determined. 2194 static_mapinfo->map_heap_regions(); 2195 CompressedKlassPointers::set_range(CompressedClassSpaceSize); 2196 } 2197 }); 2198 } else { 2199 unmap_archive(static_mapinfo); 2200 unmap_archive(dynamic_mapinfo); 2201 release_reserved_spaces(main_rs, archive_space_rs, class_space_rs); 2202 } 2203 2204 return result; 2205 } 2206 2207 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo, 2208 FileMapInfo* dynamic_mapinfo, 2209 bool use_requested_addr, 2210 ReservedSpace& main_rs, 2211 ReservedSpace& archive_space_rs, 2212 ReservedSpace& class_space_rs) { 2213 const bool use_klass_space = NOT_LP64(false) LP64_ONLY(Metaspace::using_class_space()); 2214 const size_t class_space_size = NOT_LP64(0) LP64_ONLY(Metaspace::compressed_class_space_size()); 2215 2216 if (use_klass_space) { 2217 assert(class_space_size > 0, "CompressedClassSpaceSize must have been validated"); 2218 } 2219 if (use_requested_addr && !is_aligned(static_mapinfo->requested_base_address(), reserved_space_alignment())) { 2220 return NULL; 2221 } 2222 2223 // Size and requested location of the archive_space_rs (for both static and dynamic archives) 2224 size_t base_offset = static_mapinfo->mapping_base_offset(); 2225 size_t end_offset = (dynamic_mapinfo == NULL) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset(); 2226 assert(base_offset == 0, "must be"); 2227 assert(is_aligned(end_offset, os::vm_allocation_granularity()), "must be"); 2228 assert(is_aligned(base_offset, os::vm_allocation_granularity()), "must be"); 2229 2230 // In case reserved_space_alignment() != os::vm_allocation_granularity() 2231 assert((size_t)os::vm_allocation_granularity() <= reserved_space_alignment(), "must be"); 2232 end_offset = align_up(end_offset, reserved_space_alignment()); 2233 2234 size_t archive_space_size = end_offset - base_offset; 2235 2236 // Special handling for Windows because it cannot mmap into a reserved space: 2237 // use_requested_addr: We just map each region individually, and give up if any one of them fails. 2238 // !use_requested_addr: We reserve the space first, and then os::read in all the regions (instead of mmap). 2239 // We're going to patch all the pointers anyway so there's no benefit for mmap. 2240 2241 if (use_requested_addr) { 2242 char* archive_space_base = static_mapinfo->requested_base_address() + base_offset; 2243 char* archive_space_end = archive_space_base + archive_space_size; 2244 if (!MetaspaceShared::use_windows_memory_mapping()) { 2245 archive_space_rs = reserve_shared_space(archive_space_size, archive_space_base); 2246 if (!archive_space_rs.is_reserved()) { 2247 return NULL; 2248 } 2249 } 2250 if (use_klass_space) { 2251 // Make sure we can map the klass space immediately following the archive_space space 2252 // Don't call reserve_shared_space here as that may try to enforce platform-specific 2253 // alignment rules which only apply to the archive base address 2254 char* class_space_base = archive_space_end; 2255 class_space_rs = ReservedSpace(class_space_size, reserved_space_alignment(), 2256 false /* large_pages */, class_space_base); 2257 if (!class_space_rs.is_reserved()) { 2258 return NULL; 2259 } 2260 } 2261 return static_mapinfo->requested_base_address(); 2262 } else { 2263 if (use_klass_space) { 2264 main_rs = reserve_shared_space(archive_space_size + class_space_size); 2265 if (main_rs.is_reserved()) { 2266 archive_space_rs = main_rs.first_part(archive_space_size, reserved_space_alignment(), /*split=*/true); 2267 class_space_rs = main_rs.last_part(archive_space_size); 2268 } 2269 } else { 2270 main_rs = reserve_shared_space(archive_space_size); 2271 archive_space_rs = main_rs; 2272 } 2273 if (archive_space_rs.is_reserved()) { 2274 return archive_space_rs.base(); 2275 } else { 2276 return NULL; 2277 } 2278 } 2279 } 2280 2281 void MetaspaceShared::release_reserved_spaces(ReservedSpace& main_rs, 2282 ReservedSpace& archive_space_rs, 2283 ReservedSpace& class_space_rs) { 2284 if (main_rs.is_reserved()) { 2285 assert(main_rs.contains(archive_space_rs.base()), "must be"); 2286 assert(main_rs.contains(class_space_rs.base()), "must be"); 2287 log_debug(cds)("Released shared space (archive+classes) " INTPTR_FORMAT, p2i(main_rs.base())); 2288 main_rs.release(); 2289 } else { 2290 if (archive_space_rs.is_reserved()) { 2291 log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base())); 2292 archive_space_rs.release(); 2293 } 2294 if (class_space_rs.is_reserved()) { 2295 log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base())); 2296 class_space_rs.release(); 2297 } 2298 } 2299 } 2300 2301 static int archive_regions[] = {MetaspaceShared::mc, 2302 MetaspaceShared::rw, 2303 MetaspaceShared::ro}; 2304 static int archive_regions_count = 3; 2305 2306 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) { 2307 assert(UseSharedSpaces, "must be runtime"); 2308 if (mapinfo == NULL) { 2309 return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded. 2310 } 2311 2312 mapinfo->set_is_mapped(false); 2313 2314 if (mapinfo->alignment() != (size_t)os::vm_allocation_granularity()) { 2315 log_error(cds)("Unable to map CDS archive -- os::vm_allocation_granularity() expected: " SIZE_FORMAT 2316 " actual: %d", mapinfo->alignment(), os::vm_allocation_granularity()); 2317 return MAP_ARCHIVE_OTHER_FAILURE; 2318 } 2319 2320 MapArchiveResult result = 2321 mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs); 2322 2323 if (result != MAP_ARCHIVE_SUCCESS) { 2324 unmap_archive(mapinfo); 2325 return result; 2326 } 2327 2328 if (mapinfo->is_static()) { 2329 if (!mapinfo->validate_shared_path_table()) { 2330 unmap_archive(mapinfo); 2331 return MAP_ARCHIVE_OTHER_FAILURE; 2332 } 2333 } else { 2334 if (!DynamicArchive::validate(mapinfo)) { 2335 unmap_archive(mapinfo); 2336 return MAP_ARCHIVE_OTHER_FAILURE; 2337 } 2338 } 2339 2340 mapinfo->set_is_mapped(true); 2341 return MAP_ARCHIVE_SUCCESS; 2342 } 2343 2344 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) { 2345 assert(UseSharedSpaces, "must be runtime"); 2346 if (mapinfo != NULL) { 2347 mapinfo->unmap_regions(archive_regions, archive_regions_count); 2348 mapinfo->set_is_mapped(false); 2349 } 2350 } 2351 2352 // Read the miscellaneous data from the shared file, and 2353 // serialize it out to its various destinations. 2354 2355 void MetaspaceShared::initialize_shared_spaces() { 2356 FileMapInfo *static_mapinfo = FileMapInfo::current_info(); 2357 _i2i_entry_code_buffers = static_mapinfo->i2i_entry_code_buffers(); 2358 _i2i_entry_code_buffers_size = static_mapinfo->i2i_entry_code_buffers_size(); 2359 char* buffer = static_mapinfo->cloned_vtables(); 2360 clone_cpp_vtables((intptr_t*)buffer); 2361 2362 // Verify various attributes of the archive, plus initialize the 2363 // shared string/symbol tables 2364 buffer = static_mapinfo->serialized_data(); 2365 intptr_t* array = (intptr_t*)buffer; 2366 ReadClosure rc(&array); 2367 serialize(&rc); 2368 2369 // Initialize the run-time symbol table. 2370 SymbolTable::create_table(); 2371 2372 static_mapinfo->patch_archived_heap_embedded_pointers(); 2373 2374 // Close the mapinfo file 2375 static_mapinfo->close(); 2376 2377 static_mapinfo->unmap_region(MetaspaceShared::bm); 2378 2379 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info(); 2380 if (dynamic_mapinfo != NULL) { 2381 intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data(); 2382 ReadClosure rc(&buffer); 2383 SymbolTable::serialize_shared_table_header(&rc, false); 2384 SystemDictionaryShared::serialize_dictionary_headers(&rc, false); 2385 dynamic_mapinfo->close(); 2386 } 2387 2388 if (PrintSharedArchiveAndExit) { 2389 if (PrintSharedDictionary) { 2390 tty->print_cr("\nShared classes:\n"); 2391 SystemDictionaryShared::print_on(tty); 2392 } 2393 if (FileMapInfo::current_info() == NULL || _archive_loading_failed) { 2394 tty->print_cr("archive is invalid"); 2395 vm_exit(1); 2396 } else { 2397 tty->print_cr("archive is valid"); 2398 vm_exit(0); 2399 } 2400 } 2401 } 2402 2403 // JVM/TI RedefineClasses() support: 2404 bool MetaspaceShared::remap_shared_readonly_as_readwrite() { 2405 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 2406 2407 if (UseSharedSpaces) { 2408 // remap the shared readonly space to shared readwrite, private 2409 FileMapInfo* mapinfo = FileMapInfo::current_info(); 2410 if (!mapinfo->remap_shared_readonly_as_readwrite()) { 2411 return false; 2412 } 2413 if (FileMapInfo::dynamic_info() != NULL) { 2414 mapinfo = FileMapInfo::dynamic_info(); 2415 if (!mapinfo->remap_shared_readonly_as_readwrite()) { 2416 return false; 2417 } 2418 } 2419 _remapped_readwrite = true; 2420 } 2421 return true; 2422 } 2423 2424 void MetaspaceShared::report_out_of_space(const char* name, size_t needed_bytes) { 2425 // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space. 2426 // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes 2427 // or so. 2428 _mc_region.print_out_of_space_msg(name, needed_bytes); 2429 _rw_region.print_out_of_space_msg(name, needed_bytes); 2430 _ro_region.print_out_of_space_msg(name, needed_bytes); 2431 2432 vm_exit_during_initialization(err_msg("Unable to allocate from '%s' region", name), 2433 "Please reduce the number of shared classes."); 2434 } 2435 2436 // This is used to relocate the pointers so that the base archive can be mapped at 2437 // MetaspaceShared::default_base_address() without runtime relocation. 2438 intx MetaspaceShared::final_delta() { 2439 return intx(MetaspaceShared::default_base_address()) // We want the base archive to be mapped to here at runtime 2440 - intx(SharedBaseAddress); // .. but the base archive is mapped at here at dump time 2441 }