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