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