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