1 /* 2 * Copyright (c) 2012, 2023, 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 "precompiled.hpp" 26 #include "cds/archiveBuilder.hpp" 27 #include "cds/archiveHeapLoader.hpp" 28 #include "cds/archiveHeapWriter.hpp" 29 #include "cds/cds_globals.hpp" 30 #include "cds/cdsConfig.hpp" 31 #include "cds/cdsProtectionDomain.hpp" 32 #include "cds/cds_globals.hpp" 33 #include "cds/classListParser.hpp" 34 #include "cds/classListWriter.hpp" 35 #include "cds/classPrelinker.hpp" 36 #include "cds/cppVtables.hpp" 37 #include "cds/dumpAllocStats.hpp" 38 #include "cds/dynamicArchive.hpp" 39 #include "cds/filemap.hpp" 40 #include "cds/heapShared.hpp" 41 #include "cds/lambdaFormInvokers.hpp" 42 #include "cds/metaspaceShared.hpp" 43 #include "classfile/classLoaderDataGraph.hpp" 44 #include "classfile/classLoaderDataShared.hpp" 45 #include "classfile/classLoaderExt.hpp" 46 #include "classfile/javaClasses.inline.hpp" 47 #include "classfile/loaderConstraints.hpp" 48 #include "classfile/modules.hpp" 49 #include "classfile/placeholders.hpp" 50 #include "classfile/stringTable.hpp" 51 #include "classfile/symbolTable.hpp" 52 #include "classfile/systemDictionary.hpp" 53 #include "classfile/systemDictionaryShared.hpp" 54 #include "classfile/vmClasses.hpp" 55 #include "classfile/vmSymbols.hpp" 56 #include "code/codeCache.hpp" 57 #include "gc/shared/gcVMOperations.hpp" 58 #include "interpreter/bytecodeStream.hpp" 59 #include "interpreter/bytecodes.hpp" 60 #include "jvm_io.h" 61 #include "logging/log.hpp" 62 #include "logging/logMessage.hpp" 63 #include "logging/logStream.hpp" 64 #include "memory/metaspace.hpp" 65 #include "memory/metaspaceClosure.hpp" 66 #include "memory/resourceArea.hpp" 67 #include "memory/universe.hpp" 68 #include "nmt/memTracker.hpp" 69 #include "oops/compressedKlass.hpp" 70 #include "oops/instanceMirrorKlass.hpp" 71 #include "oops/klass.inline.hpp" 72 #include "oops/objArrayOop.hpp" 73 #include "oops/oop.inline.hpp" 74 #include "oops/oopHandle.hpp" 75 #include "prims/jvmtiExport.hpp" 76 #include "runtime/arguments.hpp" 77 #include "runtime/globals.hpp" 78 #include "runtime/globals_extension.hpp" 79 #include "runtime/handles.inline.hpp" 80 #include "runtime/os.inline.hpp" 81 #include "runtime/safepointVerifiers.hpp" 82 #include "runtime/sharedRuntime.hpp" 83 #include "runtime/vmOperations.hpp" 84 #include "runtime/vmThread.hpp" 85 #include "sanitizers/leak.hpp" 86 #include "utilities/align.hpp" 87 #include "utilities/bitMap.inline.hpp" 88 #include "utilities/defaultStream.hpp" 89 #include "utilities/ostream.hpp" 90 #include "utilities/resourceHash.hpp" 91 92 ReservedSpace MetaspaceShared::_symbol_rs; 93 VirtualSpace MetaspaceShared::_symbol_vs; 94 bool MetaspaceShared::_archive_loading_failed = false; 95 bool MetaspaceShared::_remapped_readwrite = false; 96 void* MetaspaceShared::_shared_metaspace_static_top = nullptr; 97 intx MetaspaceShared::_relocation_delta; 98 char* MetaspaceShared::_requested_base_address; 99 bool MetaspaceShared::_use_optimized_module_handling = true; 100 101 // The CDS archive is divided into the following regions: 102 // rw - read-write metadata 103 // ro - read-only metadata and read-only tables 104 // hp - heap region 105 // bm - bitmap for relocating the above 7 regions. 106 // 107 // The rw and ro regions are linearly allocated, in the order of rw->ro. 108 // These regions are aligned with MetaspaceShared::core_region_alignment(). 109 // 110 // These 2 regions are populated in the following steps: 111 // [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are 112 // temporarily allocated outside of the shared regions. 113 // [1] We enter a safepoint and allocate a buffer for the rw/ro regions. 114 // [2] C++ vtables are copied into the rw region. 115 // [3] ArchiveBuilder copies RW metadata into the rw region. 116 // [4] ArchiveBuilder copies RO metadata into the ro region. 117 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data 118 // are copied into the ro region as read-only tables. 119 // 120 // The heap region is populated by HeapShared::archive_objects. 121 // 122 // The bitmap region is used to relocate the ro/rw/hp regions. 123 124 static DumpRegion _symbol_region("symbols"); 125 126 char* MetaspaceShared::symbol_space_alloc(size_t num_bytes) { 127 return _symbol_region.allocate(num_bytes); 128 } 129 130 // os::vm_allocation_granularity() is usually 4K for most OSes. However, some platforms 131 // such as linux-aarch64 and macos-x64 ... 132 // it can be either 4K or 64K and on macos-aarch64 it is 16K. To generate archives that are 133 // compatible for both settings, an alternative cds core region alignment can be enabled 134 // at building time: 135 // --enable-compactible-cds-alignment 136 // Upon successful configuration, the compactible alignment then can be defined in: 137 // os_linux_aarch64.cpp 138 // os_bsd_x86.cpp 139 size_t MetaspaceShared::core_region_alignment() { 140 return os::cds_core_region_alignment(); 141 } 142 143 static bool shared_base_valid(char* shared_base) { 144 #ifdef _LP64 145 return CompressedKlassPointers::is_valid_base((address)shared_base); 146 #else 147 return true; 148 #endif 149 } 150 151 class DumpClassListCLDClosure : public CLDClosure { 152 static const int INITIAL_TABLE_SIZE = 1987; 153 static const int MAX_TABLE_SIZE = 61333; 154 155 fileStream *_stream; 156 ResizeableResourceHashtable<InstanceKlass*, bool, 157 AnyObj::C_HEAP, mtClassShared> _dumped_classes; 158 159 void dump(InstanceKlass* ik) { 160 bool created; 161 _dumped_classes.put_if_absent(ik, &created); 162 if (!created) { 163 return; 164 } 165 if (_dumped_classes.maybe_grow()) { 166 log_info(cds, hashtables)("Expanded _dumped_classes table to %d", _dumped_classes.table_size()); 167 } 168 if (ik->java_super()) { 169 dump(ik->java_super()); 170 } 171 Array<InstanceKlass*>* interfaces = ik->local_interfaces(); 172 int len = interfaces->length(); 173 for (int i = 0; i < len; i++) { 174 dump(interfaces->at(i)); 175 } 176 ClassListWriter::write_to_stream(ik, _stream); 177 } 178 179 public: 180 DumpClassListCLDClosure(fileStream* f) 181 : CLDClosure(), _dumped_classes(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE) { 182 _stream = f; 183 } 184 185 void do_cld(ClassLoaderData* cld) { 186 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) { 187 if (klass->is_instance_klass()) { 188 dump(InstanceKlass::cast(klass)); 189 } 190 } 191 } 192 }; 193 194 void MetaspaceShared::dump_loaded_classes(const char* file_name, TRAPS) { 195 fileStream stream(file_name, "w"); 196 if (stream.is_open()) { 197 MutexLocker lock(ClassLoaderDataGraph_lock); 198 MutexLocker lock2(ClassListFile_lock, Mutex::_no_safepoint_check_flag); 199 DumpClassListCLDClosure collect_classes(&stream); 200 ClassLoaderDataGraph::loaded_cld_do(&collect_classes); 201 } else { 202 THROW_MSG(vmSymbols::java_io_IOException(), "Failed to open file"); 203 } 204 } 205 206 static bool shared_base_too_high(char* specified_base, char* aligned_base, size_t cds_max) { 207 if (specified_base != nullptr && aligned_base < specified_base) { 208 // SharedBaseAddress is very high (e.g., 0xffffffffffffff00) so 209 // align_up(SharedBaseAddress, MetaspaceShared::core_region_alignment()) has wrapped around. 210 return true; 211 } 212 if (max_uintx - uintx(aligned_base) < uintx(cds_max)) { 213 // The end of the archive will wrap around 214 return true; 215 } 216 217 return false; 218 } 219 220 static char* compute_shared_base(size_t cds_max) { 221 char* specified_base = (char*)SharedBaseAddress; 222 char* aligned_base = align_up(specified_base, MetaspaceShared::core_region_alignment()); 223 224 const char* err = nullptr; 225 if (shared_base_too_high(specified_base, aligned_base, cds_max)) { 226 err = "too high"; 227 } else if (!shared_base_valid(aligned_base)) { 228 err = "invalid for this platform"; 229 } else { 230 return aligned_base; 231 } 232 233 log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT, 234 p2i((void*)SharedBaseAddress), err, 235 p2i((void*)Arguments::default_SharedBaseAddress())); 236 237 specified_base = (char*)Arguments::default_SharedBaseAddress(); 238 aligned_base = align_up(specified_base, MetaspaceShared::core_region_alignment()); 239 240 // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane. 241 assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity"); 242 assert(shared_base_valid(aligned_base), "Sanity"); 243 return aligned_base; 244 } 245 246 void MetaspaceShared::initialize_for_static_dump() { 247 assert(CDSConfig::is_dumping_static_archive(), "sanity"); 248 log_info(cds)("Core region alignment: " SIZE_FORMAT, core_region_alignment()); 249 // The max allowed size for CDS archive. We use this to limit SharedBaseAddress 250 // to avoid address space wrap around. 251 size_t cds_max; 252 const size_t reserve_alignment = core_region_alignment(); 253 254 #ifdef _LP64 255 const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1); 256 cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment); 257 #else 258 // We don't support archives larger than 256MB on 32-bit due to limited 259 // virtual address space. 260 cds_max = align_down(256*M, reserve_alignment); 261 #endif 262 263 _requested_base_address = compute_shared_base(cds_max); 264 SharedBaseAddress = (size_t)_requested_base_address; 265 266 size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M); 267 _symbol_rs = ReservedSpace(symbol_rs_size); 268 if (!_symbol_rs.is_reserved()) { 269 log_error(cds)("Unable to reserve memory for symbols: " SIZE_FORMAT " bytes.", symbol_rs_size); 270 MetaspaceShared::unrecoverable_writing_error(); 271 } 272 _symbol_region.init(&_symbol_rs, &_symbol_vs); 273 } 274 275 // Called by universe_post_init() 276 void MetaspaceShared::post_initialize(TRAPS) { 277 if (UseSharedSpaces) { 278 int size = FileMapInfo::get_number_of_shared_paths(); 279 if (size > 0) { 280 CDSProtectionDomain::allocate_shared_data_arrays(size, CHECK); 281 if (!CDSConfig::is_dumping_dynamic_archive()) { 282 FileMapInfo* info; 283 if (FileMapInfo::dynamic_info() == nullptr) { 284 info = FileMapInfo::current_info(); 285 } else { 286 info = FileMapInfo::dynamic_info(); 287 } 288 ClassLoaderExt::init_paths_start_index(info->app_class_paths_start_index()); 289 ClassLoaderExt::init_app_module_paths_start_index(info->app_module_paths_start_index()); 290 } 291 } 292 } 293 } 294 295 static GrowableArrayCHeap<OopHandle, mtClassShared>* _extra_interned_strings = nullptr; 296 static GrowableArrayCHeap<Symbol*, mtClassShared>* _extra_symbols = nullptr; 297 298 void MetaspaceShared::read_extra_data(JavaThread* current, const char* filename) { 299 _extra_interned_strings = new GrowableArrayCHeap<OopHandle, mtClassShared>(10000); 300 _extra_symbols = new GrowableArrayCHeap<Symbol*, mtClassShared>(1000); 301 302 HashtableTextDump reader(filename); 303 reader.check_version("VERSION: 1.0"); 304 305 while (reader.remain() > 0) { 306 int utf8_length; 307 int prefix_type = reader.scan_prefix(&utf8_length); 308 ResourceMark rm(current); 309 if (utf8_length == 0x7fffffff) { 310 // buf_len will overflown 32-bit value. 311 log_error(cds)("string length too large: %d", utf8_length); 312 MetaspaceShared::unrecoverable_loading_error(); 313 } 314 int buf_len = utf8_length+1; 315 char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len); 316 reader.get_utf8(utf8_buffer, utf8_length); 317 utf8_buffer[utf8_length] = '\0'; 318 319 if (prefix_type == HashtableTextDump::SymbolPrefix) { 320 _extra_symbols->append(SymbolTable::new_permanent_symbol(utf8_buffer)); 321 } else{ 322 assert(prefix_type == HashtableTextDump::StringPrefix, "Sanity"); 323 ExceptionMark em(current); 324 JavaThread* THREAD = current; // For exception macros. 325 oop str = StringTable::intern(utf8_buffer, THREAD); 326 327 if (HAS_PENDING_EXCEPTION) { 328 log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d", 329 reader.last_line_no(), utf8_length); 330 CLEAR_PENDING_EXCEPTION; 331 } else { 332 #if INCLUDE_CDS_JAVA_HEAP 333 if (ArchiveHeapWriter::is_string_too_large_to_archive(str)) { 334 log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d", 335 reader.last_line_no(), utf8_length); 336 continue; 337 } 338 // Make sure this string is included in the dumped interned string table. 339 assert(str != nullptr, "must succeed"); 340 _extra_interned_strings->append(OopHandle(Universe::vm_global(), str)); 341 #endif 342 } 343 } 344 } 345 } 346 347 // Read/write a data stream for restoring/preserving metadata pointers and 348 // miscellaneous data from/to the shared archive file. 349 350 void MetaspaceShared::serialize(SerializeClosure* soc) { 351 int tag = 0; 352 soc->do_tag(--tag); 353 354 // Verify the sizes of various metadata in the system. 355 soc->do_tag(sizeof(Method)); 356 soc->do_tag(sizeof(ConstMethod)); 357 soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE)); 358 soc->do_tag(sizeof(ConstantPool)); 359 soc->do_tag(sizeof(ConstantPoolCache)); 360 soc->do_tag(objArrayOopDesc::base_offset_in_bytes()); 361 soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE)); 362 soc->do_tag(sizeof(Symbol)); 363 364 // Need to do this first, as subsequent steps may call virtual functions 365 // in archived Metadata objects. 366 CppVtables::serialize(soc); 367 soc->do_tag(--tag); 368 369 // Dump/restore miscellaneous metadata. 370 JavaClasses::serialize_offsets(soc); 371 Universe::serialize(soc); 372 soc->do_tag(--tag); 373 374 // Dump/restore references to commonly used names and signatures. 375 vmSymbols::serialize(soc); 376 soc->do_tag(--tag); 377 378 // Dump/restore the symbol/string/subgraph_info tables 379 SymbolTable::serialize_shared_table_header(soc); 380 StringTable::serialize_shared_table_header(soc); 381 HeapShared::serialize_tables(soc); 382 SystemDictionaryShared::serialize_dictionary_headers(soc); 383 384 InstanceMirrorKlass::serialize_offsets(soc); 385 386 // Dump/restore well known classes (pointers) 387 SystemDictionaryShared::serialize_vm_classes(soc); 388 soc->do_tag(--tag); 389 390 CDS_JAVA_HEAP_ONLY(Modules::serialize(soc);) 391 CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);) 392 393 LambdaFormInvokers::serialize(soc); 394 soc->do_tag(666); 395 } 396 397 static void rewrite_nofast_bytecode(const methodHandle& method) { 398 BytecodeStream bcs(method); 399 while (!bcs.is_last_bytecode()) { 400 Bytecodes::Code opcode = bcs.next(); 401 switch (opcode) { 402 case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break; 403 case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break; 404 case Bytecodes::_aload_0: *bcs.bcp() = Bytecodes::_nofast_aload_0; break; 405 case Bytecodes::_iload: { 406 if (!bcs.is_wide()) { 407 *bcs.bcp() = Bytecodes::_nofast_iload; 408 } 409 break; 410 } 411 default: break; 412 } 413 } 414 } 415 416 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified 417 // at run time by RewriteBytecodes/RewriteFrequentPairs 418 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time. 419 void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) { 420 for (int i = 0; i < ik->methods()->length(); i++) { 421 methodHandle m(thread, ik->methods()->at(i)); 422 if (ik->can_be_verified_at_dumptime() && ik->is_linked()) { 423 rewrite_nofast_bytecode(m); 424 } 425 Fingerprinter fp(m); 426 // The side effect of this call sets method's fingerprint field. 427 fp.fingerprint(); 428 } 429 } 430 431 class VM_PopulateDumpSharedSpace : public VM_Operation { 432 private: 433 ArchiveHeapInfo _heap_info; 434 435 void dump_java_heap_objects(GrowableArray<Klass*>* klasses) NOT_CDS_JAVA_HEAP_RETURN; 436 void dump_shared_symbol_table(GrowableArray<Symbol*>* symbols) { 437 log_info(cds)("Dumping symbol table ..."); 438 SymbolTable::write_to_archive(symbols); 439 } 440 char* dump_read_only_tables(); 441 442 public: 443 444 VM_PopulateDumpSharedSpace() : VM_Operation(), _heap_info() {} 445 446 bool skip_operation() const { return false; } 447 448 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; } 449 void doit(); // outline because gdb sucks 450 bool allow_nested_vm_operations() const { return true; } 451 }; // class VM_PopulateDumpSharedSpace 452 453 class StaticArchiveBuilder : public ArchiveBuilder { 454 public: 455 StaticArchiveBuilder() : ArchiveBuilder() {} 456 457 virtual void iterate_roots(MetaspaceClosure* it) { 458 FileMapInfo::metaspace_pointers_do(it); 459 SystemDictionaryShared::dumptime_classes_do(it); 460 Universe::metaspace_pointers_do(it); 461 vmSymbols::metaspace_pointers_do(it); 462 463 // The above code should find all the symbols that are referenced by the 464 // archived classes. We just need to add the extra symbols which 465 // may not be used by any of the archived classes -- these are usually 466 // symbols that we anticipate to be used at run time, so we can store 467 // them in the RO region, to be shared across multiple processes. 468 if (_extra_symbols != nullptr) { 469 for (int i = 0; i < _extra_symbols->length(); i++) { 470 it->push(_extra_symbols->adr_at(i)); 471 } 472 } 473 } 474 }; 475 476 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() { 477 ArchiveBuilder::OtherROAllocMark mark; 478 479 SystemDictionaryShared::write_to_archive(); 480 481 // Write lambform lines into archive 482 LambdaFormInvokers::dump_static_archive_invokers(); 483 // Write module name into archive 484 CDS_JAVA_HEAP_ONLY(Modules::dump_main_module_name();) 485 // Write the other data to the output array. 486 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region(); 487 char* start = ro_region->top(); 488 WriteClosure wc(ro_region); 489 MetaspaceShared::serialize(&wc); 490 491 return start; 492 } 493 494 void VM_PopulateDumpSharedSpace::doit() { 495 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm); 496 497 FileMapInfo::check_nonempty_dir_in_shared_path_table(); 498 499 NOT_PRODUCT(SystemDictionary::verify();) 500 501 // Block concurrent class unloading from changing the _dumptime_table 502 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag); 503 SystemDictionaryShared::check_excluded_classes(); 504 505 StaticArchiveBuilder builder; 506 builder.gather_source_objs(); 507 builder.reserve_buffer(); 508 509 char* cloned_vtables = CppVtables::dumptime_init(&builder); 510 511 // Initialize random for updating the hash of symbols 512 os::init_random(0x12345678); 513 514 builder.dump_rw_metadata(); 515 builder.dump_ro_metadata(); 516 builder.relocate_metaspaceobj_embedded_pointers(); 517 518 dump_java_heap_objects(builder.klasses()); 519 dump_shared_symbol_table(builder.symbols()); 520 521 log_info(cds)("Make classes shareable"); 522 builder.make_klasses_shareable(); 523 524 char* serialized_data = dump_read_only_tables(); 525 526 SystemDictionaryShared::adjust_lambda_proxy_class_dictionary(); 527 528 // The vtable clones contain addresses of the current process. 529 // We don't want to write these addresses into the archive. 530 CppVtables::zero_archived_vtables(); 531 532 // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address() 533 // without runtime relocation. 534 builder.relocate_to_requested(); 535 536 // Write the archive file 537 const char* static_archive = Arguments::GetSharedArchivePath(); 538 assert(static_archive != nullptr, "SharedArchiveFile not set?"); 539 FileMapInfo* mapinfo = new FileMapInfo(static_archive, true); 540 mapinfo->populate_header(MetaspaceShared::core_region_alignment()); 541 mapinfo->set_serialized_data(serialized_data); 542 mapinfo->set_cloned_vtables(cloned_vtables); 543 mapinfo->open_for_write(); 544 builder.write_archive(mapinfo, &_heap_info); 545 546 if (PrintSystemDictionaryAtExit) { 547 SystemDictionary::print(); 548 } 549 550 if (AllowArchivingWithJavaAgent) { 551 log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used " 552 "for testing purposes only and should not be used in a production environment"); 553 } 554 } 555 556 class CollectCLDClosure : public CLDClosure { 557 GrowableArray<ClassLoaderData*> _loaded_cld; 558 GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive 559 Thread* _current_thread; 560 public: 561 CollectCLDClosure(Thread* thread) : _current_thread(thread) {} 562 ~CollectCLDClosure() { 563 for (int i = 0; i < _loaded_cld_handles.length(); i++) { 564 _loaded_cld_handles.at(i).release(Universe::vm_global()); 565 } 566 } 567 void do_cld(ClassLoaderData* cld) { 568 assert(cld->is_alive(), "must be"); 569 _loaded_cld.append(cld); 570 _loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder())); 571 } 572 573 int nof_cld() const { return _loaded_cld.length(); } 574 ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); } 575 }; 576 577 // Check if we can eagerly link this class at dump time, so we can avoid the 578 // runtime linking overhead (especially verification) 579 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) { 580 if (!ik->can_be_verified_at_dumptime()) { 581 // For old classes, try to leave them in the unlinked state, so 582 // we can still store them in the archive. They must be 583 // linked/verified at runtime. 584 return false; 585 } 586 if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) { 587 // Linking of unregistered classes at this stage may cause more 588 // classes to be resolved, resulting in calls to ClassLoader.loadClass() 589 // that may not be expected by custom class loaders. 590 // 591 // It's OK to do this for the built-in loaders as we know they can 592 // tolerate this. 593 return false; 594 } 595 return true; 596 } 597 598 bool MetaspaceShared::link_class_for_cds(InstanceKlass* ik, TRAPS) { 599 // Link the class to cause the bytecodes to be rewritten and the 600 // cpcache to be created. Class verification is done according 601 // to -Xverify setting. 602 bool res = MetaspaceShared::try_link_class(THREAD, ik); 603 ClassPrelinker::dumptime_resolve_constants(ik, CHECK_(false)); 604 return res; 605 } 606 607 void MetaspaceShared::link_shared_classes(bool jcmd_request, TRAPS) { 608 ClassPrelinker::initialize(); 609 610 if (!jcmd_request) { 611 LambdaFormInvokers::regenerate_holder_classes(CHECK); 612 } 613 614 // Collect all loaded ClassLoaderData. 615 CollectCLDClosure collect_cld(THREAD); 616 { 617 // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock. 618 // We cannot link the classes while holding this lock (or else we may run into deadlock). 619 // Therefore, we need to first collect all the CLDs, and then link their classes after 620 // releasing the lock. 621 MutexLocker lock(ClassLoaderDataGraph_lock); 622 ClassLoaderDataGraph::loaded_cld_do(&collect_cld); 623 } 624 625 while (true) { 626 bool has_linked = false; 627 for (int i = 0; i < collect_cld.nof_cld(); i++) { 628 ClassLoaderData* cld = collect_cld.cld_at(i); 629 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) { 630 if (klass->is_instance_klass()) { 631 InstanceKlass* ik = InstanceKlass::cast(klass); 632 if (may_be_eagerly_linked(ik)) { 633 has_linked |= link_class_for_cds(ik, CHECK); 634 } 635 } 636 } 637 } 638 639 if (!has_linked) { 640 break; 641 } 642 // Class linking includes verification which may load more classes. 643 // Keep scanning until we have linked no more classes. 644 } 645 } 646 647 void MetaspaceShared::prepare_for_dumping() { 648 assert(CDSConfig::is_dumping_archive(), "sanity"); 649 Arguments::check_unsupported_dumping_properties(); 650 651 ClassLoader::initialize_shared_path(JavaThread::current()); 652 } 653 654 // Preload classes from a list, populate the shared spaces and dump to a 655 // file. 656 void MetaspaceShared::preload_and_dump() { 657 EXCEPTION_MARK; 658 ResourceMark rm(THREAD); 659 preload_and_dump_impl(THREAD); 660 if (HAS_PENDING_EXCEPTION) { 661 if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) { 662 log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = " 663 SIZE_FORMAT "M", MaxHeapSize/M); 664 MetaspaceShared::unrecoverable_writing_error(); 665 } else { 666 log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(), 667 java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION))); 668 MetaspaceShared::unrecoverable_writing_error("VM exits due to exception, use -Xlog:cds,exceptions=trace for detail"); 669 } 670 } 671 } 672 673 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64) 674 void MetaspaceShared::adjust_heap_sizes_for_dumping() { 675 if (!CDSConfig::is_dumping_heap() || UseCompressedOops) { 676 return; 677 } 678 // CDS heap dumping requires all string oops to have an offset 679 // from the heap bottom that can be encoded in 32-bit. 680 julong max_heap_size = (julong)(4 * G); 681 682 if (MinHeapSize > max_heap_size) { 683 log_debug(cds)("Setting MinHeapSize to 4G for CDS dumping, original size = " SIZE_FORMAT "M", MinHeapSize/M); 684 FLAG_SET_ERGO(MinHeapSize, max_heap_size); 685 } 686 if (InitialHeapSize > max_heap_size) { 687 log_debug(cds)("Setting InitialHeapSize to 4G for CDS dumping, original size = " SIZE_FORMAT "M", InitialHeapSize/M); 688 FLAG_SET_ERGO(InitialHeapSize, max_heap_size); 689 } 690 if (MaxHeapSize > max_heap_size) { 691 log_debug(cds)("Setting MaxHeapSize to 4G for CDS dumping, original size = " SIZE_FORMAT "M", MaxHeapSize/M); 692 FLAG_SET_ERGO(MaxHeapSize, max_heap_size); 693 } 694 } 695 #endif // INCLUDE_CDS_JAVA_HEAP && _LP64 696 697 void MetaspaceShared::get_default_classlist(char* default_classlist, const size_t buf_size) { 698 // Construct the path to the class list (in jre/lib) 699 // Walk up two directories from the location of the VM and 700 // optionally tack on "lib" (depending on platform) 701 os::jvm_path(default_classlist, (jint)(buf_size)); 702 for (int i = 0; i < 3; i++) { 703 char *end = strrchr(default_classlist, *os::file_separator()); 704 if (end != nullptr) *end = '\0'; 705 } 706 size_t classlist_path_len = strlen(default_classlist); 707 if (classlist_path_len >= 3) { 708 if (strcmp(default_classlist + classlist_path_len - 3, "lib") != 0) { 709 if (classlist_path_len < buf_size - 4) { 710 jio_snprintf(default_classlist + classlist_path_len, 711 buf_size - classlist_path_len, 712 "%slib", os::file_separator()); 713 classlist_path_len += 4; 714 } 715 } 716 } 717 if (classlist_path_len < buf_size - 10) { 718 jio_snprintf(default_classlist + classlist_path_len, 719 buf_size - classlist_path_len, 720 "%sclasslist", os::file_separator()); 721 } 722 } 723 724 void MetaspaceShared::preload_classes(TRAPS) { 725 char default_classlist[JVM_MAXPATHLEN]; 726 const char* classlist_path; 727 728 get_default_classlist(default_classlist, sizeof(default_classlist)); 729 if (SharedClassListFile == nullptr) { 730 classlist_path = default_classlist; 731 } else { 732 classlist_path = SharedClassListFile; 733 } 734 735 log_info(cds)("Loading classes to share ..."); 736 int class_count = ClassListParser::parse_classlist(classlist_path, 737 ClassListParser::_parse_all, CHECK); 738 if (ExtraSharedClassListFile) { 739 class_count += ClassListParser::parse_classlist(ExtraSharedClassListFile, 740 ClassListParser::_parse_all, CHECK); 741 } 742 if (classlist_path != default_classlist) { 743 struct stat statbuf; 744 if (os::stat(default_classlist, &statbuf) == 0) { 745 // File exists, let's use it. 746 class_count += ClassListParser::parse_classlist(default_classlist, 747 ClassListParser::_parse_lambda_forms_invokers_only, CHECK); 748 } 749 } 750 751 // Exercise the manifest processing code to ensure classes used by CDS at runtime 752 // are always archived 753 const char* dummy = "Manifest-Version: 1.0\n"; 754 CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK); 755 756 log_info(cds)("Loading classes to share: done."); 757 log_info(cds)("Shared spaces: preloaded %d classes", class_count); 758 } 759 760 void MetaspaceShared::preload_and_dump_impl(TRAPS) { 761 preload_classes(CHECK); 762 763 if (SharedArchiveConfigFile) { 764 log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile); 765 read_extra_data(THREAD, SharedArchiveConfigFile); 766 log_info(cds)("Reading extra data: done."); 767 } 768 769 // Rewrite and link classes 770 log_info(cds)("Rewriting and linking classes ..."); 771 772 // Link any classes which got missed. This would happen if we have loaded classes that 773 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K 774 // fails verification, all other interfaces that were not specified in the classlist but 775 // are implemented by K are not verified. 776 link_shared_classes(false/*not from jcmd*/, CHECK); 777 log_info(cds)("Rewriting and linking classes: done"); 778 779 #if INCLUDE_CDS_JAVA_HEAP 780 if (CDSConfig::is_dumping_heap()) { 781 StringTable::allocate_shared_strings_array(CHECK); 782 if (!HeapShared::is_archived_boot_layer_available(THREAD)) { 783 log_info(cds)("archivedBootLayer not available, disabling full module graph"); 784 CDSConfig::disable_dumping_full_module_graph(); 785 } 786 HeapShared::init_for_dumping(CHECK); 787 ArchiveHeapWriter::init(); 788 if (CDSConfig::is_dumping_full_module_graph()) { 789 HeapShared::reset_archived_object_states(CHECK); 790 } 791 } 792 #endif 793 794 VM_PopulateDumpSharedSpace op; 795 VMThread::execute(&op); 796 } 797 798 // Returns true if the class's status has changed. 799 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) { 800 ExceptionMark em(current); 801 JavaThread* THREAD = current; // For exception macros. 802 assert(CDSConfig::is_dumping_archive(), "sanity"); 803 if (!ik->is_shared() && ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() && 804 !SystemDictionaryShared::has_class_failed_verification(ik)) { 805 bool saved = BytecodeVerificationLocal; 806 if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) { 807 // The verification decision is based on BytecodeVerificationRemote 808 // for non-system classes. Since we are using the null classloader 809 // to load non-system classes for customized class loaders during dumping, 810 // we need to temporarily change BytecodeVerificationLocal to be the same as 811 // BytecodeVerificationRemote. Note this can cause the parent system 812 // classes also being verified. The extra overhead is acceptable during 813 // dumping. 814 BytecodeVerificationLocal = BytecodeVerificationRemote; 815 } 816 ik->link_class(THREAD); 817 if (HAS_PENDING_EXCEPTION) { 818 ResourceMark rm(THREAD); 819 log_warning(cds)("Preload Warning: Verification failed for %s", 820 ik->external_name()); 821 CLEAR_PENDING_EXCEPTION; 822 SystemDictionaryShared::set_class_has_failed_verification(ik); 823 } 824 ik->compute_has_loops_flag_for_methods(); 825 BytecodeVerificationLocal = saved; 826 return true; 827 } else { 828 return false; 829 } 830 } 831 832 #if INCLUDE_CDS_JAVA_HEAP 833 void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) { 834 if(!HeapShared::can_write()) { 835 log_info(cds)( 836 "Archived java heap is not supported as UseG1GC " 837 "and UseCompressedClassPointers are required." 838 "Current settings: UseG1GC=%s, UseCompressedClassPointers=%s.", 839 BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedClassPointers)); 840 return; 841 } 842 // Find all the interned strings that should be dumped. 843 int i; 844 for (i = 0; i < klasses->length(); i++) { 845 Klass* k = klasses->at(i); 846 if (k->is_instance_klass()) { 847 InstanceKlass* ik = InstanceKlass::cast(k); 848 if (ik->is_linked()) { 849 ik->constants()->add_dumped_interned_strings(); 850 } 851 } 852 } 853 if (_extra_interned_strings != nullptr) { 854 for (i = 0; i < _extra_interned_strings->length(); i ++) { 855 OopHandle string = _extra_interned_strings->at(i); 856 HeapShared::add_to_dumped_interned_strings(string.resolve()); 857 } 858 } 859 860 HeapShared::archive_objects(&_heap_info); 861 ArchiveBuilder::OtherROAllocMark mark; 862 HeapShared::write_subgraph_info_table(); 863 } 864 #endif // INCLUDE_CDS_JAVA_HEAP 865 866 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) { 867 assert(base <= static_top && static_top <= top, "must be"); 868 _shared_metaspace_static_top = static_top; 869 MetaspaceObj::set_shared_metaspace_range(base, top); 870 } 871 872 bool MetaspaceShared::is_shared_dynamic(void* p) { 873 if ((p < MetaspaceObj::shared_metaspace_top()) && 874 (p >= _shared_metaspace_static_top)) { 875 return true; 876 } else { 877 return false; 878 } 879 } 880 881 bool MetaspaceShared::is_shared_static(void* p) { 882 if (is_in_shared_metaspace(p) && !is_shared_dynamic(p)) { 883 return true; 884 } else { 885 return false; 886 } 887 } 888 889 // This function is called when the JVM is unable to load the specified archive(s) due to one 890 // of the following conditions. 891 // - There's an error that indicates that the archive(s) files were corrupt or otherwise damaged. 892 // - When -XX:+RequireSharedSpaces is specified, AND the JVM cannot load the archive(s) due 893 // to version or classpath mismatch. 894 void MetaspaceShared::unrecoverable_loading_error(const char* message) { 895 log_error(cds)("An error has occurred while processing the shared archive file."); 896 if (message != nullptr) { 897 log_error(cds)("%s", message); 898 } 899 vm_exit_during_initialization("Unable to use shared archive.", nullptr); 900 } 901 902 // This function is called when the JVM is unable to write the specified CDS archive due to an 903 // unrecoverable error. 904 void MetaspaceShared::unrecoverable_writing_error(const char* message) { 905 log_error(cds)("An error has occurred while writing the shared archive file."); 906 if (message != nullptr) { 907 log_error(cds)("%s", message); 908 } 909 vm_direct_exit(1); 910 } 911 912 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() { 913 assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled"); 914 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE; 915 916 FileMapInfo* static_mapinfo = open_static_archive(); 917 FileMapInfo* dynamic_mapinfo = nullptr; 918 919 if (static_mapinfo != nullptr) { 920 log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment()); 921 dynamic_mapinfo = open_dynamic_archive(); 922 923 // First try to map at the requested address 924 result = map_archives(static_mapinfo, dynamic_mapinfo, true); 925 if (result == MAP_ARCHIVE_MMAP_FAILURE) { 926 // Mapping has failed (probably due to ASLR). Let's map at an address chosen 927 // by the OS. 928 log_info(cds)("Try to map archive(s) at an alternative address"); 929 result = map_archives(static_mapinfo, dynamic_mapinfo, false); 930 } 931 } 932 933 if (result == MAP_ARCHIVE_SUCCESS) { 934 bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped()); 935 char* cds_base = static_mapinfo->mapped_base(); 936 char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end(); 937 // Register CDS memory region with LSan. 938 LSAN_REGISTER_ROOT_REGION(cds_base, cds_end - cds_base); 939 set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end); 940 _relocation_delta = static_mapinfo->relocation_delta(); 941 _requested_base_address = static_mapinfo->requested_base_address(); 942 if (dynamic_mapped) { 943 FileMapInfo::set_shared_path_table(dynamic_mapinfo); 944 // turn AutoCreateSharedArchive off if successfully mapped 945 AutoCreateSharedArchive = false; 946 } else { 947 FileMapInfo::set_shared_path_table(static_mapinfo); 948 } 949 } else { 950 set_shared_metaspace_range(nullptr, nullptr, nullptr); 951 if (CDSConfig::is_dumping_dynamic_archive()) { 952 log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info."); 953 } 954 UseSharedSpaces = false; 955 // The base archive cannot be mapped. We cannot dump the dynamic shared archive. 956 AutoCreateSharedArchive = false; 957 CDSConfig::disable_dumping_dynamic_archive(); 958 log_info(cds)("Unable to map shared spaces"); 959 if (PrintSharedArchiveAndExit) { 960 MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive."); 961 } else if (RequireSharedSpaces) { 962 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces"); 963 } 964 } 965 966 // If mapping failed and -XShare:on, the vm should exit 967 bool has_failed = false; 968 if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) { 969 has_failed = true; 970 delete static_mapinfo; 971 } 972 if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) { 973 has_failed = true; 974 delete dynamic_mapinfo; 975 } 976 if (RequireSharedSpaces && has_failed) { 977 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces"); 978 } 979 } 980 981 FileMapInfo* MetaspaceShared::open_static_archive() { 982 const char* static_archive = Arguments::GetSharedArchivePath(); 983 assert(static_archive != nullptr, "SharedArchivePath is nullptr"); 984 FileMapInfo* mapinfo = new FileMapInfo(static_archive, true); 985 if (!mapinfo->initialize()) { 986 delete(mapinfo); 987 return nullptr; 988 } 989 return mapinfo; 990 } 991 992 FileMapInfo* MetaspaceShared::open_dynamic_archive() { 993 if (CDSConfig::is_dumping_dynamic_archive()) { 994 return nullptr; 995 } 996 const char* dynamic_archive = Arguments::GetSharedDynamicArchivePath(); 997 if (dynamic_archive == nullptr) { 998 return nullptr; 999 } 1000 1001 FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false); 1002 if (!mapinfo->initialize()) { 1003 delete(mapinfo); 1004 if (RequireSharedSpaces) { 1005 MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive"); 1006 } 1007 return nullptr; 1008 } 1009 return mapinfo; 1010 } 1011 1012 // use_requested_addr: 1013 // true = map at FileMapHeader::_requested_base_address 1014 // false = map at an alternative address picked by OS. 1015 MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo, 1016 bool use_requested_addr) { 1017 if (use_requested_addr && static_mapinfo->requested_base_address() == nullptr) { 1018 log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address."); 1019 return MAP_ARCHIVE_MMAP_FAILURE; 1020 } 1021 1022 PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) { 1023 // For product build only -- this is for benchmarking the cost of doing relocation. 1024 // For debug builds, the check is done below, after reserving the space, for better test coverage 1025 // (see comment below). 1026 log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address"); 1027 return MAP_ARCHIVE_MMAP_FAILURE; 1028 }); 1029 1030 if (ArchiveRelocationMode == 2 && !use_requested_addr) { 1031 log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address"); 1032 return MAP_ARCHIVE_MMAP_FAILURE; 1033 }; 1034 1035 if (dynamic_mapinfo != nullptr) { 1036 // Ensure that the OS won't be able to allocate new memory spaces between the two 1037 // archives, or else it would mess up the simple comparison in MetaspaceObj::is_shared(). 1038 assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap"); 1039 } 1040 1041 ReservedSpace total_space_rs, archive_space_rs, class_space_rs; 1042 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE; 1043 char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo, 1044 dynamic_mapinfo, 1045 use_requested_addr, 1046 total_space_rs, 1047 archive_space_rs, 1048 class_space_rs); 1049 if (mapped_base_address == nullptr) { 1050 result = MAP_ARCHIVE_MMAP_FAILURE; 1051 log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr); 1052 } else { 1053 1054 #ifdef ASSERT 1055 // Some sanity checks after reserving address spaces for archives 1056 // and class space. 1057 assert(archive_space_rs.is_reserved(), "Sanity"); 1058 if (Metaspace::using_class_space()) { 1059 // Class space must closely follow the archive space. Both spaces 1060 // must be aligned correctly. 1061 assert(class_space_rs.is_reserved(), 1062 "A class space should have been reserved"); 1063 assert(class_space_rs.base() >= archive_space_rs.end(), 1064 "class space should follow the cds archive space"); 1065 assert(is_aligned(archive_space_rs.base(), 1066 core_region_alignment()), 1067 "Archive space misaligned"); 1068 assert(is_aligned(class_space_rs.base(), 1069 Metaspace::reserve_alignment()), 1070 "class space misaligned"); 1071 } 1072 #endif // ASSERT 1073 1074 log_info(cds)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes", 1075 p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size()); 1076 log_info(cds)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes", 1077 p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size()); 1078 1079 if (MetaspaceShared::use_windows_memory_mapping()) { 1080 // We have now reserved address space for the archives, and will map in 1081 // the archive files into this space. 1082 // 1083 // Special handling for Windows: on Windows we cannot map a file view 1084 // into an existing memory mapping. So, we unmap the address range we 1085 // just reserved again, which will make it available for mapping the 1086 // archives. 1087 // Reserving this range has not been for naught however since it makes 1088 // us reasonably sure the address range is available. 1089 // 1090 // But still it may fail, since between unmapping the range and mapping 1091 // in the archive someone else may grab the address space. Therefore 1092 // there is a fallback in FileMap::map_region() where we just read in 1093 // the archive files sequentially instead of mapping it in. We couple 1094 // this with use_requested_addr, since we're going to patch all the 1095 // pointers anyway so there's no benefit to mmap. 1096 if (use_requested_addr) { 1097 assert(!total_space_rs.is_reserved(), "Should not be reserved for Windows"); 1098 log_info(cds)("Windows mmap workaround: releasing archive space."); 1099 archive_space_rs.release(); 1100 } 1101 } 1102 MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs); 1103 MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ? 1104 map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE; 1105 1106 DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) { 1107 // This is for simulating mmap failures at the requested address. In 1108 // debug builds, we do it here (after all archives have possibly been 1109 // mapped), so we can thoroughly test the code for failure handling 1110 // (releasing all allocated resource, etc). 1111 log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address"); 1112 if (static_result == MAP_ARCHIVE_SUCCESS) { 1113 static_result = MAP_ARCHIVE_MMAP_FAILURE; 1114 } 1115 if (dynamic_result == MAP_ARCHIVE_SUCCESS) { 1116 dynamic_result = MAP_ARCHIVE_MMAP_FAILURE; 1117 } 1118 }); 1119 1120 if (static_result == MAP_ARCHIVE_SUCCESS) { 1121 if (dynamic_result == MAP_ARCHIVE_SUCCESS) { 1122 result = MAP_ARCHIVE_SUCCESS; 1123 } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) { 1124 assert(dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped(), "must have failed"); 1125 // No need to retry mapping the dynamic archive again, as it will never succeed 1126 // (bad file, etc) -- just keep the base archive. 1127 log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s", 1128 dynamic_mapinfo->full_path()); 1129 result = MAP_ARCHIVE_SUCCESS; 1130 // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no 1131 // easy API to do that right now. 1132 } else { 1133 result = MAP_ARCHIVE_MMAP_FAILURE; 1134 } 1135 } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) { 1136 result = MAP_ARCHIVE_OTHER_FAILURE; 1137 } else { 1138 result = MAP_ARCHIVE_MMAP_FAILURE; 1139 } 1140 } 1141 1142 if (result == MAP_ARCHIVE_SUCCESS) { 1143 SharedBaseAddress = (size_t)mapped_base_address; 1144 #ifdef _LP64 1145 if (Metaspace::using_class_space()) { 1146 // Set up ccs in metaspace. 1147 Metaspace::initialize_class_space(class_space_rs); 1148 1149 // Set up compressed Klass pointer encoding: the encoding range must 1150 // cover both archive and class space. 1151 address cds_base = (address)static_mapinfo->mapped_base(); 1152 address ccs_end = (address)class_space_rs.end(); 1153 assert(ccs_end > cds_base, "Sanity check"); 1154 #if INCLUDE_CDS_JAVA_HEAP 1155 // We archived objects with pre-computed narrow Klass id. Set up encoding such that these Ids stay valid. 1156 address precomputed_narrow_klass_base = cds_base; 1157 const int precomputed_narrow_klass_shift = ArchiveHeapWriter::precomputed_narrow_klass_shift; 1158 CompressedKlassPointers::initialize_for_given_encoding( 1159 cds_base, ccs_end - cds_base, // Klass range 1160 precomputed_narrow_klass_base, precomputed_narrow_klass_shift // precomputed encoding, see ArchiveHeapWriter 1161 ); 1162 #else 1163 CompressedKlassPointers::initialize ( 1164 cds_base, ccs_end - cds_base // Klass range 1165 ); 1166 #endif // INCLUDE_CDS_JAVA_HEAP 1167 // map_or_load_heap_region() compares the current narrow oop and klass encodings 1168 // with the archived ones, so it must be done after all encodings are determined. 1169 static_mapinfo->map_or_load_heap_region(); 1170 } 1171 #endif // _LP64 1172 log_info(cds)("initial optimized module handling: %s", MetaspaceShared::use_optimized_module_handling() ? "enabled" : "disabled"); 1173 log_info(cds)("initial full module graph: %s", CDSConfig::is_loading_full_module_graph() ? "enabled" : "disabled"); 1174 } else { 1175 unmap_archive(static_mapinfo); 1176 unmap_archive(dynamic_mapinfo); 1177 release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs); 1178 } 1179 1180 return result; 1181 } 1182 1183 1184 // This will reserve two address spaces suitable to house Klass structures, one 1185 // for the cds archives (static archive and optionally dynamic archive) and 1186 // optionally one move for ccs. 1187 // 1188 // Since both spaces must fall within the compressed class pointer encoding 1189 // range, they are allocated close to each other. 1190 // 1191 // Space for archives will be reserved first, followed by a potential gap, 1192 // followed by the space for ccs: 1193 // 1194 // +-- Base address A B End 1195 // | | | | 1196 // v v v v 1197 // +-------------+--------------+ +----------------------+ 1198 // | static arc | [dyn. arch] | [gap] | compr. class space | 1199 // +-------------+--------------+ +----------------------+ 1200 // 1201 // (The gap may result from different alignment requirements between metaspace 1202 // and CDS) 1203 // 1204 // If UseCompressedClassPointers is disabled, only one address space will be 1205 // reserved: 1206 // 1207 // +-- Base address End 1208 // | | 1209 // v v 1210 // +-------------+--------------+ 1211 // | static arc | [dyn. arch] | 1212 // +-------------+--------------+ 1213 // 1214 // Base address: If use_archive_base_addr address is true, the Base address is 1215 // determined by the address stored in the static archive. If 1216 // use_archive_base_addr address is false, this base address is determined 1217 // by the platform. 1218 // 1219 // If UseCompressedClassPointers=1, the range encompassing both spaces will be 1220 // suitable to en/decode narrow Klass pointers: the base will be valid for 1221 // encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax. 1222 // 1223 // Return: 1224 // 1225 // - On success: 1226 // - total_space_rs will be reserved as whole for archive_space_rs and 1227 // class_space_rs if UseCompressedClassPointers is true. 1228 // On Windows, try reserve archive_space_rs and class_space_rs 1229 // separately first if use_archive_base_addr is true. 1230 // - archive_space_rs will be reserved and large enough to host static and 1231 // if needed dynamic archive: [Base, A). 1232 // archive_space_rs.base and size will be aligned to CDS reserve 1233 // granularity. 1234 // - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will 1235 // be reserved. Its start address will be aligned to metaspace reserve 1236 // alignment, which may differ from CDS alignment. It will follow the cds 1237 // archive space, close enough such that narrow class pointer encoding 1238 // covers both spaces. 1239 // If UseCompressedClassPointers=0, class_space_rs remains unreserved. 1240 // - On error: null is returned and the spaces remain unreserved. 1241 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo, 1242 FileMapInfo* dynamic_mapinfo, 1243 bool use_archive_base_addr, 1244 ReservedSpace& total_space_rs, 1245 ReservedSpace& archive_space_rs, 1246 ReservedSpace& class_space_rs) { 1247 1248 address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : nullptr); 1249 const size_t archive_space_alignment = core_region_alignment(); 1250 1251 // Size and requested location of the archive_space_rs (for both static and dynamic archives) 1252 assert(static_mapinfo->mapping_base_offset() == 0, "Must be"); 1253 size_t archive_end_offset = (dynamic_mapinfo == nullptr) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset(); 1254 size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment); 1255 1256 // If a base address is given, it must have valid alignment and be suitable as encoding base. 1257 if (base_address != nullptr) { 1258 assert(is_aligned(base_address, archive_space_alignment), 1259 "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address)); 1260 #ifdef _LP64 1261 if (Metaspace::using_class_space()) { 1262 assert(CompressedKlassPointers::is_valid_base(base_address), 1263 "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address)); 1264 } 1265 #endif 1266 } 1267 1268 if (!Metaspace::using_class_space()) { 1269 // Get the simple case out of the way first: 1270 // no compressed class space, simple allocation. 1271 archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment, 1272 os::vm_page_size(), (char*)base_address); 1273 if (archive_space_rs.is_reserved()) { 1274 assert(base_address == nullptr || 1275 (address)archive_space_rs.base() == base_address, "Sanity"); 1276 // Register archive space with NMT. 1277 MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared); 1278 return archive_space_rs.base(); 1279 } 1280 return nullptr; 1281 } 1282 1283 #ifdef _LP64 1284 1285 // Complex case: two spaces adjacent to each other, both to be addressable 1286 // with narrow class pointers. 1287 // We reserve the whole range spanning both spaces, then split that range up. 1288 1289 const size_t class_space_alignment = Metaspace::reserve_alignment(); 1290 1291 // To simplify matters, lets assume that metaspace alignment will always be 1292 // equal or a multiple of archive alignment. 1293 assert(is_power_of_2(class_space_alignment) && 1294 is_power_of_2(archive_space_alignment) && 1295 class_space_alignment >= archive_space_alignment, 1296 "Sanity"); 1297 1298 const size_t class_space_size = CompressedClassSpaceSize; 1299 assert(CompressedClassSpaceSize > 0 && 1300 is_aligned(CompressedClassSpaceSize, class_space_alignment), 1301 "CompressedClassSpaceSize malformed: " 1302 SIZE_FORMAT, CompressedClassSpaceSize); 1303 1304 const size_t ccs_begin_offset = align_up(base_address + archive_space_size, 1305 class_space_alignment) - base_address; 1306 const size_t gap_size = ccs_begin_offset - archive_space_size; 1307 1308 const size_t total_range_size = 1309 align_up(archive_space_size + gap_size + class_space_size, core_region_alignment()); 1310 1311 assert(total_range_size > ccs_begin_offset, "must be"); 1312 if (use_windows_memory_mapping() && use_archive_base_addr) { 1313 if (base_address != nullptr) { 1314 // On Windows, we cannot safely split a reserved memory space into two (see JDK-8255917). 1315 // Hence, we optimistically reserve archive space and class space side-by-side. We only 1316 // do this for use_archive_base_addr=true since for use_archive_base_addr=false case 1317 // caller will not split the combined space for mapping, instead read the archive data 1318 // via sequential file IO. 1319 address ccs_base = base_address + archive_space_size + gap_size; 1320 archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment, 1321 os::vm_page_size(), (char*)base_address); 1322 class_space_rs = ReservedSpace(class_space_size, class_space_alignment, 1323 os::vm_page_size(), (char*)ccs_base); 1324 } 1325 if (!archive_space_rs.is_reserved() || !class_space_rs.is_reserved()) { 1326 release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs); 1327 return nullptr; 1328 } 1329 } else { 1330 if (use_archive_base_addr && base_address != nullptr) { 1331 total_space_rs = ReservedSpace(total_range_size, archive_space_alignment, 1332 os::vm_page_size(), (char*) base_address); 1333 } else { 1334 // We did not manage to reserve at the preferred address, or were instructed to relocate. In that 1335 // case we reserve whereever possible, but the start address needs to be encodable as narrow Klass 1336 // encoding base since the archived heap objects contain nKlass IDs precalculated toward the start 1337 // of the shared Metaspace. That prevents us from using zero-based encoding and therefore we won't 1338 // try allocating in low-address regions. 1339 total_space_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size, false /* try_in_low_address_ranges */); 1340 } 1341 1342 if (!total_space_rs.is_reserved()) { 1343 return nullptr; 1344 } 1345 1346 // Paranoid checks: 1347 assert(base_address == nullptr || (address)total_space_rs.base() == base_address, 1348 "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_space_rs.base())); 1349 assert(is_aligned(total_space_rs.base(), archive_space_alignment), "Sanity"); 1350 assert(total_space_rs.size() == total_range_size, "Sanity"); 1351 assert(CompressedKlassPointers::is_valid_base((address)total_space_rs.base()), "Sanity"); 1352 1353 // Now split up the space into ccs and cds archive. For simplicity, just leave 1354 // the gap reserved at the end of the archive space. Do not do real splitting. 1355 archive_space_rs = total_space_rs.first_part(ccs_begin_offset, 1356 (size_t)archive_space_alignment); 1357 class_space_rs = total_space_rs.last_part(ccs_begin_offset); 1358 MemTracker::record_virtual_memory_split_reserved(total_space_rs.base(), total_space_rs.size(), 1359 ccs_begin_offset); 1360 } 1361 assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity"); 1362 assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity"); 1363 assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity"); 1364 assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity"); 1365 1366 // NMT: fix up the space tags 1367 MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared); 1368 MemTracker::record_virtual_memory_type(class_space_rs.base(), mtClass); 1369 1370 return archive_space_rs.base(); 1371 1372 #else 1373 ShouldNotReachHere(); 1374 return nullptr; 1375 #endif 1376 1377 } 1378 1379 void MetaspaceShared::release_reserved_spaces(ReservedSpace& total_space_rs, 1380 ReservedSpace& archive_space_rs, 1381 ReservedSpace& class_space_rs) { 1382 if (total_space_rs.is_reserved()) { 1383 log_debug(cds)("Released shared space (archive + class) " INTPTR_FORMAT, p2i(total_space_rs.base())); 1384 total_space_rs.release(); 1385 } else { 1386 if (archive_space_rs.is_reserved()) { 1387 log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base())); 1388 archive_space_rs.release(); 1389 } 1390 if (class_space_rs.is_reserved()) { 1391 log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base())); 1392 class_space_rs.release(); 1393 } 1394 } 1395 } 1396 1397 static int archive_regions[] = { MetaspaceShared::rw, MetaspaceShared::ro }; 1398 static int archive_regions_count = 2; 1399 1400 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) { 1401 assert(UseSharedSpaces, "must be runtime"); 1402 if (mapinfo == nullptr) { 1403 return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded. 1404 } 1405 1406 mapinfo->set_is_mapped(false); 1407 if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) { 1408 log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT 1409 " actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment()); 1410 return MAP_ARCHIVE_OTHER_FAILURE; 1411 } 1412 1413 MapArchiveResult result = 1414 mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs); 1415 1416 if (result != MAP_ARCHIVE_SUCCESS) { 1417 unmap_archive(mapinfo); 1418 return result; 1419 } 1420 1421 if (!mapinfo->validate_shared_path_table()) { 1422 unmap_archive(mapinfo); 1423 return MAP_ARCHIVE_OTHER_FAILURE; 1424 } 1425 1426 mapinfo->set_is_mapped(true); 1427 return MAP_ARCHIVE_SUCCESS; 1428 } 1429 1430 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) { 1431 assert(UseSharedSpaces, "must be runtime"); 1432 if (mapinfo != nullptr) { 1433 mapinfo->unmap_regions(archive_regions, archive_regions_count); 1434 mapinfo->unmap_region(MetaspaceShared::bm); 1435 mapinfo->set_is_mapped(false); 1436 } 1437 } 1438 1439 // For -XX:PrintSharedArchiveAndExit 1440 class CountSharedSymbols : public SymbolClosure { 1441 private: 1442 int _count; 1443 public: 1444 CountSharedSymbols() : _count(0) {} 1445 void do_symbol(Symbol** sym) { 1446 _count++; 1447 } 1448 int total() { return _count; } 1449 1450 }; 1451 1452 // Read the miscellaneous data from the shared file, and 1453 // serialize it out to its various destinations. 1454 1455 void MetaspaceShared::initialize_shared_spaces() { 1456 FileMapInfo *static_mapinfo = FileMapInfo::current_info(); 1457 1458 // Verify various attributes of the archive, plus initialize the 1459 // shared string/symbol tables. 1460 char* buffer = static_mapinfo->serialized_data(); 1461 intptr_t* array = (intptr_t*)buffer; 1462 ReadClosure rc(&array); 1463 serialize(&rc); 1464 1465 // Finish up archived heap initialization. These must be 1466 // done after ReadClosure. 1467 static_mapinfo->patch_heap_embedded_pointers(); 1468 ArchiveHeapLoader::finish_initialization(); 1469 1470 CDS_JAVA_HEAP_ONLY(Universe::update_archived_basic_type_mirrors()); 1471 1472 // Close the mapinfo file 1473 static_mapinfo->close(); 1474 1475 static_mapinfo->unmap_region(MetaspaceShared::bm); 1476 1477 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info(); 1478 if (dynamic_mapinfo != nullptr) { 1479 intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data(); 1480 ReadClosure rc(&buffer); 1481 ArchiveBuilder::serialize_dynamic_archivable_items(&rc); 1482 DynamicArchive::setup_array_klasses(); 1483 dynamic_mapinfo->close(); 1484 dynamic_mapinfo->unmap_region(MetaspaceShared::bm); 1485 } 1486 1487 // Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump 1488 if (CDSConfig::is_dumping_dynamic_archive()) { 1489 // Read stored LF format lines stored in static archive 1490 LambdaFormInvokers::read_static_archive_invokers(); 1491 } 1492 1493 if (PrintSharedArchiveAndExit) { 1494 // Print archive names 1495 if (dynamic_mapinfo != nullptr) { 1496 tty->print_cr("\n\nBase archive name: %s", Arguments::GetSharedArchivePath()); 1497 tty->print_cr("Base archive version %d", static_mapinfo->version()); 1498 } else { 1499 tty->print_cr("Static archive name: %s", static_mapinfo->full_path()); 1500 tty->print_cr("Static archive version %d", static_mapinfo->version()); 1501 } 1502 1503 SystemDictionaryShared::print_shared_archive(tty); 1504 if (dynamic_mapinfo != nullptr) { 1505 tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path()); 1506 tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version()); 1507 SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/); 1508 } 1509 1510 // collect shared symbols and strings 1511 CountSharedSymbols cl; 1512 SymbolTable::shared_symbols_do(&cl); 1513 tty->print_cr("Number of shared symbols: %d", cl.total()); 1514 tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count()); 1515 tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version()); 1516 if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) { 1517 tty->print_cr("archive is invalid"); 1518 vm_exit(1); 1519 } else { 1520 tty->print_cr("archive is valid"); 1521 vm_exit(0); 1522 } 1523 } 1524 } 1525 1526 // JVM/TI RedefineClasses() support: 1527 bool MetaspaceShared::remap_shared_readonly_as_readwrite() { 1528 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 1529 1530 if (UseSharedSpaces) { 1531 // remap the shared readonly space to shared readwrite, private 1532 FileMapInfo* mapinfo = FileMapInfo::current_info(); 1533 if (!mapinfo->remap_shared_readonly_as_readwrite()) { 1534 return false; 1535 } 1536 if (FileMapInfo::dynamic_info() != nullptr) { 1537 mapinfo = FileMapInfo::dynamic_info(); 1538 if (!mapinfo->remap_shared_readonly_as_readwrite()) { 1539 return false; 1540 } 1541 } 1542 _remapped_readwrite = true; 1543 } 1544 return true; 1545 } 1546 1547 void MetaspaceShared::print_on(outputStream* st) { 1548 if (UseSharedSpaces) { 1549 st->print("CDS archive(s) mapped at: "); 1550 address base = (address)MetaspaceObj::shared_metaspace_base(); 1551 address static_top = (address)_shared_metaspace_static_top; 1552 address top = (address)MetaspaceObj::shared_metaspace_top(); 1553 st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top)); 1554 st->print("size " SIZE_FORMAT ", ", top - base); 1555 st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, ArchiveRelocationMode); 1556 } else { 1557 st->print("CDS archive(s) not mapped"); 1558 } 1559 st->cr(); 1560 }