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