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