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