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