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