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