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 || UseShenandoahGC) && UseCompressedClassPointers)) { 277 vm_exit_during_initialization("Cannot create the CacheDataStore", 278 "UseCompressedClassPointers must be enabled, and collector must be G1, Parallel, Serial, Epsilon, or Shenandoah"); 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 ClassLoaderExt::init_num_module_paths(info->header()->num_module_paths()); 325 } 326 } 327 } 328 } 329 330 static GrowableArrayCHeap<OopHandle, mtClassShared>* _extra_interned_strings = nullptr; 331 static GrowableArrayCHeap<Symbol*, mtClassShared>* _extra_symbols = nullptr; 332 static GrowableArray<Method*>* _method_handle_intrinsics = nullptr; 333 334 void MetaspaceShared::read_extra_data(JavaThread* current, const char* filename) { 335 _extra_interned_strings = new GrowableArrayCHeap<OopHandle, mtClassShared>(10000); 336 _extra_symbols = new GrowableArrayCHeap<Symbol*, mtClassShared>(1000); 337 338 HashtableTextDump reader(filename); 339 reader.check_version("VERSION: 1.0"); 340 341 while (reader.remain() > 0) { 342 int utf8_length; 343 int prefix_type = reader.scan_prefix(&utf8_length); 344 ResourceMark rm(current); 345 if (utf8_length == 0x7fffffff) { 346 // buf_len will overflown 32-bit value. 347 log_error(cds)("string length too large: %d", utf8_length); 348 MetaspaceShared::unrecoverable_loading_error(); 349 } 350 int buf_len = utf8_length+1; 351 char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len); 352 reader.get_utf8(utf8_buffer, utf8_length); 353 utf8_buffer[utf8_length] = '\0'; 354 355 if (prefix_type == HashtableTextDump::SymbolPrefix) { 356 _extra_symbols->append(SymbolTable::new_permanent_symbol(utf8_buffer)); 357 } else{ 358 assert(prefix_type == HashtableTextDump::StringPrefix, "Sanity"); 359 ExceptionMark em(current); 360 JavaThread* THREAD = current; // For exception macros. 361 oop str = StringTable::intern(utf8_buffer, THREAD); 362 363 if (HAS_PENDING_EXCEPTION) { 364 log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d", 365 reader.last_line_no(), utf8_length); 366 CLEAR_PENDING_EXCEPTION; 367 } else { 368 #if INCLUDE_CDS_JAVA_HEAP 369 if (ArchiveHeapWriter::is_string_too_large_to_archive(str)) { 370 log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d", 371 reader.last_line_no(), utf8_length); 372 continue; 373 } 374 // Make sure this string is included in the dumped interned string table. 375 assert(str != nullptr, "must succeed"); 376 _extra_interned_strings->append(OopHandle(Universe::vm_global(), str)); 377 #endif 378 } 379 } 380 } 381 } 382 383 void MetaspaceShared::make_method_handle_intrinsics_shareable() { 384 for (int i = 0; i < _method_handle_intrinsics->length(); i++) { 385 Method* m = ArchiveBuilder::current()->get_buffered_addr(_method_handle_intrinsics->at(i)); 386 m->remove_unshareable_info(); 387 // Each method has its own constant pool (which is distinct from m->method_holder()->constants()); 388 m->constants()->remove_unshareable_info(); 389 } 390 } 391 392 void MetaspaceShared::write_method_handle_intrinsics() { 393 int len = _method_handle_intrinsics->length(); 394 _archived_method_handle_intrinsics = ArchiveBuilder::new_ro_array<Method*>(len); 395 for (int i = 0; i < len; i++) { 396 ArchiveBuilder::current()->write_pointer_in_buffer(_archived_method_handle_intrinsics->adr_at(i), 397 _method_handle_intrinsics->at(i)); 398 } 399 log_info(cds)("Archived %d method handle intrinsics", len); 400 } 401 402 // Read/write a data stream for restoring/preserving metadata pointers and 403 // miscellaneous data from/to the shared archive file. 404 405 void MetaspaceShared::serialize(SerializeClosure* soc) { 406 int tag = 0; 407 soc->do_tag(--tag); 408 409 // Verify the sizes of various metadata in the system. 410 soc->do_tag(sizeof(Method)); 411 soc->do_tag(sizeof(ConstMethod)); 412 soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE)); 413 soc->do_tag(sizeof(ConstantPool)); 414 soc->do_tag(sizeof(ConstantPoolCache)); 415 soc->do_tag(objArrayOopDesc::base_offset_in_bytes()); 416 soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE)); 417 soc->do_tag(sizeof(Symbol)); 418 419 // Need to do this first, as subsequent steps may call virtual functions 420 // in archived Metadata objects. 421 CppVtables::serialize(soc); 422 soc->do_tag(--tag); 423 424 // Dump/restore miscellaneous metadata. 425 JavaClasses::serialize_offsets(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 _method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared); 576 SystemDictionary::get_all_method_handle_intrinsics(_method_handle_intrinsics); 577 _method_handle_intrinsics->sort([] (Method** a, Method** b) -> int { 578 Symbol* a_holder = (*a)->method_holder()->name(); 579 Symbol* b_holder = (*b)->method_holder()->name(); 580 if (a_holder != b_holder) { 581 return a_holder->cmp(b_holder); 582 } 583 Symbol* a_name = (*a)->name(); 584 Symbol* b_name = (*b)->name(); 585 if (a_name != b_name) { 586 return a_name->cmp(b_name); 587 } 588 Symbol* a_signature = (*a)->signature(); 589 Symbol* b_signature = (*b)->signature(); 590 if (a_signature != b_signature) { 591 return a_signature->cmp(b_signature); 592 } 593 return 0; 594 }); 595 596 FileMapInfo::check_nonempty_dir_in_shared_path_table(); 597 598 NOT_PRODUCT(SystemDictionary::verify();) 599 600 // Block concurrent class unloading from changing the _dumptime_table 601 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag); 602 603 SystemDictionaryShared::find_all_archivable_classes(); 604 605 _builder.gather_source_objs(); 606 _builder.reserve_buffer(); 607 608 CppVtables::dumptime_init(&_builder); 609 610 _builder.sort_metadata_objs(); 611 _builder.dump_rw_metadata(); 612 _builder.dump_ro_metadata(); 613 _builder.relocate_metaspaceobj_embedded_pointers(); 614 615 dump_java_heap_objects(_builder.klasses()); 616 dump_shared_symbol_table(_builder.symbols()); 617 618 log_info(cds)("Make classes shareable"); 619 _builder.make_klasses_shareable(); 620 MetaspaceShared::make_method_handle_intrinsics_shareable(); 621 622 char* serialized_data = dump_read_only_tables(); 623 624 SystemDictionaryShared::adjust_lambda_proxy_class_dictionary(); 625 626 log_info(cds)("Make training data shareable"); 627 _builder.make_training_data_shareable(); 628 629 // The vtable clones contain addresses of the current process. 630 // We don't want to write these addresses into the archive. 631 CppVtables::zero_archived_vtables(); 632 633 // Write the archive file 634 const char* static_archive; 635 if (CDSConfig::is_dumping_final_static_archive()) { 636 static_archive = CacheDataStore; 637 assert(FileMapInfo::current_info() != nullptr, "sanity"); 638 delete FileMapInfo::current_info(); 639 } else { 640 static_archive = CDSConfig::static_archive_path(); 641 } 642 assert(static_archive != nullptr, "SharedArchiveFile not set?"); 643 _map_info = new FileMapInfo(static_archive, true); 644 _map_info->populate_header(MetaspaceShared::core_region_alignment()); 645 _map_info->set_serialized_data(serialized_data); 646 _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base()); 647 } 648 649 class CollectCLDClosure : public CLDClosure { 650 GrowableArray<ClassLoaderData*> _loaded_cld; 651 GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive 652 Thread* _current_thread; 653 public: 654 CollectCLDClosure(Thread* thread) : _current_thread(thread) {} 655 ~CollectCLDClosure() { 656 for (int i = 0; i < _loaded_cld_handles.length(); i++) { 657 _loaded_cld_handles.at(i).release(Universe::vm_global()); 658 } 659 } 660 void do_cld(ClassLoaderData* cld) { 661 assert(cld->is_alive(), "must be"); 662 _loaded_cld.append(cld); 663 _loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder())); 664 } 665 666 int nof_cld() const { return _loaded_cld.length(); } 667 ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); } 668 }; 669 670 // Check if we can eagerly link this class at dump time, so we can avoid the 671 // runtime linking overhead (especially verification) 672 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) { 673 if (CDSConfig::preserve_all_dumptime_verification_states(ik)) { 674 assert(ik->can_be_verified_at_dumptime(), "sanity"); 675 } 676 if (!ik->can_be_verified_at_dumptime()) { 677 // For old classes, try to leave them in the unlinked state, so 678 // we can still store them in the archive. They must be 679 // linked/verified at runtime. 680 return false; 681 } 682 683 if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) { 684 // Linking of unregistered classes at this stage may cause more 685 // classes to be resolved, resulting in calls to ClassLoader.loadClass() 686 // that may not be expected by custom class loaders. 687 // 688 // It's OK to do this for the built-in loaders as we know they can 689 // tolerate this. 690 return false; 691 } 692 return true; 693 } 694 695 void MetaspaceShared::link_shared_classes(bool jcmd_request, TRAPS) { 696 AOTClassLinker::initialize(); 697 698 if (!jcmd_request && !CDSConfig::is_dumping_dynamic_archive() 699 && !CDSConfig::is_dumping_preimage_static_archive() 700 && !CDSConfig::is_dumping_final_static_archive()) { 701 // If we have regenerated invoker classes in the dynamic archive, 702 // they will conflict with the resolved CONSTANT_Klass references that are stored 703 // in the static archive. This is not easy to handle. Let's disable 704 // it for dynamic archive for now. 705 LambdaFormInvokers::regenerate_holder_classes(CHECK); 706 } 707 708 // Collect all loaded ClassLoaderData. 709 CollectCLDClosure collect_cld(THREAD); 710 { 711 // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock. 712 // We cannot link the classes while holding this lock (or else we may run into deadlock). 713 // Therefore, we need to first collect all the CLDs, and then link their classes after 714 // releasing the lock. 715 MutexLocker lock(ClassLoaderDataGraph_lock); 716 ClassLoaderDataGraph::loaded_cld_do(&collect_cld); 717 } 718 719 while (true) { 720 bool has_linked = false; 721 for (int i = 0; i < collect_cld.nof_cld(); i++) { 722 ClassLoaderData* cld = collect_cld.cld_at(i); 723 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) { 724 if (klass->is_instance_klass()) { 725 InstanceKlass* ik = InstanceKlass::cast(klass); 726 if (may_be_eagerly_linked(ik)) { 727 has_linked |= try_link_class(THREAD, ik); 728 } 729 if (CDSConfig::is_dumping_heap() && ik->is_linked() && !ik->is_initialized()) { 730 AOTClassInitializer::maybe_preinit_class(ik, CHECK); 731 } 732 } 733 } 734 } 735 736 if (!has_linked) { 737 break; 738 } 739 // Class linking includes verification which may load more classes. 740 // Keep scanning until we have linked no more classes. 741 } 742 743 // Resolve constant pool entries -- we don't load any new classes during this stage 744 for (int i = 0; i < collect_cld.nof_cld(); i++) { 745 ClassLoaderData* cld = collect_cld.cld_at(i); 746 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) { 747 if (klass->is_instance_klass()) { 748 InstanceKlass* ik = InstanceKlass::cast(klass); 749 AOTConstantPoolResolver::dumptime_resolve_constants(ik, CHECK); 750 if (CDSConfig::is_dumping_preimage_static_archive()) { 751 FinalImageRecipes::add_reflection_data_flags(ik, CHECK); 752 } 753 } 754 } 755 } 756 757 if (CDSConfig::is_dumping_preimage_static_archive()) { 758 // Do this after all classes are verified by the above loop. 759 // Any classes loaded from here on will be automatically excluded, so 760 // there's no need to force verification or resolve CP entries. 761 RecordTraining = false; 762 SystemDictionaryShared::ignore_new_classes(); 763 LambdaFormInvokers::regenerate_holder_classes(CHECK); 764 RecordTraining = true; 765 } 766 767 if (CDSConfig::is_dumping_final_static_archive()) { 768 FinalImageRecipes::apply_recipes(CHECK); 769 } 770 } 771 772 void MetaspaceShared::prepare_for_dumping() { 773 assert(CDSConfig::is_dumping_archive(), "sanity"); 774 CDSConfig::check_unsupported_dumping_module_options(); 775 ClassLoader::initialize_shared_path(JavaThread::current()); 776 } 777 778 // Preload classes from a list, populate the shared spaces and dump to a 779 // file. 780 void MetaspaceShared::preload_and_dump(TRAPS) { 781 ResourceMark rm(THREAD); 782 HandleMark hm(THREAD); 783 784 if (CDSConfig::is_dumping_final_static_archive() && PrintTrainingInfo) { 785 tty->print_cr("==================== archived_training_data ** before dumping ===================="); 786 TrainingData::print_archived_training_data_on(tty); 787 } 788 789 StaticArchiveBuilder builder; 790 preload_and_dump_impl(builder, THREAD); 791 if (HAS_PENDING_EXCEPTION) { 792 if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) { 793 log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = " 794 SIZE_FORMAT "M", MaxHeapSize/M); 795 MetaspaceShared::writing_error(); 796 } else { 797 log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(), 798 java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION))); 799 MetaspaceShared::writing_error("Unexpected exception, use -Xlog:cds,exceptions=trace for detail"); 800 } 801 } 802 } 803 804 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64) 805 void MetaspaceShared::adjust_heap_sizes_for_dumping() { 806 if (!CDSConfig::is_dumping_heap() || UseCompressedOops) { 807 return; 808 } 809 // CDS heap dumping requires all string oops to have an offset 810 // from the heap bottom that can be encoded in 32-bit. 811 julong max_heap_size = (julong)(4 * G); 812 813 if (MinHeapSize > max_heap_size) { 814 log_debug(cds)("Setting MinHeapSize to 4G for CDS dumping, original size = " SIZE_FORMAT "M", MinHeapSize/M); 815 FLAG_SET_ERGO(MinHeapSize, max_heap_size); 816 } 817 if (InitialHeapSize > max_heap_size) { 818 log_debug(cds)("Setting InitialHeapSize to 4G for CDS dumping, original size = " SIZE_FORMAT "M", InitialHeapSize/M); 819 FLAG_SET_ERGO(InitialHeapSize, max_heap_size); 820 } 821 if (MaxHeapSize > max_heap_size) { 822 log_debug(cds)("Setting MaxHeapSize to 4G for CDS dumping, original size = " SIZE_FORMAT "M", MaxHeapSize/M); 823 FLAG_SET_ERGO(MaxHeapSize, max_heap_size); 824 } 825 } 826 #endif // INCLUDE_CDS_JAVA_HEAP && _LP64 827 828 void MetaspaceShared::get_default_classlist(char* default_classlist, const size_t buf_size) { 829 // Construct the path to the class list (in jre/lib) 830 // Walk up two directories from the location of the VM and 831 // optionally tack on "lib" (depending on platform) 832 os::jvm_path(default_classlist, (jint)(buf_size)); 833 for (int i = 0; i < 3; i++) { 834 char *end = strrchr(default_classlist, *os::file_separator()); 835 if (end != nullptr) *end = '\0'; 836 } 837 size_t classlist_path_len = strlen(default_classlist); 838 if (classlist_path_len >= 3) { 839 if (strcmp(default_classlist + classlist_path_len - 3, "lib") != 0) { 840 if (classlist_path_len < buf_size - 4) { 841 jio_snprintf(default_classlist + classlist_path_len, 842 buf_size - classlist_path_len, 843 "%slib", os::file_separator()); 844 classlist_path_len += 4; 845 } 846 } 847 } 848 if (classlist_path_len < buf_size - 10) { 849 jio_snprintf(default_classlist + classlist_path_len, 850 buf_size - classlist_path_len, 851 "%sclasslist", os::file_separator()); 852 } 853 } 854 855 void MetaspaceShared::preload_classes(TRAPS) { 856 char default_classlist[JVM_MAXPATHLEN]; 857 const char* classlist_path; 858 859 get_default_classlist(default_classlist, sizeof(default_classlist)); 860 if (SharedClassListFile == nullptr) { 861 classlist_path = default_classlist; 862 } else { 863 classlist_path = SharedClassListFile; 864 } 865 866 log_info(cds)("Loading classes to share ..."); 867 ClassListParser::parse_classlist(classlist_path, 868 ClassListParser::_parse_all, CHECK); 869 if (ExtraSharedClassListFile) { 870 ClassListParser::parse_classlist(ExtraSharedClassListFile, 871 ClassListParser::_parse_all, CHECK); 872 } 873 if (classlist_path != default_classlist) { 874 struct stat statbuf; 875 if (os::stat(default_classlist, &statbuf) == 0) { 876 // File exists, let's use it. 877 ClassListParser::parse_classlist(default_classlist, 878 ClassListParser::_parse_lambda_forms_invokers_only, CHECK); 879 } 880 } 881 882 // Exercise the manifest processing code to ensure classes used by CDS at runtime 883 // are always archived 884 const char* dummy = "Manifest-Version: 1.0\n"; 885 CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK); 886 887 log_info(cds)("Loading classes to share: done."); 888 } 889 890 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) { 891 if (CDSConfig::is_dumping_classic_static_archive()) { 892 // We are running with -Xshare:dump 893 preload_classes(CHECK); 894 895 if (SharedArchiveConfigFile) { 896 log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile); 897 read_extra_data(THREAD, SharedArchiveConfigFile); 898 log_info(cds)("Reading extra data: done."); 899 } 900 } 901 902 if (CDSConfig::is_dumping_preimage_static_archive()) { 903 log_info(cds)("Reading lambda form invokers of in JDK default classlist ..."); 904 char default_classlist[JVM_MAXPATHLEN]; 905 get_default_classlist(default_classlist, sizeof(default_classlist)); 906 struct stat statbuf; 907 if (os::stat(default_classlist, &statbuf) == 0) { 908 ClassListParser::parse_classlist(default_classlist, 909 ClassListParser::_parse_lambda_forms_invokers_only, CHECK); 910 } 911 } 912 913 // Rewrite and link classes 914 log_info(cds)("Rewriting and linking classes ..."); 915 // Link any classes which got missed. This would happen if we have loaded classes that 916 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K 917 // fails verification, all other interfaces that were not specified in the classlist but 918 // are implemented by K are not verified. 919 link_shared_classes(false/*not from jcmd*/, CHECK); 920 log_info(cds)("Rewriting and linking classes: done"); 921 922 if (CDSConfig::is_dumping_final_static_archive()) { 923 assert(RecordTraining == false, "must be"); 924 RecordTraining = true; 925 } 926 927 TrainingData::init_dumptime_table(CHECK); // captures TrainingDataSetLocker 928 929 #if INCLUDE_CDS_JAVA_HEAP 930 if (CDSConfig::is_dumping_heap()) { 931 if (!HeapShared::is_archived_boot_layer_available(THREAD)) { 932 log_info(cds)("archivedBootLayer not available, disabling full module graph"); 933 CDSConfig::stop_dumping_full_module_graph(); 934 } 935 HeapShared::init_for_dumping(CHECK); 936 ArchiveHeapWriter::init(); 937 if (CDSConfig::is_dumping_full_module_graph()) { 938 HeapShared::reset_archived_object_states(CHECK); 939 } 940 941 if (ArchiveLoaderLookupCache) { 942 SystemDictionaryShared::create_loader_positive_lookup_cache(CHECK); 943 } 944 945 if (CDSConfig::is_dumping_invokedynamic()) { 946 // This makes sure that the MethodType and MethodTypeForm tables won't be updated 947 // concurrently when we are saving their contents into a side table. 948 assert(CDSConfig::allow_only_single_java_thread(), "Required"); 949 950 JavaValue result(T_VOID); 951 JavaCalls::call_static(&result, vmClasses::MethodType_klass(), 952 vmSymbols::createArchivedObjects(), 953 vmSymbols::void_method_signature(), 954 CHECK); 955 } 956 957 // Do this at the very end, when no Java code will be executed. Otherwise 958 // some new strings may be added to the intern table. 959 StringTable::allocate_shared_strings_array(CHECK); 960 } else { 961 log_info(cds)("Not dumping heap, reset CDSConfig::_is_using_optimized_module_handling"); 962 CDSConfig::stop_using_optimized_module_handling(); 963 } 964 #endif 965 966 // Dummy call to load classes used at CDS runtime 967 JavaValue result(T_OBJECT); 968 Handle path_string = java_lang_String::create_from_str("dummy.jar", CHECK); 969 JavaCalls::call_static(&result, 970 vmClasses::jdk_internal_loader_ClassLoaders_klass(), 971 vmSymbols::toFileURL_name(), 972 vmSymbols::toFileURL_signature(), 973 path_string, 974 CHECK); 975 976 VM_PopulateDumpSharedSpace op(builder); 977 VMThread::execute(&op); 978 FileMapInfo* mapinfo = op.map_info(); 979 ArchiveHeapInfo* heap_info = op.heap_info(); 980 bool status; 981 if (CDSConfig::is_dumping_preimage_static_archive()) { 982 if ((status = write_static_archive(&builder, mapinfo, heap_info))) { 983 fork_and_dump_final_static_archive(); 984 } 985 } else if (CDSConfig::is_dumping_final_static_archive()) { 986 RecordTraining = false; 987 if (StoreCachedCode && CachedCodeFile != nullptr) { // FIXME: new workflow -- remove the CachedCodeFile flag 988 if (log_is_enabled(Info, cds, jit)) { 989 CDSAccess::test_heap_access_api(); 990 } 991 992 // We have just created the final image. Let's run the AOT compiler 993 if (PrintTrainingInfo) { 994 tty->print_cr("==================== archived_training_data ** after dumping ===================="); 995 TrainingData::print_archived_training_data_on(tty); 996 } 997 998 CDSConfig::enable_dumping_cached_code(); 999 { 1000 builder.start_cc_region(); 1001 Precompiler::compile_cached_code(&builder, CHECK); 1002 builder.end_cc_region(); 1003 } 1004 CDSConfig::disable_dumping_cached_code(); 1005 1006 SCCache::close(); // Write final data and close archive 1007 } 1008 status = write_static_archive(&builder, mapinfo, heap_info); 1009 } else { 1010 status = write_static_archive(&builder, mapinfo, heap_info); 1011 } 1012 1013 if (!status) { 1014 THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping"); 1015 } 1016 } 1017 1018 bool MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) { 1019 // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address() 1020 // without runtime relocation. 1021 builder->relocate_to_requested(); 1022 1023 map_info->open_for_write(); 1024 if (!map_info->is_open()) { 1025 return false; 1026 } 1027 builder->write_archive(map_info, heap_info); 1028 1029 if (AllowArchivingWithJavaAgent) { 1030 log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used " 1031 "for testing purposes only and should not be used in a production environment"); 1032 } 1033 return true; 1034 } 1035 1036 static void print_java_launcher(outputStream* st) { 1037 st->print("%s%sbin%sjava", Arguments::get_java_home(), os::file_separator(), os::file_separator()); 1038 } 1039 1040 static void print_vm_arguments(outputStream* st) { 1041 const char* cp = Arguments::get_appclasspath(); 1042 if (cp != nullptr && strlen(cp) > 0 && strcmp(cp, ".") != 0) { 1043 st->print(" -cp "); st->print_raw(cp); 1044 } 1045 for (int i = 0; i < Arguments::num_jvm_flags(); i++) { 1046 st->print(" %s", Arguments::jvm_flags_array()[i]); 1047 } 1048 for (int i = 0; i < Arguments::num_jvm_args(); i++) { 1049 st->print(" %s", Arguments::jvm_args_array()[i]); 1050 } 1051 } 1052 1053 void MetaspaceShared::fork_and_dump_final_static_archive() { 1054 assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity"); 1055 1056 ResourceMark rm; 1057 stringStream ss; 1058 print_java_launcher(&ss); 1059 print_vm_arguments(&ss); 1060 ss.print(" -XX:CDSPreimage=%s", SharedArchiveFile); 1061 1062 const char* cmd = ss.freeze(); 1063 if (CDSManualFinalImage) { 1064 tty->print_cr("-XX:+CDSManualFinalImage is specified"); 1065 tty->print_cr("Please manually execute the following command to create the final CDS image:"); 1066 tty->print(" "); tty->print_raw_cr(cmd); 1067 1068 // The following is useful if the dumping was trigger by a script that builds 1069 // a complex command-line. 1070 tty->print_cr("Note: to recreate the preimage only:"); 1071 tty->print_cr(" rm -f %s", CacheDataStore); 1072 tty->print(" "); 1073 print_java_launcher(tty); 1074 print_vm_arguments(tty); 1075 if (Arguments::java_command() != nullptr) { 1076 tty->print(" %s", Arguments::java_command()); 1077 } 1078 tty->cr(); 1079 } else { 1080 // FIXME: space characters are not properly quoated. E.g., 1081 // java -Dfoo='a b c' HelloWorld 1082 log_info(cds)("Launching child process to create final CDS image:"); 1083 log_info(cds)(" %s", cmd); 1084 int status = os::fork_and_exec(cmd); 1085 if (status != 0) { 1086 log_error(cds)("Child process finished; status = %d", status); 1087 log_error(cds)("To reproduce the error"); 1088 ResourceMark rm; 1089 LogStream ls(Log(cds)::error()); 1090 ls.print(" "); ls.print_raw_cr(cmd); 1091 1092 // The following is useful if the dumping was trigger by a script that builds 1093 // a complex command-line. 1094 ls.print_cr("Note: to recreate the preimage only:"); 1095 ls.print_cr(" rm -f %s", CacheDataStore); 1096 ls.print(" "); 1097 print_java_launcher(&ls); 1098 print_vm_arguments(&ls); 1099 ls.print(" -XX:+UnlockDiagnosticVMOptions -XX:+CDSManualFinalImage"); 1100 if (Arguments::java_command() != nullptr) { 1101 ls.print(" %s", Arguments::java_command()); 1102 } 1103 ls.cr(); 1104 1105 vm_direct_exit(status); 1106 } else { 1107 log_info(cds)("Child process finished; status = %d", status); 1108 // On Windows, need WRITE permission to remove the file. 1109 WINDOWS_ONLY(chmod(SharedArchiveFile, _S_IREAD | _S_IWRITE)); 1110 status = remove(SharedArchiveFile); 1111 if (status != 0) { 1112 log_error(cds)("Failed to remove CDSPreimage file %s", SharedArchiveFile); 1113 } else { 1114 log_info(cds)("Removed CDSPreimage file %s", SharedArchiveFile); 1115 } 1116 } 1117 } 1118 } 1119 1120 // Returns true if the class's status has changed. 1121 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) { 1122 ExceptionMark em(current); 1123 JavaThread* THREAD = current; // For exception macros. 1124 assert(CDSConfig::is_dumping_archive(), "sanity"); 1125 1126 if (ik->is_shared() && !CDSConfig::is_dumping_final_static_archive()) { 1127 assert(CDSConfig::is_dumping_dynamic_archive(), "must be"); 1128 return false; 1129 } 1130 1131 if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() && 1132 !SystemDictionaryShared::has_class_failed_verification(ik)) { 1133 bool saved = BytecodeVerificationLocal; 1134 if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) { 1135 // The verification decision is based on BytecodeVerificationRemote 1136 // for non-system classes. Since we are using the null classloader 1137 // to load non-system classes for customized class loaders during dumping, 1138 // we need to temporarily change BytecodeVerificationLocal to be the same as 1139 // BytecodeVerificationRemote. Note this can cause the parent system 1140 // classes also being verified. The extra overhead is acceptable during 1141 // dumping. 1142 BytecodeVerificationLocal = BytecodeVerificationRemote; 1143 } 1144 ik->link_class(THREAD); 1145 if (HAS_PENDING_EXCEPTION) { 1146 ResourceMark rm(THREAD); 1147 log_warning(cds)("Preload Warning: Verification failed for %s", 1148 ik->external_name()); 1149 CLEAR_PENDING_EXCEPTION; 1150 SystemDictionaryShared::set_class_has_failed_verification(ik); 1151 } 1152 ik->compute_has_loops_flag_for_methods(); 1153 BytecodeVerificationLocal = saved; 1154 return true; 1155 } else { 1156 return false; 1157 } 1158 } 1159 1160 #if INCLUDE_CDS_JAVA_HEAP 1161 void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) { 1162 if(!HeapShared::can_write()) { 1163 if (!CDSConfig::is_dumping_preimage_static_archive()) { 1164 log_info(cds)( 1165 "Archived java heap is not supported as UseG1GC " 1166 "and UseCompressedClassPointers are required." 1167 "Current settings: UseG1GC=%s, UseCompressedClassPointers=%s.", 1168 BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedClassPointers)); 1169 } 1170 return; 1171 } 1172 // Find all the interned strings that should be dumped. 1173 int i; 1174 for (i = 0; i < klasses->length(); i++) { 1175 Klass* k = klasses->at(i); 1176 if (k->is_instance_klass()) { 1177 InstanceKlass* ik = InstanceKlass::cast(k); 1178 if (ik->is_linked()) { 1179 ik->constants()->add_dumped_interned_strings(); 1180 } 1181 } 1182 } 1183 if (_extra_interned_strings != nullptr) { 1184 for (i = 0; i < _extra_interned_strings->length(); i ++) { 1185 OopHandle string = _extra_interned_strings->at(i); 1186 HeapShared::add_to_dumped_interned_strings(string.resolve()); 1187 } 1188 } 1189 1190 HeapShared::archive_objects(&_heap_info); 1191 ArchiveBuilder::OtherROAllocMark mark; 1192 HeapShared::write_subgraph_info_table(); 1193 } 1194 #endif // INCLUDE_CDS_JAVA_HEAP 1195 1196 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) { 1197 assert(base <= static_top && static_top <= top, "must be"); 1198 _shared_metaspace_static_top = static_top; 1199 MetaspaceObj::set_shared_metaspace_range(base, top); 1200 } 1201 1202 bool MetaspaceShared::is_shared_dynamic(void* p) { 1203 if ((p < MetaspaceObj::shared_metaspace_top()) && 1204 (p >= _shared_metaspace_static_top)) { 1205 return true; 1206 } else { 1207 return false; 1208 } 1209 } 1210 1211 bool MetaspaceShared::is_shared_static(void* p) { 1212 if (is_in_shared_metaspace(p) && !is_shared_dynamic(p)) { 1213 return true; 1214 } else { 1215 return false; 1216 } 1217 } 1218 1219 // This function is called when the JVM is unable to load the specified archive(s) due to one 1220 // of the following conditions. 1221 // - There's an error that indicates that the archive(s) files were corrupt or otherwise damaged. 1222 // - When -XX:+RequireSharedSpaces is specified, AND the JVM cannot load the archive(s) due 1223 // to version or classpath mismatch. 1224 void MetaspaceShared::unrecoverable_loading_error(const char* message) { 1225 log_error(cds)("An error has occurred while processing the shared archive file."); 1226 if (message != nullptr) { 1227 log_error(cds)("%s", message); 1228 } 1229 vm_exit_during_initialization("Unable to use shared archive.", nullptr); 1230 } 1231 1232 // This function is called when the JVM is unable to write the specified CDS archive due to an 1233 // unrecoverable error. 1234 void MetaspaceShared::unrecoverable_writing_error(const char* message) { 1235 writing_error(message); 1236 vm_direct_exit(1); 1237 } 1238 1239 // This function is called when the JVM is unable to write the specified CDS archive due to a 1240 // an error. The error will be propagated 1241 void MetaspaceShared::writing_error(const char* message) { 1242 log_error(cds)("An error has occurred while writing the shared archive file."); 1243 if (message != nullptr) { 1244 log_error(cds)("%s", message); 1245 } 1246 } 1247 1248 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() { 1249 assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled"); 1250 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE; 1251 1252 FileMapInfo* static_mapinfo = FileMapInfo::current_info(); 1253 FileMapInfo* dynamic_mapinfo = nullptr; 1254 1255 if (static_mapinfo != nullptr) { 1256 log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment()); 1257 dynamic_mapinfo = open_dynamic_archive(); 1258 1259 // First try to map at the requested address 1260 result = map_archives(static_mapinfo, dynamic_mapinfo, true); 1261 if (result == MAP_ARCHIVE_MMAP_FAILURE) { 1262 // Mapping has failed (probably due to ASLR). Let's map at an address chosen 1263 // by the OS. 1264 log_info(cds)("Try to map archive(s) at an alternative address"); 1265 result = map_archives(static_mapinfo, dynamic_mapinfo, false); 1266 } 1267 } 1268 1269 if (result == MAP_ARCHIVE_SUCCESS) { 1270 bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped()); 1271 char* cds_base = static_mapinfo->mapped_base(); 1272 char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end(); 1273 // Register CDS memory region with LSan. 1274 LSAN_REGISTER_ROOT_REGION(cds_base, cds_end - cds_base); 1275 set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end); 1276 _relocation_delta = static_mapinfo->relocation_delta(); 1277 _requested_base_address = static_mapinfo->requested_base_address(); 1278 if (dynamic_mapped) { 1279 FileMapInfo::set_shared_path_table(dynamic_mapinfo); 1280 // turn AutoCreateSharedArchive off if successfully mapped 1281 AutoCreateSharedArchive = false; 1282 } else { 1283 FileMapInfo::set_shared_path_table(static_mapinfo); 1284 } 1285 } else { 1286 set_shared_metaspace_range(nullptr, nullptr, nullptr); 1287 if (CDSConfig::is_dumping_dynamic_archive()) { 1288 log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info."); 1289 } 1290 UseSharedSpaces = false; 1291 // The base archive cannot be mapped. We cannot dump the dynamic shared archive. 1292 AutoCreateSharedArchive = false; 1293 CDSConfig::disable_dumping_dynamic_archive(); 1294 log_info(cds)("Unable to map shared spaces"); 1295 if (PrintSharedArchiveAndExit) { 1296 MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive."); 1297 } else if (RequireSharedSpaces) { 1298 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces"); 1299 } else if (CDSConfig::is_dumping_final_static_archive()) { 1300 assert(CDSPreimage != nullptr, "must be"); 1301 log_error(cds)("Unable to map shared spaces for CDSPreimage = %s", CDSPreimage); 1302 MetaspaceShared::unrecoverable_loading_error(); 1303 } 1304 } 1305 1306 // If mapping failed and -XShare:on, the vm should exit 1307 bool has_failed = false; 1308 if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) { 1309 has_failed = true; 1310 delete static_mapinfo; 1311 } 1312 if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) { 1313 has_failed = true; 1314 delete dynamic_mapinfo; 1315 } 1316 if (RequireSharedSpaces && has_failed) { 1317 // static archive mapped but dynamic archive failed 1318 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces"); 1319 } 1320 } 1321 1322 // This is called very early at VM start up to get the size of the cached_code region, which 1323 // is used in CodeCache::initialize_heaps() 1324 void MetaspaceShared::open_static_archive() { 1325 if (!UseSharedSpaces) { 1326 return; 1327 } 1328 const char* static_archive = CDSConfig::static_archive_path(); 1329 assert(static_archive != nullptr, "sanity"); 1330 FileMapInfo* mapinfo = new FileMapInfo(static_archive, true); 1331 if (!mapinfo->initialize()) { 1332 delete(mapinfo); 1333 } else { 1334 FileMapRegion* r = mapinfo->region_at(MetaspaceShared::cc); 1335 CDSAccess::set_cached_code_size(r->used_aligned()); 1336 } 1337 } 1338 1339 FileMapInfo* MetaspaceShared::open_dynamic_archive() { 1340 if (CDSConfig::is_dumping_dynamic_archive()) { 1341 return nullptr; 1342 } 1343 const char* dynamic_archive = CDSConfig::dynamic_archive_path(); 1344 if (dynamic_archive == nullptr) { 1345 return nullptr; 1346 } 1347 1348 FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false); 1349 if (!mapinfo->initialize()) { 1350 delete(mapinfo); 1351 if (RequireSharedSpaces) { 1352 MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive"); 1353 } 1354 return nullptr; 1355 } 1356 return mapinfo; 1357 } 1358 1359 // use_requested_addr: 1360 // true = map at FileMapHeader::_requested_base_address 1361 // false = map at an alternative address picked by OS. 1362 MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo, 1363 bool use_requested_addr) { 1364 if (use_requested_addr && static_mapinfo->requested_base_address() == nullptr) { 1365 log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address."); 1366 return MAP_ARCHIVE_MMAP_FAILURE; 1367 } 1368 1369 PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) { 1370 // For product build only -- this is for benchmarking the cost of doing relocation. 1371 // For debug builds, the check is done below, after reserving the space, for better test coverage 1372 // (see comment below). 1373 log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address"); 1374 return MAP_ARCHIVE_MMAP_FAILURE; 1375 }); 1376 1377 if (ArchiveRelocationMode == 2 && !use_requested_addr) { 1378 log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address"); 1379 return MAP_ARCHIVE_MMAP_FAILURE; 1380 }; 1381 1382 if (dynamic_mapinfo != nullptr) { 1383 // Ensure that the OS won't be able to allocate new memory spaces between the two 1384 // archives, or else it would mess up the simple comparison in MetaspaceObj::is_shared(). 1385 assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap"); 1386 } 1387 1388 ReservedSpace total_space_rs, archive_space_rs, class_space_rs; 1389 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE; 1390 char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo, 1391 dynamic_mapinfo, 1392 use_requested_addr, 1393 total_space_rs, 1394 archive_space_rs, 1395 class_space_rs); 1396 if (mapped_base_address == nullptr) { 1397 result = MAP_ARCHIVE_MMAP_FAILURE; 1398 log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr); 1399 } else { 1400 1401 #ifdef ASSERT 1402 // Some sanity checks after reserving address spaces for archives 1403 // and class space. 1404 assert(archive_space_rs.is_reserved(), "Sanity"); 1405 if (Metaspace::using_class_space()) { 1406 // Class space must closely follow the archive space. Both spaces 1407 // must be aligned correctly. 1408 assert(class_space_rs.is_reserved(), 1409 "A class space should have been reserved"); 1410 assert(class_space_rs.base() >= archive_space_rs.end(), 1411 "class space should follow the cds archive space"); 1412 assert(is_aligned(archive_space_rs.base(), 1413 core_region_alignment()), 1414 "Archive space misaligned"); 1415 assert(is_aligned(class_space_rs.base(), 1416 Metaspace::reserve_alignment()), 1417 "class space misaligned"); 1418 } 1419 #endif // ASSERT 1420 1421 log_info(cds)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes", 1422 p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size()); 1423 log_info(cds)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes", 1424 p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size()); 1425 1426 if (MetaspaceShared::use_windows_memory_mapping()) { 1427 // We have now reserved address space for the archives, and will map in 1428 // the archive files into this space. 1429 // 1430 // Special handling for Windows: on Windows we cannot map a file view 1431 // into an existing memory mapping. So, we unmap the address range we 1432 // just reserved again, which will make it available for mapping the 1433 // archives. 1434 // Reserving this range has not been for naught however since it makes 1435 // us reasonably sure the address range is available. 1436 // 1437 // But still it may fail, since between unmapping the range and mapping 1438 // in the archive someone else may grab the address space. Therefore 1439 // there is a fallback in FileMap::map_region() where we just read in 1440 // the archive files sequentially instead of mapping it in. We couple 1441 // this with use_requested_addr, since we're going to patch all the 1442 // pointers anyway so there's no benefit to mmap. 1443 if (use_requested_addr) { 1444 assert(!total_space_rs.is_reserved(), "Should not be reserved for Windows"); 1445 log_info(cds)("Windows mmap workaround: releasing archive space."); 1446 archive_space_rs.release(); 1447 } 1448 } 1449 MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs); 1450 MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ? 1451 map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE; 1452 1453 DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) { 1454 // This is for simulating mmap failures at the requested address. In 1455 // debug builds, we do it here (after all archives have possibly been 1456 // mapped), so we can thoroughly test the code for failure handling 1457 // (releasing all allocated resource, etc). 1458 log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address"); 1459 if (static_result == MAP_ARCHIVE_SUCCESS) { 1460 static_result = MAP_ARCHIVE_MMAP_FAILURE; 1461 } 1462 if (dynamic_result == MAP_ARCHIVE_SUCCESS) { 1463 dynamic_result = MAP_ARCHIVE_MMAP_FAILURE; 1464 } 1465 }); 1466 1467 if (static_result == MAP_ARCHIVE_SUCCESS) { 1468 if (dynamic_result == MAP_ARCHIVE_SUCCESS) { 1469 result = MAP_ARCHIVE_SUCCESS; 1470 } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) { 1471 assert(dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped(), "must have failed"); 1472 // No need to retry mapping the dynamic archive again, as it will never succeed 1473 // (bad file, etc) -- just keep the base archive. 1474 log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s", 1475 dynamic_mapinfo->full_path()); 1476 result = MAP_ARCHIVE_SUCCESS; 1477 // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no 1478 // easy API to do that right now. 1479 } else { 1480 result = MAP_ARCHIVE_MMAP_FAILURE; 1481 } 1482 } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) { 1483 result = MAP_ARCHIVE_OTHER_FAILURE; 1484 } else { 1485 result = MAP_ARCHIVE_MMAP_FAILURE; 1486 } 1487 } 1488 1489 if (result == MAP_ARCHIVE_SUCCESS) { 1490 SharedBaseAddress = (size_t)mapped_base_address; 1491 #ifdef _LP64 1492 if (Metaspace::using_class_space()) { 1493 // Set up ccs in metaspace. 1494 Metaspace::initialize_class_space(class_space_rs); 1495 1496 // Set up compressed Klass pointer encoding: the encoding range must 1497 // cover both archive and class space. 1498 address cds_base = (address)static_mapinfo->mapped_base(); 1499 address ccs_end = (address)class_space_rs.end(); 1500 assert(ccs_end > cds_base, "Sanity check"); 1501 #if INCLUDE_CDS_JAVA_HEAP 1502 // We archived objects with pre-computed narrow Klass id. Set up encoding such that these Ids stay valid. 1503 address precomputed_narrow_klass_base = cds_base; 1504 const int precomputed_narrow_klass_shift = ArchiveHeapWriter::precomputed_narrow_klass_shift; 1505 CompressedKlassPointers::initialize_for_given_encoding( 1506 cds_base, ccs_end - cds_base, // Klass range 1507 precomputed_narrow_klass_base, precomputed_narrow_klass_shift // precomputed encoding, see ArchiveHeapWriter 1508 ); 1509 #else 1510 CompressedKlassPointers::initialize ( 1511 cds_base, ccs_end - cds_base // Klass range 1512 ); 1513 #endif // INCLUDE_CDS_JAVA_HEAP 1514 // map_or_load_heap_region() compares the current narrow oop and klass encodings 1515 // with the archived ones, so it must be done after all encodings are determined. 1516 static_mapinfo->map_or_load_heap_region(); 1517 } 1518 #endif // _LP64 1519 log_info(cds)("initial optimized module handling: %s", CDSConfig::is_using_optimized_module_handling() ? "enabled" : "disabled"); 1520 log_info(cds)("initial full module graph: %s", CDSConfig::is_using_full_module_graph() ? "enabled" : "disabled"); 1521 } else { 1522 unmap_archive(static_mapinfo); 1523 unmap_archive(dynamic_mapinfo); 1524 release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs); 1525 } 1526 1527 return result; 1528 } 1529 1530 1531 // This will reserve two address spaces suitable to house Klass structures, one 1532 // for the cds archives (static archive and optionally dynamic archive) and 1533 // optionally one move for ccs. 1534 // 1535 // Since both spaces must fall within the compressed class pointer encoding 1536 // range, they are allocated close to each other. 1537 // 1538 // Space for archives will be reserved first, followed by a potential gap, 1539 // followed by the space for ccs: 1540 // 1541 // +-- Base address A B End 1542 // | | | | 1543 // v v v v 1544 // +-------------+--------------+ +----------------------+ 1545 // | static arc | [dyn. arch] | [gap] | compr. class space | 1546 // +-------------+--------------+ +----------------------+ 1547 // 1548 // (The gap may result from different alignment requirements between metaspace 1549 // and CDS) 1550 // 1551 // If UseCompressedClassPointers is disabled, only one address space will be 1552 // reserved: 1553 // 1554 // +-- Base address End 1555 // | | 1556 // v v 1557 // +-------------+--------------+ 1558 // | static arc | [dyn. arch] | 1559 // +-------------+--------------+ 1560 // 1561 // Base address: If use_archive_base_addr address is true, the Base address is 1562 // determined by the address stored in the static archive. If 1563 // use_archive_base_addr address is false, this base address is determined 1564 // by the platform. 1565 // 1566 // If UseCompressedClassPointers=1, the range encompassing both spaces will be 1567 // suitable to en/decode narrow Klass pointers: the base will be valid for 1568 // encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax. 1569 // 1570 // Return: 1571 // 1572 // - On success: 1573 // - total_space_rs will be reserved as whole for archive_space_rs and 1574 // class_space_rs if UseCompressedClassPointers is true. 1575 // On Windows, try reserve archive_space_rs and class_space_rs 1576 // separately first if use_archive_base_addr is true. 1577 // - archive_space_rs will be reserved and large enough to host static and 1578 // if needed dynamic archive: [Base, A). 1579 // archive_space_rs.base and size will be aligned to CDS reserve 1580 // granularity. 1581 // - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will 1582 // be reserved. Its start address will be aligned to metaspace reserve 1583 // alignment, which may differ from CDS alignment. It will follow the cds 1584 // archive space, close enough such that narrow class pointer encoding 1585 // covers both spaces. 1586 // If UseCompressedClassPointers=0, class_space_rs remains unreserved. 1587 // - On error: null is returned and the spaces remain unreserved. 1588 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo, 1589 FileMapInfo* dynamic_mapinfo, 1590 bool use_archive_base_addr, 1591 ReservedSpace& total_space_rs, 1592 ReservedSpace& archive_space_rs, 1593 ReservedSpace& class_space_rs) { 1594 1595 address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : nullptr); 1596 const size_t archive_space_alignment = core_region_alignment(); 1597 1598 // Size and requested location of the archive_space_rs (for both static and dynamic archives) 1599 assert(static_mapinfo->mapping_base_offset() == 0, "Must be"); 1600 size_t archive_end_offset = (dynamic_mapinfo == nullptr) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset(); 1601 size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment); 1602 1603 if (!Metaspace::using_class_space()) { 1604 // Get the simple case out of the way first: 1605 // no compressed class space, simple allocation. 1606 1607 // When running without class space, requested archive base should be aligned to cds core alignment. 1608 assert(is_aligned(base_address, archive_space_alignment), 1609 "Archive base address unaligned: " PTR_FORMAT ", needs alignment: %zu.", 1610 p2i(base_address), archive_space_alignment); 1611 1612 archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment, 1613 os::vm_page_size(), (char*)base_address); 1614 if (archive_space_rs.is_reserved()) { 1615 assert(base_address == nullptr || 1616 (address)archive_space_rs.base() == base_address, "Sanity"); 1617 // Register archive space with NMT. 1618 MemTracker::record_virtual_memory_tag(archive_space_rs.base(), mtClassShared); 1619 return archive_space_rs.base(); 1620 } 1621 return nullptr; 1622 } 1623 1624 #ifdef _LP64 1625 1626 // Complex case: two spaces adjacent to each other, both to be addressable 1627 // with narrow class pointers. 1628 // We reserve the whole range spanning both spaces, then split that range up. 1629 1630 const size_t class_space_alignment = Metaspace::reserve_alignment(); 1631 1632 // When running with class space, requested archive base must satisfy both cds core alignment 1633 // and class space alignment. 1634 const size_t base_address_alignment = MAX2(class_space_alignment, archive_space_alignment); 1635 assert(is_aligned(base_address, base_address_alignment), 1636 "Archive base address unaligned: " PTR_FORMAT ", needs alignment: %zu.", 1637 p2i(base_address), base_address_alignment); 1638 1639 size_t class_space_size = CompressedClassSpaceSize; 1640 assert(CompressedClassSpaceSize > 0 && 1641 is_aligned(CompressedClassSpaceSize, class_space_alignment), 1642 "CompressedClassSpaceSize malformed: " 1643 SIZE_FORMAT, CompressedClassSpaceSize); 1644 1645 const size_t ccs_begin_offset = align_up(archive_space_size, class_space_alignment); 1646 const size_t gap_size = ccs_begin_offset - archive_space_size; 1647 1648 // Reduce class space size if it would not fit into the Klass encoding range 1649 constexpr size_t max_encoding_range_size = 4 * G; 1650 guarantee(archive_space_size < max_encoding_range_size - class_space_alignment, "Archive too large"); 1651 if ((archive_space_size + gap_size + class_space_size) > max_encoding_range_size) { 1652 class_space_size = align_down(max_encoding_range_size - archive_space_size - gap_size, class_space_alignment); 1653 log_info(metaspace)("CDS initialization: reducing class space size from " SIZE_FORMAT " to " SIZE_FORMAT, 1654 CompressedClassSpaceSize, class_space_size); 1655 FLAG_SET_ERGO(CompressedClassSpaceSize, class_space_size); 1656 } 1657 1658 const size_t total_range_size = 1659 archive_space_size + gap_size + class_space_size; 1660 1661 assert(total_range_size > ccs_begin_offset, "must be"); 1662 if (use_windows_memory_mapping() && use_archive_base_addr) { 1663 if (base_address != nullptr) { 1664 // On Windows, we cannot safely split a reserved memory space into two (see JDK-8255917). 1665 // Hence, we optimistically reserve archive space and class space side-by-side. We only 1666 // do this for use_archive_base_addr=true since for use_archive_base_addr=false case 1667 // caller will not split the combined space for mapping, instead read the archive data 1668 // via sequential file IO. 1669 address ccs_base = base_address + archive_space_size + gap_size; 1670 archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment, 1671 os::vm_page_size(), (char*)base_address); 1672 class_space_rs = ReservedSpace(class_space_size, class_space_alignment, 1673 os::vm_page_size(), (char*)ccs_base); 1674 } 1675 if (!archive_space_rs.is_reserved() || !class_space_rs.is_reserved()) { 1676 release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs); 1677 return nullptr; 1678 } 1679 // NMT: fix up the space tags 1680 MemTracker::record_virtual_memory_tag(archive_space_rs.base(), mtClassShared); 1681 MemTracker::record_virtual_memory_tag(class_space_rs.base(), mtClass); 1682 } else { 1683 if (use_archive_base_addr && base_address != nullptr) { 1684 total_space_rs = ReservedSpace(total_range_size, base_address_alignment, 1685 os::vm_page_size(), (char*) base_address); 1686 } else { 1687 // We did not manage to reserve at the preferred address, or were instructed to relocate. In that 1688 // case we reserve wherever possible, but the start address needs to be encodable as narrow Klass 1689 // encoding base since the archived heap objects contain nKlass IDs pre-calculated toward the start 1690 // of the shared Metaspace. That prevents us from using zero-based encoding and therefore we won't 1691 // try allocating in low-address regions. 1692 total_space_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size, false /* optimize_for_zero_base */); 1693 } 1694 1695 if (!total_space_rs.is_reserved()) { 1696 return nullptr; 1697 } 1698 1699 // Paranoid checks: 1700 assert(base_address == nullptr || (address)total_space_rs.base() == base_address, 1701 "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_space_rs.base())); 1702 assert(is_aligned(total_space_rs.base(), base_address_alignment), "Sanity"); 1703 assert(total_space_rs.size() == total_range_size, "Sanity"); 1704 1705 // Now split up the space into ccs and cds archive. For simplicity, just leave 1706 // the gap reserved at the end of the archive space. Do not do real splitting. 1707 archive_space_rs = total_space_rs.first_part(ccs_begin_offset, 1708 (size_t)archive_space_alignment); 1709 class_space_rs = total_space_rs.last_part(ccs_begin_offset); 1710 MemTracker::record_virtual_memory_split_reserved(total_space_rs.base(), total_space_rs.size(), 1711 ccs_begin_offset, mtClassShared, mtClass); 1712 } 1713 assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity"); 1714 assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity"); 1715 assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity"); 1716 assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity"); 1717 1718 1719 return archive_space_rs.base(); 1720 1721 #else 1722 ShouldNotReachHere(); 1723 return nullptr; 1724 #endif 1725 1726 } 1727 1728 void MetaspaceShared::release_reserved_spaces(ReservedSpace& total_space_rs, 1729 ReservedSpace& archive_space_rs, 1730 ReservedSpace& class_space_rs) { 1731 if (total_space_rs.is_reserved()) { 1732 log_debug(cds)("Released shared space (archive + class) " INTPTR_FORMAT, p2i(total_space_rs.base())); 1733 total_space_rs.release(); 1734 } else { 1735 if (archive_space_rs.is_reserved()) { 1736 log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base())); 1737 archive_space_rs.release(); 1738 } 1739 if (class_space_rs.is_reserved()) { 1740 log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base())); 1741 class_space_rs.release(); 1742 } 1743 } 1744 } 1745 1746 static int archive_regions[] = { MetaspaceShared::rw, MetaspaceShared::ro }; 1747 static int archive_regions_count = 2; 1748 1749 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) { 1750 assert(CDSConfig::is_using_archive(), "must be runtime"); 1751 if (mapinfo == nullptr) { 1752 return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded. 1753 } 1754 1755 if (!mapinfo->validate_aot_class_linking()) { 1756 return MAP_ARCHIVE_OTHER_FAILURE; 1757 } 1758 1759 mapinfo->set_is_mapped(false); 1760 if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) { 1761 log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT 1762 " actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment()); 1763 return MAP_ARCHIVE_OTHER_FAILURE; 1764 } 1765 1766 MapArchiveResult result = 1767 mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs); 1768 1769 if (result != MAP_ARCHIVE_SUCCESS) { 1770 unmap_archive(mapinfo); 1771 return result; 1772 } 1773 1774 if (!mapinfo->validate_shared_path_table()) { 1775 unmap_archive(mapinfo); 1776 return MAP_ARCHIVE_OTHER_FAILURE; 1777 } 1778 1779 mapinfo->set_is_mapped(true); 1780 return MAP_ARCHIVE_SUCCESS; 1781 } 1782 1783 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) { 1784 assert(CDSConfig::is_using_archive(), "must be runtime"); 1785 if (mapinfo != nullptr) { 1786 mapinfo->unmap_regions(archive_regions, archive_regions_count); 1787 mapinfo->unmap_region(MetaspaceShared::bm); 1788 mapinfo->set_is_mapped(false); 1789 } 1790 } 1791 1792 // For -XX:PrintSharedArchiveAndExit 1793 class CountSharedSymbols : public SymbolClosure { 1794 private: 1795 int _count; 1796 public: 1797 CountSharedSymbols() : _count(0) {} 1798 void do_symbol(Symbol** sym) { 1799 _count++; 1800 } 1801 int total() { return _count; } 1802 1803 }; 1804 1805 // Read the miscellaneous data from the shared file, and 1806 // serialize it out to its various destinations. 1807 1808 void MetaspaceShared::initialize_shared_spaces() { 1809 FileMapInfo *static_mapinfo = FileMapInfo::current_info(); 1810 1811 // Verify various attributes of the archive, plus initialize the 1812 // shared string/symbol tables. 1813 char* buffer = static_mapinfo->serialized_data(); 1814 intptr_t* array = (intptr_t*)buffer; 1815 ReadClosure rc(&array); 1816 serialize(&rc); 1817 1818 // Finish up archived heap initialization. These must be 1819 // done after ReadClosure. 1820 static_mapinfo->patch_heap_embedded_pointers(); 1821 ArchiveHeapLoader::finish_initialization(); 1822 Universe::load_archived_object_instances(); 1823 SCCache::new_workflow_load_cache(); 1824 1825 // Close the mapinfo file 1826 static_mapinfo->close(); 1827 1828 static_mapinfo->unmap_region(MetaspaceShared::bm); 1829 1830 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info(); 1831 if (dynamic_mapinfo != nullptr) { 1832 intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data(); 1833 ReadClosure rc(&buffer); 1834 ArchiveBuilder::serialize_dynamic_archivable_items(&rc); 1835 DynamicArchive::setup_array_klasses(); 1836 dynamic_mapinfo->close(); 1837 dynamic_mapinfo->unmap_region(MetaspaceShared::bm); 1838 } 1839 1840 log_info(cds)("Using AOT-linked classes: %s (%s%s)", 1841 CDSConfig::is_using_aot_linked_classes() ? "true" : "false", 1842 static_mapinfo->header()->has_aot_linked_classes() ? "static archive: true" : "static archive: false", 1843 (dynamic_mapinfo == nullptr) ? "" : 1844 (dynamic_mapinfo->header()->has_aot_linked_classes() ? ", dynamic archive: true" : ", dynamic archive: false")); 1845 1846 // Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump 1847 if (CDSConfig::is_dumping_dynamic_archive()) { 1848 // Read stored LF format lines stored in static archive 1849 LambdaFormInvokers::read_static_archive_invokers(); 1850 } 1851 1852 if (PrintSharedArchiveAndExit) { 1853 // Print archive names 1854 if (dynamic_mapinfo != nullptr) { 1855 tty->print_cr("\n\nBase archive name: %s", CDSConfig::static_archive_path()); 1856 tty->print_cr("Base archive version %d", static_mapinfo->version()); 1857 } else { 1858 tty->print_cr("Static archive name: %s", static_mapinfo->full_path()); 1859 tty->print_cr("Static archive version %d", static_mapinfo->version()); 1860 } 1861 1862 SystemDictionaryShared::print_shared_archive(tty); 1863 if (dynamic_mapinfo != nullptr) { 1864 tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path()); 1865 tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version()); 1866 SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/); 1867 } 1868 TrainingData::print_archived_training_data_on(tty); 1869 1870 if (LoadCachedCode) { 1871 tty->print_cr("\n\nCached Code file: %s", CachedCodeFile); 1872 SCCache::print_on(tty); 1873 } 1874 1875 // collect shared symbols and strings 1876 CountSharedSymbols cl; 1877 SymbolTable::shared_symbols_do(&cl); 1878 tty->print_cr("Number of shared symbols: %d", cl.total()); 1879 tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count()); 1880 tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version()); 1881 if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) { 1882 tty->print_cr("archive is invalid"); 1883 vm_exit(1); 1884 } else { 1885 tty->print_cr("archive is valid"); 1886 vm_exit(0); 1887 } 1888 } 1889 } 1890 1891 // JVM/TI RedefineClasses() support: 1892 bool MetaspaceShared::remap_shared_readonly_as_readwrite() { 1893 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 1894 1895 if (CDSConfig::is_using_archive()) { 1896 // remap the shared readonly space to shared readwrite, private 1897 FileMapInfo* mapinfo = FileMapInfo::current_info(); 1898 if (!mapinfo->remap_shared_readonly_as_readwrite()) { 1899 return false; 1900 } 1901 if (FileMapInfo::dynamic_info() != nullptr) { 1902 mapinfo = FileMapInfo::dynamic_info(); 1903 if (!mapinfo->remap_shared_readonly_as_readwrite()) { 1904 return false; 1905 } 1906 } 1907 _remapped_readwrite = true; 1908 } 1909 return true; 1910 } 1911 1912 void MetaspaceShared::print_on(outputStream* st) { 1913 if (CDSConfig::is_using_archive()) { 1914 st->print("CDS archive(s) mapped at: "); 1915 address base = (address)MetaspaceObj::shared_metaspace_base(); 1916 address static_top = (address)_shared_metaspace_static_top; 1917 address top = (address)MetaspaceObj::shared_metaspace_top(); 1918 st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top)); 1919 st->print("size " SIZE_FORMAT ", ", top - base); 1920 st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, ArchiveRelocationMode); 1921 } else { 1922 st->print("CDS archive(s) not mapped"); 1923 } 1924 st->cr(); 1925 }