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