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