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