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::preload_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, true); 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 if (!CDSConfig::is_dumping_final_static_archive()) { 656 guarantee(!CDSConfig::is_using_archive(), "We should not be using an archive when we dump"); 657 } 658 659 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm); 660 661 _pending_method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared); 662 if (CDSConfig::is_dumping_method_handles()) { 663 // When dumping AOT-linked classes, some classes may have direct references to a method handle 664 // intrinsic. The easiest thing is to save all of them into the AOT cache. 665 SystemDictionary::get_all_method_handle_intrinsics(_pending_method_handle_intrinsics); 666 } 667 668 AOTClassLocationConfig::dumptime_check_nonempty_dirs(); 669 670 NOT_PRODUCT(SystemDictionary::verify();) 671 672 // Block concurrent class unloading from changing the _dumptime_table 673 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag); 674 675 _builder.gather_source_objs(); 676 _builder.reserve_buffer(); 677 678 CppVtables::dumptime_init(&_builder); 679 680 _builder.sort_metadata_objs(); 681 _builder.dump_rw_metadata(); 682 _builder.dump_ro_metadata(); 683 _builder.relocate_metaspaceobj_embedded_pointers(); 684 685 log_info(aot)("Make classes shareable"); 686 _builder.make_klasses_shareable(); 687 AOTMetaspace::make_method_handle_intrinsics_shareable(); 688 689 dump_java_heap_objects(); 690 dump_shared_symbol_table(_builder.symbols()); 691 692 char* early_serialized_data = dump_early_read_only_tables(); 693 AOTClassLocationConfig* cl_config; 694 char* serialized_data = dump_read_only_tables(cl_config); 695 696 if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) { 697 log_info(aot)("Adjust lambda proxy class dictionary"); 698 LambdaProxyClassDictionary::adjust_dumptime_table(); 699 } 700 701 log_info(cds)("Make training data shareable"); 702 _builder.make_training_data_shareable(); 703 704 // The vtable clones contain addresses of the current process. 705 // We don't want to write these addresses into the archive. 706 CppVtables::zero_archived_vtables(); 707 708 // Write the archive file 709 if (CDSConfig::is_dumping_final_static_archive()) { 710 FileMapInfo::free_current_info(); // FIXME: should not free current info 711 } 712 const char* static_archive = CDSConfig::output_archive_path(); 713 assert(static_archive != nullptr, "sanity"); 714 _map_info = new FileMapInfo(static_archive, true); 715 _map_info->populate_header(AOTMetaspace::core_region_alignment()); 716 _map_info->set_early_serialized_data(early_serialized_data); 717 _map_info->set_serialized_data(serialized_data); 718 _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base()); 719 _map_info->header()->set_class_location_config(cl_config); 720 } 721 722 class CollectClassesForLinking : public KlassClosure { 723 GrowableArray<OopHandle> _mirrors; 724 725 public: 726 CollectClassesForLinking() : _mirrors() { 727 // ClassLoaderDataGraph::loaded_classes_do_keepalive() requires ClassLoaderDataGraph_lock. 728 // We cannot link the classes while holding this lock (or else we may run into deadlock). 729 // Therefore, we need to first collect all the classes, keeping them alive by 730 // holding onto their java_mirrors in global OopHandles. We then link the classes after 731 // releasing the lock. 732 MutexLocker lock(ClassLoaderDataGraph_lock); 733 ClassLoaderDataGraph::loaded_classes_do_keepalive(this); 734 } 735 736 ~CollectClassesForLinking() { 737 for (int i = 0; i < _mirrors.length(); i++) { 738 _mirrors.at(i).release(Universe::vm_global()); 739 } 740 } 741 742 void do_cld(ClassLoaderData* cld) { 743 assert(cld->is_alive(), "must be"); 744 } 745 746 void do_klass(Klass* k) { 747 if (k->is_instance_klass()) { 748 _mirrors.append(OopHandle(Universe::vm_global(), k->java_mirror())); 749 } 750 } 751 752 const GrowableArray<OopHandle>* mirrors() const { return &_mirrors; } 753 }; 754 755 // Check if we can eagerly link this class at dump time, so we can avoid the 756 // runtime linking overhead (especially verification) 757 bool AOTMetaspace::may_be_eagerly_linked(InstanceKlass* ik) { 758 if (!ik->can_be_verified_at_dumptime()) { 759 // For old classes, try to leave them in the unlinked state, so 760 // we can still store them in the archive. They must be 761 // linked/verified at runtime. 762 return false; 763 } 764 if (CDSConfig::is_dumping_dynamic_archive() && ik->defined_by_other_loaders()) { 765 // Linking of unregistered classes at this stage may cause more 766 // classes to be resolved, resulting in calls to ClassLoader.loadClass() 767 // that may not be expected by custom class loaders. 768 // 769 // It's OK to do this for the built-in loaders as we know they can 770 // tolerate this. 771 return false; 772 } 773 return true; 774 } 775 776 void AOTMetaspace::link_shared_classes(TRAPS) { 777 AOTClassLinker::initialize(); 778 AOTClassInitializer::init_test_class(CHECK); 779 780 while (true) { 781 ResourceMark rm(THREAD); 782 CollectClassesForLinking collect_classes; 783 bool has_linked = false; 784 const GrowableArray<OopHandle>* mirrors = collect_classes.mirrors(); 785 for (int i = 0; i < mirrors->length(); i++) { 786 OopHandle mirror = mirrors->at(i); 787 InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(mirror.resolve())); 788 if (may_be_eagerly_linked(ik)) { 789 has_linked |= try_link_class(THREAD, ik); 790 } 791 } 792 793 if (!has_linked) { 794 break; 795 } 796 // Class linking includes verification which may load more classes. 797 // Keep scanning until we have linked no more classes. 798 } 799 800 // Eargerly resolve all string constants in constant pools 801 { 802 ResourceMark rm(THREAD); 803 CollectClassesForLinking collect_classes; 804 const GrowableArray<OopHandle>* mirrors = collect_classes.mirrors(); 805 for (int i = 0; i < mirrors->length(); i++) { 806 OopHandle mirror = mirrors->at(i); 807 InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(mirror.resolve())); 808 AOTConstantPoolResolver::preresolve_string_cp_entries(ik, CHECK); 809 } 810 } 811 812 if (CDSConfig::is_dumping_final_static_archive()) { 813 FinalImageRecipes::apply_recipes(CHECK); 814 } 815 } 816 817 // Preload classes from a list, populate the shared spaces and dump to a 818 // file. 819 void AOTMetaspace::preload_and_dump(TRAPS) { 820 CDSConfig::DumperThreadMark dumper_thread_mark(THREAD); 821 ResourceMark rm(THREAD); 822 HandleMark hm(THREAD); 823 824 if (CDSConfig::is_dumping_final_static_archive() && AOTPrintTrainingInfo) { 825 tty->print_cr("==================== archived_training_data ** before dumping ===================="); 826 TrainingData::print_archived_training_data_on(tty); 827 } 828 829 StaticArchiveBuilder builder; 830 preload_and_dump_impl(builder, THREAD); 831 if (HAS_PENDING_EXCEPTION) { 832 if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) { 833 aot_log_error(aot)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = " 834 "%zuM", MaxHeapSize/M); 835 AOTMetaspace::writing_error(); 836 } else { 837 oop message = java_lang_Throwable::message(PENDING_EXCEPTION); 838 aot_log_error(aot)("%s: %s", PENDING_EXCEPTION->klass()->external_name(), 839 message == nullptr ? "(null)" : java_lang_String::as_utf8_string(message)); 840 AOTMetaspace::writing_error(err_msg("Unexpected exception, use -Xlog:aot%s,exceptions=trace for detail", 841 CDSConfig::new_aot_flags_used() ? "" : ",cds")); 842 } 843 } 844 845 if (CDSConfig::new_aot_flags_used()) { 846 if (CDSConfig::is_dumping_preimage_static_archive()) { 847 // We are in the JVM that runs the training run. Continue execution, 848 // so that it can finish all clean-up and return the correct exit 849 // code to the OS. 850 } else { 851 // The JLI launcher only recognizes the "old" -Xshare:dump flag. 852 // When the new -XX:AOTMode=create flag is used, we can't return 853 // to the JLI launcher, as the launcher will fail when trying to 854 // run the main class, which is not what we want. 855 struct stat st; 856 if (os::stat(AOTCache, &st) != 0) { 857 tty->print_cr("AOTCache creation failed: %s", AOTCache); 858 } else { 859 tty->print_cr("AOTCache creation is complete: %s " INT64_FORMAT " bytes", AOTCache, (int64_t)(st.st_size)); 860 } 861 vm_direct_exit(0); 862 } 863 } 864 } 865 866 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64) 867 void AOTMetaspace::adjust_heap_sizes_for_dumping() { 868 if (!CDSConfig::is_dumping_heap() || UseCompressedOops) { 869 return; 870 } 871 // CDS heap dumping requires all string oops to have an offset 872 // from the heap bottom that can be encoded in 32-bit. 873 julong max_heap_size = (julong)(4 * G); 874 875 if (MinHeapSize > max_heap_size) { 876 log_debug(aot)("Setting MinHeapSize to 4G for CDS dumping, original size = %zuM", MinHeapSize/M); 877 FLAG_SET_ERGO(MinHeapSize, max_heap_size); 878 } 879 if (InitialHeapSize > max_heap_size) { 880 log_debug(aot)("Setting InitialHeapSize to 4G for CDS dumping, original size = %zuM", InitialHeapSize/M); 881 FLAG_SET_ERGO(InitialHeapSize, max_heap_size); 882 } 883 if (MaxHeapSize > max_heap_size) { 884 log_debug(aot)("Setting MaxHeapSize to 4G for CDS dumping, original size = %zuM", MaxHeapSize/M); 885 FLAG_SET_ERGO(MaxHeapSize, max_heap_size); 886 } 887 } 888 #endif // INCLUDE_CDS_JAVA_HEAP && _LP64 889 890 void AOTMetaspace::get_default_classlist(char* default_classlist, const size_t buf_size) { 891 const char* filesep = os::file_separator(); 892 jio_snprintf(default_classlist, buf_size, "%s%slib%sclasslist", 893 Arguments::get_java_home(), filesep, filesep); 894 } 895 896 void AOTMetaspace::preload_classes(TRAPS) { 897 char default_classlist[JVM_MAXPATHLEN]; 898 const char* classlist_path; 899 900 get_default_classlist(default_classlist, JVM_MAXPATHLEN); 901 if (SharedClassListFile == nullptr) { 902 classlist_path = default_classlist; 903 } else { 904 classlist_path = SharedClassListFile; 905 } 906 907 aot_log_info(aot)("Loading classes to share ..."); 908 ClassListParser::parse_classlist(classlist_path, 909 ClassListParser::_parse_all, CHECK); 910 if (ExtraSharedClassListFile) { 911 ClassListParser::parse_classlist(ExtraSharedClassListFile, 912 ClassListParser::_parse_all, CHECK); 913 } 914 if (classlist_path != default_classlist) { 915 struct stat statbuf; 916 if (os::stat(default_classlist, &statbuf) == 0) { 917 // File exists, let's use it. 918 ClassListParser::parse_classlist(default_classlist, 919 ClassListParser::_parse_lambda_forms_invokers_only, CHECK); 920 } 921 } 922 923 // Some classes are used at CDS runtime but are not loaded, and therefore archived, at 924 // dumptime. We can perform dummmy calls to these classes at dumptime to ensure they 925 // are archived. 926 exercise_runtime_cds_code(CHECK); 927 928 aot_log_info(aot)("Loading classes to share: done."); 929 } 930 931 void AOTMetaspace::exercise_runtime_cds_code(TRAPS) { 932 // Exercise the manifest processing code 933 const char* dummy = "Manifest-Version: 1.0\n"; 934 CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK); 935 936 // Exercise FileSystem and URL code 937 CDSProtectionDomain::to_file_URL("dummy.jar", Handle(), CHECK); 938 } 939 940 void AOTMetaspace::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) { 941 if (CDSConfig::is_dumping_classic_static_archive()) { 942 // We are running with -Xshare:dump 943 preload_classes(CHECK); 944 945 if (SharedArchiveConfigFile) { 946 log_info(aot)("Reading extra data from %s ...", SharedArchiveConfigFile); 947 read_extra_data(THREAD, SharedArchiveConfigFile); 948 log_info(aot)("Reading extra data: done."); 949 } 950 } 951 952 if (CDSConfig::is_dumping_preimage_static_archive()) { 953 log_info(aot)("Reading lambda form invokers from JDK default classlist ..."); 954 char default_classlist[JVM_MAXPATHLEN]; 955 get_default_classlist(default_classlist, JVM_MAXPATHLEN); 956 struct stat statbuf; 957 if (os::stat(default_classlist, &statbuf) == 0) { 958 ClassListParser::parse_classlist(default_classlist, 959 ClassListParser::_parse_lambda_forms_invokers_only, CHECK); 960 } 961 } 962 963 #if INCLUDE_CDS_JAVA_HEAP 964 if (CDSConfig::is_dumping_heap()) { 965 assert(CDSConfig::allow_only_single_java_thread(), "Required"); 966 if (!HeapShared::is_archived_boot_layer_available(THREAD)) { 967 report_loading_error("archivedBootLayer not available, disabling full module graph"); 968 CDSConfig::stop_dumping_full_module_graph(); 969 } 970 // Do this before link_shared_classes(), as the following line may load new classes. 971 HeapShared::init_for_dumping(CHECK); 972 } 973 #endif 974 975 if (CDSConfig::is_dumping_final_static_archive()) { 976 if (ExtraSharedClassListFile) { 977 log_info(aot)("Loading extra classes from %s ...", ExtraSharedClassListFile); 978 ClassListParser::parse_classlist(ExtraSharedClassListFile, 979 ClassListParser::_parse_all, CHECK); 980 } 981 } 982 983 // Rewrite and link classes 984 log_info(aot)("Rewriting and linking classes ..."); 985 986 // Link any classes which got missed. This would happen if we have loaded classes that 987 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K 988 // fails verification, all other interfaces that were not specified in the classlist but 989 // are implemented by K are not verified. 990 link_shared_classes(CHECK); 991 log_info(aot)("Rewriting and linking classes: done"); 992 TrainingData::init_dumptime_table(CHECK); // captures TrainingDataSetLocker 993 994 if (CDSConfig::is_dumping_regenerated_lambdaform_invokers()) { 995 LambdaFormInvokers::regenerate_holder_classes(CHECK); 996 } 997 998 #if INCLUDE_CDS_JAVA_HEAP 999 if (CDSConfig::is_dumping_heap()) { 1000 ArchiveHeapWriter::init(); 1001 1002 if (CDSConfig::is_dumping_full_module_graph()) { 1003 ClassLoaderDataShared::ensure_module_entry_tables_exist(); 1004 HeapShared::reset_archived_object_states(CHECK); 1005 } 1006 1007 AOTReferenceObjSupport::initialize(CHECK); 1008 AOTReferenceObjSupport::stabilize_cached_reference_objects(CHECK); 1009 1010 if (CDSConfig::is_initing_classes_at_dump_time()) { 1011 // java.lang.Class::reflectionFactory cannot be archived yet. We set this field 1012 // to null, and it will be initialized again at runtime. 1013 log_debug(aot)("Resetting Class::reflectionFactory"); 1014 TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates"); 1015 Symbol* method_sig = vmSymbols::void_method_signature(); 1016 JavaValue result(T_VOID); 1017 JavaCalls::call_static(&result, vmClasses::Class_klass(), 1018 method_name, method_sig, CHECK); 1019 1020 // Perhaps there is a way to avoid hard-coding these names here. 1021 // See discussion in JDK-8342481. 1022 } 1023 1024 // Do this at the very end, when no Java code will be executed. Otherwise 1025 // some new strings may be added to the intern table. 1026 StringTable::allocate_shared_strings_array(CHECK); 1027 } else { 1028 log_info(aot)("Not dumping heap, reset CDSConfig::_is_using_optimized_module_handling"); 1029 CDSConfig::stop_using_optimized_module_handling(); 1030 } 1031 #endif 1032 1033 VM_PopulateDumpSharedSpace op(builder); 1034 VMThread::execute(&op); 1035 1036 if (AOTCodeCache::is_on_for_dump() && CDSConfig::is_dumping_final_static_archive()) { 1037 CDSConfig::enable_dumping_aot_code(); 1038 { 1039 builder.start_ac_region(); 1040 // Write the contents to AOT code region and close AOTCodeCache before packing the region 1041 AOTCodeCache::close(); 1042 builder.end_ac_region(); 1043 } 1044 CDSConfig::disable_dumping_aot_code(); 1045 } 1046 1047 bool status = write_static_archive(&builder, op.map_info(), op.heap_info()); 1048 if (status && CDSConfig::is_dumping_preimage_static_archive()) { 1049 tty->print_cr("%s AOTConfiguration recorded: %s", 1050 CDSConfig::has_temp_aot_config_file() ? "Temporary" : "", AOTConfiguration); 1051 if (CDSConfig::is_single_command_training()) { 1052 fork_and_dump_final_static_archive(CHECK); 1053 } 1054 } 1055 1056 if (!status) { 1057 THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping"); 1058 } 1059 } 1060 1061 bool AOTMetaspace::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) { 1062 // relocate the data so that it can be mapped to AOTMetaspace::requested_base_address() 1063 // without runtime relocation. 1064 builder->relocate_to_requested(); 1065 1066 map_info->open_as_output(); 1067 if (!map_info->is_open()) { 1068 return false; 1069 } 1070 builder->write_archive(map_info, heap_info); 1071 1072 if (AllowArchivingWithJavaAgent) { 1073 aot_log_warning(aot)("This %s was created with AllowArchivingWithJavaAgent. It should be used " 1074 "for testing purposes only and should not be used in a production environment", CDSConfig::type_of_archive_being_loaded()); 1075 } 1076 return true; 1077 } 1078 1079 static void print_java_launcher(outputStream* st) { 1080 st->print("%s%sbin%sjava", Arguments::get_java_home(), os::file_separator(), os::file_separator()); 1081 } 1082 1083 static void append_args(GrowableArray<Handle>* args, const char* arg, TRAPS) { 1084 Handle string = java_lang_String::create_from_str(arg, CHECK); 1085 args->append(string); 1086 } 1087 1088 // Pass all options in Arguments::jvm_args_array() to a child JVM process 1089 // using the JAVA_TOOL_OPTIONS environment variable. 1090 static int exec_jvm_with_java_tool_options(const char* java_launcher_path, TRAPS) { 1091 ResourceMark rm(THREAD); 1092 HandleMark hm(THREAD); 1093 GrowableArray<Handle> args; 1094 1095 const char* cp = Arguments::get_appclasspath(); 1096 if (cp != nullptr && strlen(cp) > 0 && strcmp(cp, ".") != 0) { 1097 // We cannot use "-cp", because "-cp" is only interpreted by the java launcher, 1098 // and is not interpreter by arguments.cpp when it loads args from JAVA_TOOL_OPTIONS 1099 stringStream ss; 1100 ss.print("-Djava.class.path="); 1101 ss.print_raw(cp); 1102 append_args(&args, ss.freeze(), CHECK_0); 1103 // CDS$ProcessLauncher::execWithJavaToolOptions() must unset CLASSPATH, which has 1104 // a higher priority than -Djava.class.path= 1105 } 1106 1107 // Pass all arguments. These include those from JAVA_TOOL_OPTIONS and _JAVA_OPTIONS. 1108 for (int i = 0; i < Arguments::num_jvm_args(); i++) { 1109 const char* arg = Arguments::jvm_args_array()[i]; 1110 if (strstr(arg, "-XX:AOTCacheOutput=") == arg || // arg starts with ... 1111 strstr(arg, "-XX:AOTConfiguration=") == arg || 1112 strstr(arg, "-XX:AOTMode=") == arg) { 1113 // Filter these out. They wiill be set below. 1114 } else { 1115 append_args(&args, arg, CHECK_0); 1116 } 1117 } 1118 1119 // Note: because we are running in AOTMode=record, JDK_AOT_VM_OPTIONS have not been 1120 // parsed, so they are not in Arguments::jvm_args_array. If JDK_AOT_VM_OPTIONS is in 1121 // the environment, it will be inherited and parsed by the child JVM process 1122 // in Arguments::parse_java_tool_options_environment_variable(). 1123 precond(strcmp(AOTMode, "record") == 0); 1124 1125 // We don't pass Arguments::jvm_flags_array(), as those will be added by 1126 // the child process when it loads .hotspotrc 1127 1128 { 1129 // If AOTCacheOutput contains %p, it should have been already substituted with the 1130 // pid of the training process. 1131 stringStream ss; 1132 ss.print("-XX:AOTCacheOutput="); 1133 ss.print_raw(AOTCacheOutput); 1134 append_args(&args, ss.freeze(), CHECK_0); 1135 } 1136 { 1137 // If AOTCacheConfiguration contains %p, it should have been already substituted with the 1138 // pid of the training process. 1139 // If AOTCacheConfiguration was not explicitly specified, it should have been assigned a 1140 // temporary file name. 1141 stringStream ss; 1142 ss.print("-XX:AOTConfiguration="); 1143 ss.print_raw(AOTConfiguration); 1144 append_args(&args, ss.freeze(), CHECK_0); 1145 } 1146 1147 append_args(&args, "-XX:AOTMode=create", CHECK_0); 1148 1149 Symbol* klass_name = SymbolTable::new_symbol("jdk/internal/misc/CDS$ProcessLauncher"); 1150 Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, CHECK_0); 1151 Symbol* methodName = SymbolTable::new_symbol("execWithJavaToolOptions"); 1152 Symbol* methodSignature = SymbolTable::new_symbol("(Ljava/lang/String;[Ljava/lang/String;)I"); 1153 1154 Handle launcher = java_lang_String::create_from_str(java_launcher_path, CHECK_0); 1155 objArrayOop array = oopFactory::new_objArray(vmClasses::String_klass(), args.length(), CHECK_0); 1156 for (int i = 0; i < args.length(); i++) { 1157 array->obj_at_put(i, args.at(i)()); 1158 } 1159 objArrayHandle launcher_args(THREAD, array); 1160 1161 // The following call will pass all options inside the JAVA_TOOL_OPTIONS env variable to 1162 // the child process. It will also clear the _JAVA_OPTIONS and CLASSPATH env variables for 1163 // the child process. 1164 // 1165 // Note: the env variables are set only for the child process. They are not changed 1166 // for the current process. See java.lang.ProcessBuilder::environment(). 1167 JavaValue result(T_OBJECT); 1168 JavaCallArguments javacall_args(2); 1169 javacall_args.push_oop(launcher); 1170 javacall_args.push_oop(launcher_args); 1171 JavaCalls::call_static(&result, 1172 InstanceKlass::cast(k), 1173 methodName, 1174 methodSignature, 1175 &javacall_args, 1176 CHECK_0); 1177 return result.get_jint(); 1178 } 1179 1180 void AOTMetaspace::fork_and_dump_final_static_archive(TRAPS) { 1181 assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity"); 1182 1183 ResourceMark rm; 1184 stringStream ss; 1185 print_java_launcher(&ss); 1186 const char* cmd = ss.freeze(); 1187 tty->print_cr("Launching child process %s to assemble AOT cache %s using configuration %s", cmd, AOTCacheOutput, AOTConfiguration); 1188 int status = exec_jvm_with_java_tool_options(cmd, CHECK); 1189 if (status != 0) { 1190 log_error(aot)("Child process failed; status = %d", status); 1191 // We leave the temp config file for debugging 1192 } else if (CDSConfig::has_temp_aot_config_file()) { 1193 const char* tmp_config = AOTConfiguration; 1194 // On Windows, need WRITE permission to remove the file. 1195 WINDOWS_ONLY(chmod(tmp_config, _S_IREAD | _S_IWRITE)); 1196 status = remove(tmp_config); 1197 if (status != 0) { 1198 log_error(aot)("Failed to remove temporary AOT configuration file %s", tmp_config); 1199 } else { 1200 tty->print_cr("Removed temporary AOT configuration file %s", tmp_config); 1201 } 1202 } 1203 } 1204 1205 // Returns true if the class's status has changed. 1206 bool AOTMetaspace::try_link_class(JavaThread* current, InstanceKlass* ik) { 1207 ExceptionMark em(current); 1208 JavaThread* THREAD = current; // For exception macros. 1209 assert(CDSConfig::is_dumping_archive(), "sanity"); 1210 1211 if (ik->in_aot_cache() && !CDSConfig::is_dumping_final_static_archive()) { 1212 assert(CDSConfig::is_dumping_dynamic_archive(), "must be"); 1213 return false; 1214 } 1215 1216 if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() && 1217 !SystemDictionaryShared::has_class_failed_verification(ik)) { 1218 bool saved = BytecodeVerificationLocal; 1219 if (ik->defined_by_other_loaders() && ik->class_loader() == nullptr) { 1220 // The verification decision is based on BytecodeVerificationRemote 1221 // for non-system classes. Since we are using the null classloader 1222 // to load non-system classes for customized class loaders during dumping, 1223 // we need to temporarily change BytecodeVerificationLocal to be the same as 1224 // BytecodeVerificationRemote. Note this can cause the parent system 1225 // classes also being verified. The extra overhead is acceptable during 1226 // dumping. 1227 BytecodeVerificationLocal = BytecodeVerificationRemote; 1228 } 1229 ik->link_class(THREAD); 1230 if (HAS_PENDING_EXCEPTION) { 1231 ResourceMark rm(THREAD); 1232 aot_log_warning(aot)("Preload Warning: Verification failed for %s", 1233 ik->external_name()); 1234 CLEAR_PENDING_EXCEPTION; 1235 SystemDictionaryShared::set_class_has_failed_verification(ik); 1236 } else { 1237 assert(!SystemDictionaryShared::has_class_failed_verification(ik), "sanity"); 1238 ik->compute_has_loops_flag_for_methods(); 1239 } 1240 BytecodeVerificationLocal = saved; 1241 return true; 1242 } else { 1243 return false; 1244 } 1245 } 1246 1247 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() { 1248 if (CDSConfig::is_dumping_heap()) { 1249 HeapShared::write_heap(&_heap_info); 1250 } else { 1251 CDSConfig::log_reasons_for_not_dumping_heap(); 1252 } 1253 } 1254 1255 void AOTMetaspace::set_aot_metaspace_range(void* base, void *static_top, void* top) { 1256 assert(base <= static_top && static_top <= top, "must be"); 1257 _aot_metaspace_static_top = static_top; 1258 MetaspaceObj::set_aot_metaspace_range(base, top); 1259 } 1260 1261 bool AOTMetaspace::in_aot_cache_dynamic_region(void* p) { 1262 if ((p < MetaspaceObj::aot_metaspace_top()) && 1263 (p >= _aot_metaspace_static_top)) { 1264 return true; 1265 } else { 1266 return false; 1267 } 1268 } 1269 1270 bool AOTMetaspace::in_aot_cache_static_region(void* p) { 1271 if (in_aot_cache(p) && !in_aot_cache_dynamic_region(p)) { 1272 return true; 1273 } else { 1274 return false; 1275 } 1276 } 1277 1278 // This function is called when the JVM is unable to load the specified archive(s) due to one 1279 // of the following conditions. 1280 // - There's an error that indicates that the archive(s) files were corrupt or otherwise damaged. 1281 // - When -XX:+RequireSharedSpaces is specified, AND the JVM cannot load the archive(s) due 1282 // to version or classpath mismatch. 1283 void AOTMetaspace::unrecoverable_loading_error(const char* message) { 1284 report_loading_error("%s", message); 1285 1286 if (CDSConfig::is_dumping_final_static_archive()) { 1287 vm_exit_during_initialization("Must be a valid AOT configuration generated by the current JVM", AOTConfiguration); 1288 } else if (CDSConfig::new_aot_flags_used()) { 1289 vm_exit_during_initialization("Unable to use AOT cache.", nullptr); 1290 } else { 1291 vm_exit_during_initialization("Unable to use shared archive.", nullptr); 1292 } 1293 } 1294 1295 void AOTMetaspace::report_loading_error(const char* format, ...) { 1296 // When using AOT cache, errors messages are always printed on the error channel. 1297 LogStream ls_aot(LogLevel::Error, LogTagSetMapping<LOG_TAGS(aot)>::tagset()); 1298 1299 // If we are loading load the default CDS archive, it may fail due to incompatible VM options. 1300 // Print at the info level to avoid excessive verbosity. 1301 // However, if the user has specified a CDS archive (or AOT cache), they would be interested in 1302 // knowing that the loading fails, so we print at the error level. 1303 LogLevelType level = (!CDSConfig::is_using_archive() || CDSConfig::is_using_only_default_archive()) ? 1304 LogLevel::Info : LogLevel::Error; 1305 LogStream ls_cds(level, LogTagSetMapping<LOG_TAGS(cds)>::tagset()); 1306 1307 LogStream& ls = CDSConfig::new_aot_flags_used() ? ls_aot : ls_cds; 1308 if (!ls.is_enabled()) { 1309 return; 1310 } 1311 1312 va_list ap; 1313 va_start(ap, format); 1314 1315 static bool printed_error = false; 1316 if (!printed_error) { // No need for locks. Loading error checks happen only in main thread. 1317 ls.print_cr("An error has occurred while processing the %s. Run with -Xlog:%s for details.", 1318 CDSConfig::type_of_archive_being_loaded(), CDSConfig::new_aot_flags_used() ? "aot" : "aot,cds"); 1319 printed_error = true; 1320 } 1321 ls.vprint_cr(format, ap); 1322 1323 va_end(ap); 1324 } 1325 1326 // This function is called when the JVM is unable to write the specified CDS archive due to an 1327 // unrecoverable error. 1328 void AOTMetaspace::unrecoverable_writing_error(const char* message) { 1329 writing_error(message); 1330 vm_direct_exit(1); 1331 } 1332 1333 // This function is called when the JVM is unable to write the specified CDS archive due to a 1334 // an error. The error will be propagated 1335 void AOTMetaspace::writing_error(const char* message) { 1336 aot_log_error(aot)("An error has occurred while writing the shared archive file."); 1337 if (message != nullptr) { 1338 aot_log_error(aot)("%s", message); 1339 } 1340 } 1341 1342 void AOTMetaspace::initialize_runtime_shared_and_meta_spaces() { 1343 assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled"); 1344 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE; 1345 1346 FileMapInfo* static_mapinfo = open_static_archive(); 1347 FileMapInfo* dynamic_mapinfo = nullptr; 1348 1349 if (static_mapinfo != nullptr) { 1350 aot_log_info(aot)("Core region alignment: %zu", static_mapinfo->core_region_alignment()); 1351 dynamic_mapinfo = open_dynamic_archive(); 1352 1353 aot_log_info(aot)("ArchiveRelocationMode: %d", ArchiveRelocationMode); 1354 1355 // First try to map at the requested address 1356 result = map_archives(static_mapinfo, dynamic_mapinfo, true); 1357 if (result == MAP_ARCHIVE_MMAP_FAILURE) { 1358 // Mapping has failed (probably due to ASLR). Let's map at an address chosen 1359 // by the OS. 1360 aot_log_info(aot)("Try to map archive(s) at an alternative address"); 1361 result = map_archives(static_mapinfo, dynamic_mapinfo, false); 1362 } 1363 } 1364 1365 if (result == MAP_ARCHIVE_SUCCESS) { 1366 bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped()); 1367 char* cds_base = static_mapinfo->mapped_base(); 1368 char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end(); 1369 // Register CDS memory region with LSan. 1370 LSAN_REGISTER_ROOT_REGION(cds_base, cds_end - cds_base); 1371 set_aot_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end); 1372 _relocation_delta = static_mapinfo->relocation_delta(); 1373 _requested_base_address = static_mapinfo->requested_base_address(); 1374 if (dynamic_mapped) { 1375 // turn AutoCreateSharedArchive off if successfully mapped 1376 AutoCreateSharedArchive = false; 1377 } 1378 } else { 1379 set_aot_metaspace_range(nullptr, nullptr, nullptr); 1380 if (CDSConfig::is_dumping_dynamic_archive()) { 1381 aot_log_warning(aot)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info."); 1382 } 1383 UseSharedSpaces = false; 1384 // The base archive cannot be mapped. We cannot dump the dynamic shared archive. 1385 AutoCreateSharedArchive = false; 1386 CDSConfig::disable_dumping_dynamic_archive(); 1387 if (PrintSharedArchiveAndExit) { 1388 AOTMetaspace::unrecoverable_loading_error("Unable to use shared archive."); 1389 } else { 1390 if (RequireSharedSpaces) { 1391 AOTMetaspace::unrecoverable_loading_error("Unable to map shared spaces"); 1392 } else { 1393 report_loading_error("Unable to map shared spaces"); 1394 } 1395 } 1396 } 1397 1398 // If mapping failed and -XShare:on, the vm should exit 1399 bool has_failed = false; 1400 if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) { 1401 has_failed = true; 1402 delete static_mapinfo; 1403 } 1404 if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) { 1405 has_failed = true; 1406 delete dynamic_mapinfo; 1407 } 1408 if (RequireSharedSpaces && has_failed) { 1409 AOTMetaspace::unrecoverable_loading_error("Unable to map shared spaces"); 1410 } 1411 } 1412 1413 FileMapInfo* AOTMetaspace::open_static_archive() { 1414 const char* static_archive = CDSConfig::input_static_archive_path(); 1415 assert(static_archive != nullptr, "sanity"); 1416 FileMapInfo* mapinfo = new FileMapInfo(static_archive, true); 1417 if (!mapinfo->open_as_input()) { 1418 delete(mapinfo); 1419 return nullptr; 1420 } 1421 return mapinfo; 1422 } 1423 1424 FileMapInfo* AOTMetaspace::open_dynamic_archive() { 1425 if (CDSConfig::is_dumping_dynamic_archive()) { 1426 return nullptr; 1427 } 1428 const char* dynamic_archive = CDSConfig::input_dynamic_archive_path(); 1429 if (dynamic_archive == nullptr) { 1430 return nullptr; 1431 } 1432 1433 FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false); 1434 if (!mapinfo->open_as_input()) { 1435 delete(mapinfo); 1436 if (RequireSharedSpaces) { 1437 AOTMetaspace::unrecoverable_loading_error("Failed to initialize dynamic archive"); 1438 } 1439 return nullptr; 1440 } 1441 return mapinfo; 1442 } 1443 1444 // use_requested_addr: 1445 // true = map at FileMapHeader::_requested_base_address 1446 // false = map at an alternative address picked by OS. 1447 MapArchiveResult AOTMetaspace::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo, 1448 bool use_requested_addr) { 1449 if (use_requested_addr && static_mapinfo->requested_base_address() == nullptr) { 1450 aot_log_info(aot)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address."); 1451 return MAP_ARCHIVE_MMAP_FAILURE; 1452 } 1453 1454 PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) { 1455 // For product build only -- this is for benchmarking the cost of doing relocation. 1456 // For debug builds, the check is done below, after reserving the space, for better test coverage 1457 // (see comment below). 1458 aot_log_info(aot)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address"); 1459 return MAP_ARCHIVE_MMAP_FAILURE; 1460 }); 1461 1462 if (ArchiveRelocationMode == 2 && !use_requested_addr) { 1463 aot_log_info(aot)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address"); 1464 return MAP_ARCHIVE_MMAP_FAILURE; 1465 }; 1466 1467 if (dynamic_mapinfo != nullptr) { 1468 // Ensure that the OS won't be able to allocate new memory spaces between the two 1469 // archives, or else it would mess up the simple comparison in MetaspaceObj::in_aot_cache(). 1470 assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap"); 1471 } 1472 1473 ReservedSpace total_space_rs, archive_space_rs, class_space_rs; 1474 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE; 1475 size_t prot_zone_size = 0; 1476 char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo, 1477 dynamic_mapinfo, 1478 use_requested_addr, 1479 total_space_rs, 1480 archive_space_rs, 1481 class_space_rs); 1482 if (mapped_base_address == nullptr) { 1483 result = MAP_ARCHIVE_MMAP_FAILURE; 1484 aot_log_debug(aot)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr); 1485 } else { 1486 1487 if (Metaspace::using_class_space()) { 1488 prot_zone_size = protection_zone_size(); 1489 } 1490 1491 #ifdef ASSERT 1492 // Some sanity checks after reserving address spaces for archives 1493 // and class space. 1494 assert(archive_space_rs.is_reserved(), "Sanity"); 1495 if (Metaspace::using_class_space()) { 1496 assert(archive_space_rs.base() == mapped_base_address && 1497 archive_space_rs.size() > protection_zone_size(), 1498 "Archive space must lead and include the protection zone"); 1499 // Class space must closely follow the archive space. Both spaces 1500 // must be aligned correctly. 1501 assert(class_space_rs.is_reserved() && class_space_rs.size() > 0, 1502 "A class space should have been reserved"); 1503 assert(class_space_rs.base() >= archive_space_rs.end(), 1504 "class space should follow the cds archive space"); 1505 assert(is_aligned(archive_space_rs.base(), 1506 core_region_alignment()), 1507 "Archive space misaligned"); 1508 assert(is_aligned(class_space_rs.base(), 1509 Metaspace::reserve_alignment()), 1510 "class space misaligned"); 1511 } 1512 #endif // ASSERT 1513 1514 aot_log_info(aot)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (%zu) bytes%s", 1515 p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size(), 1516 (prot_zone_size > 0 ? " (includes protection zone)" : "")); 1517 aot_log_info(aot)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (%zu) bytes", 1518 p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size()); 1519 1520 if (AOTMetaspace::use_windows_memory_mapping()) { 1521 // We have now reserved address space for the archives, and will map in 1522 // the archive files into this space. 1523 // 1524 // Special handling for Windows: on Windows we cannot map a file view 1525 // into an existing memory mapping. So, we unmap the address range we 1526 // just reserved again, which will make it available for mapping the 1527 // archives. 1528 // Reserving this range has not been for naught however since it makes 1529 // us reasonably sure the address range is available. 1530 // 1531 // But still it may fail, since between unmapping the range and mapping 1532 // in the archive someone else may grab the address space. Therefore 1533 // there is a fallback in FileMap::map_region() where we just read in 1534 // the archive files sequentially instead of mapping it in. We couple 1535 // this with use_requested_addr, since we're going to patch all the 1536 // pointers anyway so there's no benefit to mmap. 1537 if (use_requested_addr) { 1538 assert(!total_space_rs.is_reserved(), "Should not be reserved for Windows"); 1539 aot_log_info(aot)("Windows mmap workaround: releasing archive space."); 1540 MemoryReserver::release(archive_space_rs); 1541 // Mark as not reserved 1542 archive_space_rs = {}; 1543 // The protection zone is part of the archive: 1544 // See comment above, the Windows way of loading CDS is to mmap the individual 1545 // parts of the archive into the address region we just vacated. The protection 1546 // zone will not be mapped (and, in fact, does not exist as physical region in 1547 // the archive). Therefore, after removing the archive space above, we must 1548 // re-reserve the protection zone part lest something else gets mapped into that 1549 // area later. 1550 if (prot_zone_size > 0) { 1551 assert(prot_zone_size >= os::vm_allocation_granularity(), "must be"); // not just page size! 1552 char* p = os::attempt_reserve_memory_at(mapped_base_address, prot_zone_size, 1553 mtClassShared); 1554 assert(p == mapped_base_address || p == nullptr, "must be"); 1555 if (p == nullptr) { 1556 aot_log_debug(aot)("Failed to re-reserve protection zone"); 1557 return MAP_ARCHIVE_MMAP_FAILURE; 1558 } 1559 } 1560 } 1561 } 1562 1563 if (prot_zone_size > 0) { 1564 os::commit_memory(mapped_base_address, prot_zone_size, false); // will later be protected 1565 // Before mapping the core regions into the newly established address space, we mark 1566 // start and the end of the future protection zone with canaries. That way we easily 1567 // catch mapping errors (accidentally mapping data into the future protection zone). 1568 *(mapped_base_address) = 'P'; 1569 *(mapped_base_address + prot_zone_size - 1) = 'P'; 1570 } 1571 1572 MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs); 1573 MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ? 1574 map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE; 1575 1576 DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) { 1577 // This is for simulating mmap failures at the requested address. In 1578 // debug builds, we do it here (after all archives have possibly been 1579 // mapped), so we can thoroughly test the code for failure handling 1580 // (releasing all allocated resource, etc). 1581 aot_log_info(aot)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address"); 1582 if (static_result == MAP_ARCHIVE_SUCCESS) { 1583 static_result = MAP_ARCHIVE_MMAP_FAILURE; 1584 } 1585 if (dynamic_result == MAP_ARCHIVE_SUCCESS) { 1586 dynamic_result = MAP_ARCHIVE_MMAP_FAILURE; 1587 } 1588 }); 1589 1590 if (static_result == MAP_ARCHIVE_SUCCESS) { 1591 if (dynamic_result == MAP_ARCHIVE_SUCCESS) { 1592 result = MAP_ARCHIVE_SUCCESS; 1593 } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) { 1594 assert(dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped(), "must have failed"); 1595 // No need to retry mapping the dynamic archive again, as it will never succeed 1596 // (bad file, etc) -- just keep the base archive. 1597 log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s", 1598 dynamic_mapinfo->full_path()); 1599 result = MAP_ARCHIVE_SUCCESS; 1600 // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no 1601 // easy API to do that right now. 1602 } else { 1603 result = MAP_ARCHIVE_MMAP_FAILURE; 1604 } 1605 } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) { 1606 result = MAP_ARCHIVE_OTHER_FAILURE; 1607 } else { 1608 result = MAP_ARCHIVE_MMAP_FAILURE; 1609 } 1610 } 1611 1612 if (result == MAP_ARCHIVE_SUCCESS) { 1613 SharedBaseAddress = (size_t)mapped_base_address; 1614 #ifdef _LP64 1615 if (Metaspace::using_class_space()) { 1616 assert(prot_zone_size > 0 && 1617 *(mapped_base_address) == 'P' && 1618 *(mapped_base_address + prot_zone_size - 1) == 'P', 1619 "Protection zone was overwritten?"); 1620 // Set up ccs in metaspace. 1621 Metaspace::initialize_class_space(class_space_rs); 1622 1623 // Set up compressed Klass pointer encoding: the encoding range must 1624 // cover both archive and class space. 1625 const address klass_range_start = (address)mapped_base_address; 1626 const size_t klass_range_size = (address)class_space_rs.end() - klass_range_start; 1627 if (INCLUDE_CDS_JAVA_HEAP || UseCompactObjectHeaders) { 1628 // The CDS archive may contain narrow Klass IDs that were precomputed at archive generation time: 1629 // - every archived java object header (only if INCLUDE_CDS_JAVA_HEAP) 1630 // - every archived Klass' prototype (only if +UseCompactObjectHeaders) 1631 // 1632 // In order for those IDs to still be valid, we need to dictate base and shift: base should be the 1633 // mapping start (including protection zone), shift should be the shift used at archive generation time. 1634 CompressedKlassPointers::initialize_for_given_encoding( 1635 klass_range_start, klass_range_size, 1636 klass_range_start, ArchiveBuilder::precomputed_narrow_klass_shift() // precomputed encoding, see ArchiveBuilder 1637 ); 1638 assert(CompressedKlassPointers::base() == klass_range_start, "must be"); 1639 } else { 1640 // Let JVM freely choose encoding base and shift 1641 CompressedKlassPointers::initialize(klass_range_start, klass_range_size); 1642 assert(CompressedKlassPointers::base() == nullptr || 1643 CompressedKlassPointers::base() == klass_range_start, "must be"); 1644 } 1645 // Establish protection zone, but only if we need one 1646 if (CompressedKlassPointers::base() == klass_range_start) { 1647 CompressedKlassPointers::establish_protection_zone(klass_range_start, prot_zone_size); 1648 } 1649 1650 // map_or_load_heap_region() compares the current narrow oop and klass encodings 1651 // with the archived ones, so it must be done after all encodings are determined. 1652 static_mapinfo->map_or_load_heap_region(); 1653 } 1654 #endif // _LP64 1655 log_info(aot)("initial optimized module handling: %s", CDSConfig::is_using_optimized_module_handling() ? "enabled" : "disabled"); 1656 log_info(aot)("initial full module graph: %s", CDSConfig::is_using_full_module_graph() ? "enabled" : "disabled"); 1657 } else { 1658 unmap_archive(static_mapinfo); 1659 unmap_archive(dynamic_mapinfo); 1660 release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs); 1661 } 1662 1663 return result; 1664 } 1665 1666 1667 // This will reserve two address spaces suitable to house Klass structures, one 1668 // for the cds archives (static archive and optionally dynamic archive) and 1669 // optionally one move for ccs. 1670 // 1671 // Since both spaces must fall within the compressed class pointer encoding 1672 // range, they are allocated close to each other. 1673 // 1674 // Space for archives will be reserved first, followed by a potential gap, 1675 // followed by the space for ccs: 1676 // 1677 // +-- Base address A B End 1678 // | | | | 1679 // v v v v 1680 // +-------------+--------------+ +----------------------+ 1681 // | static arc | [dyn. arch] | [gap] | compr. class space | 1682 // +-------------+--------------+ +----------------------+ 1683 // 1684 // (The gap may result from different alignment requirements between metaspace 1685 // and CDS) 1686 // 1687 // If UseCompressedClassPointers is disabled, only one address space will be 1688 // reserved: 1689 // 1690 // +-- Base address End 1691 // | | 1692 // v v 1693 // +-------------+--------------+ 1694 // | static arc | [dyn. arch] | 1695 // +-------------+--------------+ 1696 // 1697 // Base address: If use_archive_base_addr address is true, the Base address is 1698 // determined by the address stored in the static archive. If 1699 // use_archive_base_addr address is false, this base address is determined 1700 // by the platform. 1701 // 1702 // If UseCompressedClassPointers=1, the range encompassing both spaces will be 1703 // suitable to en/decode narrow Klass pointers: the base will be valid for 1704 // encoding, the range [Base, End) and not surpass the max. range for that encoding. 1705 // 1706 // Return: 1707 // 1708 // - On success: 1709 // - total_space_rs will be reserved as whole for archive_space_rs and 1710 // class_space_rs if UseCompressedClassPointers is true. 1711 // On Windows, try reserve archive_space_rs and class_space_rs 1712 // separately first if use_archive_base_addr is true. 1713 // - archive_space_rs will be reserved and large enough to host static and 1714 // if needed dynamic archive: [Base, A). 1715 // archive_space_rs.base and size will be aligned to CDS reserve 1716 // granularity. 1717 // - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will 1718 // be reserved. Its start address will be aligned to metaspace reserve 1719 // alignment, which may differ from CDS alignment. It will follow the cds 1720 // archive space, close enough such that narrow class pointer encoding 1721 // covers both spaces. 1722 // If UseCompressedClassPointers=0, class_space_rs remains unreserved. 1723 // - On error: null is returned and the spaces remain unreserved. 1724 char* AOTMetaspace::reserve_address_space_for_archives(FileMapInfo* static_mapinfo, 1725 FileMapInfo* dynamic_mapinfo, 1726 bool use_archive_base_addr, 1727 ReservedSpace& total_space_rs, 1728 ReservedSpace& archive_space_rs, 1729 ReservedSpace& class_space_rs) { 1730 1731 address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : nullptr); 1732 const size_t archive_space_alignment = core_region_alignment(); 1733 1734 // Size and requested location of the archive_space_rs (for both static and dynamic archives) 1735 size_t archive_end_offset = (dynamic_mapinfo == nullptr) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset(); 1736 size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment); 1737 1738 if (!Metaspace::using_class_space()) { 1739 // Get the simple case out of the way first: 1740 // no compressed class space, simple allocation. 1741 1742 // When running without class space, requested archive base should be aligned to cds core alignment. 1743 assert(is_aligned(base_address, archive_space_alignment), 1744 "Archive base address unaligned: " PTR_FORMAT ", needs alignment: %zu.", 1745 p2i(base_address), archive_space_alignment); 1746 1747 archive_space_rs = MemoryReserver::reserve((char*)base_address, 1748 archive_space_size, 1749 archive_space_alignment, 1750 os::vm_page_size(), 1751 mtNone); 1752 if (archive_space_rs.is_reserved()) { 1753 assert(base_address == nullptr || 1754 (address)archive_space_rs.base() == base_address, "Sanity"); 1755 // Register archive space with NMT. 1756 MemTracker::record_virtual_memory_tag(archive_space_rs, mtClassShared); 1757 return archive_space_rs.base(); 1758 } 1759 return nullptr; 1760 } 1761 1762 #ifdef _LP64 1763 1764 // Complex case: two spaces adjacent to each other, both to be addressable 1765 // with narrow class pointers. 1766 // We reserve the whole range spanning both spaces, then split that range up. 1767 1768 const size_t class_space_alignment = Metaspace::reserve_alignment(); 1769 1770 // When running with class space, requested archive base must satisfy both cds core alignment 1771 // and class space alignment. 1772 const size_t base_address_alignment = MAX2(class_space_alignment, archive_space_alignment); 1773 assert(is_aligned(base_address, base_address_alignment), 1774 "Archive base address unaligned: " PTR_FORMAT ", needs alignment: %zu.", 1775 p2i(base_address), base_address_alignment); 1776 1777 size_t class_space_size = CompressedClassSpaceSize; 1778 assert(CompressedClassSpaceSize > 0 && 1779 is_aligned(CompressedClassSpaceSize, class_space_alignment), 1780 "CompressedClassSpaceSize malformed: %zu", CompressedClassSpaceSize); 1781 1782 const size_t ccs_begin_offset = align_up(archive_space_size, class_space_alignment); 1783 const size_t gap_size = ccs_begin_offset - archive_space_size; 1784 1785 // Reduce class space size if it would not fit into the Klass encoding range 1786 constexpr size_t max_encoding_range_size = 4 * G; 1787 guarantee(archive_space_size < max_encoding_range_size - class_space_alignment, "Archive too large"); 1788 if ((archive_space_size + gap_size + class_space_size) > max_encoding_range_size) { 1789 class_space_size = align_down(max_encoding_range_size - archive_space_size - gap_size, class_space_alignment); 1790 log_info(metaspace)("CDS initialization: reducing class space size from %zu to %zu", 1791 CompressedClassSpaceSize, class_space_size); 1792 FLAG_SET_ERGO(CompressedClassSpaceSize, class_space_size); 1793 } 1794 1795 const size_t total_range_size = 1796 archive_space_size + gap_size + class_space_size; 1797 1798 // Test that class space base address plus shift can be decoded by aarch64, when restored. 1799 const int precomputed_narrow_klass_shift = ArchiveBuilder::precomputed_narrow_klass_shift(); 1800 if (!CompressedKlassPointers::check_klass_decode_mode(base_address, precomputed_narrow_klass_shift, 1801 total_range_size)) { 1802 aot_log_info(aot)("CDS initialization: Cannot use SharedBaseAddress " PTR_FORMAT " with precomputed shift %d.", 1803 p2i(base_address), precomputed_narrow_klass_shift); 1804 use_archive_base_addr = false; 1805 } 1806 1807 assert(total_range_size > ccs_begin_offset, "must be"); 1808 if (use_windows_memory_mapping() && use_archive_base_addr) { 1809 if (base_address != nullptr) { 1810 // On Windows, we cannot safely split a reserved memory space into two (see JDK-8255917). 1811 // Hence, we optimistically reserve archive space and class space side-by-side. We only 1812 // do this for use_archive_base_addr=true since for use_archive_base_addr=false case 1813 // caller will not split the combined space for mapping, instead read the archive data 1814 // via sequential file IO. 1815 address ccs_base = base_address + archive_space_size + gap_size; 1816 archive_space_rs = MemoryReserver::reserve((char*)base_address, 1817 archive_space_size, 1818 archive_space_alignment, 1819 os::vm_page_size(), 1820 mtNone); 1821 class_space_rs = MemoryReserver::reserve((char*)ccs_base, 1822 class_space_size, 1823 class_space_alignment, 1824 os::vm_page_size(), 1825 mtNone); 1826 } 1827 if (!archive_space_rs.is_reserved() || !class_space_rs.is_reserved()) { 1828 release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs); 1829 return nullptr; 1830 } 1831 MemTracker::record_virtual_memory_tag(archive_space_rs, mtClassShared); 1832 MemTracker::record_virtual_memory_tag(class_space_rs, mtClass); 1833 } else { 1834 if (use_archive_base_addr && base_address != nullptr) { 1835 total_space_rs = MemoryReserver::reserve((char*) base_address, 1836 total_range_size, 1837 base_address_alignment, 1838 os::vm_page_size(), 1839 mtNone); 1840 } else { 1841 // We did not manage to reserve at the preferred address, or were instructed to relocate. In that 1842 // case we reserve wherever possible, but the start address needs to be encodable as narrow Klass 1843 // encoding base since the archived heap objects contain narrow Klass IDs pre-calculated toward the start 1844 // of the shared Metaspace. That prevents us from using zero-based encoding and therefore we won't 1845 // try allocating in low-address regions. 1846 total_space_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size, false /* optimize_for_zero_base */); 1847 } 1848 1849 if (!total_space_rs.is_reserved()) { 1850 return nullptr; 1851 } 1852 1853 // Paranoid checks: 1854 assert(!use_archive_base_addr || (address)total_space_rs.base() == base_address, 1855 "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_space_rs.base())); 1856 assert(is_aligned(total_space_rs.base(), base_address_alignment), "Sanity"); 1857 assert(total_space_rs.size() == total_range_size, "Sanity"); 1858 1859 // Now split up the space into ccs and cds archive. For simplicity, just leave 1860 // the gap reserved at the end of the archive space. Do not do real splitting. 1861 archive_space_rs = total_space_rs.first_part(ccs_begin_offset, 1862 (size_t)archive_space_alignment); 1863 class_space_rs = total_space_rs.last_part(ccs_begin_offset); 1864 MemTracker::record_virtual_memory_split_reserved(total_space_rs.base(), total_space_rs.size(), 1865 ccs_begin_offset, mtClassShared, mtClass); 1866 } 1867 assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity"); 1868 assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity"); 1869 assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity"); 1870 assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity"); 1871 1872 1873 return archive_space_rs.base(); 1874 1875 #else 1876 ShouldNotReachHere(); 1877 return nullptr; 1878 #endif 1879 1880 } 1881 1882 void AOTMetaspace::release_reserved_spaces(ReservedSpace& total_space_rs, 1883 ReservedSpace& archive_space_rs, 1884 ReservedSpace& class_space_rs) { 1885 if (total_space_rs.is_reserved()) { 1886 aot_log_debug(aot)("Released shared space (archive + class) " INTPTR_FORMAT, p2i(total_space_rs.base())); 1887 MemoryReserver::release(total_space_rs); 1888 total_space_rs = {}; 1889 } else { 1890 if (archive_space_rs.is_reserved()) { 1891 aot_log_debug(aot)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base())); 1892 MemoryReserver::release(archive_space_rs); 1893 archive_space_rs = {}; 1894 } 1895 if (class_space_rs.is_reserved()) { 1896 aot_log_debug(aot)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base())); 1897 MemoryReserver::release(class_space_rs); 1898 class_space_rs = {}; 1899 } 1900 } 1901 } 1902 1903 static int archive_regions[] = { AOTMetaspace::rw, AOTMetaspace::ro }; 1904 static int archive_regions_count = 2; 1905 1906 MapArchiveResult AOTMetaspace::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) { 1907 assert(CDSConfig::is_using_archive(), "must be runtime"); 1908 if (mapinfo == nullptr) { 1909 return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded. 1910 } 1911 1912 mapinfo->set_is_mapped(false); 1913 if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) { 1914 report_loading_error("Unable to map CDS archive -- core_region_alignment() expected: %zu" 1915 " actual: %zu", mapinfo->core_region_alignment(), core_region_alignment()); 1916 return MAP_ARCHIVE_OTHER_FAILURE; 1917 } 1918 1919 MapArchiveResult result = 1920 mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs); 1921 1922 if (result != MAP_ARCHIVE_SUCCESS) { 1923 unmap_archive(mapinfo); 1924 return result; 1925 } 1926 1927 if (!mapinfo->validate_class_location()) { 1928 unmap_archive(mapinfo); 1929 return MAP_ARCHIVE_OTHER_FAILURE; 1930 } 1931 1932 if (mapinfo->is_static()) { 1933 // Currently, only static archive uses early serialized data. 1934 char* buffer = mapinfo->early_serialized_data(); 1935 intptr_t* array = (intptr_t*)buffer; 1936 ReadClosure rc(&array, (intptr_t)mapped_base_address); 1937 early_serialize(&rc); 1938 } 1939 1940 if (!mapinfo->validate_aot_class_linking()) { 1941 unmap_archive(mapinfo); 1942 return MAP_ARCHIVE_OTHER_FAILURE; 1943 } 1944 1945 mapinfo->set_is_mapped(true); 1946 return MAP_ARCHIVE_SUCCESS; 1947 } 1948 1949 void AOTMetaspace::unmap_archive(FileMapInfo* mapinfo) { 1950 assert(CDSConfig::is_using_archive(), "must be runtime"); 1951 if (mapinfo != nullptr) { 1952 mapinfo->unmap_regions(archive_regions, archive_regions_count); 1953 mapinfo->unmap_region(AOTMetaspace::bm); 1954 mapinfo->set_is_mapped(false); 1955 } 1956 } 1957 1958 // For -XX:PrintSharedArchiveAndExit 1959 class CountSharedSymbols : public SymbolClosure { 1960 private: 1961 int _count; 1962 public: 1963 CountSharedSymbols() : _count(0) {} 1964 void do_symbol(Symbol** sym) { 1965 _count++; 1966 } 1967 int total() { return _count; } 1968 1969 }; 1970 1971 // Read the miscellaneous data from the shared file, and 1972 // serialize it out to its various destinations. 1973 1974 void AOTMetaspace::initialize_shared_spaces() { 1975 FileMapInfo *static_mapinfo = FileMapInfo::current_info(); 1976 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info(); 1977 1978 // Verify various attributes of the archive, plus initialize the 1979 // shared string/symbol tables. 1980 char* buffer = static_mapinfo->serialized_data(); 1981 intptr_t* array = (intptr_t*)buffer; 1982 ReadClosure rc(&array, (intptr_t)SharedBaseAddress); 1983 serialize(&rc); 1984 1985 // Finish up archived heap initialization. These must be 1986 // done after ReadClosure. 1987 static_mapinfo->patch_heap_embedded_pointers(); 1988 ArchiveHeapLoader::finish_initialization(); 1989 Universe::load_archived_object_instances(); 1990 AOTCodeCache::initialize(); 1991 1992 if (dynamic_mapinfo != nullptr) { 1993 intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data(); 1994 ReadClosure rc(&buffer, (intptr_t)SharedBaseAddress); 1995 ArchiveBuilder::serialize_dynamic_archivable_items(&rc); 1996 DynamicArchive::setup_array_klasses(); 1997 } 1998 1999 LogStreamHandle(Info, aot) lsh; 2000 if (lsh.is_enabled()) { 2001 lsh.print("Using AOT-linked classes: %s (static archive: %s aot-linked classes", 2002 BOOL_TO_STR(CDSConfig::is_using_aot_linked_classes()), 2003 static_mapinfo->header()->has_aot_linked_classes() ? "has" : "no"); 2004 if (dynamic_mapinfo != nullptr) { 2005 lsh.print(", dynamic archive: %s aot-linked classes", 2006 dynamic_mapinfo->header()->has_aot_linked_classes() ? "has" : "no"); 2007 } 2008 lsh.print_cr(")"); 2009 } 2010 2011 // Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump 2012 if (CDSConfig::is_dumping_dynamic_archive()) { 2013 // Read stored LF format lines stored in static archive 2014 LambdaFormInvokers::read_static_archive_invokers(); 2015 } 2016 2017 if (PrintSharedArchiveAndExit) { 2018 // Print archive names 2019 if (dynamic_mapinfo != nullptr) { 2020 tty->print_cr("\n\nBase archive name: %s", CDSConfig::input_static_archive_path()); 2021 tty->print_cr("Base archive version %d", static_mapinfo->version()); 2022 } else { 2023 tty->print_cr("Static archive name: %s", static_mapinfo->full_path()); 2024 tty->print_cr("Static archive version %d", static_mapinfo->version()); 2025 } 2026 2027 SystemDictionaryShared::print_shared_archive(tty); 2028 if (dynamic_mapinfo != nullptr) { 2029 tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path()); 2030 tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version()); 2031 SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/); 2032 } 2033 2034 TrainingData::print_archived_training_data_on(tty); 2035 2036 AOTCodeCache::print_on(tty); 2037 2038 // collect shared symbols and strings 2039 CountSharedSymbols cl; 2040 SymbolTable::shared_symbols_do(&cl); 2041 tty->print_cr("Number of shared symbols: %d", cl.total()); 2042 tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count()); 2043 tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version()); 2044 if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) { 2045 tty->print_cr("archive is invalid"); 2046 vm_exit(1); 2047 } else { 2048 tty->print_cr("archive is valid"); 2049 vm_exit(0); 2050 } 2051 } 2052 } 2053 2054 // JVM/TI RedefineClasses() support: 2055 bool AOTMetaspace::remap_shared_readonly_as_readwrite() { 2056 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 2057 2058 if (CDSConfig::is_using_archive()) { 2059 // remap the shared readonly space to shared readwrite, private 2060 FileMapInfo* mapinfo = FileMapInfo::current_info(); 2061 if (!mapinfo->remap_shared_readonly_as_readwrite()) { 2062 return false; 2063 } 2064 if (FileMapInfo::dynamic_info() != nullptr) { 2065 mapinfo = FileMapInfo::dynamic_info(); 2066 if (!mapinfo->remap_shared_readonly_as_readwrite()) { 2067 return false; 2068 } 2069 } 2070 _remapped_readwrite = true; 2071 } 2072 return true; 2073 } 2074 2075 void AOTMetaspace::print_on(outputStream* st) { 2076 if (CDSConfig::is_using_archive()) { 2077 st->print("CDS archive(s) mapped at: "); 2078 address base = (address)MetaspaceObj::aot_metaspace_base(); 2079 address static_top = (address)_aot_metaspace_static_top; 2080 address top = (address)MetaspaceObj::aot_metaspace_top(); 2081 st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top)); 2082 st->print("size %zu, ", top - base); 2083 st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, ArchiveRelocationMode); 2084 } else { 2085 st->print("CDS archive(s) not mapped"); 2086 } 2087 st->cr(); 2088 }