1 /* 2 * Copyright (c) 2012, 2025, 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 "cds/aotArtifactFinder.hpp" 26 #include "cds/aotClassLinker.hpp" 27 #include "cds/aotConstantPoolResolver.hpp" 28 #include "cds/aotLinkedClassBulkLoader.hpp" 29 #include "cds/archiveBuilder.hpp" 30 #include "cds/archiveHeapLoader.hpp" 31 #include "cds/archiveHeapWriter.hpp" 32 #include "cds/cds_globals.hpp" 33 #include "cds/cdsConfig.hpp" 34 #include "cds/cdsProtectionDomain.hpp" 35 #include "cds/classListParser.hpp" 36 #include "cds/classListWriter.hpp" 37 #include "cds/cppVtables.hpp" 38 #include "cds/dumpAllocStats.hpp" 39 #include "cds/dynamicArchive.hpp" 40 #include "cds/filemap.hpp" 41 #include "cds/heapShared.hpp" 42 #include "cds/lambdaFormInvokers.hpp" 43 #include "cds/metaspaceShared.hpp" 44 #include "classfile/classLoaderDataGraph.hpp" 45 #include "classfile/classLoaderDataShared.hpp" 46 #include "classfile/classLoaderExt.hpp" 47 #include "classfile/javaClasses.inline.hpp" 48 #include "classfile/loaderConstraints.hpp" 49 #include "classfile/modules.hpp" 50 #include "classfile/placeholders.hpp" 51 #include "classfile/stringTable.hpp" 52 #include "classfile/symbolTable.hpp" 53 #include "classfile/systemDictionary.hpp" 54 #include "classfile/systemDictionaryShared.hpp" 55 #include "classfile/vmClasses.hpp" 56 #include "classfile/vmSymbols.hpp" 57 #include "code/codeCache.hpp" 58 #include "gc/shared/gcVMOperations.hpp" 59 #include "interpreter/bytecodeStream.hpp" 60 #include "interpreter/bytecodes.hpp" 61 #include "jvm_io.h" 62 #include "logging/log.hpp" 63 #include "logging/logMessage.hpp" 64 #include "logging/logStream.hpp" 65 #include "memory/memoryReserver.hpp" 66 #include "memory/metaspace.hpp" 67 #include "memory/metaspaceClosure.hpp" 68 #include "memory/resourceArea.hpp" 69 #include "memory/universe.hpp" 70 #include "nmt/memTracker.hpp" 71 #include "oops/compressedKlass.hpp" 72 #include "oops/instanceMirrorKlass.hpp" 73 #include "oops/klass.inline.hpp" 74 #include "oops/objArrayOop.hpp" 75 #include "oops/oop.inline.hpp" 76 #include "oops/oopHandle.hpp" 77 #include "prims/jvmtiExport.hpp" 78 #include "runtime/arguments.hpp" 79 #include "runtime/globals.hpp" 80 #include "runtime/globals_extension.hpp" 81 #include "runtime/handles.inline.hpp" 82 #include "runtime/javaCalls.hpp" 83 #include "runtime/os.inline.hpp" 84 #include "runtime/safepointVerifiers.hpp" 85 #include "runtime/sharedRuntime.hpp" 86 #include "runtime/vmOperations.hpp" 87 #include "runtime/vmThread.hpp" 88 #include "sanitizers/leak.hpp" 89 #include "utilities/align.hpp" 90 #include "utilities/bitMap.inline.hpp" 91 #include "utilities/defaultStream.hpp" 92 #include "utilities/macros.hpp" 93 #include "utilities/ostream.hpp" 94 #include "utilities/resourceHash.hpp" 95 96 ReservedSpace MetaspaceShared::_symbol_rs; 97 VirtualSpace MetaspaceShared::_symbol_vs; 98 bool MetaspaceShared::_archive_loading_failed = false; 99 bool MetaspaceShared::_remapped_readwrite = false; 100 void* MetaspaceShared::_shared_metaspace_static_top = nullptr; 101 intx MetaspaceShared::_relocation_delta; 102 char* MetaspaceShared::_requested_base_address; 103 Array<Method*>* MetaspaceShared::_archived_method_handle_intrinsics = nullptr; 104 bool MetaspaceShared::_use_optimized_module_handling = true; 105 106 // The CDS archive is divided into the following regions: 107 // rw - read-write metadata 108 // ro - read-only metadata and read-only tables 109 // hp - heap region 110 // bm - bitmap for relocating the above 7 regions. 111 // 112 // The rw and ro regions are linearly allocated, in the order of rw->ro. 113 // These regions are aligned with MetaspaceShared::core_region_alignment(). 114 // 115 // These 2 regions are populated in the following steps: 116 // [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are 117 // temporarily allocated outside of the shared regions. 118 // [1] We enter a safepoint and allocate a buffer for the rw/ro regions. 119 // [2] C++ vtables are copied into the rw region. 120 // [3] ArchiveBuilder copies RW metadata into the rw region. 121 // [4] ArchiveBuilder copies RO metadata into the ro region. 122 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data 123 // are copied into the ro region as read-only tables. 124 // 125 // The heap region is written by HeapShared::write_heap(). 126 // 127 // The bitmap region is used to relocate the ro/rw/hp regions. 128 129 static DumpRegion _symbol_region("symbols"); 130 131 char* MetaspaceShared::symbol_space_alloc(size_t num_bytes) { 132 return _symbol_region.allocate(num_bytes); 133 } 134 135 // os::vm_allocation_granularity() is usually 4K for most OSes. However, some platforms 136 // such as linux-aarch64 and macos-x64 ... 137 // it can be either 4K or 64K and on macos-aarch64 it is 16K. To generate archives that are 138 // compatible for both settings, an alternative cds core region alignment can be enabled 139 // at building time: 140 // --enable-compactible-cds-alignment 141 // Upon successful configuration, the compactible alignment then can be defined in: 142 // os_linux_aarch64.cpp 143 // os_bsd_x86.cpp 144 size_t MetaspaceShared::core_region_alignment() { 145 return os::cds_core_region_alignment(); 146 } 147 148 static bool shared_base_valid(char* shared_base) { 149 // We check user input for SharedBaseAddress at dump time. 150 151 // At CDS runtime, "shared_base" will be the (attempted) mapping start. It will also 152 // be the encoding base, since the the headers of archived base objects (and with Lilliput, 153 // the prototype mark words) carry pre-computed narrow Klass IDs that refer to the mapping 154 // start as base. 155 // 156 // On AARCH64, The "shared_base" may not be later usable as encoding base, depending on the 157 // total size of the reserved area and the precomputed_narrow_klass_shift. This is checked 158 // before reserving memory. Here we weed out values already known to be invalid later. 159 return AARCH64_ONLY(is_aligned(shared_base, 4 * G)) NOT_AARCH64(true); 160 } 161 162 class DumpClassListCLDClosure : public CLDClosure { 163 static const int INITIAL_TABLE_SIZE = 1987; 164 static const int MAX_TABLE_SIZE = 61333; 165 166 fileStream *_stream; 167 ResizeableResourceHashtable<InstanceKlass*, bool, 168 AnyObj::C_HEAP, mtClassShared> _dumped_classes; 169 170 void dump(InstanceKlass* ik) { 171 bool created; 172 _dumped_classes.put_if_absent(ik, &created); 173 if (!created) { 174 return; 175 } 176 if (_dumped_classes.maybe_grow()) { 177 log_info(cds, hashtables)("Expanded _dumped_classes table to %d", _dumped_classes.table_size()); 178 } 179 if (ik->java_super()) { 180 dump(ik->java_super()); 181 } 182 Array<InstanceKlass*>* interfaces = ik->local_interfaces(); 183 int len = interfaces->length(); 184 for (int i = 0; i < len; i++) { 185 dump(interfaces->at(i)); 186 } 187 ClassListWriter::write_to_stream(ik, _stream); 188 } 189 190 public: 191 DumpClassListCLDClosure(fileStream* f) 192 : CLDClosure(), _dumped_classes(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE) { 193 _stream = f; 194 } 195 196 void do_cld(ClassLoaderData* cld) { 197 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) { 198 if (klass->is_instance_klass()) { 199 dump(InstanceKlass::cast(klass)); 200 } 201 } 202 } 203 }; 204 205 void MetaspaceShared::dump_loaded_classes(const char* file_name, TRAPS) { 206 fileStream stream(file_name, "w"); 207 if (stream.is_open()) { 208 MutexLocker lock(ClassLoaderDataGraph_lock); 209 MutexLocker lock2(ClassListFile_lock, Mutex::_no_safepoint_check_flag); 210 DumpClassListCLDClosure collect_classes(&stream); 211 ClassLoaderDataGraph::loaded_cld_do(&collect_classes); 212 } else { 213 THROW_MSG(vmSymbols::java_io_IOException(), "Failed to open file"); 214 } 215 } 216 217 // If p is not aligned, move it up to the next address that's aligned with alignment. 218 // If this is not possible (because p is too high), return nullptr. Example: 219 // p = 0xffffffffffff0000, alignment= 0x10000 => return nullptr. 220 static char* align_up_or_null(char* p, size_t alignment) { 221 assert(p != nullptr, "sanity"); 222 if (is_aligned(p, alignment)) { 223 return p; 224 } 225 226 char* down = align_down(p, alignment); 227 if (max_uintx - uintx(down) < uintx(alignment)) { 228 // Run out of address space to align up. 229 return nullptr; 230 } 231 232 char* aligned = align_up(p, alignment); 233 assert(aligned >= p, "sanity"); 234 assert(aligned != nullptr, "sanity"); 235 return aligned; 236 } 237 238 static bool shared_base_too_high(char* specified_base, char* aligned_base, size_t cds_max) { 239 // Caller should have checked if align_up_or_null( returns nullptr (comparing specified_base 240 // with nullptr is UB). 241 assert(aligned_base != nullptr, "sanity"); 242 assert(aligned_base >= specified_base, "sanity"); 243 244 if (max_uintx - uintx(aligned_base) < uintx(cds_max)) { 245 // Not enough address space to hold an archive of cds_max bytes from aligned_base. 246 return true; 247 } else { 248 return false; 249 } 250 } 251 252 static char* compute_shared_base(size_t cds_max) { 253 char* specified_base = (char*)SharedBaseAddress; 254 size_t alignment = MetaspaceShared::core_region_alignment(); 255 if (UseCompressedClassPointers) { 256 alignment = MAX2(alignment, Metaspace::reserve_alignment()); 257 } 258 259 if (SharedBaseAddress == 0) { 260 // Special meaning of -XX:SharedBaseAddress=0 -> Always map archive at os-selected address. 261 return specified_base; 262 } 263 264 char* aligned_base = align_up_or_null(specified_base, alignment); 265 266 if (aligned_base != specified_base) { 267 log_info(cds)("SharedBaseAddress (" INTPTR_FORMAT ") aligned up to " INTPTR_FORMAT, 268 p2i(specified_base), p2i(aligned_base)); 269 } 270 271 const char* err = nullptr; 272 if (aligned_base == nullptr) { 273 err = "too high"; 274 } else if (shared_base_too_high(specified_base, aligned_base, cds_max)) { 275 err = "too high"; 276 } else if (!shared_base_valid(aligned_base)) { 277 err = "invalid for this platform"; 278 } else { 279 return aligned_base; 280 } 281 282 // Arguments::default_SharedBaseAddress() is hard-coded in cds_globals.hpp. It must be carefully 283 // picked that (a) the align_up() below will always return a valid value; (b) none of 284 // the following asserts will fail. 285 log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT, 286 p2i((void*)SharedBaseAddress), err, 287 p2i((void*)Arguments::default_SharedBaseAddress())); 288 289 specified_base = (char*)Arguments::default_SharedBaseAddress(); 290 aligned_base = align_up(specified_base, alignment); 291 292 // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane. 293 assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity"); 294 assert(shared_base_valid(aligned_base), "Sanity"); 295 return aligned_base; 296 } 297 298 void MetaspaceShared::initialize_for_static_dump() { 299 assert(CDSConfig::is_dumping_static_archive(), "sanity"); 300 log_info(cds)("Core region alignment: %zu", core_region_alignment()); 301 // The max allowed size for CDS archive. We use this to limit SharedBaseAddress 302 // to avoid address space wrap around. 303 size_t cds_max; 304 const size_t reserve_alignment = core_region_alignment(); 305 306 #ifdef _LP64 307 const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1); 308 cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment); 309 #else 310 // We don't support archives larger than 256MB on 32-bit due to limited 311 // virtual address space. 312 cds_max = align_down(256*M, reserve_alignment); 313 #endif 314 315 _requested_base_address = compute_shared_base(cds_max); 316 SharedBaseAddress = (size_t)_requested_base_address; 317 318 size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M); 319 _symbol_rs = MemoryReserver::reserve(symbol_rs_size, 320 os::vm_allocation_granularity(), 321 os::vm_page_size(), 322 mtClassShared); 323 if (!_symbol_rs.is_reserved()) { 324 log_error(cds)("Unable to reserve memory for symbols: %zu bytes.", symbol_rs_size); 325 MetaspaceShared::unrecoverable_writing_error(); 326 } 327 _symbol_region.init(&_symbol_rs, &_symbol_vs); 328 } 329 330 // Called by universe_post_init() 331 void MetaspaceShared::post_initialize(TRAPS) { 332 if (CDSConfig::is_using_archive()) { 333 int size = FileMapInfo::get_number_of_shared_paths(); 334 if (size > 0) { 335 CDSProtectionDomain::allocate_shared_data_arrays(size, CHECK); 336 if (!CDSConfig::is_dumping_dynamic_archive()) { 337 FileMapInfo* info; 338 if (FileMapInfo::dynamic_info() == nullptr) { 339 info = FileMapInfo::current_info(); 340 } else { 341 info = FileMapInfo::dynamic_info(); 342 } 343 ClassLoaderExt::init_paths_start_index(info->app_class_paths_start_index()); 344 ClassLoaderExt::init_app_module_paths_start_index(info->app_module_paths_start_index()); 345 ClassLoaderExt::init_num_module_paths(info->header()->num_module_paths()); 346 } 347 } 348 } 349 } 350 351 // Extra java.lang.Strings to be added to the archive 352 static GrowableArrayCHeap<OopHandle, mtClassShared>* _extra_interned_strings = nullptr; 353 // Extra Symbols to be added to the archive 354 static GrowableArrayCHeap<Symbol*, mtClassShared>* _extra_symbols = nullptr; 355 // Methods managed by SystemDictionary::find_method_handle_intrinsic() to be added to the archive 356 static GrowableArray<Method*>* _pending_method_handle_intrinsics = nullptr; 357 358 void MetaspaceShared::read_extra_data(JavaThread* current, const char* filename) { 359 _extra_interned_strings = new GrowableArrayCHeap<OopHandle, mtClassShared>(10000); 360 _extra_symbols = new GrowableArrayCHeap<Symbol*, mtClassShared>(1000); 361 362 HashtableTextDump reader(filename); 363 reader.check_version("VERSION: 1.0"); 364 365 while (reader.remain() > 0) { 366 int utf8_length; 367 int prefix_type = reader.scan_prefix(&utf8_length); 368 ResourceMark rm(current); 369 if (utf8_length == 0x7fffffff) { 370 // buf_len will overflown 32-bit value. 371 log_error(cds)("string length too large: %d", utf8_length); 372 MetaspaceShared::unrecoverable_loading_error(); 373 } 374 int buf_len = utf8_length+1; 375 char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len); 376 reader.get_utf8(utf8_buffer, utf8_length); 377 utf8_buffer[utf8_length] = '\0'; 378 379 if (prefix_type == HashtableTextDump::SymbolPrefix) { 380 _extra_symbols->append(SymbolTable::new_permanent_symbol(utf8_buffer)); 381 } else{ 382 assert(prefix_type == HashtableTextDump::StringPrefix, "Sanity"); 383 ExceptionMark em(current); 384 JavaThread* THREAD = current; // For exception macros. 385 oop str = StringTable::intern(utf8_buffer, THREAD); 386 387 if (HAS_PENDING_EXCEPTION) { 388 log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d", 389 reader.last_line_no(), utf8_length); 390 CLEAR_PENDING_EXCEPTION; 391 } else { 392 #if INCLUDE_CDS_JAVA_HEAP 393 if (ArchiveHeapWriter::is_string_too_large_to_archive(str)) { 394 log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d", 395 reader.last_line_no(), utf8_length); 396 continue; 397 } 398 // Make sure this string is included in the dumped interned string table. 399 assert(str != nullptr, "must succeed"); 400 _extra_interned_strings->append(OopHandle(Universe::vm_global(), str)); 401 #endif 402 } 403 } 404 } 405 } 406 407 void MetaspaceShared::make_method_handle_intrinsics_shareable() { 408 for (int i = 0; i < _pending_method_handle_intrinsics->length(); i++) { 409 Method* m = ArchiveBuilder::current()->get_buffered_addr(_pending_method_handle_intrinsics->at(i)); 410 m->remove_unshareable_info(); 411 // Each method has its own constant pool (which is distinct from m->method_holder()->constants()); 412 m->constants()->remove_unshareable_info(); 413 } 414 } 415 416 void MetaspaceShared::write_method_handle_intrinsics() { 417 int len = _pending_method_handle_intrinsics->length(); 418 _archived_method_handle_intrinsics = ArchiveBuilder::new_ro_array<Method*>(len); 419 int word_size = _archived_method_handle_intrinsics->size(); 420 for (int i = 0; i < len; i++) { 421 Method* m = _pending_method_handle_intrinsics->at(i); 422 ArchiveBuilder::current()->write_pointer_in_buffer(_archived_method_handle_intrinsics->adr_at(i), m); 423 word_size += m->size() + m->constMethod()->size() + m->constants()->size(); 424 if (m->constants()->cache() != nullptr) { 425 word_size += m->constants()->cache()->size(); 426 } 427 } 428 log_info(cds)("Archived %d method handle intrinsics (%d bytes)", len, word_size * BytesPerWord); 429 } 430 431 // About "serialize" -- 432 // 433 // This is (probably a badly named) way to read/write a data stream of pointers and 434 // miscellaneous data from/to the shared archive file. The usual code looks like this: 435 // 436 // // These two global C++ variables are initialized during dump time. 437 // static int _archived_int; 438 // static MetaspaceObj* archived_ptr; 439 // 440 // void MyClass::serialize(SerializeClosure* soc) { 441 // soc->do_int(&_archived_int); 442 // soc->do_int(&_archived_ptr); 443 // } 444 // 445 // At dumptime, these two variables are stored into the CDS archive. 446 // At runtime, these two variables are loaded from the CDS archive. 447 // In addition, the pointer is relocated as necessary. 448 // 449 // Some of the xxx::serialize() functions may have side effects and assume that 450 // the archive is already mapped. For example, SymbolTable::serialize_shared_table_header() 451 // unconditionally makes the set of archived symbols available. Therefore, we put most 452 // of these xxx::serialize() functions inside MetaspaceShared::serialize(), which 453 // is called AFTER we made the decision to map the archive. 454 // 455 // However, some of the "serialized" data are used to decide whether an archive should 456 // be mapped or not (e.g., for checking if the -Djdk.module.main property is compatible 457 // with the archive). The xxx::serialize() functions for these data must be put inside 458 // MetaspaceShared::early_serialize(). Such functions must not produce side effects that 459 // assume we will always decides to map the archive. 460 461 void MetaspaceShared::early_serialize(SerializeClosure* soc) { 462 int tag = 0; 463 soc->do_tag(--tag); 464 CDS_JAVA_HEAP_ONLY(Modules::serialize_archived_module_info(soc);) 465 soc->do_tag(666); 466 } 467 468 void MetaspaceShared::serialize(SerializeClosure* soc) { 469 int tag = 0; 470 soc->do_tag(--tag); 471 472 // Verify the sizes of various metadata in the system. 473 soc->do_tag(sizeof(Method)); 474 soc->do_tag(sizeof(ConstMethod)); 475 soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE)); 476 soc->do_tag(sizeof(ConstantPool)); 477 soc->do_tag(sizeof(ConstantPoolCache)); 478 soc->do_tag(objArrayOopDesc::base_offset_in_bytes()); 479 soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE)); 480 soc->do_tag(sizeof(Symbol)); 481 482 // Need to do this first, as subsequent steps may call virtual functions 483 // in archived Metadata objects. 484 CppVtables::serialize(soc); 485 soc->do_tag(--tag); 486 487 // Dump/restore miscellaneous metadata. 488 JavaClasses::serialize_offsets(soc); 489 Universe::serialize(soc); 490 soc->do_tag(--tag); 491 492 // Dump/restore references to commonly used names and signatures. 493 vmSymbols::serialize(soc); 494 soc->do_tag(--tag); 495 496 // Dump/restore the symbol/string/subgraph_info tables 497 SymbolTable::serialize_shared_table_header(soc); 498 StringTable::serialize_shared_table_header(soc); 499 HeapShared::serialize_tables(soc); 500 SystemDictionaryShared::serialize_dictionary_headers(soc); 501 AOTLinkedClassBulkLoader::serialize(soc, true); 502 InstanceMirrorKlass::serialize_offsets(soc); 503 504 // Dump/restore well known classes (pointers) 505 SystemDictionaryShared::serialize_vm_classes(soc); 506 soc->do_tag(--tag); 507 508 CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);) 509 soc->do_ptr((void**)&_archived_method_handle_intrinsics); 510 511 LambdaFormInvokers::serialize(soc); 512 soc->do_tag(666); 513 } 514 515 static void rewrite_nofast_bytecode(const methodHandle& method) { 516 BytecodeStream bcs(method); 517 while (!bcs.is_last_bytecode()) { 518 Bytecodes::Code opcode = bcs.next(); 519 switch (opcode) { 520 case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break; 521 case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break; 522 case Bytecodes::_aload_0: *bcs.bcp() = Bytecodes::_nofast_aload_0; break; 523 case Bytecodes::_iload: { 524 if (!bcs.is_wide()) { 525 *bcs.bcp() = Bytecodes::_nofast_iload; 526 } 527 break; 528 } 529 default: break; 530 } 531 } 532 } 533 534 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified 535 // at run time by RewriteBytecodes/RewriteFrequentPairs 536 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time. 537 void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) { 538 for (int i = 0; i < ik->methods()->length(); i++) { 539 methodHandle m(thread, ik->methods()->at(i)); 540 if (ik->can_be_verified_at_dumptime() && ik->is_linked()) { 541 rewrite_nofast_bytecode(m); 542 } 543 Fingerprinter fp(m); 544 // The side effect of this call sets method's fingerprint field. 545 fp.fingerprint(); 546 } 547 } 548 549 class VM_PopulateDumpSharedSpace : public VM_Operation { 550 private: 551 ArchiveHeapInfo _heap_info; 552 FileMapInfo* _map_info; 553 StaticArchiveBuilder& _builder; 554 555 void dump_java_heap_objects(); 556 void dump_shared_symbol_table(GrowableArray<Symbol*>* symbols) { 557 log_info(cds)("Dumping symbol table ..."); 558 SymbolTable::write_to_archive(symbols); 559 } 560 char* dump_early_read_only_tables(); 561 char* dump_read_only_tables(); 562 563 public: 564 565 VM_PopulateDumpSharedSpace(StaticArchiveBuilder& b) : 566 VM_Operation(), _heap_info(), _map_info(nullptr), _builder(b) {} 567 568 bool skip_operation() const { return false; } 569 570 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; } 571 ArchiveHeapInfo* heap_info() { return &_heap_info; } 572 FileMapInfo* map_info() const { return _map_info; } 573 void doit(); // outline because gdb sucks 574 bool allow_nested_vm_operations() const { return true; } 575 }; // class VM_PopulateDumpSharedSpace 576 577 class StaticArchiveBuilder : public ArchiveBuilder { 578 public: 579 StaticArchiveBuilder() : ArchiveBuilder() {} 580 581 virtual void iterate_roots(MetaspaceClosure* it) { 582 FileMapInfo::metaspace_pointers_do(it); 583 AOTArtifactFinder::all_cached_classes_do(it); 584 SystemDictionaryShared::dumptime_classes_do(it); 585 Universe::metaspace_pointers_do(it); 586 vmSymbols::metaspace_pointers_do(it); 587 588 // The above code should find all the symbols that are referenced by the 589 // archived classes. We just need to add the extra symbols which 590 // may not be used by any of the archived classes -- these are usually 591 // symbols that we anticipate to be used at run time, so we can store 592 // them in the RO region, to be shared across multiple processes. 593 if (_extra_symbols != nullptr) { 594 for (int i = 0; i < _extra_symbols->length(); i++) { 595 it->push(_extra_symbols->adr_at(i)); 596 } 597 } 598 599 for (int i = 0; i < _pending_method_handle_intrinsics->length(); i++) { 600 it->push(_pending_method_handle_intrinsics->adr_at(i)); 601 } 602 } 603 }; 604 605 char* VM_PopulateDumpSharedSpace::dump_early_read_only_tables() { 606 ArchiveBuilder::OtherROAllocMark mark; 607 608 CDS_JAVA_HEAP_ONLY(Modules::dump_archived_module_info()); 609 610 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region(); 611 char* start = ro_region->top(); 612 WriteClosure wc(ro_region); 613 MetaspaceShared::early_serialize(&wc); 614 return start; 615 } 616 617 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() { 618 ArchiveBuilder::OtherROAllocMark mark; 619 620 SystemDictionaryShared::write_to_archive(); 621 AOTClassLinker::write_to_archive(); 622 MetaspaceShared::write_method_handle_intrinsics(); 623 624 // Write lambform lines into archive 625 LambdaFormInvokers::dump_static_archive_invokers(); 626 627 // Write the other data to the output array. 628 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region(); 629 char* start = ro_region->top(); 630 WriteClosure wc(ro_region); 631 MetaspaceShared::serialize(&wc); 632 633 return start; 634 } 635 636 void VM_PopulateDumpSharedSpace::doit() { 637 guarantee(!CDSConfig::is_using_archive(), "We should not be using an archive when we dump"); 638 639 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm); 640 641 _pending_method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared); 642 if (CDSConfig::is_dumping_aot_linked_classes()) { 643 // When dumping AOT-linked classes, some classes may have direct references to a method handle 644 // intrinsic. The easiest thing is to save all of them into the AOT cache. 645 SystemDictionary::get_all_method_handle_intrinsics(_pending_method_handle_intrinsics); 646 } 647 648 FileMapInfo::check_nonempty_dir_in_shared_path_table(); 649 650 NOT_PRODUCT(SystemDictionary::verify();) 651 652 // Block concurrent class unloading from changing the _dumptime_table 653 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag); 654 655 #if INCLUDE_CDS_JAVA_HEAP 656 if (CDSConfig::is_dumping_heap() && _extra_interned_strings != nullptr) { 657 for (int i = 0; i < _extra_interned_strings->length(); i ++) { 658 OopHandle string = _extra_interned_strings->at(i); 659 HeapShared::add_to_dumped_interned_strings(string.resolve()); 660 } 661 } 662 #endif 663 664 _builder.gather_source_objs(); 665 _builder.reserve_buffer(); 666 667 CppVtables::dumptime_init(&_builder); 668 669 _builder.sort_metadata_objs(); 670 _builder.dump_rw_metadata(); 671 _builder.dump_ro_metadata(); 672 _builder.relocate_metaspaceobj_embedded_pointers(); 673 674 log_info(cds)("Make classes shareable"); 675 _builder.make_klasses_shareable(); 676 MetaspaceShared::make_method_handle_intrinsics_shareable(); 677 678 dump_java_heap_objects(); 679 dump_shared_symbol_table(_builder.symbols()); 680 681 char* early_serialized_data = dump_early_read_only_tables(); 682 char* serialized_data = dump_read_only_tables(); 683 684 SystemDictionaryShared::adjust_lambda_proxy_class_dictionary(); 685 686 // The vtable clones contain addresses of the current process. 687 // We don't want to write these addresses into the archive. 688 CppVtables::zero_archived_vtables(); 689 690 // Write the archive file 691 const char* static_archive = CDSConfig::static_archive_path(); 692 assert(static_archive != nullptr, "SharedArchiveFile not set?"); 693 _map_info = new FileMapInfo(static_archive, true); 694 _map_info->populate_header(MetaspaceShared::core_region_alignment()); 695 _map_info->set_early_serialized_data(early_serialized_data); 696 _map_info->set_serialized_data(serialized_data); 697 _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base()); 698 } 699 700 class CollectCLDClosure : public CLDClosure { 701 GrowableArray<ClassLoaderData*> _loaded_cld; 702 GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive 703 Thread* _current_thread; 704 public: 705 CollectCLDClosure(Thread* thread) : _current_thread(thread) {} 706 ~CollectCLDClosure() { 707 for (int i = 0; i < _loaded_cld_handles.length(); i++) { 708 _loaded_cld_handles.at(i).release(Universe::vm_global()); 709 } 710 } 711 void do_cld(ClassLoaderData* cld) { 712 assert(cld->is_alive(), "must be"); 713 _loaded_cld.append(cld); 714 _loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder())); 715 } 716 717 int nof_cld() const { return _loaded_cld.length(); } 718 ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); } 719 }; 720 721 // Check if we can eagerly link this class at dump time, so we can avoid the 722 // runtime linking overhead (especially verification) 723 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) { 724 if (!ik->can_be_verified_at_dumptime()) { 725 // For old classes, try to leave them in the unlinked state, so 726 // we can still store them in the archive. They must be 727 // linked/verified at runtime. 728 return false; 729 } 730 if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) { 731 // Linking of unregistered classes at this stage may cause more 732 // classes to be resolved, resulting in calls to ClassLoader.loadClass() 733 // that may not be expected by custom class loaders. 734 // 735 // It's OK to do this for the built-in loaders as we know they can 736 // tolerate this. 737 return false; 738 } 739 return true; 740 } 741 742 bool MetaspaceShared::link_class_for_cds(InstanceKlass* ik, TRAPS) { 743 // Link the class to cause the bytecodes to be rewritten and the 744 // cpcache to be created. Class verification is done according 745 // to -Xverify setting. 746 bool res = MetaspaceShared::try_link_class(THREAD, ik); 747 AOTConstantPoolResolver::dumptime_resolve_constants(ik, CHECK_(false)); 748 return res; 749 } 750 751 void MetaspaceShared::link_shared_classes(bool jcmd_request, TRAPS) { 752 AOTClassLinker::initialize(); 753 754 if (!jcmd_request) { 755 LambdaFormInvokers::regenerate_holder_classes(CHECK); 756 } 757 758 // Collect all loaded ClassLoaderData. 759 CollectCLDClosure collect_cld(THREAD); 760 { 761 // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock. 762 // We cannot link the classes while holding this lock (or else we may run into deadlock). 763 // Therefore, we need to first collect all the CLDs, and then link their classes after 764 // releasing the lock. 765 MutexLocker lock(ClassLoaderDataGraph_lock); 766 ClassLoaderDataGraph::loaded_cld_do(&collect_cld); 767 } 768 769 while (true) { 770 bool has_linked = false; 771 for (int i = 0; i < collect_cld.nof_cld(); i++) { 772 ClassLoaderData* cld = collect_cld.cld_at(i); 773 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) { 774 if (klass->is_instance_klass()) { 775 InstanceKlass* ik = InstanceKlass::cast(klass); 776 if (may_be_eagerly_linked(ik)) { 777 has_linked |= link_class_for_cds(ik, CHECK); 778 } 779 } 780 } 781 } 782 783 if (!has_linked) { 784 break; 785 } 786 // Class linking includes verification which may load more classes. 787 // Keep scanning until we have linked no more classes. 788 } 789 } 790 791 void MetaspaceShared::prepare_for_dumping() { 792 assert(CDSConfig::is_dumping_archive(), "sanity"); 793 CDSConfig::check_unsupported_dumping_module_options(); 794 ClassLoader::initialize_shared_path(JavaThread::current()); 795 } 796 797 // Preload classes from a list, populate the shared spaces and dump to a 798 // file. 799 void MetaspaceShared::preload_and_dump(TRAPS) { 800 CDSConfig::DumperThreadMark dumper_thread_mark(THREAD); 801 ResourceMark rm(THREAD); 802 StaticArchiveBuilder builder; 803 preload_and_dump_impl(builder, THREAD); 804 if (HAS_PENDING_EXCEPTION) { 805 if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) { 806 log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = " 807 "%zuM", MaxHeapSize/M); 808 MetaspaceShared::writing_error(); 809 } else { 810 log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(), 811 java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION))); 812 MetaspaceShared::writing_error("Unexpected exception, use -Xlog:cds,exceptions=trace for detail"); 813 } 814 } 815 816 if (!CDSConfig::old_cds_flags_used()) { 817 // The JLI launcher only recognizes the "old" -Xshare:dump flag. 818 // When the new -XX:AOTMode=create flag is used, we can't return 819 // to the JLI launcher, as the launcher will fail when trying to 820 // run the main class, which is not what we want. 821 tty->print_cr("AOTCache creation is complete: %s", AOTCache); 822 vm_exit(0); 823 } 824 } 825 826 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64) 827 void MetaspaceShared::adjust_heap_sizes_for_dumping() { 828 if (!CDSConfig::is_dumping_heap() || UseCompressedOops) { 829 return; 830 } 831 // CDS heap dumping requires all string oops to have an offset 832 // from the heap bottom that can be encoded in 32-bit. 833 julong max_heap_size = (julong)(4 * G); 834 835 if (MinHeapSize > max_heap_size) { 836 log_debug(cds)("Setting MinHeapSize to 4G for CDS dumping, original size = %zuM", MinHeapSize/M); 837 FLAG_SET_ERGO(MinHeapSize, max_heap_size); 838 } 839 if (InitialHeapSize > max_heap_size) { 840 log_debug(cds)("Setting InitialHeapSize to 4G for CDS dumping, original size = %zuM", InitialHeapSize/M); 841 FLAG_SET_ERGO(InitialHeapSize, max_heap_size); 842 } 843 if (MaxHeapSize > max_heap_size) { 844 log_debug(cds)("Setting MaxHeapSize to 4G for CDS dumping, original size = %zuM", MaxHeapSize/M); 845 FLAG_SET_ERGO(MaxHeapSize, max_heap_size); 846 } 847 } 848 #endif // INCLUDE_CDS_JAVA_HEAP && _LP64 849 850 void MetaspaceShared::get_default_classlist(char* default_classlist, const size_t buf_size) { 851 // Construct the path to the class list (in jre/lib) 852 // Walk up two directories from the location of the VM and 853 // optionally tack on "lib" (depending on platform) 854 os::jvm_path(default_classlist, (jint)(buf_size)); 855 for (int i = 0; i < 3; i++) { 856 char *end = strrchr(default_classlist, *os::file_separator()); 857 if (end != nullptr) *end = '\0'; 858 } 859 size_t classlist_path_len = strlen(default_classlist); 860 if (classlist_path_len >= 3) { 861 if (strcmp(default_classlist + classlist_path_len - 3, "lib") != 0) { 862 if (classlist_path_len < buf_size - 4) { 863 jio_snprintf(default_classlist + classlist_path_len, 864 buf_size - classlist_path_len, 865 "%slib", os::file_separator()); 866 classlist_path_len += 4; 867 } 868 } 869 } 870 if (classlist_path_len < buf_size - 10) { 871 jio_snprintf(default_classlist + classlist_path_len, 872 buf_size - classlist_path_len, 873 "%sclasslist", os::file_separator()); 874 } 875 } 876 877 void MetaspaceShared::preload_classes(TRAPS) { 878 char default_classlist[JVM_MAXPATHLEN]; 879 const char* classlist_path; 880 881 get_default_classlist(default_classlist, sizeof(default_classlist)); 882 if (SharedClassListFile == nullptr) { 883 classlist_path = default_classlist; 884 } else { 885 classlist_path = SharedClassListFile; 886 } 887 888 log_info(cds)("Loading classes to share ..."); 889 ClassListParser::parse_classlist(classlist_path, 890 ClassListParser::_parse_all, CHECK); 891 if (ExtraSharedClassListFile) { 892 ClassListParser::parse_classlist(ExtraSharedClassListFile, 893 ClassListParser::_parse_all, CHECK); 894 } 895 if (classlist_path != default_classlist) { 896 struct stat statbuf; 897 if (os::stat(default_classlist, &statbuf) == 0) { 898 // File exists, let's use it. 899 ClassListParser::parse_classlist(default_classlist, 900 ClassListParser::_parse_lambda_forms_invokers_only, CHECK); 901 } 902 } 903 904 // Some classes are used at CDS runtime but are not loaded, and therefore archived, at 905 // dumptime. We can perform dummmy calls to these classes at dumptime to ensure they 906 // are archived. 907 exercise_runtime_cds_code(CHECK); 908 909 log_info(cds)("Loading classes to share: done."); 910 } 911 912 void MetaspaceShared::exercise_runtime_cds_code(TRAPS) { 913 // Exercise the manifest processing code 914 const char* dummy = "Manifest-Version: 1.0\n"; 915 CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK); 916 917 // Exercise FileSystem and URL code 918 CDSProtectionDomain::to_file_URL("dummy.jar", Handle(), CHECK); 919 } 920 921 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) { 922 preload_classes(CHECK); 923 924 if (SharedArchiveConfigFile) { 925 log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile); 926 read_extra_data(THREAD, SharedArchiveConfigFile); 927 log_info(cds)("Reading extra data: done."); 928 } 929 930 // Rewrite and link classes 931 log_info(cds)("Rewriting and linking classes ..."); 932 933 // Link any classes which got missed. This would happen if we have loaded classes that 934 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K 935 // fails verification, all other interfaces that were not specified in the classlist but 936 // are implemented by K are not verified. 937 link_shared_classes(false/*not from jcmd*/, CHECK); 938 log_info(cds)("Rewriting and linking classes: done"); 939 940 #if INCLUDE_CDS_JAVA_HEAP 941 if (CDSConfig::is_dumping_heap()) { 942 if (!HeapShared::is_archived_boot_layer_available(THREAD)) { 943 log_info(cds)("archivedBootLayer not available, disabling full module graph"); 944 CDSConfig::stop_dumping_full_module_graph(); 945 } 946 HeapShared::init_for_dumping(CHECK); 947 ArchiveHeapWriter::init(); 948 if (CDSConfig::is_dumping_full_module_graph()) { 949 HeapShared::reset_archived_object_states(CHECK); 950 } 951 952 if (CDSConfig::is_dumping_invokedynamic()) { 953 // This assert means that the MethodType and MethodTypeForm tables won't be 954 // updated concurrently when we are saving their contents into a side table. 955 assert(CDSConfig::allow_only_single_java_thread(), "Required"); 956 957 JavaValue result(T_VOID); 958 JavaCalls::call_static(&result, vmClasses::MethodType_klass(), 959 vmSymbols::createArchivedObjects(), 960 vmSymbols::void_method_signature(), 961 CHECK); 962 963 // java.lang.Class::reflectionFactory cannot be archived yet. We set this field 964 // to null, and it will be initialized again at runtime. 965 log_debug(cds)("Resetting Class::reflectionFactory"); 966 TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates"); 967 Symbol* method_sig = vmSymbols::void_method_signature(); 968 JavaCalls::call_static(&result, vmClasses::Class_klass(), 969 method_name, method_sig, CHECK); 970 971 // Perhaps there is a way to avoid hard-coding these names here. 972 // See discussion in JDK-8342481. 973 } 974 975 // Do this at the very end, when no Java code will be executed. Otherwise 976 // some new strings may be added to the intern table. 977 StringTable::allocate_shared_strings_array(CHECK); 978 } else { 979 log_info(cds)("Not dumping heap, reset CDSConfig::_is_using_optimized_module_handling"); 980 CDSConfig::stop_using_optimized_module_handling(); 981 } 982 #endif 983 984 VM_PopulateDumpSharedSpace op(builder); 985 VMThread::execute(&op); 986 987 if (!write_static_archive(&builder, op.map_info(), op.heap_info())) { 988 THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping"); 989 } 990 } 991 992 bool MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) { 993 // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address() 994 // without runtime relocation. 995 builder->relocate_to_requested(); 996 997 map_info->open_for_write(); 998 if (!map_info->is_open()) { 999 return false; 1000 } 1001 builder->write_archive(map_info, heap_info); 1002 1003 if (AllowArchivingWithJavaAgent) { 1004 log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used " 1005 "for testing purposes only and should not be used in a production environment"); 1006 } 1007 return true; 1008 } 1009 1010 // Returns true if the class's status has changed. 1011 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) { 1012 ExceptionMark em(current); 1013 JavaThread* THREAD = current; // For exception macros. 1014 assert(CDSConfig::is_dumping_archive(), "sanity"); 1015 if (!ik->is_shared() && ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() && 1016 !SystemDictionaryShared::has_class_failed_verification(ik)) { 1017 bool saved = BytecodeVerificationLocal; 1018 if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) { 1019 // The verification decision is based on BytecodeVerificationRemote 1020 // for non-system classes. Since we are using the null classloader 1021 // to load non-system classes for customized class loaders during dumping, 1022 // we need to temporarily change BytecodeVerificationLocal to be the same as 1023 // BytecodeVerificationRemote. Note this can cause the parent system 1024 // classes also being verified. The extra overhead is acceptable during 1025 // dumping. 1026 BytecodeVerificationLocal = BytecodeVerificationRemote; 1027 } 1028 ik->link_class(THREAD); 1029 if (HAS_PENDING_EXCEPTION) { 1030 ResourceMark rm(THREAD); 1031 log_warning(cds)("Preload Warning: Verification failed for %s", 1032 ik->external_name()); 1033 CLEAR_PENDING_EXCEPTION; 1034 SystemDictionaryShared::set_class_has_failed_verification(ik); 1035 } else { 1036 assert(!SystemDictionaryShared::has_class_failed_verification(ik), "sanity"); 1037 ik->compute_has_loops_flag_for_methods(); 1038 } 1039 BytecodeVerificationLocal = saved; 1040 return true; 1041 } else { 1042 return false; 1043 } 1044 } 1045 1046 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() { 1047 if (CDSConfig::is_dumping_heap()) { 1048 HeapShared::write_heap(&_heap_info); 1049 } else { 1050 CDSConfig::log_reasons_for_not_dumping_heap(); 1051 } 1052 } 1053 1054 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) { 1055 assert(base <= static_top && static_top <= top, "must be"); 1056 _shared_metaspace_static_top = static_top; 1057 MetaspaceObj::set_shared_metaspace_range(base, top); 1058 } 1059 1060 bool MetaspaceShared::is_shared_dynamic(void* p) { 1061 if ((p < MetaspaceObj::shared_metaspace_top()) && 1062 (p >= _shared_metaspace_static_top)) { 1063 return true; 1064 } else { 1065 return false; 1066 } 1067 } 1068 1069 bool MetaspaceShared::is_shared_static(void* p) { 1070 if (is_in_shared_metaspace(p) && !is_shared_dynamic(p)) { 1071 return true; 1072 } else { 1073 return false; 1074 } 1075 } 1076 1077 // This function is called when the JVM is unable to load the specified archive(s) due to one 1078 // of the following conditions. 1079 // - There's an error that indicates that the archive(s) files were corrupt or otherwise damaged. 1080 // - When -XX:+RequireSharedSpaces is specified, AND the JVM cannot load the archive(s) due 1081 // to version or classpath mismatch. 1082 void MetaspaceShared::unrecoverable_loading_error(const char* message) { 1083 log_error(cds)("An error has occurred while processing the shared archive file."); 1084 if (message != nullptr) { 1085 log_error(cds)("%s", message); 1086 } 1087 vm_exit_during_initialization("Unable to use shared archive.", nullptr); 1088 } 1089 1090 // This function is called when the JVM is unable to write the specified CDS archive due to an 1091 // unrecoverable error. 1092 void MetaspaceShared::unrecoverable_writing_error(const char* message) { 1093 writing_error(message); 1094 vm_direct_exit(1); 1095 } 1096 1097 // This function is called when the JVM is unable to write the specified CDS archive due to a 1098 // an error. The error will be propagated 1099 void MetaspaceShared::writing_error(const char* message) { 1100 log_error(cds)("An error has occurred while writing the shared archive file."); 1101 if (message != nullptr) { 1102 log_error(cds)("%s", message); 1103 } 1104 } 1105 1106 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() { 1107 assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled"); 1108 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE; 1109 1110 FileMapInfo* static_mapinfo = open_static_archive(); 1111 FileMapInfo* dynamic_mapinfo = nullptr; 1112 1113 if (static_mapinfo != nullptr) { 1114 log_info(cds)("Core region alignment: %zu", static_mapinfo->core_region_alignment()); 1115 dynamic_mapinfo = open_dynamic_archive(); 1116 1117 // First try to map at the requested address 1118 result = map_archives(static_mapinfo, dynamic_mapinfo, true); 1119 if (result == MAP_ARCHIVE_MMAP_FAILURE) { 1120 // Mapping has failed (probably due to ASLR). Let's map at an address chosen 1121 // by the OS. 1122 log_info(cds)("Try to map archive(s) at an alternative address"); 1123 result = map_archives(static_mapinfo, dynamic_mapinfo, false); 1124 } 1125 } 1126 1127 if (result == MAP_ARCHIVE_SUCCESS) { 1128 bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped()); 1129 char* cds_base = static_mapinfo->mapped_base(); 1130 char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end(); 1131 // Register CDS memory region with LSan. 1132 LSAN_REGISTER_ROOT_REGION(cds_base, cds_end - cds_base); 1133 set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end); 1134 _relocation_delta = static_mapinfo->relocation_delta(); 1135 _requested_base_address = static_mapinfo->requested_base_address(); 1136 if (dynamic_mapped) { 1137 FileMapInfo::set_shared_path_table(dynamic_mapinfo); 1138 // turn AutoCreateSharedArchive off if successfully mapped 1139 AutoCreateSharedArchive = false; 1140 } else { 1141 FileMapInfo::set_shared_path_table(static_mapinfo); 1142 } 1143 } else { 1144 set_shared_metaspace_range(nullptr, nullptr, nullptr); 1145 if (CDSConfig::is_dumping_dynamic_archive()) { 1146 log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info."); 1147 } 1148 UseSharedSpaces = false; 1149 // The base archive cannot be mapped. We cannot dump the dynamic shared archive. 1150 AutoCreateSharedArchive = false; 1151 CDSConfig::disable_dumping_dynamic_archive(); 1152 log_info(cds)("Unable to map shared spaces"); 1153 if (PrintSharedArchiveAndExit) { 1154 MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive."); 1155 } else if (RequireSharedSpaces) { 1156 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces"); 1157 } 1158 } 1159 1160 // If mapping failed and -XShare:on, the vm should exit 1161 bool has_failed = false; 1162 if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) { 1163 has_failed = true; 1164 delete static_mapinfo; 1165 } 1166 if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) { 1167 has_failed = true; 1168 delete dynamic_mapinfo; 1169 } 1170 if (RequireSharedSpaces && has_failed) { 1171 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces"); 1172 } 1173 } 1174 1175 FileMapInfo* MetaspaceShared::open_static_archive() { 1176 const char* static_archive = CDSConfig::static_archive_path(); 1177 assert(static_archive != nullptr, "sanity"); 1178 FileMapInfo* mapinfo = new FileMapInfo(static_archive, true); 1179 if (!mapinfo->initialize()) { 1180 delete(mapinfo); 1181 return nullptr; 1182 } 1183 return mapinfo; 1184 } 1185 1186 FileMapInfo* MetaspaceShared::open_dynamic_archive() { 1187 if (CDSConfig::is_dumping_dynamic_archive()) { 1188 return nullptr; 1189 } 1190 const char* dynamic_archive = CDSConfig::dynamic_archive_path(); 1191 if (dynamic_archive == nullptr) { 1192 return nullptr; 1193 } 1194 1195 FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false); 1196 if (!mapinfo->initialize()) { 1197 delete(mapinfo); 1198 if (RequireSharedSpaces) { 1199 MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive"); 1200 } 1201 return nullptr; 1202 } 1203 return mapinfo; 1204 } 1205 1206 // use_requested_addr: 1207 // true = map at FileMapHeader::_requested_base_address 1208 // false = map at an alternative address picked by OS. 1209 MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo, 1210 bool use_requested_addr) { 1211 if (use_requested_addr && static_mapinfo->requested_base_address() == nullptr) { 1212 log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address."); 1213 return MAP_ARCHIVE_MMAP_FAILURE; 1214 } 1215 1216 PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) { 1217 // For product build only -- this is for benchmarking the cost of doing relocation. 1218 // For debug builds, the check is done below, after reserving the space, for better test coverage 1219 // (see comment below). 1220 log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address"); 1221 return MAP_ARCHIVE_MMAP_FAILURE; 1222 }); 1223 1224 if (ArchiveRelocationMode == 2 && !use_requested_addr) { 1225 log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address"); 1226 return MAP_ARCHIVE_MMAP_FAILURE; 1227 }; 1228 1229 if (dynamic_mapinfo != nullptr) { 1230 // Ensure that the OS won't be able to allocate new memory spaces between the two 1231 // archives, or else it would mess up the simple comparison in MetaspaceObj::is_shared(). 1232 assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap"); 1233 } 1234 1235 ReservedSpace total_space_rs, archive_space_rs, class_space_rs; 1236 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE; 1237 char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo, 1238 dynamic_mapinfo, 1239 use_requested_addr, 1240 total_space_rs, 1241 archive_space_rs, 1242 class_space_rs); 1243 if (mapped_base_address == nullptr) { 1244 result = MAP_ARCHIVE_MMAP_FAILURE; 1245 log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr); 1246 } else { 1247 1248 #ifdef ASSERT 1249 // Some sanity checks after reserving address spaces for archives 1250 // and class space. 1251 assert(archive_space_rs.is_reserved(), "Sanity"); 1252 if (Metaspace::using_class_space()) { 1253 // Class space must closely follow the archive space. Both spaces 1254 // must be aligned correctly. 1255 assert(class_space_rs.is_reserved(), 1256 "A class space should have been reserved"); 1257 assert(class_space_rs.base() >= archive_space_rs.end(), 1258 "class space should follow the cds archive space"); 1259 assert(is_aligned(archive_space_rs.base(), 1260 core_region_alignment()), 1261 "Archive space misaligned"); 1262 assert(is_aligned(class_space_rs.base(), 1263 Metaspace::reserve_alignment()), 1264 "class space misaligned"); 1265 } 1266 #endif // ASSERT 1267 1268 log_info(cds)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (%zu) bytes", 1269 p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size()); 1270 log_info(cds)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (%zu) bytes", 1271 p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size()); 1272 1273 if (MetaspaceShared::use_windows_memory_mapping()) { 1274 // We have now reserved address space for the archives, and will map in 1275 // the archive files into this space. 1276 // 1277 // Special handling for Windows: on Windows we cannot map a file view 1278 // into an existing memory mapping. So, we unmap the address range we 1279 // just reserved again, which will make it available for mapping the 1280 // archives. 1281 // Reserving this range has not been for naught however since it makes 1282 // us reasonably sure the address range is available. 1283 // 1284 // But still it may fail, since between unmapping the range and mapping 1285 // in the archive someone else may grab the address space. Therefore 1286 // there is a fallback in FileMap::map_region() where we just read in 1287 // the archive files sequentially instead of mapping it in. We couple 1288 // this with use_requested_addr, since we're going to patch all the 1289 // pointers anyway so there's no benefit to mmap. 1290 if (use_requested_addr) { 1291 assert(!total_space_rs.is_reserved(), "Should not be reserved for Windows"); 1292 log_info(cds)("Windows mmap workaround: releasing archive space."); 1293 MemoryReserver::release(archive_space_rs); 1294 // Mark as not reserved 1295 archive_space_rs = {}; 1296 } 1297 } 1298 MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs); 1299 MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ? 1300 map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE; 1301 1302 DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) { 1303 // This is for simulating mmap failures at the requested address. In 1304 // debug builds, we do it here (after all archives have possibly been 1305 // mapped), so we can thoroughly test the code for failure handling 1306 // (releasing all allocated resource, etc). 1307 log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address"); 1308 if (static_result == MAP_ARCHIVE_SUCCESS) { 1309 static_result = MAP_ARCHIVE_MMAP_FAILURE; 1310 } 1311 if (dynamic_result == MAP_ARCHIVE_SUCCESS) { 1312 dynamic_result = MAP_ARCHIVE_MMAP_FAILURE; 1313 } 1314 }); 1315 1316 if (static_result == MAP_ARCHIVE_SUCCESS) { 1317 if (dynamic_result == MAP_ARCHIVE_SUCCESS) { 1318 result = MAP_ARCHIVE_SUCCESS; 1319 } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) { 1320 assert(dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped(), "must have failed"); 1321 // No need to retry mapping the dynamic archive again, as it will never succeed 1322 // (bad file, etc) -- just keep the base archive. 1323 log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s", 1324 dynamic_mapinfo->full_path()); 1325 result = MAP_ARCHIVE_SUCCESS; 1326 // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no 1327 // easy API to do that right now. 1328 } else { 1329 result = MAP_ARCHIVE_MMAP_FAILURE; 1330 } 1331 } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) { 1332 result = MAP_ARCHIVE_OTHER_FAILURE; 1333 } else { 1334 result = MAP_ARCHIVE_MMAP_FAILURE; 1335 } 1336 } 1337 1338 if (result == MAP_ARCHIVE_SUCCESS) { 1339 SharedBaseAddress = (size_t)mapped_base_address; 1340 #ifdef _LP64 1341 if (Metaspace::using_class_space()) { 1342 // Set up ccs in metaspace. 1343 Metaspace::initialize_class_space(class_space_rs); 1344 1345 // Set up compressed Klass pointer encoding: the encoding range must 1346 // cover both archive and class space. 1347 address cds_base = (address)static_mapinfo->mapped_base(); 1348 address ccs_end = (address)class_space_rs.end(); 1349 assert(ccs_end > cds_base, "Sanity check"); 1350 if (INCLUDE_CDS_JAVA_HEAP || UseCompactObjectHeaders) { 1351 // The CDS archive may contain narrow Klass IDs that were precomputed at archive generation time: 1352 // - every archived java object header (only if INCLUDE_CDS_JAVA_HEAP) 1353 // - every archived Klass' prototype (only if +UseCompactObjectHeaders) 1354 // 1355 // In order for those IDs to still be valid, we need to dictate base and shift: base should be the 1356 // mapping start, shift the shift used at archive generation time. 1357 address precomputed_narrow_klass_base = cds_base; 1358 const int precomputed_narrow_klass_shift = ArchiveBuilder::precomputed_narrow_klass_shift(); 1359 CompressedKlassPointers::initialize_for_given_encoding( 1360 cds_base, ccs_end - cds_base, // Klass range 1361 precomputed_narrow_klass_base, precomputed_narrow_klass_shift // precomputed encoding, see ArchiveBuilder 1362 ); 1363 } else { 1364 // Let JVM freely chose encoding base and shift 1365 CompressedKlassPointers::initialize ( 1366 cds_base, ccs_end - cds_base // Klass range 1367 ); 1368 } 1369 // map_or_load_heap_region() compares the current narrow oop and klass encodings 1370 // with the archived ones, so it must be done after all encodings are determined. 1371 static_mapinfo->map_or_load_heap_region(); 1372 } 1373 #endif // _LP64 1374 log_info(cds)("initial optimized module handling: %s", CDSConfig::is_using_optimized_module_handling() ? "enabled" : "disabled"); 1375 log_info(cds)("initial full module graph: %s", CDSConfig::is_using_full_module_graph() ? "enabled" : "disabled"); 1376 } else { 1377 unmap_archive(static_mapinfo); 1378 unmap_archive(dynamic_mapinfo); 1379 release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs); 1380 } 1381 1382 return result; 1383 } 1384 1385 1386 // This will reserve two address spaces suitable to house Klass structures, one 1387 // for the cds archives (static archive and optionally dynamic archive) and 1388 // optionally one move for ccs. 1389 // 1390 // Since both spaces must fall within the compressed class pointer encoding 1391 // range, they are allocated close to each other. 1392 // 1393 // Space for archives will be reserved first, followed by a potential gap, 1394 // followed by the space for ccs: 1395 // 1396 // +-- Base address A B End 1397 // | | | | 1398 // v v v v 1399 // +-------------+--------------+ +----------------------+ 1400 // | static arc | [dyn. arch] | [gap] | compr. class space | 1401 // +-------------+--------------+ +----------------------+ 1402 // 1403 // (The gap may result from different alignment requirements between metaspace 1404 // and CDS) 1405 // 1406 // If UseCompressedClassPointers is disabled, only one address space will be 1407 // reserved: 1408 // 1409 // +-- Base address End 1410 // | | 1411 // v v 1412 // +-------------+--------------+ 1413 // | static arc | [dyn. arch] | 1414 // +-------------+--------------+ 1415 // 1416 // Base address: If use_archive_base_addr address is true, the Base address is 1417 // determined by the address stored in the static archive. If 1418 // use_archive_base_addr address is false, this base address is determined 1419 // by the platform. 1420 // 1421 // If UseCompressedClassPointers=1, the range encompassing both spaces will be 1422 // suitable to en/decode narrow Klass pointers: the base will be valid for 1423 // encoding, the range [Base, End) and not surpass the max. range for that encoding. 1424 // 1425 // Return: 1426 // 1427 // - On success: 1428 // - total_space_rs will be reserved as whole for archive_space_rs and 1429 // class_space_rs if UseCompressedClassPointers is true. 1430 // On Windows, try reserve archive_space_rs and class_space_rs 1431 // separately first if use_archive_base_addr is true. 1432 // - archive_space_rs will be reserved and large enough to host static and 1433 // if needed dynamic archive: [Base, A). 1434 // archive_space_rs.base and size will be aligned to CDS reserve 1435 // granularity. 1436 // - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will 1437 // be reserved. Its start address will be aligned to metaspace reserve 1438 // alignment, which may differ from CDS alignment. It will follow the cds 1439 // archive space, close enough such that narrow class pointer encoding 1440 // covers both spaces. 1441 // If UseCompressedClassPointers=0, class_space_rs remains unreserved. 1442 // - On error: null is returned and the spaces remain unreserved. 1443 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo, 1444 FileMapInfo* dynamic_mapinfo, 1445 bool use_archive_base_addr, 1446 ReservedSpace& total_space_rs, 1447 ReservedSpace& archive_space_rs, 1448 ReservedSpace& class_space_rs) { 1449 1450 address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : nullptr); 1451 const size_t archive_space_alignment = core_region_alignment(); 1452 1453 // Size and requested location of the archive_space_rs (for both static and dynamic archives) 1454 assert(static_mapinfo->mapping_base_offset() == 0, "Must be"); 1455 size_t archive_end_offset = (dynamic_mapinfo == nullptr) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset(); 1456 size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment); 1457 1458 if (!Metaspace::using_class_space()) { 1459 // Get the simple case out of the way first: 1460 // no compressed class space, simple allocation. 1461 1462 // When running without class space, requested archive base should be aligned to cds core alignment. 1463 assert(is_aligned(base_address, archive_space_alignment), 1464 "Archive base address unaligned: " PTR_FORMAT ", needs alignment: %zu.", 1465 p2i(base_address), archive_space_alignment); 1466 1467 archive_space_rs = MemoryReserver::reserve((char*)base_address, 1468 archive_space_size, 1469 archive_space_alignment, 1470 os::vm_page_size()); 1471 if (archive_space_rs.is_reserved()) { 1472 assert(base_address == nullptr || 1473 (address)archive_space_rs.base() == base_address, "Sanity"); 1474 // Register archive space with NMT. 1475 MemTracker::record_virtual_memory_tag(archive_space_rs.base(), mtClassShared); 1476 return archive_space_rs.base(); 1477 } 1478 return nullptr; 1479 } 1480 1481 #ifdef _LP64 1482 1483 // Complex case: two spaces adjacent to each other, both to be addressable 1484 // with narrow class pointers. 1485 // We reserve the whole range spanning both spaces, then split that range up. 1486 1487 const size_t class_space_alignment = Metaspace::reserve_alignment(); 1488 1489 // When running with class space, requested archive base must satisfy both cds core alignment 1490 // and class space alignment. 1491 const size_t base_address_alignment = MAX2(class_space_alignment, archive_space_alignment); 1492 assert(is_aligned(base_address, base_address_alignment), 1493 "Archive base address unaligned: " PTR_FORMAT ", needs alignment: %zu.", 1494 p2i(base_address), base_address_alignment); 1495 1496 size_t class_space_size = CompressedClassSpaceSize; 1497 assert(CompressedClassSpaceSize > 0 && 1498 is_aligned(CompressedClassSpaceSize, class_space_alignment), 1499 "CompressedClassSpaceSize malformed: %zu", CompressedClassSpaceSize); 1500 1501 const size_t ccs_begin_offset = align_up(archive_space_size, class_space_alignment); 1502 const size_t gap_size = ccs_begin_offset - archive_space_size; 1503 1504 // Reduce class space size if it would not fit into the Klass encoding range 1505 constexpr size_t max_encoding_range_size = 4 * G; 1506 guarantee(archive_space_size < max_encoding_range_size - class_space_alignment, "Archive too large"); 1507 if ((archive_space_size + gap_size + class_space_size) > max_encoding_range_size) { 1508 class_space_size = align_down(max_encoding_range_size - archive_space_size - gap_size, class_space_alignment); 1509 log_info(metaspace)("CDS initialization: reducing class space size from %zu to %zu", 1510 CompressedClassSpaceSize, class_space_size); 1511 FLAG_SET_ERGO(CompressedClassSpaceSize, class_space_size); 1512 } 1513 1514 const size_t total_range_size = 1515 archive_space_size + gap_size + class_space_size; 1516 1517 // Test that class space base address plus shift can be decoded by aarch64, when restored. 1518 const int precomputed_narrow_klass_shift = ArchiveBuilder::precomputed_narrow_klass_shift(); 1519 if (!CompressedKlassPointers::check_klass_decode_mode(base_address, precomputed_narrow_klass_shift, 1520 total_range_size)) { 1521 log_info(cds)("CDS initialization: Cannot use SharedBaseAddress " PTR_FORMAT " with precomputed shift %d.", 1522 p2i(base_address), precomputed_narrow_klass_shift); 1523 use_archive_base_addr = false; 1524 } 1525 1526 assert(total_range_size > ccs_begin_offset, "must be"); 1527 if (use_windows_memory_mapping() && use_archive_base_addr) { 1528 if (base_address != nullptr) { 1529 // On Windows, we cannot safely split a reserved memory space into two (see JDK-8255917). 1530 // Hence, we optimistically reserve archive space and class space side-by-side. We only 1531 // do this for use_archive_base_addr=true since for use_archive_base_addr=false case 1532 // caller will not split the combined space for mapping, instead read the archive data 1533 // via sequential file IO. 1534 address ccs_base = base_address + archive_space_size + gap_size; 1535 archive_space_rs = MemoryReserver::reserve((char*)base_address, 1536 archive_space_size, 1537 archive_space_alignment, 1538 os::vm_page_size()); 1539 class_space_rs = MemoryReserver::reserve((char*)ccs_base, 1540 class_space_size, 1541 class_space_alignment, 1542 os::vm_page_size()); 1543 } 1544 if (!archive_space_rs.is_reserved() || !class_space_rs.is_reserved()) { 1545 release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs); 1546 return nullptr; 1547 } 1548 // NMT: fix up the space tags 1549 MemTracker::record_virtual_memory_tag(archive_space_rs.base(), mtClassShared); 1550 MemTracker::record_virtual_memory_tag(class_space_rs.base(), mtClass); 1551 } else { 1552 if (use_archive_base_addr && base_address != nullptr) { 1553 total_space_rs = MemoryReserver::reserve((char*) base_address, 1554 total_range_size, 1555 base_address_alignment, 1556 os::vm_page_size()); 1557 } else { 1558 // We did not manage to reserve at the preferred address, or were instructed to relocate. In that 1559 // case we reserve wherever possible, but the start address needs to be encodable as narrow Klass 1560 // encoding base since the archived heap objects contain narrow Klass IDs pre-calculated toward the start 1561 // of the shared Metaspace. That prevents us from using zero-based encoding and therefore we won't 1562 // try allocating in low-address regions. 1563 total_space_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size, false /* optimize_for_zero_base */); 1564 } 1565 1566 if (!total_space_rs.is_reserved()) { 1567 return nullptr; 1568 } 1569 1570 // Paranoid checks: 1571 assert(!use_archive_base_addr || (address)total_space_rs.base() == base_address, 1572 "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_space_rs.base())); 1573 assert(is_aligned(total_space_rs.base(), base_address_alignment), "Sanity"); 1574 assert(total_space_rs.size() == total_range_size, "Sanity"); 1575 1576 // Now split up the space into ccs and cds archive. For simplicity, just leave 1577 // the gap reserved at the end of the archive space. Do not do real splitting. 1578 archive_space_rs = total_space_rs.first_part(ccs_begin_offset, 1579 (size_t)archive_space_alignment); 1580 class_space_rs = total_space_rs.last_part(ccs_begin_offset); 1581 MemTracker::record_virtual_memory_split_reserved(total_space_rs.base(), total_space_rs.size(), 1582 ccs_begin_offset, mtClassShared, mtClass); 1583 } 1584 assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity"); 1585 assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity"); 1586 assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity"); 1587 assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity"); 1588 1589 1590 return archive_space_rs.base(); 1591 1592 #else 1593 ShouldNotReachHere(); 1594 return nullptr; 1595 #endif 1596 1597 } 1598 1599 void MetaspaceShared::release_reserved_spaces(ReservedSpace& total_space_rs, 1600 ReservedSpace& archive_space_rs, 1601 ReservedSpace& class_space_rs) { 1602 if (total_space_rs.is_reserved()) { 1603 log_debug(cds)("Released shared space (archive + class) " INTPTR_FORMAT, p2i(total_space_rs.base())); 1604 MemoryReserver::release(total_space_rs); 1605 total_space_rs = {}; 1606 } else { 1607 if (archive_space_rs.is_reserved()) { 1608 log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base())); 1609 MemoryReserver::release(archive_space_rs); 1610 archive_space_rs = {}; 1611 } 1612 if (class_space_rs.is_reserved()) { 1613 log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base())); 1614 MemoryReserver::release(class_space_rs); 1615 class_space_rs = {}; 1616 } 1617 } 1618 } 1619 1620 static int archive_regions[] = { MetaspaceShared::rw, MetaspaceShared::ro }; 1621 static int archive_regions_count = 2; 1622 1623 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) { 1624 assert(CDSConfig::is_using_archive(), "must be runtime"); 1625 if (mapinfo == nullptr) { 1626 return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded. 1627 } 1628 1629 mapinfo->set_is_mapped(false); 1630 if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) { 1631 log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: %zu" 1632 " actual: %zu", mapinfo->core_region_alignment(), core_region_alignment()); 1633 return MAP_ARCHIVE_OTHER_FAILURE; 1634 } 1635 1636 MapArchiveResult result = 1637 mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs); 1638 1639 if (result != MAP_ARCHIVE_SUCCESS) { 1640 unmap_archive(mapinfo); 1641 return result; 1642 } 1643 1644 if (!mapinfo->validate_shared_path_table()) { 1645 unmap_archive(mapinfo); 1646 return MAP_ARCHIVE_OTHER_FAILURE; 1647 } 1648 1649 if (mapinfo->is_static()) { 1650 // Currently, only static archive uses early serialized data. 1651 char* buffer = mapinfo->early_serialized_data(); 1652 intptr_t* array = (intptr_t*)buffer; 1653 ReadClosure rc(&array, (intptr_t)mapped_base_address); 1654 early_serialize(&rc); 1655 } 1656 1657 if (!mapinfo->validate_aot_class_linking()) { 1658 unmap_archive(mapinfo); 1659 return MAP_ARCHIVE_OTHER_FAILURE; 1660 } 1661 1662 mapinfo->set_is_mapped(true); 1663 return MAP_ARCHIVE_SUCCESS; 1664 } 1665 1666 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) { 1667 assert(CDSConfig::is_using_archive(), "must be runtime"); 1668 if (mapinfo != nullptr) { 1669 mapinfo->unmap_regions(archive_regions, archive_regions_count); 1670 mapinfo->unmap_region(MetaspaceShared::bm); 1671 mapinfo->set_is_mapped(false); 1672 } 1673 } 1674 1675 // For -XX:PrintSharedArchiveAndExit 1676 class CountSharedSymbols : public SymbolClosure { 1677 private: 1678 int _count; 1679 public: 1680 CountSharedSymbols() : _count(0) {} 1681 void do_symbol(Symbol** sym) { 1682 _count++; 1683 } 1684 int total() { return _count; } 1685 1686 }; 1687 1688 // Read the miscellaneous data from the shared file, and 1689 // serialize it out to its various destinations. 1690 1691 void MetaspaceShared::initialize_shared_spaces() { 1692 FileMapInfo *static_mapinfo = FileMapInfo::current_info(); 1693 1694 // Verify various attributes of the archive, plus initialize the 1695 // shared string/symbol tables. 1696 char* buffer = static_mapinfo->serialized_data(); 1697 intptr_t* array = (intptr_t*)buffer; 1698 ReadClosure rc(&array, (intptr_t)SharedBaseAddress); 1699 serialize(&rc); 1700 1701 // Finish up archived heap initialization. These must be 1702 // done after ReadClosure. 1703 static_mapinfo->patch_heap_embedded_pointers(); 1704 ArchiveHeapLoader::finish_initialization(); 1705 Universe::load_archived_object_instances(); 1706 1707 // Close the mapinfo file 1708 static_mapinfo->close(); 1709 1710 static_mapinfo->unmap_region(MetaspaceShared::bm); 1711 1712 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info(); 1713 if (dynamic_mapinfo != nullptr) { 1714 intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data(); 1715 ReadClosure rc(&buffer, (intptr_t)SharedBaseAddress); 1716 ArchiveBuilder::serialize_dynamic_archivable_items(&rc); 1717 DynamicArchive::setup_array_klasses(); 1718 dynamic_mapinfo->close(); 1719 dynamic_mapinfo->unmap_region(MetaspaceShared::bm); 1720 } 1721 1722 LogStreamHandle(Info, cds) lsh; 1723 if (lsh.is_enabled()) { 1724 lsh.print("Using AOT-linked classes: %s (static archive: %s aot-linked classes", 1725 BOOL_TO_STR(CDSConfig::is_using_aot_linked_classes()), 1726 static_mapinfo->header()->has_aot_linked_classes() ? "has" : "no"); 1727 if (dynamic_mapinfo != nullptr) { 1728 lsh.print(", dynamic archive: %s aot-linked classes", 1729 dynamic_mapinfo->header()->has_aot_linked_classes() ? "has" : "no"); 1730 } 1731 lsh.print_cr(")"); 1732 } 1733 1734 // Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump 1735 if (CDSConfig::is_dumping_dynamic_archive()) { 1736 // Read stored LF format lines stored in static archive 1737 LambdaFormInvokers::read_static_archive_invokers(); 1738 } 1739 1740 if (PrintSharedArchiveAndExit) { 1741 // Print archive names 1742 if (dynamic_mapinfo != nullptr) { 1743 tty->print_cr("\n\nBase archive name: %s", CDSConfig::static_archive_path()); 1744 tty->print_cr("Base archive version %d", static_mapinfo->version()); 1745 } else { 1746 tty->print_cr("Static archive name: %s", static_mapinfo->full_path()); 1747 tty->print_cr("Static archive version %d", static_mapinfo->version()); 1748 } 1749 1750 SystemDictionaryShared::print_shared_archive(tty); 1751 if (dynamic_mapinfo != nullptr) { 1752 tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path()); 1753 tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version()); 1754 SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/); 1755 } 1756 1757 // collect shared symbols and strings 1758 CountSharedSymbols cl; 1759 SymbolTable::shared_symbols_do(&cl); 1760 tty->print_cr("Number of shared symbols: %d", cl.total()); 1761 tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count()); 1762 tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version()); 1763 if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) { 1764 tty->print_cr("archive is invalid"); 1765 vm_exit(1); 1766 } else { 1767 tty->print_cr("archive is valid"); 1768 vm_exit(0); 1769 } 1770 } 1771 } 1772 1773 // JVM/TI RedefineClasses() support: 1774 bool MetaspaceShared::remap_shared_readonly_as_readwrite() { 1775 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 1776 1777 if (CDSConfig::is_using_archive()) { 1778 // remap the shared readonly space to shared readwrite, private 1779 FileMapInfo* mapinfo = FileMapInfo::current_info(); 1780 if (!mapinfo->remap_shared_readonly_as_readwrite()) { 1781 return false; 1782 } 1783 if (FileMapInfo::dynamic_info() != nullptr) { 1784 mapinfo = FileMapInfo::dynamic_info(); 1785 if (!mapinfo->remap_shared_readonly_as_readwrite()) { 1786 return false; 1787 } 1788 } 1789 _remapped_readwrite = true; 1790 } 1791 return true; 1792 } 1793 1794 void MetaspaceShared::print_on(outputStream* st) { 1795 if (CDSConfig::is_using_archive()) { 1796 st->print("CDS archive(s) mapped at: "); 1797 address base = (address)MetaspaceObj::shared_metaspace_base(); 1798 address static_top = (address)_shared_metaspace_static_top; 1799 address top = (address)MetaspaceObj::shared_metaspace_top(); 1800 st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top)); 1801 st->print("size %zu, ", top - base); 1802 st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, ArchiveRelocationMode); 1803 } else { 1804 st->print("CDS archive(s) not mapped"); 1805 } 1806 st->cr(); 1807 }