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