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