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