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