1 /* 2 * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "cds/aotClassLocation.hpp" 26 #include "cds/aotLogging.hpp" 27 #include "cds/archiveBuilder.hpp" 28 #include "cds/archiveHeapLoader.inline.hpp" 29 #include "cds/archiveHeapWriter.hpp" 30 #include "cds/archiveUtils.inline.hpp" 31 #include "cds/cds_globals.hpp" 32 #include "cds/cdsConfig.hpp" 33 #include "cds/dynamicArchive.hpp" 34 #include "cds/filemap.hpp" 35 #include "cds/heapShared.hpp" 36 #include "cds/metaspaceShared.hpp" 37 #include "classfile/altHashing.hpp" 38 #include "classfile/classFileStream.hpp" 39 #include "classfile/classLoader.hpp" 40 #include "classfile/classLoader.inline.hpp" 41 #include "classfile/classLoaderData.inline.hpp" 42 #include "classfile/symbolTable.hpp" 43 #include "classfile/systemDictionaryShared.hpp" 44 #include "classfile/vmClasses.hpp" 45 #include "classfile/vmSymbols.hpp" 46 #include "compiler/compilerDefinitions.inline.hpp" 47 #include "jvm.h" 48 #include "logging/log.hpp" 49 #include "logging/logMessage.hpp" 50 #include "logging/logStream.hpp" 51 #include "memory/iterator.inline.hpp" 52 #include "memory/metadataFactory.hpp" 53 #include "memory/metaspaceClosure.hpp" 54 #include "memory/oopFactory.hpp" 55 #include "memory/universe.hpp" 56 #include "nmt/memTracker.hpp" 57 #include "oops/access.hpp" 58 #include "oops/compressedKlass.hpp" 59 #include "oops/compressedOops.hpp" 60 #include "oops/compressedOops.inline.hpp" 61 #include "oops/objArrayOop.hpp" 62 #include "oops/oop.inline.hpp" 63 #include "oops/trainingData.hpp" 64 #include "oops/typeArrayKlass.hpp" 65 #include "prims/jvmtiExport.hpp" 66 #include "runtime/arguments.hpp" 67 #include "runtime/globals_extension.hpp" 68 #include "runtime/java.hpp" 69 #include "runtime/javaCalls.hpp" 70 #include "runtime/mutexLocker.hpp" 71 #include "runtime/os.hpp" 72 #include "runtime/vm_version.hpp" 73 #include "utilities/align.hpp" 74 #include "utilities/bitMap.inline.hpp" 75 #include "utilities/classpathStream.hpp" 76 #include "utilities/defaultStream.hpp" 77 #include "utilities/ostream.hpp" 78 #if INCLUDE_G1GC 79 #include "gc/g1/g1CollectedHeap.hpp" 80 #include "gc/g1/g1HeapRegion.hpp" 81 #endif 82 83 #include <errno.h> 84 #include <sys/stat.h> 85 86 #ifndef O_BINARY // if defined (Win32) use binary files. 87 #define O_BINARY 0 // otherwise do nothing. 88 #endif 89 90 // Fill in the fileMapInfo structure with data about this VM instance. 91 92 // This method copies the vm version info into header_version. If the version is too 93 // long then a truncated version, which has a hash code appended to it, is copied. 94 // 95 // Using a template enables this method to verify that header_version is an array of 96 // length JVM_IDENT_MAX. This ensures that the code that writes to the CDS file and 97 // the code that reads the CDS file will both use the same size buffer. Hence, will 98 // use identical truncation. This is necessary for matching of truncated versions. 99 template <int N> static void get_header_version(char (&header_version) [N]) { 100 assert(N == JVM_IDENT_MAX, "Bad header_version size"); 101 102 const char *vm_version = VM_Version::internal_vm_info_string(); 103 const int version_len = (int)strlen(vm_version); 104 105 memset(header_version, 0, JVM_IDENT_MAX); 106 107 if (version_len < (JVM_IDENT_MAX-1)) { 108 strcpy(header_version, vm_version); 109 110 } else { 111 // Get the hash value. Use a static seed because the hash needs to return the same 112 // value over multiple jvm invocations. 113 uint32_t hash = AltHashing::halfsiphash_32(8191, (const uint8_t*)vm_version, version_len); 114 115 // Truncate the ident, saving room for the 8 hex character hash value. 116 strncpy(header_version, vm_version, JVM_IDENT_MAX-9); 117 118 // Append the hash code as eight hex digits. 119 os::snprintf_checked(&header_version[JVM_IDENT_MAX-9], 9, "%08x", hash); 120 header_version[JVM_IDENT_MAX-1] = 0; // Null terminate. 121 } 122 123 assert(header_version[JVM_IDENT_MAX-1] == 0, "must be"); 124 } 125 126 FileMapInfo::FileMapInfo(const char* full_path, bool is_static) : 127 _is_static(is_static), _file_open(false), _is_mapped(false), _fd(-1), _file_offset(0), 128 _full_path(full_path), _base_archive_name(nullptr), _header(nullptr) { 129 if (_is_static) { 130 assert(_current_info == nullptr, "must be singleton"); // not thread safe 131 _current_info = this; 132 } else { 133 assert(_dynamic_archive_info == nullptr, "must be singleton"); // not thread safe 134 _dynamic_archive_info = this; 135 } 136 } 137 138 FileMapInfo::~FileMapInfo() { 139 if (_is_static) { 140 assert(_current_info == this, "must be singleton"); // not thread safe 141 _current_info = nullptr; 142 } else { 143 assert(_dynamic_archive_info == this, "must be singleton"); // not thread safe 144 _dynamic_archive_info = nullptr; 145 } 146 147 if (_header != nullptr) { 148 os::free(_header); 149 } 150 151 if (_file_open) { 152 ::close(_fd); 153 } 154 } 155 156 void FileMapInfo::free_current_info() { 157 assert(CDSConfig::is_dumping_final_static_archive(), "only supported in this mode"); 158 assert(_current_info != nullptr, "sanity"); 159 delete _current_info; 160 assert(_current_info == nullptr, "sanity"); // Side effect expected from the above "delete" operator. 161 } 162 163 void FileMapInfo::populate_header(size_t core_region_alignment) { 164 assert(_header == nullptr, "Sanity check"); 165 size_t c_header_size; 166 size_t header_size; 167 size_t base_archive_name_size = 0; 168 size_t base_archive_name_offset = 0; 169 if (is_static()) { 170 c_header_size = sizeof(FileMapHeader); 171 header_size = c_header_size; 172 } else { 173 // dynamic header including base archive name for non-default base archive 174 c_header_size = sizeof(DynamicArchiveHeader); 175 header_size = c_header_size; 176 177 const char* default_base_archive_name = CDSConfig::default_archive_path(); 178 const char* current_base_archive_name = CDSConfig::input_static_archive_path(); 179 if (!os::same_files(current_base_archive_name, default_base_archive_name)) { 180 base_archive_name_size = strlen(current_base_archive_name) + 1; 181 header_size += base_archive_name_size; 182 base_archive_name_offset = c_header_size; 183 } 184 } 185 _header = (FileMapHeader*)os::malloc(header_size, mtInternal); 186 memset((void*)_header, 0, header_size); 187 _header->populate(this, 188 core_region_alignment, 189 header_size, 190 base_archive_name_size, 191 base_archive_name_offset); 192 } 193 194 void FileMapHeader::populate(FileMapInfo *info, size_t core_region_alignment, 195 size_t header_size, size_t base_archive_name_size, 196 size_t base_archive_name_offset) { 197 // 1. We require _generic_header._magic to be at the beginning of the file 198 // 2. FileMapHeader also assumes that _generic_header is at the beginning of the file 199 assert(offset_of(FileMapHeader, _generic_header) == 0, "must be"); 200 set_header_size((unsigned int)header_size); 201 set_base_archive_name_offset((unsigned int)base_archive_name_offset); 202 set_base_archive_name_size((unsigned int)base_archive_name_size); 203 if (CDSConfig::is_dumping_dynamic_archive()) { 204 set_magic(CDS_DYNAMIC_ARCHIVE_MAGIC); 205 } else if (CDSConfig::is_dumping_preimage_static_archive()) { 206 set_magic(CDS_PREIMAGE_ARCHIVE_MAGIC); 207 } else { 208 set_magic(CDS_ARCHIVE_MAGIC); 209 } 210 set_version(CURRENT_CDS_ARCHIVE_VERSION); 211 212 if (!info->is_static() && base_archive_name_size != 0) { 213 // copy base archive name 214 copy_base_archive_name(CDSConfig::input_static_archive_path()); 215 } 216 _core_region_alignment = core_region_alignment; 217 _obj_alignment = ObjectAlignmentInBytes; 218 _compact_strings = CompactStrings; 219 _compact_headers = UseCompactObjectHeaders; 220 if (CDSConfig::is_dumping_heap()) { 221 _narrow_oop_mode = CompressedOops::mode(); 222 _narrow_oop_base = CompressedOops::base(); 223 _narrow_oop_shift = CompressedOops::shift(); 224 } 225 _compressed_oops = UseCompressedOops; 226 _compressed_class_ptrs = UseCompressedClassPointers; 227 if (UseCompressedClassPointers) { 228 #ifdef _LP64 229 _narrow_klass_pointer_bits = CompressedKlassPointers::narrow_klass_pointer_bits(); 230 _narrow_klass_shift = ArchiveBuilder::precomputed_narrow_klass_shift(); 231 #endif 232 } else { 233 _narrow_klass_pointer_bits = _narrow_klass_shift = -1; 234 } 235 // Which JIT compier is used 236 _compiler_type = (u1)CompilerConfig::compiler_type(); 237 _type_profile_level = TypeProfileLevel; 238 _type_profile_args_limit = TypeProfileArgsLimit; 239 _type_profile_parms_limit = TypeProfileParmsLimit; 240 _type_profile_width = TypeProfileWidth; 241 _bci_profile_width = BciProfileWidth; 242 _profile_traps = ProfileTraps; 243 _type_profile_casts = TypeProfileCasts; 244 _spec_trap_limit_extra_entries = SpecTrapLimitExtraEntries; 245 _max_heap_size = MaxHeapSize; 246 _use_optimized_module_handling = CDSConfig::is_using_optimized_module_handling(); 247 _has_aot_linked_classes = CDSConfig::is_dumping_aot_linked_classes(); 248 _has_full_module_graph = CDSConfig::is_dumping_full_module_graph(); 249 250 // The following fields are for sanity checks for whether this archive 251 // will function correctly with this JVM and the bootclasspath it's 252 // invoked with. 253 254 // JVM version string ... changes on each build. 255 get_header_version(_jvm_ident); 256 257 _verify_local = BytecodeVerificationLocal; 258 _verify_remote = BytecodeVerificationRemote; 259 _has_platform_or_app_classes = AOTClassLocationConfig::dumptime()->has_platform_or_app_classes(); 260 _requested_base_address = (char*)SharedBaseAddress; 261 _mapped_base_address = (char*)SharedBaseAddress; 262 _allow_archiving_with_java_agent = AllowArchivingWithJavaAgent; 263 } 264 265 void FileMapHeader::copy_base_archive_name(const char* archive) { 266 assert(base_archive_name_size() != 0, "_base_archive_name_size not set"); 267 assert(base_archive_name_offset() != 0, "_base_archive_name_offset not set"); 268 assert(header_size() > sizeof(*this), "_base_archive_name_size not included in header size?"); 269 memcpy((char*)this + base_archive_name_offset(), archive, base_archive_name_size()); 270 } 271 272 void FileMapHeader::print(outputStream* st) { 273 ResourceMark rm; 274 275 st->print_cr("- magic: 0x%08x", magic()); 276 st->print_cr("- crc: 0x%08x", crc()); 277 st->print_cr("- version: 0x%x", version()); 278 st->print_cr("- header_size: " UINT32_FORMAT, header_size()); 279 st->print_cr("- base_archive_name_offset: " UINT32_FORMAT, base_archive_name_offset()); 280 st->print_cr("- base_archive_name_size: " UINT32_FORMAT, base_archive_name_size()); 281 282 for (int i = 0; i < NUM_CDS_REGIONS; i++) { 283 FileMapRegion* r = region_at(i); 284 r->print(st, i); 285 } 286 st->print_cr("============ end regions ======== "); 287 288 st->print_cr("- core_region_alignment: %zu", _core_region_alignment); 289 st->print_cr("- obj_alignment: %d", _obj_alignment); 290 st->print_cr("- narrow_oop_base: " INTPTR_FORMAT, p2i(_narrow_oop_base)); 291 st->print_cr("- narrow_oop_shift %d", _narrow_oop_shift); 292 st->print_cr("- compact_strings: %d", _compact_strings); 293 st->print_cr("- compact_headers: %d", _compact_headers); 294 st->print_cr("- max_heap_size: %zu", _max_heap_size); 295 st->print_cr("- narrow_oop_mode: %d", _narrow_oop_mode); 296 st->print_cr("- compressed_oops: %d", _compressed_oops); 297 st->print_cr("- compressed_class_ptrs: %d", _compressed_class_ptrs); 298 st->print_cr("- narrow_klass_pointer_bits: %d", _narrow_klass_pointer_bits); 299 st->print_cr("- narrow_klass_shift: %d", _narrow_klass_shift); 300 st->print_cr("- cloned_vtables_offset: 0x%zx", _cloned_vtables_offset); 301 st->print_cr("- early_serialized_data_offset: 0x%zx", _early_serialized_data_offset); 302 st->print_cr("- serialized_data_offset: 0x%zx", _serialized_data_offset); 303 st->print_cr("- jvm_ident: %s", _jvm_ident); 304 st->print_cr("- class_location_config_offset: 0x%zx", _class_location_config_offset); 305 st->print_cr("- verify_local: %d", _verify_local); 306 st->print_cr("- verify_remote: %d", _verify_remote); 307 st->print_cr("- has_platform_or_app_classes: %d", _has_platform_or_app_classes); 308 st->print_cr("- requested_base_address: " INTPTR_FORMAT, p2i(_requested_base_address)); 309 st->print_cr("- mapped_base_address: " INTPTR_FORMAT, p2i(_mapped_base_address)); 310 st->print_cr("- heap_root_segments.roots_count: %d" , _heap_root_segments.roots_count()); 311 st->print_cr("- heap_root_segments.base_offset: 0x%zx", _heap_root_segments.base_offset()); 312 st->print_cr("- heap_root_segments.count: %zu", _heap_root_segments.count()); 313 st->print_cr("- heap_root_segments.max_size_elems: %d", _heap_root_segments.max_size_in_elems()); 314 st->print_cr("- heap_root_segments.max_size_bytes: %d", _heap_root_segments.max_size_in_bytes()); 315 st->print_cr("- _heap_oopmap_start_pos: %zu", _heap_oopmap_start_pos); 316 st->print_cr("- _heap_ptrmap_start_pos: %zu", _heap_ptrmap_start_pos); 317 st->print_cr("- _rw_ptrmap_start_pos: %zu", _rw_ptrmap_start_pos); 318 st->print_cr("- _ro_ptrmap_start_pos: %zu", _ro_ptrmap_start_pos); 319 st->print_cr("- allow_archiving_with_java_agent:%d", _allow_archiving_with_java_agent); 320 st->print_cr("- use_optimized_module_handling: %d", _use_optimized_module_handling); 321 st->print_cr("- has_full_module_graph %d", _has_full_module_graph); 322 st->print_cr("- has_aot_linked_classes %d", _has_aot_linked_classes); 323 } 324 325 bool FileMapInfo::validate_class_location() { 326 assert(CDSConfig::is_using_archive(), "runtime only"); 327 328 AOTClassLocationConfig* config = header()->class_location_config(); 329 bool has_extra_module_paths = false; 330 if (!config->validate(full_path(), header()->has_aot_linked_classes(), &has_extra_module_paths)) { 331 if (PrintSharedArchiveAndExit) { 332 MetaspaceShared::set_archive_loading_failed(); 333 return true; 334 } else { 335 return false; 336 } 337 } 338 339 if (header()->has_full_module_graph() && has_extra_module_paths) { 340 CDSConfig::stop_using_optimized_module_handling(); 341 MetaspaceShared::report_loading_error("optimized module handling: disabled because extra module path(s) are specified"); 342 } 343 344 if (CDSConfig::is_dumping_dynamic_archive()) { 345 // Only support dynamic dumping with the usage of the default CDS archive 346 // or a simple base archive. 347 // If the base layer archive contains additional path component besides 348 // the runtime image and the -cp, dynamic dumping is disabled. 349 if (config->num_boot_classpaths() > 0) { 350 CDSConfig::disable_dumping_dynamic_archive(); 351 aot_log_warning(aot)( 352 "Dynamic archiving is disabled because base layer archive has appended boot classpath"); 353 } 354 if (config->num_module_paths() > 0) { 355 if (has_extra_module_paths) { 356 CDSConfig::disable_dumping_dynamic_archive(); 357 aot_log_warning(aot)( 358 "Dynamic archiving is disabled because base layer archive has a different module path"); 359 } 360 } 361 } 362 363 #if INCLUDE_JVMTI 364 if (_classpath_entries_for_jvmti != nullptr) { 365 os::free(_classpath_entries_for_jvmti); 366 } 367 size_t sz = sizeof(ClassPathEntry*) * AOTClassLocationConfig::runtime()->length(); 368 _classpath_entries_for_jvmti = (ClassPathEntry**)os::malloc(sz, mtClass); 369 memset((void*)_classpath_entries_for_jvmti, 0, sz); 370 #endif 371 372 return true; 373 } 374 375 // A utility class for reading/validating the GenericCDSFileMapHeader portion of 376 // a CDS archive's header. The file header of all CDS archives with versions from 377 // CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION (12) are guaranteed to always start 378 // with GenericCDSFileMapHeader. This makes it possible to read important information 379 // from a CDS archive created by a different version of HotSpot, so that we can 380 // automatically regenerate the archive as necessary (JDK-8261455). 381 class FileHeaderHelper { 382 int _fd; 383 bool _is_valid; 384 bool _is_static; 385 GenericCDSFileMapHeader* _header; 386 const char* _archive_name; 387 const char* _base_archive_name; 388 389 public: 390 FileHeaderHelper(const char* archive_name, bool is_static) { 391 _fd = -1; 392 _is_valid = false; 393 _header = nullptr; 394 _base_archive_name = nullptr; 395 _archive_name = archive_name; 396 _is_static = is_static; 397 } 398 399 ~FileHeaderHelper() { 400 if (_header != nullptr) { 401 FREE_C_HEAP_ARRAY(char, _header); 402 } 403 if (_fd != -1) { 404 ::close(_fd); 405 } 406 } 407 408 bool initialize() { 409 assert(_archive_name != nullptr, "Archive name is null"); 410 _fd = os::open(_archive_name, O_RDONLY | O_BINARY, 0); 411 if (_fd < 0) { 412 MetaspaceShared::report_loading_error("Specified %s not found (%s)", CDSConfig::type_of_archive_being_loaded(), _archive_name); 413 return false; 414 } 415 return initialize(_fd); 416 } 417 418 // for an already opened file, do not set _fd 419 bool initialize(int fd) { 420 assert(_archive_name != nullptr, "Archive name is null"); 421 assert(fd != -1, "Archive must be opened already"); 422 // First read the generic header so we know the exact size of the actual header. 423 const char* file_type = CDSConfig::type_of_archive_being_loaded(); 424 GenericCDSFileMapHeader gen_header; 425 size_t size = sizeof(GenericCDSFileMapHeader); 426 os::lseek(fd, 0, SEEK_SET); 427 size_t n = ::read(fd, (void*)&gen_header, (unsigned int)size); 428 if (n != size) { 429 aot_log_warning(aot)("Unable to read generic CDS file map header from %s", file_type); 430 return false; 431 } 432 433 if (gen_header._magic != CDS_ARCHIVE_MAGIC && 434 gen_header._magic != CDS_DYNAMIC_ARCHIVE_MAGIC && 435 gen_header._magic != CDS_PREIMAGE_ARCHIVE_MAGIC) { 436 aot_log_warning(aot)("The %s has a bad magic number: %#x", file_type, gen_header._magic); 437 return false; 438 } 439 440 if (gen_header._version < CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION) { 441 aot_log_warning(aot)("Cannot handle %s version 0x%x. Must be at least 0x%x.", 442 file_type, gen_header._version, CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION); 443 return false; 444 } 445 446 if (gen_header._version != CURRENT_CDS_ARCHIVE_VERSION) { 447 aot_log_warning(aot)("The %s version 0x%x does not match the required version 0x%x.", 448 file_type, gen_header._version, CURRENT_CDS_ARCHIVE_VERSION); 449 } 450 451 size_t filelen = os::lseek(fd, 0, SEEK_END); 452 if (gen_header._header_size >= filelen) { 453 aot_log_warning(aot)("Archive file header larger than archive file"); 454 return false; 455 } 456 457 // Read the actual header and perform more checks 458 size = gen_header._header_size; 459 _header = (GenericCDSFileMapHeader*)NEW_C_HEAP_ARRAY(char, size, mtInternal); 460 os::lseek(fd, 0, SEEK_SET); 461 n = ::read(fd, (void*)_header, (unsigned int)size); 462 if (n != size) { 463 aot_log_warning(aot)("Unable to read file map header from %s", file_type); 464 return false; 465 } 466 467 if (!check_header_crc()) { 468 return false; 469 } 470 471 if (!check_and_init_base_archive_name()) { 472 return false; 473 } 474 475 // All fields in the GenericCDSFileMapHeader has been validated. 476 _is_valid = true; 477 return true; 478 } 479 480 GenericCDSFileMapHeader* get_generic_file_header() { 481 assert(_header != nullptr && _is_valid, "must be a valid archive file"); 482 return _header; 483 } 484 485 const char* base_archive_name() { 486 assert(_header != nullptr && _is_valid, "must be a valid archive file"); 487 return _base_archive_name; 488 } 489 490 bool is_static_archive() const { 491 return _header->_magic == CDS_ARCHIVE_MAGIC; 492 } 493 494 bool is_dynamic_archive() const { 495 return _header->_magic == CDS_DYNAMIC_ARCHIVE_MAGIC; 496 } 497 498 bool is_preimage_static_archive() const { 499 return _header->_magic == CDS_PREIMAGE_ARCHIVE_MAGIC; 500 } 501 502 private: 503 bool check_header_crc() const { 504 if (VerifySharedSpaces) { 505 FileMapHeader* header = (FileMapHeader*)_header; 506 int actual_crc = header->compute_crc(); 507 if (actual_crc != header->crc()) { 508 aot_log_info(aot)("_crc expected: %d", header->crc()); 509 aot_log_info(aot)(" actual: %d", actual_crc); 510 aot_log_warning(aot)("Header checksum verification failed."); 511 return false; 512 } 513 } 514 return true; 515 } 516 517 bool check_and_init_base_archive_name() { 518 unsigned int name_offset = _header->_base_archive_name_offset; 519 unsigned int name_size = _header->_base_archive_name_size; 520 unsigned int header_size = _header->_header_size; 521 522 if (name_offset + name_size < name_offset) { 523 aot_log_warning(aot)("base_archive_name offset/size overflow: " UINT32_FORMAT "/" UINT32_FORMAT, 524 name_offset, name_size); 525 return false; 526 } 527 528 if (is_static_archive() || is_preimage_static_archive()) { 529 if (name_offset != 0) { 530 aot_log_warning(aot)("static shared archive must have zero _base_archive_name_offset"); 531 return false; 532 } 533 if (name_size != 0) { 534 aot_log_warning(aot)("static shared archive must have zero _base_archive_name_size"); 535 return false; 536 } 537 } else { 538 assert(is_dynamic_archive(), "must be"); 539 if ((name_size == 0 && name_offset != 0) || 540 (name_size != 0 && name_offset == 0)) { 541 // If either is zero, both must be zero. This indicates that we are using the default base archive. 542 aot_log_warning(aot)("Invalid base_archive_name offset/size: " UINT32_FORMAT "/" UINT32_FORMAT, 543 name_offset, name_size); 544 return false; 545 } 546 if (name_size > 0) { 547 if (name_offset + name_size > header_size) { 548 aot_log_warning(aot)("Invalid base_archive_name offset/size (out of range): " 549 UINT32_FORMAT " + " UINT32_FORMAT " > " UINT32_FORMAT , 550 name_offset, name_size, header_size); 551 return false; 552 } 553 const char* name = ((const char*)_header) + _header->_base_archive_name_offset; 554 if (name[name_size - 1] != '\0' || strlen(name) != name_size - 1) { 555 aot_log_warning(aot)("Base archive name is damaged"); 556 return false; 557 } 558 if (!os::file_exists(name)) { 559 aot_log_warning(aot)("Base archive %s does not exist", name); 560 return false; 561 } 562 _base_archive_name = name; 563 } 564 } 565 566 return true; 567 } 568 }; 569 570 // Return value: 571 // false: 572 // <archive_name> is not a valid archive. *base_archive_name is set to null. 573 // true && (*base_archive_name) == nullptr: 574 // <archive_name> is a valid static archive. 575 // true && (*base_archive_name) != nullptr: 576 // <archive_name> is a valid dynamic archive. 577 bool FileMapInfo::get_base_archive_name_from_header(const char* archive_name, 578 const char** base_archive_name) { 579 FileHeaderHelper file_helper(archive_name, false); 580 *base_archive_name = nullptr; 581 582 if (!file_helper.initialize()) { 583 return false; 584 } 585 GenericCDSFileMapHeader* header = file_helper.get_generic_file_header(); 586 switch (header->_magic) { 587 case CDS_PREIMAGE_ARCHIVE_MAGIC: 588 return false; // This is a binary config file, not a proper archive 589 case CDS_DYNAMIC_ARCHIVE_MAGIC: 590 break; 591 default: 592 assert(header->_magic == CDS_ARCHIVE_MAGIC, "must be"); 593 if (AutoCreateSharedArchive) { 594 aot_log_warning(aot)("AutoCreateSharedArchive is ignored because %s is a static archive", archive_name); 595 } 596 return true; 597 } 598 599 const char* base = file_helper.base_archive_name(); 600 if (base == nullptr) { 601 *base_archive_name = CDSConfig::default_archive_path(); 602 } else { 603 *base_archive_name = os::strdup_check_oom(base); 604 } 605 606 return true; 607 } 608 609 bool FileMapInfo::is_preimage_static_archive(const char* file) { 610 FileHeaderHelper file_helper(file, false); 611 if (!file_helper.initialize()) { 612 return false; 613 } 614 return file_helper.is_preimage_static_archive(); 615 } 616 617 // Read the FileMapInfo information from the file. 618 619 bool FileMapInfo::init_from_file(int fd) { 620 FileHeaderHelper file_helper(_full_path, _is_static); 621 if (!file_helper.initialize(fd)) { 622 aot_log_warning(aot)("Unable to read the file header."); 623 return false; 624 } 625 GenericCDSFileMapHeader* gen_header = file_helper.get_generic_file_header(); 626 627 const char* file_type = CDSConfig::type_of_archive_being_loaded(); 628 if (_is_static) { 629 if ((gen_header->_magic == CDS_ARCHIVE_MAGIC) || 630 (gen_header->_magic == CDS_PREIMAGE_ARCHIVE_MAGIC && CDSConfig::is_dumping_final_static_archive())) { 631 // Good 632 } else { 633 if (CDSConfig::new_aot_flags_used()) { 634 aot_log_warning(aot)("Not a valid %s (%s)", file_type, _full_path); 635 } else { 636 aot_log_warning(aot)("Not a base shared archive: %s", _full_path); 637 } 638 return false; 639 } 640 } else { 641 if (gen_header->_magic != CDS_DYNAMIC_ARCHIVE_MAGIC) { 642 aot_log_warning(aot)("Not a top shared archive: %s", _full_path); 643 return false; 644 } 645 } 646 647 _header = (FileMapHeader*)os::malloc(gen_header->_header_size, mtInternal); 648 os::lseek(fd, 0, SEEK_SET); // reset to begin of the archive 649 size_t size = gen_header->_header_size; 650 size_t n = ::read(fd, (void*)_header, (unsigned int)size); 651 if (n != size) { 652 aot_log_warning(aot)("Failed to read file header from the top archive file\n"); 653 return false; 654 } 655 656 if (header()->version() != CURRENT_CDS_ARCHIVE_VERSION) { 657 aot_log_info(aot)("_version expected: 0x%x", CURRENT_CDS_ARCHIVE_VERSION); 658 aot_log_info(aot)(" actual: 0x%x", header()->version()); 659 aot_log_warning(aot)("The %s has the wrong version.", file_type); 660 return false; 661 } 662 663 unsigned int base_offset = header()->base_archive_name_offset(); 664 unsigned int name_size = header()->base_archive_name_size(); 665 unsigned int header_size = header()->header_size(); 666 if (base_offset != 0 && name_size != 0) { 667 if (header_size != base_offset + name_size) { 668 aot_log_info(aot)("_header_size: " UINT32_FORMAT, header_size); 669 aot_log_info(aot)("base_archive_name_size: " UINT32_FORMAT, header()->base_archive_name_size()); 670 aot_log_info(aot)("base_archive_name_offset: " UINT32_FORMAT, header()->base_archive_name_offset()); 671 aot_log_warning(aot)("The %s has an incorrect header size.", file_type); 672 return false; 673 } 674 } 675 676 const char* actual_ident = header()->jvm_ident(); 677 678 if (actual_ident[JVM_IDENT_MAX-1] != 0) { 679 aot_log_warning(aot)("JVM version identifier is corrupted."); 680 return false; 681 } 682 683 char expected_ident[JVM_IDENT_MAX]; 684 get_header_version(expected_ident); 685 if (strncmp(actual_ident, expected_ident, JVM_IDENT_MAX-1) != 0) { 686 aot_log_info(aot)("_jvm_ident expected: %s", expected_ident); 687 aot_log_info(aot)(" actual: %s", actual_ident); 688 aot_log_warning(aot)("The %s was created by a different" 689 " version or build of HotSpot", file_type); 690 return false; 691 } 692 693 _file_offset = header()->header_size(); // accounts for the size of _base_archive_name 694 695 size_t len = os::lseek(fd, 0, SEEK_END); 696 697 for (int i = 0; i < MetaspaceShared::n_regions; i++) { 698 FileMapRegion* r = region_at(i); 699 if (r->file_offset() > len || len - r->file_offset() < r->used()) { 700 aot_log_warning(aot)("The %s has been truncated.", file_type); 701 return false; 702 } 703 } 704 705 return true; 706 } 707 708 void FileMapInfo::seek_to_position(size_t pos) { 709 if (os::lseek(_fd, (long)pos, SEEK_SET) < 0) { 710 aot_log_error(aot)("Unable to seek to position %zu", pos); 711 MetaspaceShared::unrecoverable_loading_error(); 712 } 713 } 714 715 // Read the FileMapInfo information from the file. 716 bool FileMapInfo::open_for_read() { 717 if (_file_open) { 718 return true; 719 } 720 const char* file_type = CDSConfig::type_of_archive_being_loaded(); 721 const char* info = CDSConfig::is_dumping_final_static_archive() ? 722 "AOTConfiguration file " : ""; 723 aot_log_info(aot)("trying to map %s%s", info, _full_path); 724 int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0); 725 if (fd < 0) { 726 if (errno == ENOENT) { 727 aot_log_info(aot)("Specified %s not found (%s)", file_type, _full_path); 728 } else { 729 aot_log_warning(aot)("Failed to open %s (%s)", file_type, 730 os::strerror(errno)); 731 } 732 return false; 733 } else { 734 aot_log_info(aot)("Opened %s %s.", file_type, _full_path); 735 } 736 737 _fd = fd; 738 _file_open = true; 739 return true; 740 } 741 742 // Write the FileMapInfo information to the file. 743 744 void FileMapInfo::open_as_output() { 745 if (CDSConfig::new_aot_flags_used()) { 746 if (CDSConfig::is_dumping_preimage_static_archive()) { 747 log_info(aot)("Writing binary AOTConfiguration file: %s", _full_path); 748 } else { 749 log_info(aot)("Writing AOTCache file: %s", _full_path); 750 } 751 } else { 752 aot_log_info(aot)("Dumping shared data to file: %s", _full_path); 753 } 754 755 #ifdef _WINDOWS // On Windows, need WRITE permission to remove the file. 756 chmod(_full_path, _S_IREAD | _S_IWRITE); 757 #endif 758 759 // Use remove() to delete the existing file because, on Unix, this will 760 // allow processes that have it open continued access to the file. 761 remove(_full_path); 762 int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666); 763 if (fd < 0) { 764 aot_log_error(aot)("Unable to create %s %s: (%s).", CDSConfig::type_of_archive_being_written(), _full_path, 765 os::strerror(errno)); 766 MetaspaceShared::writing_error(); 767 return; 768 } 769 _fd = fd; 770 _file_open = true; 771 772 // Seek past the header. We will write the header after all regions are written 773 // and their CRCs computed. 774 size_t header_bytes = header()->header_size(); 775 776 header_bytes = align_up(header_bytes, MetaspaceShared::core_region_alignment()); 777 _file_offset = header_bytes; 778 seek_to_position(_file_offset); 779 } 780 781 // Write the header to the file, seek to the next allocation boundary. 782 783 void FileMapInfo::write_header() { 784 _file_offset = 0; 785 seek_to_position(_file_offset); 786 assert(is_file_position_aligned(), "must be"); 787 write_bytes(header(), header()->header_size()); 788 } 789 790 size_t FileMapRegion::used_aligned() const { 791 return align_up(used(), MetaspaceShared::core_region_alignment()); 792 } 793 794 void FileMapRegion::init(int region_index, size_t mapping_offset, size_t size, bool read_only, 795 bool allow_exec, int crc) { 796 _is_heap_region = HeapShared::is_heap_region(region_index); 797 _is_bitmap_region = (region_index == MetaspaceShared::bm); 798 _mapping_offset = mapping_offset; 799 _used = size; 800 _read_only = read_only; 801 _allow_exec = allow_exec; 802 _crc = crc; 803 _mapped_from_file = false; 804 _mapped_base = nullptr; 805 _in_reserved_space = false; 806 } 807 808 void FileMapRegion::init_oopmap(size_t offset, size_t size_in_bits) { 809 _oopmap_offset = offset; 810 _oopmap_size_in_bits = size_in_bits; 811 } 812 813 void FileMapRegion::init_ptrmap(size_t offset, size_t size_in_bits) { 814 _ptrmap_offset = offset; 815 _ptrmap_size_in_bits = size_in_bits; 816 } 817 818 bool FileMapRegion::check_region_crc(char* base) const { 819 // This function should be called after the region has been properly 820 // loaded into memory via FileMapInfo::map_region() or FileMapInfo::read_region(). 821 // I.e., this->mapped_base() must be valid. 822 size_t sz = used(); 823 if (sz == 0) { 824 return true; 825 } 826 827 assert(base != nullptr, "must be initialized"); 828 int crc = ClassLoader::crc32(0, base, (jint)sz); 829 if (crc != this->crc()) { 830 aot_log_warning(aot)("Checksum verification failed."); 831 return false; 832 } 833 return true; 834 } 835 836 static const char* region_name(int region_index) { 837 static const char* names[] = { 838 "rw", "ro", "bm", "hp", "ac" 839 }; 840 const int num_regions = sizeof(names)/sizeof(names[0]); 841 assert(0 <= region_index && region_index < num_regions, "sanity"); 842 843 return names[region_index]; 844 } 845 846 BitMapView FileMapInfo::bitmap_view(int region_index, bool is_oopmap) { 847 FileMapRegion* r = region_at(region_index); 848 char* bitmap_base = is_static() ? FileMapInfo::current_info()->map_bitmap_region() : FileMapInfo::dynamic_info()->map_bitmap_region(); 849 bitmap_base += is_oopmap ? r->oopmap_offset() : r->ptrmap_offset(); 850 size_t size_in_bits = is_oopmap ? r->oopmap_size_in_bits() : r->ptrmap_size_in_bits(); 851 852 aot_log_debug(aot, reloc)("mapped %s relocation %smap @ " INTPTR_FORMAT " (%zu bits)", 853 region_name(region_index), is_oopmap ? "oop" : "ptr", 854 p2i(bitmap_base), size_in_bits); 855 856 return BitMapView((BitMap::bm_word_t*)(bitmap_base), size_in_bits); 857 } 858 859 BitMapView FileMapInfo::oopmap_view(int region_index) { 860 return bitmap_view(region_index, /*is_oopmap*/true); 861 } 862 863 BitMapView FileMapInfo::ptrmap_view(int region_index) { 864 return bitmap_view(region_index, /*is_oopmap*/false); 865 } 866 867 void FileMapRegion::print(outputStream* st, int region_index) { 868 st->print_cr("============ region ============= %d \"%s\"", region_index, region_name(region_index)); 869 st->print_cr("- crc: 0x%08x", _crc); 870 st->print_cr("- read_only: %d", _read_only); 871 st->print_cr("- allow_exec: %d", _allow_exec); 872 st->print_cr("- is_heap_region: %d", _is_heap_region); 873 st->print_cr("- is_bitmap_region: %d", _is_bitmap_region); 874 st->print_cr("- mapped_from_file: %d", _mapped_from_file); 875 st->print_cr("- file_offset: 0x%zx", _file_offset); 876 st->print_cr("- mapping_offset: 0x%zx", _mapping_offset); 877 st->print_cr("- used: %zu", _used); 878 st->print_cr("- oopmap_offset: 0x%zx", _oopmap_offset); 879 st->print_cr("- oopmap_size_in_bits: %zu", _oopmap_size_in_bits); 880 st->print_cr("- ptrmap_offset: 0x%zx", _ptrmap_offset); 881 st->print_cr("- ptrmap_size_in_bits: %zu", _ptrmap_size_in_bits); 882 st->print_cr("- mapped_base: " INTPTR_FORMAT, p2i(_mapped_base)); 883 } 884 885 void FileMapInfo::write_region(int region, char* base, size_t size, 886 bool read_only, bool allow_exec) { 887 assert(CDSConfig::is_dumping_archive(), "sanity"); 888 889 FileMapRegion* r = region_at(region); 890 char* requested_base; 891 size_t mapping_offset = 0; 892 893 if (region == MetaspaceShared::bm) { 894 requested_base = nullptr; // always null for bm region 895 } else if (size == 0) { 896 // This is an unused region (e.g., a heap region when !INCLUDE_CDS_JAVA_HEAP) 897 requested_base = nullptr; 898 } else if (HeapShared::is_heap_region(region)) { 899 assert(CDSConfig::is_dumping_heap(), "sanity"); 900 #if INCLUDE_CDS_JAVA_HEAP 901 assert(!CDSConfig::is_dumping_dynamic_archive(), "must be"); 902 requested_base = (char*)ArchiveHeapWriter::requested_address(); 903 if (UseCompressedOops) { 904 mapping_offset = (size_t)((address)requested_base - CompressedOops::base()); 905 assert((mapping_offset >> CompressedOops::shift()) << CompressedOops::shift() == mapping_offset, "must be"); 906 } else { 907 mapping_offset = 0; // not used with !UseCompressedOops 908 } 909 #endif // INCLUDE_CDS_JAVA_HEAP 910 } else { 911 char* requested_SharedBaseAddress = (char*)MetaspaceShared::requested_base_address(); 912 requested_base = ArchiveBuilder::current()->to_requested(base); 913 assert(requested_base >= requested_SharedBaseAddress, "must be"); 914 mapping_offset = requested_base - requested_SharedBaseAddress; 915 } 916 917 r->set_file_offset(_file_offset); 918 int crc = ClassLoader::crc32(0, base, (jint)size); 919 if (size > 0) { 920 aot_log_info(aot)("Shared file region (%s) %d: %8zu" 921 " bytes, addr " INTPTR_FORMAT " file offset 0x%08" PRIxPTR 922 " crc 0x%08x", 923 region_name(region), region, size, p2i(requested_base), _file_offset, crc); 924 } else { 925 aot_log_info(aot)("Shared file region (%s) %d: %8zu" 926 " bytes", region_name(region), region, size); 927 } 928 929 r->init(region, mapping_offset, size, read_only, allow_exec, crc); 930 931 if (base != nullptr) { 932 write_bytes_aligned(base, size); 933 } 934 } 935 936 static size_t write_bitmap(const CHeapBitMap* map, char* output, size_t offset) { 937 size_t size_in_bytes = map->size_in_bytes(); 938 map->write_to((BitMap::bm_word_t*)(output + offset), size_in_bytes); 939 return offset + size_in_bytes; 940 } 941 942 // The sorting code groups the objects with non-null oop/ptrs together. 943 // Relevant bitmaps then have lots of leading and trailing zeros, which 944 // we do not have to store. 945 size_t FileMapInfo::remove_bitmap_zeros(CHeapBitMap* map) { 946 BitMap::idx_t first_set = map->find_first_set_bit(0); 947 BitMap::idx_t last_set = map->find_last_set_bit(0); 948 size_t old_size = map->size(); 949 950 // Slice and resize bitmap 951 map->truncate(first_set, last_set + 1); 952 953 assert(map->at(0), "First bit should be set"); 954 assert(map->at(map->size() - 1), "Last bit should be set"); 955 assert(map->size() <= old_size, "sanity"); 956 957 return first_set; 958 } 959 960 char* FileMapInfo::write_bitmap_region(CHeapBitMap* rw_ptrmap, CHeapBitMap* ro_ptrmap, ArchiveHeapInfo* heap_info, 961 size_t &size_in_bytes) { 962 size_t removed_rw_leading_zeros = remove_bitmap_zeros(rw_ptrmap); 963 size_t removed_ro_leading_zeros = remove_bitmap_zeros(ro_ptrmap); 964 header()->set_rw_ptrmap_start_pos(removed_rw_leading_zeros); 965 header()->set_ro_ptrmap_start_pos(removed_ro_leading_zeros); 966 size_in_bytes = rw_ptrmap->size_in_bytes() + ro_ptrmap->size_in_bytes(); 967 968 if (heap_info->is_used()) { 969 // Remove leading and trailing zeros 970 size_t removed_oop_leading_zeros = remove_bitmap_zeros(heap_info->oopmap()); 971 size_t removed_ptr_leading_zeros = remove_bitmap_zeros(heap_info->ptrmap()); 972 header()->set_heap_oopmap_start_pos(removed_oop_leading_zeros); 973 header()->set_heap_ptrmap_start_pos(removed_ptr_leading_zeros); 974 975 size_in_bytes += heap_info->oopmap()->size_in_bytes(); 976 size_in_bytes += heap_info->ptrmap()->size_in_bytes(); 977 } 978 979 // The bitmap region contains up to 4 parts: 980 // rw_ptrmap: metaspace pointers inside the read-write region 981 // ro_ptrmap: metaspace pointers inside the read-only region 982 // heap_info->oopmap(): Java oop pointers in the heap region 983 // heap_info->ptrmap(): metaspace pointers in the heap region 984 char* buffer = NEW_C_HEAP_ARRAY(char, size_in_bytes, mtClassShared); 985 size_t written = 0; 986 987 region_at(MetaspaceShared::rw)->init_ptrmap(0, rw_ptrmap->size()); 988 written = write_bitmap(rw_ptrmap, buffer, written); 989 990 region_at(MetaspaceShared::ro)->init_ptrmap(written, ro_ptrmap->size()); 991 written = write_bitmap(ro_ptrmap, buffer, written); 992 993 if (heap_info->is_used()) { 994 FileMapRegion* r = region_at(MetaspaceShared::hp); 995 996 r->init_oopmap(written, heap_info->oopmap()->size()); 997 written = write_bitmap(heap_info->oopmap(), buffer, written); 998 999 r->init_ptrmap(written, heap_info->ptrmap()->size()); 1000 written = write_bitmap(heap_info->ptrmap(), buffer, written); 1001 } 1002 1003 write_region(MetaspaceShared::bm, (char*)buffer, size_in_bytes, /*read_only=*/true, /*allow_exec=*/false); 1004 return buffer; 1005 } 1006 1007 size_t FileMapInfo::write_heap_region(ArchiveHeapInfo* heap_info) { 1008 char* buffer_start = heap_info->buffer_start(); 1009 size_t buffer_size = heap_info->buffer_byte_size(); 1010 write_region(MetaspaceShared::hp, buffer_start, buffer_size, false, false); 1011 header()->set_heap_root_segments(heap_info->heap_root_segments()); 1012 return buffer_size; 1013 } 1014 1015 // Dump bytes to file -- at the current file position. 1016 1017 void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) { 1018 assert(_file_open, "must be"); 1019 if (!os::write(_fd, buffer, nbytes)) { 1020 // If the shared archive is corrupted, close it and remove it. 1021 close(); 1022 remove(_full_path); 1023 1024 if (CDSConfig::is_dumping_preimage_static_archive()) { 1025 MetaspaceShared::writing_error("Unable to write to AOT configuration file."); 1026 } else if (CDSConfig::new_aot_flags_used()) { 1027 MetaspaceShared::writing_error("Unable to write to AOT cache."); 1028 } else { 1029 MetaspaceShared::writing_error("Unable to write to shared archive."); 1030 } 1031 } 1032 _file_offset += nbytes; 1033 } 1034 1035 bool FileMapInfo::is_file_position_aligned() const { 1036 return _file_offset == align_up(_file_offset, 1037 MetaspaceShared::core_region_alignment()); 1038 } 1039 1040 // Align file position to an allocation unit boundary. 1041 1042 void FileMapInfo::align_file_position() { 1043 assert(_file_open, "must be"); 1044 size_t new_file_offset = align_up(_file_offset, 1045 MetaspaceShared::core_region_alignment()); 1046 if (new_file_offset != _file_offset) { 1047 _file_offset = new_file_offset; 1048 // Seek one byte back from the target and write a byte to insure 1049 // that the written file is the correct length. 1050 _file_offset -= 1; 1051 seek_to_position(_file_offset); 1052 char zero = 0; 1053 write_bytes(&zero, 1); 1054 } 1055 } 1056 1057 1058 // Dump bytes to file -- at the current file position. 1059 1060 void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) { 1061 align_file_position(); 1062 write_bytes(buffer, nbytes); 1063 align_file_position(); 1064 } 1065 1066 // Close the shared archive file. This does NOT unmap mapped regions. 1067 1068 void FileMapInfo::close() { 1069 if (_file_open) { 1070 if (::close(_fd) < 0) { 1071 MetaspaceShared::unrecoverable_loading_error("Unable to close the shared archive file."); 1072 } 1073 _file_open = false; 1074 _fd = -1; 1075 } 1076 } 1077 1078 /* 1079 * Same as os::map_memory() but also pretouches if AlwaysPreTouch is enabled. 1080 */ 1081 static char* map_memory(int fd, const char* file_name, size_t file_offset, 1082 char *addr, size_t bytes, bool read_only, 1083 bool allow_exec, MemTag mem_tag) { 1084 char* mem = os::map_memory(fd, file_name, file_offset, addr, bytes, 1085 mem_tag, AlwaysPreTouch ? false : read_only, 1086 allow_exec); 1087 if (mem != nullptr && AlwaysPreTouch) { 1088 os::pretouch_memory(mem, mem + bytes); 1089 } 1090 return mem; 1091 } 1092 1093 // JVM/TI RedefineClasses() support: 1094 // Remap the shared readonly space to shared readwrite, private. 1095 bool FileMapInfo::remap_shared_readonly_as_readwrite() { 1096 int idx = MetaspaceShared::ro; 1097 FileMapRegion* r = region_at(idx); 1098 if (!r->read_only()) { 1099 // the space is already readwrite so we are done 1100 return true; 1101 } 1102 size_t size = r->used_aligned(); 1103 if (!open_for_read()) { 1104 return false; 1105 } 1106 char *addr = r->mapped_base(); 1107 // This path should not be reached for Windows; see JDK-8222379. 1108 assert(WINDOWS_ONLY(false) NOT_WINDOWS(true), "Don't call on Windows"); 1109 // Replace old mapping with new one that is writable. 1110 char *base = os::map_memory(_fd, _full_path, r->file_offset(), 1111 addr, size, mtNone, false /* !read_only */, 1112 r->allow_exec()); 1113 close(); 1114 // These have to be errors because the shared region is now unmapped. 1115 if (base == nullptr) { 1116 aot_log_error(aot)("Unable to remap shared readonly space (errno=%d).", errno); 1117 vm_exit(1); 1118 } 1119 if (base != addr) { 1120 aot_log_error(aot)("Unable to remap shared readonly space (errno=%d).", errno); 1121 vm_exit(1); 1122 } 1123 r->set_read_only(false); 1124 return true; 1125 } 1126 1127 // Memory map a region in the address space. 1128 static const char* shared_region_name[] = { "ReadWrite", "ReadOnly", "Bitmap", "Heap", "Code" }; 1129 1130 MapArchiveResult FileMapInfo::map_regions(int regions[], int num_regions, char* mapped_base_address, ReservedSpace rs) { 1131 DEBUG_ONLY(FileMapRegion* last_region = nullptr); 1132 intx addr_delta = mapped_base_address - header()->requested_base_address(); 1133 1134 // Make sure we don't attempt to use header()->mapped_base_address() unless 1135 // it's been successfully mapped. 1136 DEBUG_ONLY(header()->set_mapped_base_address((char*)(uintptr_t)0xdeadbeef);) 1137 1138 for (int i = 0; i < num_regions; i++) { 1139 int idx = regions[i]; 1140 MapArchiveResult result = map_region(idx, addr_delta, mapped_base_address, rs); 1141 if (result != MAP_ARCHIVE_SUCCESS) { 1142 return result; 1143 } 1144 FileMapRegion* r = region_at(idx); 1145 DEBUG_ONLY(if (last_region != nullptr) { 1146 // Ensure that the OS won't be able to allocate new memory spaces between any mapped 1147 // regions, or else it would mess up the simple comparison in MetaspaceObj::is_shared(). 1148 assert(r->mapped_base() == last_region->mapped_end(), "must have no gaps"); 1149 } 1150 last_region = r;) 1151 aot_log_info(aot)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)", is_static() ? "static " : "dynamic", 1152 idx, p2i(r->mapped_base()), p2i(r->mapped_end()), 1153 shared_region_name[idx]); 1154 1155 } 1156 1157 header()->set_mapped_base_address(header()->requested_base_address() + addr_delta); 1158 if (addr_delta != 0 && !relocate_pointers_in_core_regions(addr_delta)) { 1159 return MAP_ARCHIVE_OTHER_FAILURE; 1160 } 1161 1162 return MAP_ARCHIVE_SUCCESS; 1163 } 1164 1165 bool FileMapInfo::read_region(int i, char* base, size_t size, bool do_commit) { 1166 FileMapRegion* r = region_at(i); 1167 if (do_commit) { 1168 aot_log_info(aot)("Commit %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)%s", 1169 is_static() ? "static " : "dynamic", i, p2i(base), p2i(base + size), 1170 shared_region_name[i], r->allow_exec() ? " exec" : ""); 1171 if (!os::commit_memory(base, size, r->allow_exec())) { 1172 aot_log_error(aot)("Failed to commit %s region #%d (%s)", is_static() ? "static " : "dynamic", 1173 i, shared_region_name[i]); 1174 return false; 1175 } 1176 } 1177 if (os::lseek(_fd, (long)r->file_offset(), SEEK_SET) != (int)r->file_offset() || 1178 read_bytes(base, size) != size) { 1179 return false; 1180 } 1181 1182 if (VerifySharedSpaces && !r->check_region_crc(base)) { 1183 return false; 1184 } 1185 1186 r->set_mapped_from_file(false); 1187 r->set_mapped_base(base); 1188 1189 return true; 1190 } 1191 1192 MapArchiveResult FileMapInfo::map_region(int i, intx addr_delta, char* mapped_base_address, ReservedSpace rs) { 1193 assert(!HeapShared::is_heap_region(i), "sanity"); 1194 FileMapRegion* r = region_at(i); 1195 size_t size = r->used_aligned(); 1196 char *requested_addr = mapped_base_address + r->mapping_offset(); 1197 assert(!is_mapped(), "must be not mapped yet"); 1198 assert(requested_addr != nullptr, "must be specified"); 1199 1200 r->set_mapped_from_file(false); 1201 r->set_in_reserved_space(false); 1202 1203 if (MetaspaceShared::use_windows_memory_mapping()) { 1204 // Windows cannot remap read-only shared memory to read-write when required for 1205 // RedefineClasses, which is also used by JFR. Always map windows regions as RW. 1206 r->set_read_only(false); 1207 } else if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space() || 1208 Arguments::has_jfr_option()) { 1209 // If a tool agent is in use (debugging enabled), or JFR, we must map the address space RW 1210 r->set_read_only(false); 1211 } else if (addr_delta != 0) { 1212 r->set_read_only(false); // Need to patch the pointers 1213 } 1214 1215 if (MetaspaceShared::use_windows_memory_mapping() && rs.is_reserved()) { 1216 // This is the second time we try to map the archive(s). We have already created a ReservedSpace 1217 // that covers all the FileMapRegions to ensure all regions can be mapped. However, Windows 1218 // can't mmap into a ReservedSpace, so we just ::read() the data. We're going to patch all the 1219 // regions anyway, so there's no benefit for mmap anyway. 1220 if (!read_region(i, requested_addr, size, /* do_commit = */ true)) { 1221 MetaspaceShared::report_loading_error("Failed to read %s shared space into reserved space at " INTPTR_FORMAT, 1222 shared_region_name[i], p2i(requested_addr)); 1223 return MAP_ARCHIVE_OTHER_FAILURE; // oom or I/O error. 1224 } else { 1225 assert(r->mapped_base() != nullptr, "must be initialized"); 1226 } 1227 } else { 1228 // Note that this may either be a "fresh" mapping into unreserved address 1229 // space (Windows, first mapping attempt), or a mapping into pre-reserved 1230 // space (Posix). See also comment in MetaspaceShared::map_archives(). 1231 char* base = map_memory(_fd, _full_path, r->file_offset(), 1232 requested_addr, size, r->read_only(), 1233 r->allow_exec(), mtClassShared); 1234 if (base != requested_addr) { 1235 MetaspaceShared::report_loading_error("Unable to map %s shared space at " INTPTR_FORMAT, 1236 shared_region_name[i], p2i(requested_addr)); 1237 _memory_mapping_failed = true; 1238 return MAP_ARCHIVE_MMAP_FAILURE; 1239 } 1240 1241 if (VerifySharedSpaces && !r->check_region_crc(requested_addr)) { 1242 return MAP_ARCHIVE_OTHER_FAILURE; 1243 } 1244 1245 r->set_mapped_from_file(true); 1246 r->set_mapped_base(requested_addr); 1247 } 1248 1249 if (rs.is_reserved()) { 1250 char* mapped_base = r->mapped_base(); 1251 assert(rs.base() <= mapped_base && mapped_base + size <= rs.end(), 1252 PTR_FORMAT " <= " PTR_FORMAT " < " PTR_FORMAT " <= " PTR_FORMAT, 1253 p2i(rs.base()), p2i(mapped_base), p2i(mapped_base + size), p2i(rs.end())); 1254 r->set_in_reserved_space(rs.is_reserved()); 1255 } 1256 return MAP_ARCHIVE_SUCCESS; 1257 } 1258 1259 // The return value is the location of the archive relocation bitmap. 1260 char* FileMapInfo::map_bitmap_region() { 1261 FileMapRegion* r = region_at(MetaspaceShared::bm); 1262 if (r->mapped_base() != nullptr) { 1263 return r->mapped_base(); 1264 } 1265 bool read_only = true, allow_exec = false; 1266 char* requested_addr = nullptr; // allow OS to pick any location 1267 char* bitmap_base = map_memory(_fd, _full_path, r->file_offset(), 1268 requested_addr, r->used_aligned(), read_only, allow_exec, mtClassShared); 1269 if (bitmap_base == nullptr) { 1270 MetaspaceShared::report_loading_error("failed to map relocation bitmap"); 1271 return nullptr; 1272 } 1273 1274 if (VerifySharedSpaces && !r->check_region_crc(bitmap_base)) { 1275 aot_log_error(aot)("relocation bitmap CRC error"); 1276 if (!os::unmap_memory(bitmap_base, r->used_aligned())) { 1277 fatal("os::unmap_memory of relocation bitmap failed"); 1278 } 1279 return nullptr; 1280 } 1281 1282 r->set_mapped_from_file(true); 1283 r->set_mapped_base(bitmap_base); 1284 aot_log_info(aot)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)", 1285 is_static() ? "static " : "dynamic", 1286 MetaspaceShared::bm, p2i(r->mapped_base()), p2i(r->mapped_end()), 1287 shared_region_name[MetaspaceShared::bm]); 1288 return bitmap_base; 1289 } 1290 1291 bool FileMapInfo::map_aot_code_region(ReservedSpace rs) { 1292 FileMapRegion* r = region_at(MetaspaceShared::ac); 1293 assert(r->used() > 0 && r->used_aligned() == rs.size(), "must be"); 1294 1295 char* requested_base = rs.base(); 1296 assert(requested_base != nullptr, "should be inside code cache"); 1297 1298 char* mapped_base; 1299 if (MetaspaceShared::use_windows_memory_mapping()) { 1300 if (!read_region(MetaspaceShared::ac, requested_base, r->used_aligned(), /* do_commit = */ true)) { 1301 MetaspaceShared::report_loading_error("Failed to read aot code shared space into reserved space at " INTPTR_FORMAT, 1302 p2i(requested_base)); 1303 return false; 1304 } 1305 mapped_base = requested_base; 1306 } else { 1307 // We do not execute in-place in the AOT code region. 1308 // AOT code is copied to the CodeCache for execution. 1309 bool read_only = false, allow_exec = false; 1310 mapped_base = map_memory(_fd, _full_path, r->file_offset(), 1311 requested_base, r->used_aligned(), read_only, allow_exec, mtClassShared); 1312 } 1313 if (mapped_base == nullptr) { 1314 MetaspaceShared::report_loading_error("failed to map aot code region"); 1315 return false; 1316 } else { 1317 assert(mapped_base == requested_base, "must be"); 1318 r->set_mapped_from_file(true); 1319 r->set_mapped_base(mapped_base); 1320 aot_log_info(aot)("Mapped static region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)", 1321 MetaspaceShared::ac, p2i(r->mapped_base()), p2i(r->mapped_end()), 1322 shared_region_name[MetaspaceShared::ac]); 1323 return true; 1324 } 1325 } 1326 1327 class SharedDataRelocationTask : public ArchiveWorkerTask { 1328 private: 1329 BitMapView* const _rw_bm; 1330 BitMapView* const _ro_bm; 1331 SharedDataRelocator* const _rw_reloc; 1332 SharedDataRelocator* const _ro_reloc; 1333 1334 public: 1335 SharedDataRelocationTask(BitMapView* rw_bm, BitMapView* ro_bm, SharedDataRelocator* rw_reloc, SharedDataRelocator* ro_reloc) : 1336 ArchiveWorkerTask("Shared Data Relocation"), 1337 _rw_bm(rw_bm), _ro_bm(ro_bm), _rw_reloc(rw_reloc), _ro_reloc(ro_reloc) {} 1338 1339 void work(int chunk, int max_chunks) override { 1340 work_on(chunk, max_chunks, _rw_bm, _rw_reloc); 1341 work_on(chunk, max_chunks, _ro_bm, _ro_reloc); 1342 } 1343 1344 void work_on(int chunk, int max_chunks, BitMapView* bm, SharedDataRelocator* reloc) { 1345 BitMap::idx_t size = bm->size(); 1346 BitMap::idx_t start = MIN2(size, size * chunk / max_chunks); 1347 BitMap::idx_t end = MIN2(size, size * (chunk + 1) / max_chunks); 1348 assert(end > start, "Sanity: no empty slices"); 1349 bm->iterate(reloc, start, end); 1350 } 1351 }; 1352 1353 // This is called when we cannot map the archive at the requested[ base address (usually 0x800000000). 1354 // We relocate all pointers in the 2 core regions (ro, rw). 1355 bool FileMapInfo::relocate_pointers_in_core_regions(intx addr_delta) { 1356 aot_log_debug(aot, reloc)("runtime archive relocation start"); 1357 char* bitmap_base = map_bitmap_region(); 1358 1359 if (bitmap_base == nullptr) { 1360 return false; // OOM, or CRC check failure 1361 } else { 1362 BitMapView rw_ptrmap = ptrmap_view(MetaspaceShared::rw); 1363 BitMapView ro_ptrmap = ptrmap_view(MetaspaceShared::ro); 1364 1365 FileMapRegion* rw_region = first_core_region(); 1366 FileMapRegion* ro_region = last_core_region(); 1367 1368 // Patch all pointers inside the RW region 1369 address rw_patch_base = (address)rw_region->mapped_base(); 1370 address rw_patch_end = (address)rw_region->mapped_end(); 1371 1372 // Patch all pointers inside the RO region 1373 address ro_patch_base = (address)ro_region->mapped_base(); 1374 address ro_patch_end = (address)ro_region->mapped_end(); 1375 1376 // the current value of the pointers to be patched must be within this 1377 // range (i.e., must be between the requested base address and the address of the current archive). 1378 // Note: top archive may point to objects in the base archive, but not the other way around. 1379 address valid_old_base = (address)header()->requested_base_address(); 1380 address valid_old_end = valid_old_base + mapping_end_offset(); 1381 1382 // after patching, the pointers must point inside this range 1383 // (the requested location of the archive, as mapped at runtime). 1384 address valid_new_base = (address)header()->mapped_base_address(); 1385 address valid_new_end = (address)mapped_end(); 1386 1387 SharedDataRelocator rw_patcher((address*)rw_patch_base + header()->rw_ptrmap_start_pos(), (address*)rw_patch_end, valid_old_base, valid_old_end, 1388 valid_new_base, valid_new_end, addr_delta); 1389 SharedDataRelocator ro_patcher((address*)ro_patch_base + header()->ro_ptrmap_start_pos(), (address*)ro_patch_end, valid_old_base, valid_old_end, 1390 valid_new_base, valid_new_end, addr_delta); 1391 1392 if (AOTCacheParallelRelocation) { 1393 ArchiveWorkers workers; 1394 SharedDataRelocationTask task(&rw_ptrmap, &ro_ptrmap, &rw_patcher, &ro_patcher); 1395 workers.run_task(&task); 1396 } else { 1397 rw_ptrmap.iterate(&rw_patcher); 1398 ro_ptrmap.iterate(&ro_patcher); 1399 } 1400 1401 // The MetaspaceShared::bm region will be unmapped in MetaspaceShared::initialize_shared_spaces(). 1402 1403 aot_log_debug(aot, reloc)("runtime archive relocation done"); 1404 return true; 1405 } 1406 } 1407 1408 size_t FileMapInfo::read_bytes(void* buffer, size_t count) { 1409 assert(_file_open, "Archive file is not open"); 1410 size_t n = ::read(_fd, buffer, (unsigned int)count); 1411 if (n != count) { 1412 // Close the file if there's a problem reading it. 1413 close(); 1414 return 0; 1415 } 1416 _file_offset += count; 1417 return count; 1418 } 1419 1420 // Get the total size in bytes of a read only region 1421 size_t FileMapInfo::readonly_total() { 1422 size_t total = 0; 1423 if (current_info() != nullptr) { 1424 FileMapRegion* r = FileMapInfo::current_info()->region_at(MetaspaceShared::ro); 1425 if (r->read_only()) total += r->used(); 1426 } 1427 if (dynamic_info() != nullptr) { 1428 FileMapRegion* r = FileMapInfo::dynamic_info()->region_at(MetaspaceShared::ro); 1429 if (r->read_only()) total += r->used(); 1430 } 1431 return total; 1432 } 1433 1434 #if INCLUDE_CDS_JAVA_HEAP 1435 MemRegion FileMapInfo::_mapped_heap_memregion; 1436 1437 bool FileMapInfo::has_heap_region() { 1438 return (region_at(MetaspaceShared::hp)->used() > 0); 1439 } 1440 1441 // Returns the address range of the archived heap region computed using the 1442 // current oop encoding mode. This range may be different than the one seen at 1443 // dump time due to encoding mode differences. The result is used in determining 1444 // if/how these regions should be relocated at run time. 1445 MemRegion FileMapInfo::get_heap_region_requested_range() { 1446 FileMapRegion* r = region_at(MetaspaceShared::hp); 1447 size_t size = r->used(); 1448 assert(size > 0, "must have non-empty heap region"); 1449 1450 address start = heap_region_requested_address(); 1451 address end = start + size; 1452 aot_log_info(aot)("Requested heap region [" INTPTR_FORMAT " - " INTPTR_FORMAT "] = %8zu bytes", 1453 p2i(start), p2i(end), size); 1454 1455 return MemRegion((HeapWord*)start, (HeapWord*)end); 1456 } 1457 1458 void FileMapInfo::map_or_load_heap_region() { 1459 bool success = false; 1460 1461 if (can_use_heap_region()) { 1462 if (ArchiveHeapLoader::can_map()) { 1463 success = map_heap_region(); 1464 } else if (ArchiveHeapLoader::can_load()) { 1465 success = ArchiveHeapLoader::load_heap_region(this); 1466 } else { 1467 if (!UseCompressedOops && !ArchiveHeapLoader::can_map()) { 1468 MetaspaceShared::report_loading_error("Cannot use CDS heap data. Selected GC not compatible -XX:-UseCompressedOops"); 1469 } else { 1470 MetaspaceShared::report_loading_error("Cannot use CDS heap data. UseEpsilonGC, UseG1GC, UseSerialGC, UseParallelGC, or UseShenandoahGC are required."); 1471 } 1472 } 1473 } 1474 1475 if (!success) { 1476 if (CDSConfig::is_using_aot_linked_classes()) { 1477 // It's too late to recover -- we have already committed to use the archived metaspace objects, but 1478 // the archived heap objects cannot be loaded, so we don't have the archived FMG to guarantee that 1479 // all AOT-linked classes are visible. 1480 // 1481 // We get here because the heap is too small. The app will fail anyway. So let's quit. 1482 aot_log_error(aot)("%s has aot-linked classes but the archived " 1483 "heap objects cannot be loaded. Try increasing your heap size.", 1484 CDSConfig::type_of_archive_being_loaded()); 1485 MetaspaceShared::unrecoverable_loading_error(); 1486 } 1487 CDSConfig::stop_using_full_module_graph("archive heap loading failed"); 1488 } 1489 } 1490 1491 bool FileMapInfo::can_use_heap_region() { 1492 if (!has_heap_region()) { 1493 return false; 1494 } 1495 if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) { 1496 ShouldNotReachHere(); // CDS should have been disabled. 1497 // The archived objects are mapped at JVM start-up, but we don't know if 1498 // j.l.String or j.l.Class might be replaced by the ClassFileLoadHook, 1499 // which would make the archived String or mirror objects invalid. Let's be safe and not 1500 // use the archived objects. These 2 classes are loaded during the JVMTI "early" stage. 1501 // 1502 // If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects 1503 // in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK 1504 // because we won't install an archived object subgraph if the klass of any of the 1505 // referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph(). 1506 } 1507 1508 // We pre-compute narrow Klass IDs with the runtime mapping start intended to be the base, and a shift of 1509 // ArchiveBuilder::precomputed_narrow_klass_shift. We enforce this encoding at runtime (see 1510 // CompressedKlassPointers::initialize_for_given_encoding()). Therefore, the following assertions must 1511 // hold: 1512 address archive_narrow_klass_base = (address)header()->mapped_base_address(); 1513 const int archive_narrow_klass_pointer_bits = header()->narrow_klass_pointer_bits(); 1514 const int archive_narrow_klass_shift = header()->narrow_klass_shift(); 1515 1516 aot_log_info(aot)("CDS archive was created with max heap size = %zuM, and the following configuration:", 1517 max_heap_size()/M); 1518 aot_log_info(aot)(" narrow_klass_base at mapping start address, narrow_klass_pointer_bits = %d, narrow_klass_shift = %d", 1519 archive_narrow_klass_pointer_bits, archive_narrow_klass_shift); 1520 aot_log_info(aot)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d", 1521 narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift()); 1522 aot_log_info(aot)("The current max heap size = %zuM, G1HeapRegion::GrainBytes = %zu", 1523 MaxHeapSize/M, G1HeapRegion::GrainBytes); 1524 aot_log_info(aot)(" narrow_klass_base = " PTR_FORMAT ", arrow_klass_pointer_bits = %d, narrow_klass_shift = %d", 1525 p2i(CompressedKlassPointers::base()), CompressedKlassPointers::narrow_klass_pointer_bits(), CompressedKlassPointers::shift()); 1526 aot_log_info(aot)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d", 1527 CompressedOops::mode(), p2i(CompressedOops::base()), CompressedOops::shift()); 1528 aot_log_info(aot)(" heap range = [" PTR_FORMAT " - " PTR_FORMAT "]", 1529 UseCompressedOops ? p2i(CompressedOops::begin()) : 1530 UseG1GC ? p2i((address)G1CollectedHeap::heap()->reserved().start()) : 0L, 1531 UseCompressedOops ? p2i(CompressedOops::end()) : 1532 UseG1GC ? p2i((address)G1CollectedHeap::heap()->reserved().end()) : 0L); 1533 1534 int err = 0; 1535 if ( archive_narrow_klass_base != CompressedKlassPointers::base() || 1536 (err = 1, archive_narrow_klass_pointer_bits != CompressedKlassPointers::narrow_klass_pointer_bits()) || 1537 (err = 2, archive_narrow_klass_shift != CompressedKlassPointers::shift()) ) { 1538 stringStream ss; 1539 switch (err) { 1540 case 0: 1541 ss.print("Unexpected encoding base encountered (" PTR_FORMAT ", expected " PTR_FORMAT ")", 1542 p2i(CompressedKlassPointers::base()), p2i(archive_narrow_klass_base)); 1543 break; 1544 case 1: 1545 ss.print("Unexpected narrow Klass bit length encountered (%d, expected %d)", 1546 CompressedKlassPointers::narrow_klass_pointer_bits(), archive_narrow_klass_pointer_bits); 1547 break; 1548 case 2: 1549 ss.print("Unexpected narrow Klass shift encountered (%d, expected %d)", 1550 CompressedKlassPointers::shift(), archive_narrow_klass_shift); 1551 break; 1552 default: 1553 ShouldNotReachHere(); 1554 }; 1555 if (CDSConfig::new_aot_flags_used()) { 1556 LogTarget(Info, aot) lt; 1557 if (lt.is_enabled()) { 1558 LogStream ls(lt); 1559 ls.print_raw(ss.base()); 1560 header()->print(&ls); 1561 } 1562 } else { 1563 LogTarget(Info, cds) lt; 1564 if (lt.is_enabled()) { 1565 LogStream ls(lt); 1566 ls.print_raw(ss.base()); 1567 header()->print(&ls); 1568 } 1569 } 1570 assert(false, "%s", ss.base()); 1571 } 1572 1573 return true; 1574 } 1575 1576 // The actual address of this region during dump time. 1577 address FileMapInfo::heap_region_dumptime_address() { 1578 FileMapRegion* r = region_at(MetaspaceShared::hp); 1579 assert(CDSConfig::is_using_archive(), "runtime only"); 1580 assert(is_aligned(r->mapping_offset(), sizeof(HeapWord)), "must be"); 1581 if (UseCompressedOops) { 1582 return /*dumptime*/ (address)((uintptr_t)narrow_oop_base() + r->mapping_offset()); 1583 } else { 1584 return heap_region_requested_address(); 1585 } 1586 } 1587 1588 // The address where this region can be mapped into the runtime heap without 1589 // patching any of the pointers that are embedded in this region. 1590 address FileMapInfo::heap_region_requested_address() { 1591 assert(CDSConfig::is_using_archive(), "runtime only"); 1592 FileMapRegion* r = region_at(MetaspaceShared::hp); 1593 assert(is_aligned(r->mapping_offset(), sizeof(HeapWord)), "must be"); 1594 assert(ArchiveHeapLoader::can_use(), "GC must support mapping or loading"); 1595 if (UseCompressedOops) { 1596 // We can avoid relocation if each region's offset from the runtime CompressedOops::base() 1597 // is the same as its offset from the CompressedOops::base() during dumptime. 1598 // Note that CompressedOops::base() may be different between dumptime and runtime. 1599 // 1600 // Example: 1601 // Dumptime base = 0x1000 and shift is 0. We have a region at address 0x2000. There's a 1602 // narrowOop P stored in this region that points to an object at address 0x2200. 1603 // P's encoded value is 0x1200. 1604 // 1605 // Runtime base = 0x4000 and shift is also 0. If we map this region at 0x5000, then 1606 // the value P can remain 0x1200. The decoded address = (0x4000 + (0x1200 << 0)) = 0x5200, 1607 // which is the runtime location of the referenced object. 1608 return /*runtime*/ (address)((uintptr_t)CompressedOops::base() + r->mapping_offset()); 1609 } else { 1610 // This was the hard-coded requested base address used at dump time. With uncompressed oops, 1611 // the heap range is assigned by the OS so we will most likely have to relocate anyway, no matter 1612 // what base address was picked at duump time. 1613 return (address)ArchiveHeapWriter::NOCOOPS_REQUESTED_BASE; 1614 } 1615 } 1616 1617 bool FileMapInfo::map_heap_region() { 1618 if (map_heap_region_impl()) { 1619 #ifdef ASSERT 1620 // The "old" regions must be parsable -- we cannot have any unused space 1621 // at the start of the lowest G1 region that contains archived objects. 1622 assert(is_aligned(_mapped_heap_memregion.start(), G1HeapRegion::GrainBytes), "must be"); 1623 1624 // Make sure we map at the very top of the heap - see comments in 1625 // init_heap_region_relocation(). 1626 MemRegion heap_range = G1CollectedHeap::heap()->reserved(); 1627 assert(heap_range.contains(_mapped_heap_memregion), "must be"); 1628 1629 address heap_end = (address)heap_range.end(); 1630 address mapped_heap_region_end = (address)_mapped_heap_memregion.end(); 1631 assert(heap_end >= mapped_heap_region_end, "must be"); 1632 assert(heap_end - mapped_heap_region_end < (intx)(G1HeapRegion::GrainBytes), 1633 "must be at the top of the heap to avoid fragmentation"); 1634 #endif 1635 1636 ArchiveHeapLoader::set_mapped(); 1637 return true; 1638 } else { 1639 return false; 1640 } 1641 } 1642 1643 bool FileMapInfo::map_heap_region_impl() { 1644 assert(UseG1GC, "the following code assumes G1"); 1645 1646 FileMapRegion* r = region_at(MetaspaceShared::hp); 1647 size_t size = r->used(); 1648 if (size == 0) { 1649 return false; // no archived java heap data 1650 } 1651 1652 size_t word_size = size / HeapWordSize; 1653 address requested_start = heap_region_requested_address(); 1654 1655 aot_log_info(aot)("Preferred address to map heap data (to avoid relocation) is " INTPTR_FORMAT, p2i(requested_start)); 1656 1657 // allocate from java heap 1658 HeapWord* start = G1CollectedHeap::heap()->alloc_archive_region(word_size, (HeapWord*)requested_start); 1659 if (start == nullptr) { 1660 MetaspaceShared::report_loading_error("UseSharedSpaces: Unable to allocate java heap region for archive heap."); 1661 return false; 1662 } 1663 1664 _mapped_heap_memregion = MemRegion(start, word_size); 1665 1666 // Map the archived heap data. No need to call MemTracker::record_virtual_memory_tag() 1667 // for mapped region as it is part of the reserved java heap, which is already recorded. 1668 char* addr = (char*)_mapped_heap_memregion.start(); 1669 char* base; 1670 1671 if (MetaspaceShared::use_windows_memory_mapping() || UseLargePages) { 1672 // With UseLargePages, memory mapping may fail on some OSes if the size is not 1673 // large page aligned, so let's use read() instead. In this case, the memory region 1674 // is already commited by G1 so we don't need to commit it again. 1675 if (!read_region(MetaspaceShared::hp, addr, 1676 align_up(_mapped_heap_memregion.byte_size(), os::vm_page_size()), 1677 /* do_commit = */ !UseLargePages)) { 1678 dealloc_heap_region(); 1679 aot_log_error(aot)("Failed to read archived heap region into " INTPTR_FORMAT, p2i(addr)); 1680 return false; 1681 } 1682 // Checks for VerifySharedSpaces is already done inside read_region() 1683 base = addr; 1684 } else { 1685 base = map_memory(_fd, _full_path, r->file_offset(), 1686 addr, _mapped_heap_memregion.byte_size(), r->read_only(), 1687 r->allow_exec(), mtJavaHeap); 1688 if (base == nullptr || base != addr) { 1689 dealloc_heap_region(); 1690 MetaspaceShared::report_loading_error("UseSharedSpaces: Unable to map at required address in java heap. " 1691 INTPTR_FORMAT ", size = %zu bytes", 1692 p2i(addr), _mapped_heap_memregion.byte_size()); 1693 return false; 1694 } 1695 1696 if (VerifySharedSpaces && !r->check_region_crc(base)) { 1697 dealloc_heap_region(); 1698 MetaspaceShared::report_loading_error("UseSharedSpaces: mapped heap region is corrupt"); 1699 return false; 1700 } 1701 } 1702 1703 r->set_mapped_base(base); 1704 1705 // If the requested range is different from the range allocated by GC, then 1706 // the pointers need to be patched. 1707 address mapped_start = (address) _mapped_heap_memregion.start(); 1708 ptrdiff_t delta = mapped_start - requested_start; 1709 if (UseCompressedOops && 1710 (narrow_oop_mode() != CompressedOops::mode() || 1711 narrow_oop_shift() != CompressedOops::shift())) { 1712 _heap_pointers_need_patching = true; 1713 } 1714 if (delta != 0) { 1715 _heap_pointers_need_patching = true; 1716 } 1717 ArchiveHeapLoader::init_mapped_heap_info(mapped_start, delta, narrow_oop_shift()); 1718 1719 if (_heap_pointers_need_patching) { 1720 char* bitmap_base = map_bitmap_region(); 1721 if (bitmap_base == nullptr) { 1722 MetaspaceShared::report_loading_error("CDS heap cannot be used because bitmap region cannot be mapped"); 1723 dealloc_heap_region(); 1724 _heap_pointers_need_patching = false; 1725 return false; 1726 } 1727 } 1728 aot_log_info(aot)("Heap data mapped at " INTPTR_FORMAT ", size = %8zu bytes", 1729 p2i(mapped_start), _mapped_heap_memregion.byte_size()); 1730 aot_log_info(aot)("CDS heap data relocation delta = %zd bytes", delta); 1731 return true; 1732 } 1733 1734 narrowOop FileMapInfo::encoded_heap_region_dumptime_address() { 1735 assert(CDSConfig::is_using_archive(), "runtime only"); 1736 assert(UseCompressedOops, "sanity"); 1737 FileMapRegion* r = region_at(MetaspaceShared::hp); 1738 return CompressedOops::narrow_oop_cast(r->mapping_offset() >> narrow_oop_shift()); 1739 } 1740 1741 void FileMapInfo::patch_heap_embedded_pointers() { 1742 if (!ArchiveHeapLoader::is_mapped() || !_heap_pointers_need_patching) { 1743 return; 1744 } 1745 1746 char* bitmap_base = map_bitmap_region(); 1747 assert(bitmap_base != nullptr, "must have already been mapped"); 1748 1749 FileMapRegion* r = region_at(MetaspaceShared::hp); 1750 ArchiveHeapLoader::patch_embedded_pointers( 1751 this, _mapped_heap_memregion, 1752 (address)(region_at(MetaspaceShared::bm)->mapped_base()) + r->oopmap_offset(), 1753 r->oopmap_size_in_bits()); 1754 } 1755 1756 void FileMapInfo::fixup_mapped_heap_region() { 1757 if (ArchiveHeapLoader::is_mapped()) { 1758 assert(!_mapped_heap_memregion.is_empty(), "sanity"); 1759 1760 // Populate the archive regions' G1BlockOffsetTables. That ensures 1761 // fast G1BlockOffsetTable::block_start operations for any given address 1762 // within the archive regions when trying to find start of an object 1763 // (e.g. during card table scanning). 1764 G1CollectedHeap::heap()->populate_archive_regions_bot(_mapped_heap_memregion); 1765 } 1766 } 1767 1768 // dealloc the archive regions from java heap 1769 void FileMapInfo::dealloc_heap_region() { 1770 G1CollectedHeap::heap()->dealloc_archive_regions(_mapped_heap_memregion); 1771 } 1772 #endif // INCLUDE_CDS_JAVA_HEAP 1773 1774 void FileMapInfo::unmap_regions(int regions[], int num_regions) { 1775 for (int r = 0; r < num_regions; r++) { 1776 int idx = regions[r]; 1777 unmap_region(idx); 1778 } 1779 } 1780 1781 // Unmap a memory region in the address space. 1782 1783 void FileMapInfo::unmap_region(int i) { 1784 FileMapRegion* r = region_at(i); 1785 char* mapped_base = r->mapped_base(); 1786 size_t size = r->used_aligned(); 1787 1788 if (mapped_base != nullptr) { 1789 if (size > 0 && r->mapped_from_file()) { 1790 aot_log_info(aot)("Unmapping region #%d at base " INTPTR_FORMAT " (%s)", i, p2i(mapped_base), 1791 shared_region_name[i]); 1792 if (r->in_reserved_space()) { 1793 // This region was mapped inside a ReservedSpace. Its memory will be freed when the ReservedSpace 1794 // is released. Zero it so that we don't accidentally read its content. 1795 aot_log_info(aot)("Region #%d (%s) is in a reserved space, it will be freed when the space is released", i, shared_region_name[i]); 1796 } else { 1797 if (!os::unmap_memory(mapped_base, size)) { 1798 fatal("os::unmap_memory failed"); 1799 } 1800 } 1801 } 1802 r->set_mapped_base(nullptr); 1803 } 1804 } 1805 1806 void FileMapInfo::assert_mark(bool check) { 1807 if (!check) { 1808 MetaspaceShared::unrecoverable_loading_error("Mark mismatch while restoring from shared file."); 1809 } 1810 } 1811 1812 FileMapInfo* FileMapInfo::_current_info = nullptr; 1813 FileMapInfo* FileMapInfo::_dynamic_archive_info = nullptr; 1814 bool FileMapInfo::_heap_pointers_need_patching = false; 1815 bool FileMapInfo::_memory_mapping_failed = false; 1816 1817 // Open the shared archive file, read and validate the header 1818 // information (version, boot classpath, etc.). If initialization 1819 // fails, shared spaces are disabled and the file is closed. 1820 // 1821 // Validation of the archive is done in two steps: 1822 // 1823 // [1] validate_header() - done here. 1824 // [2] validate_shared_path_table - this is done later, because the table is in the RO 1825 // region of the archive, which is not mapped yet. 1826 bool FileMapInfo::open_as_input() { 1827 assert(CDSConfig::is_using_archive(), "UseSharedSpaces expected."); 1828 assert(Arguments::has_jimage(), "The shared archive file cannot be used with an exploded module build."); 1829 1830 if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) { 1831 // CDS assumes that no classes resolved in vmClasses::resolve_all() 1832 // are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved 1833 // during the JVMTI "early" stage, so we can still use CDS if 1834 // JvmtiExport::has_early_class_hook_env() is false. 1835 MetaspaceShared::report_loading_error("CDS is disabled because early JVMTI ClassFileLoadHook is in use."); 1836 return false; 1837 } 1838 1839 if (!open_for_read() || !init_from_file(_fd) || !validate_header()) { 1840 if (_is_static) { 1841 MetaspaceShared::report_loading_error("Loading static archive failed."); 1842 return false; 1843 } else { 1844 MetaspaceShared::report_loading_error("Loading dynamic archive failed."); 1845 if (AutoCreateSharedArchive) { 1846 CDSConfig::enable_dumping_dynamic_archive(_full_path); 1847 } 1848 return false; 1849 } 1850 } 1851 1852 return true; 1853 } 1854 1855 bool FileMapInfo::validate_aot_class_linking() { 1856 // These checks need to be done after FileMapInfo::initialize(), which gets called before Universe::heap() 1857 // is available. 1858 if (header()->has_aot_linked_classes()) { 1859 const char* archive_type = CDSConfig::type_of_archive_being_loaded(); 1860 CDSConfig::set_has_aot_linked_classes(true); 1861 if (JvmtiExport::should_post_class_file_load_hook()) { 1862 aot_log_error(aot)("%s has aot-linked classes. It cannot be used when JVMTI ClassFileLoadHook is in use.", 1863 archive_type); 1864 return false; 1865 } 1866 if (JvmtiExport::has_early_vmstart_env()) { 1867 aot_log_error(aot)("%s has aot-linked classes. It cannot be used when JVMTI early vm start is in use.", 1868 archive_type); 1869 return false; 1870 } 1871 if (!CDSConfig::is_using_full_module_graph()) { 1872 aot_log_error(aot)("%s has aot-linked classes. It cannot be used when archived full module graph is not used.", 1873 archive_type); 1874 return false; 1875 } 1876 1877 const char* prop = Arguments::get_property("java.security.manager"); 1878 if (prop != nullptr && strcmp(prop, "disallow") != 0) { 1879 aot_log_error(aot)("%s has aot-linked classes. It cannot be used with -Djava.security.manager=%s.", 1880 archive_type, prop); 1881 return false; 1882 } 1883 1884 #if INCLUDE_JVMTI 1885 if (Arguments::has_jdwp_agent()) { 1886 aot_log_error(aot)("%s has aot-linked classes. It cannot be used with JDWP agent", archive_type); 1887 return false; 1888 } 1889 #endif 1890 } 1891 1892 return true; 1893 } 1894 1895 // The 2 core spaces are RW->RO 1896 FileMapRegion* FileMapInfo::first_core_region() const { 1897 return region_at(MetaspaceShared::rw); 1898 } 1899 1900 FileMapRegion* FileMapInfo::last_core_region() const { 1901 return region_at(MetaspaceShared::ro); 1902 } 1903 1904 void FileMapInfo::print(outputStream* st) const { 1905 header()->print(st); 1906 if (!is_static()) { 1907 dynamic_header()->print(st); 1908 } 1909 } 1910 1911 void FileMapHeader::set_as_offset(char* p, size_t *offset) { 1912 *offset = ArchiveBuilder::current()->any_to_offset((address)p); 1913 } 1914 1915 int FileMapHeader::compute_crc() { 1916 char* start = (char*)this; 1917 // start computing from the field after _header_size to end of base archive name. 1918 char* buf = (char*)&(_generic_header._header_size) + sizeof(_generic_header._header_size); 1919 size_t sz = header_size() - (buf - start); 1920 int crc = ClassLoader::crc32(0, buf, (jint)sz); 1921 return crc; 1922 } 1923 1924 // This function should only be called during run time with UseSharedSpaces enabled. 1925 bool FileMapHeader::validate() { 1926 const char* file_type = CDSConfig::type_of_archive_being_loaded(); 1927 if (_obj_alignment != ObjectAlignmentInBytes) { 1928 MetaspaceShared::report_loading_error("The %s's ObjectAlignmentInBytes of %d" 1929 " does not equal the current ObjectAlignmentInBytes of %d.", 1930 file_type, _obj_alignment, ObjectAlignmentInBytes); 1931 return false; 1932 } 1933 if (_compact_strings != CompactStrings) { 1934 MetaspaceShared::report_loading_error("The %s's CompactStrings setting (%s)" 1935 " does not equal the current CompactStrings setting (%s).", file_type, 1936 _compact_strings ? "enabled" : "disabled", 1937 CompactStrings ? "enabled" : "disabled"); 1938 return false; 1939 } 1940 bool jvmci_compiler_is_enabled = CompilerConfig::is_jvmci_compiler_enabled(); 1941 CompilerType compiler_type = CompilerConfig::compiler_type(); 1942 CompilerType archive_compiler_type = CompilerType(_compiler_type); 1943 // JVMCI compiler does different type profiling settigns and generate 1944 // different code. We can't use archive which was produced 1945 // without it and reverse. 1946 // Only allow mix when JIT compilation is disabled. 1947 // Interpreter is used by default when dumping archive. 1948 bool intepreter_is_used = (archive_compiler_type == CompilerType::compiler_none) || 1949 (compiler_type == CompilerType::compiler_none); 1950 if (!intepreter_is_used && 1951 jvmci_compiler_is_enabled != (archive_compiler_type == CompilerType::compiler_jvmci)) { 1952 MetaspaceShared::report_loading_error("The %s's JIT compiler setting (%s)" 1953 " does not equal the current setting (%s).", file_type, 1954 compilertype2name(archive_compiler_type), compilertype2name(compiler_type)); 1955 return false; 1956 } 1957 if (TrainingData::have_data()) { 1958 if (_type_profile_level != TypeProfileLevel) { 1959 MetaspaceShared::report_loading_error("The %s's TypeProfileLevel setting (%d)" 1960 " does not equal the current TypeProfileLevel setting (%d).", file_type, 1961 _type_profile_level, TypeProfileLevel); 1962 return false; 1963 } 1964 if (_type_profile_args_limit != TypeProfileArgsLimit) { 1965 MetaspaceShared::report_loading_error("The %s's TypeProfileArgsLimit setting (%d)" 1966 " does not equal the current TypeProfileArgsLimit setting (%d).", file_type, 1967 _type_profile_args_limit, TypeProfileArgsLimit); 1968 return false; 1969 } 1970 if (_type_profile_parms_limit != TypeProfileParmsLimit) { 1971 MetaspaceShared::report_loading_error("The %s's TypeProfileParamsLimit setting (%d)" 1972 " does not equal the current TypeProfileParamsLimit setting (%d).", file_type, 1973 _type_profile_args_limit, TypeProfileArgsLimit); 1974 return false; 1975 1976 } 1977 if (_type_profile_width != TypeProfileWidth) { 1978 MetaspaceShared::report_loading_error("The %s's TypeProfileWidth setting (%d)" 1979 " does not equal the current TypeProfileWidth setting (%d).", file_type, 1980 (int)_type_profile_width, (int)TypeProfileWidth); 1981 return false; 1982 1983 } 1984 if (_bci_profile_width != BciProfileWidth) { 1985 MetaspaceShared::report_loading_error("The %s's BciProfileWidth setting (%d)" 1986 " does not equal the current BciProfileWidth setting (%d).", file_type, 1987 (int)_bci_profile_width, (int)BciProfileWidth); 1988 return false; 1989 } 1990 if (_type_profile_casts != TypeProfileCasts) { 1991 MetaspaceShared::report_loading_error("The %s's TypeProfileCasts setting (%s)" 1992 " does not equal the current TypeProfileCasts setting (%s).", file_type, 1993 _type_profile_casts ? "enabled" : "disabled", 1994 TypeProfileCasts ? "enabled" : "disabled"); 1995 1996 return false; 1997 1998 } 1999 if (_profile_traps != ProfileTraps) { 2000 MetaspaceShared::report_loading_error("The %s's ProfileTraps setting (%s)" 2001 " does not equal the current ProfileTraps setting (%s).", file_type, 2002 _profile_traps ? "enabled" : "disabled", 2003 ProfileTraps ? "enabled" : "disabled"); 2004 2005 return false; 2006 } 2007 if (_spec_trap_limit_extra_entries != SpecTrapLimitExtraEntries) { 2008 MetaspaceShared::report_loading_error("The %s's SpecTrapLimitExtraEntries setting (%d)" 2009 " does not equal the current SpecTrapLimitExtraEntries setting (%d).", file_type, 2010 _spec_trap_limit_extra_entries, SpecTrapLimitExtraEntries); 2011 return false; 2012 2013 } 2014 } 2015 2016 // This must be done after header validation because it might change the 2017 // header data 2018 const char* prop = Arguments::get_property("java.system.class.loader"); 2019 if (prop != nullptr) { 2020 if (has_aot_linked_classes()) { 2021 MetaspaceShared::report_loading_error("%s has aot-linked classes. It cannot be used when the " 2022 "java.system.class.loader property is specified.", 2023 CDSConfig::type_of_archive_being_loaded()); 2024 return false; 2025 } 2026 aot_log_warning(aot)("Archived non-system classes are disabled because the " 2027 "java.system.class.loader property is specified (value = \"%s\"). " 2028 "To use archived non-system classes, this property must not be set", prop); 2029 _has_platform_or_app_classes = false; 2030 } 2031 2032 2033 if (!_verify_local && BytecodeVerificationLocal) { 2034 // we cannot load boot classes, so there's no point of using the CDS archive 2035 MetaspaceShared::report_loading_error("The %s's BytecodeVerificationLocal setting (%s)" 2036 " does not equal the current BytecodeVerificationLocal setting (%s).", file_type, 2037 _verify_local ? "enabled" : "disabled", 2038 BytecodeVerificationLocal ? "enabled" : "disabled"); 2039 return false; 2040 } 2041 2042 // For backwards compatibility, we don't check the BytecodeVerificationRemote setting 2043 // if the archive only contains system classes. 2044 if (_has_platform_or_app_classes 2045 && !_verify_remote // we didn't verify the archived platform/app classes 2046 && BytecodeVerificationRemote) { // but we want to verify all loaded platform/app classes 2047 aot_log_info(aot)("The %s was created with less restrictive " 2048 "verification setting than the current setting.", file_type); 2049 // Pretend that we didn't have any archived platform/app classes, so they won't be loaded 2050 // by SystemDictionaryShared. 2051 _has_platform_or_app_classes = false; 2052 } 2053 2054 // Java agents are allowed during run time. Therefore, the following condition is not 2055 // checked: (!_allow_archiving_with_java_agent && AllowArchivingWithJavaAgent) 2056 // Note: _allow_archiving_with_java_agent is set in the shared archive during dump time 2057 // while AllowArchivingWithJavaAgent is set during the current run. 2058 if (_allow_archiving_with_java_agent && !AllowArchivingWithJavaAgent) { 2059 MetaspaceShared::report_loading_error("The setting of the AllowArchivingWithJavaAgent is different " 2060 "from the setting in the %s.", file_type); 2061 return false; 2062 } 2063 2064 if (_allow_archiving_with_java_agent) { 2065 aot_log_warning(aot)("This %s was created with AllowArchivingWithJavaAgent. It should be used " 2066 "for testing purposes only and should not be used in a production environment", file_type); 2067 } 2068 2069 aot_log_info(aot)("The %s was created with UseCompressedOops = %d, UseCompressedClassPointers = %d, UseCompactObjectHeaders = %d", 2070 file_type, compressed_oops(), compressed_class_pointers(), compact_headers()); 2071 if (compressed_oops() != UseCompressedOops || compressed_class_pointers() != UseCompressedClassPointers) { 2072 aot_log_warning(aot)("Unable to use %s.\nThe saved state of UseCompressedOops and UseCompressedClassPointers is " 2073 "different from runtime, CDS will be disabled.", file_type); 2074 return false; 2075 } 2076 2077 if (compact_headers() != UseCompactObjectHeaders) { 2078 aot_log_warning(aot)("Unable to use %s.\nThe %s's UseCompactObjectHeaders setting (%s)" 2079 " does not equal the current UseCompactObjectHeaders setting (%s).", file_type, file_type, 2080 _compact_headers ? "enabled" : "disabled", 2081 UseCompactObjectHeaders ? "enabled" : "disabled"); 2082 return false; 2083 } 2084 2085 if (!_use_optimized_module_handling && !CDSConfig::is_dumping_final_static_archive()) { 2086 CDSConfig::stop_using_optimized_module_handling(); 2087 aot_log_info(aot)("optimized module handling: disabled because archive was created without optimized module handling"); 2088 } 2089 2090 if (is_static()) { 2091 // Only the static archive can contain the full module graph. 2092 if (!_has_full_module_graph) { 2093 CDSConfig::stop_using_full_module_graph("archive was created without full module graph"); 2094 } 2095 } 2096 2097 return true; 2098 } 2099 2100 bool FileMapInfo::validate_header() { 2101 if (!header()->validate()) { 2102 return false; 2103 } 2104 if (_is_static) { 2105 return true; 2106 } else { 2107 return DynamicArchive::validate(this); 2108 } 2109 } 2110 2111 #if INCLUDE_JVMTI 2112 ClassPathEntry** FileMapInfo::_classpath_entries_for_jvmti = nullptr; 2113 2114 ClassPathEntry* FileMapInfo::get_classpath_entry_for_jvmti(int i, TRAPS) { 2115 if (i == 0) { 2116 // index 0 corresponds to the ClassPathImageEntry which is a globally shared object 2117 // and should never be deleted. 2118 return ClassLoader::get_jrt_entry(); 2119 } 2120 ClassPathEntry* ent = _classpath_entries_for_jvmti[i]; 2121 if (ent == nullptr) { 2122 const AOTClassLocation* cl = AOTClassLocationConfig::runtime()->class_location_at(i); 2123 const char* path = cl->path(); 2124 struct stat st; 2125 if (os::stat(path, &st) != 0) { 2126 char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128); 2127 jio_snprintf(msg, strlen(path) + 127, "error in finding JAR file %s", path); 2128 THROW_MSG_(vmSymbols::java_io_IOException(), msg, nullptr); 2129 } else { 2130 ent = ClassLoader::create_class_path_entry(THREAD, path, &st); 2131 if (ent == nullptr) { 2132 char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128); 2133 jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path); 2134 THROW_MSG_(vmSymbols::java_io_IOException(), msg, nullptr); 2135 } 2136 } 2137 2138 MutexLocker mu(THREAD, CDSClassFileStream_lock); 2139 if (_classpath_entries_for_jvmti[i] == nullptr) { 2140 _classpath_entries_for_jvmti[i] = ent; 2141 } else { 2142 // Another thread has beat me to creating this entry 2143 delete ent; 2144 ent = _classpath_entries_for_jvmti[i]; 2145 } 2146 } 2147 2148 return ent; 2149 } 2150 2151 ClassFileStream* FileMapInfo::open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS) { 2152 int path_index = ik->shared_classpath_index(); 2153 assert(path_index >= 0, "should be called for shared built-in classes only"); 2154 assert(path_index < AOTClassLocationConfig::runtime()->length(), "sanity"); 2155 2156 ClassPathEntry* cpe = get_classpath_entry_for_jvmti(path_index, CHECK_NULL); 2157 assert(cpe != nullptr, "must be"); 2158 2159 Symbol* name = ik->name(); 2160 const char* const class_name = name->as_C_string(); 2161 const char* const file_name = ClassLoader::file_name_for_class_name(class_name, 2162 name->utf8_length()); 2163 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader()); 2164 const AOTClassLocation* cl = AOTClassLocationConfig::runtime()->class_location_at(path_index); 2165 ClassFileStream* cfs; 2166 if (class_loader() != nullptr && cl->is_multi_release_jar()) { 2167 // This class was loaded from a multi-release JAR file during dump time. The 2168 // process for finding its classfile is complex. Let's defer to the Java code 2169 // in java.lang.ClassLoader. 2170 cfs = get_stream_from_class_loader(class_loader, cpe, file_name, CHECK_NULL); 2171 } else { 2172 cfs = cpe->open_stream_for_loader(THREAD, file_name, loader_data); 2173 } 2174 assert(cfs != nullptr, "must be able to read the classfile data of shared classes for built-in loaders."); 2175 log_debug(aot, jvmti)("classfile data for %s [%d: %s] = %d bytes", class_name, path_index, 2176 cfs->source(), cfs->length()); 2177 return cfs; 2178 } 2179 2180 ClassFileStream* FileMapInfo::get_stream_from_class_loader(Handle class_loader, 2181 ClassPathEntry* cpe, 2182 const char* file_name, 2183 TRAPS) { 2184 JavaValue result(T_OBJECT); 2185 oop class_name = java_lang_String::create_oop_from_str(file_name, THREAD); 2186 Handle h_class_name = Handle(THREAD, class_name); 2187 2188 // byte[] ClassLoader.getResourceAsByteArray(String name) 2189 JavaCalls::call_virtual(&result, 2190 class_loader, 2191 vmClasses::ClassLoader_klass(), 2192 vmSymbols::getResourceAsByteArray_name(), 2193 vmSymbols::getResourceAsByteArray_signature(), 2194 h_class_name, 2195 CHECK_NULL); 2196 assert(result.get_type() == T_OBJECT, "just checking"); 2197 oop obj = result.get_oop(); 2198 assert(obj != nullptr, "ClassLoader.getResourceAsByteArray should not return null"); 2199 2200 // copy from byte[] to a buffer 2201 typeArrayOop ba = typeArrayOop(obj); 2202 jint len = ba->length(); 2203 u1* buffer = NEW_RESOURCE_ARRAY(u1, len); 2204 ArrayAccess<>::arraycopy_to_native<>(ba, typeArrayOopDesc::element_offset<jbyte>(0), buffer, len); 2205 2206 return new ClassFileStream(buffer, len, cpe->name()); 2207 } 2208 #endif