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