1 /* 2 * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "precompiled.hpp" 26 #include "cds/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/compressedOops.hpp" 57 #include "oops/compressedOops.inline.hpp" 58 #include "oops/objArrayOop.hpp" 59 #include "oops/oop.inline.hpp" 60 #include "prims/jvmtiExport.hpp" 61 #include "runtime/arguments.hpp" 62 #include "runtime/globals_extension.hpp" 63 #include "runtime/java.hpp" 64 #include "runtime/mutexLocker.hpp" 65 #include "runtime/os.hpp" 66 #include "runtime/vm_version.hpp" 67 #include "utilities/align.hpp" 68 #include "utilities/bitMap.inline.hpp" 69 #include "utilities/classpathStream.hpp" 70 #include "utilities/defaultStream.hpp" 71 #include "utilities/ostream.hpp" 72 #if INCLUDE_G1GC 73 #include "gc/g1/g1CollectedHeap.hpp" 74 #include "gc/g1/heapRegion.hpp" 75 #endif 76 77 # include <sys/stat.h> 78 # include <errno.h> 79 80 #ifndef O_BINARY // if defined (Win32) use binary files. 81 #define O_BINARY 0 // otherwise do nothing. 82 #endif 83 84 inline void CDSMustMatchFlags::do_print(outputStream* st, bool v) { 85 st->print("%s", v ? "true" : "false"); 86 } 87 88 inline void CDSMustMatchFlags::do_print(outputStream* st, intx v) { 89 st->print(INTX_FORMAT, v); 90 } 91 92 inline void CDSMustMatchFlags::do_print(outputStream* st, uintx v) { 93 st->print(UINTX_FORMAT, v); 94 } 95 96 inline void CDSMustMatchFlags::do_print(outputStream* st, double v) { 97 st->print("%f", v); 98 } 99 100 void CDSMustMatchFlags::init() { 101 assert(CDSConfig::is_dumping_archive(), "sanity"); 102 _max_name_width = 0; 103 104 #define INIT_CDS_MUST_MATCH_FLAG(n) \ 105 _v_##n = n; \ 106 _max_name_width = MAX2(_max_name_width,strlen(#n)); 107 CDS_MUST_MATCH_FLAGS_DO(INIT_CDS_MUST_MATCH_FLAG); 108 #undef INIT_CDS_MUST_MATCH_FLAG 109 } 110 111 bool CDSMustMatchFlags::runtime_check() const { 112 #define CHECK_CDS_MUST_MATCH_FLAG(n) \ 113 if (_v_##n != n) { \ 114 ResourceMark rm; \ 115 stringStream ss; \ 116 ss.print("VM option %s is different between dumptime (", #n); \ 117 do_print(&ss, _v_ ## n); \ 118 ss.print(") and runtime ("); \ 119 do_print(&ss, n); \ 120 ss.print(")"); \ 121 log_info(cds)("%s", ss.as_string()); \ 122 return false; \ 123 } 124 CDS_MUST_MATCH_FLAGS_DO(CHECK_CDS_MUST_MATCH_FLAG); 125 #undef CHECK_CDS_MUST_MATCH_FLAG 126 127 return true; 128 } 129 130 void CDSMustMatchFlags::print_info() const { 131 LogTarget(Info, cds) lt; 132 if (lt.is_enabled()) { 133 LogStream ls(lt); 134 ls.print_cr("Recorded VM flags during dumptime:"); 135 print(&ls); 136 } 137 } 138 139 void CDSMustMatchFlags::print(outputStream* st) const { 140 #define PRINT_CDS_MUST_MATCH_FLAG(n) \ 141 st->print("- %-s ", #n); \ 142 st->sp(int(_max_name_width - strlen(#n))); \ 143 do_print(st, _v_##n); \ 144 st->cr(); 145 CDS_MUST_MATCH_FLAGS_DO(PRINT_CDS_MUST_MATCH_FLAG); 146 #undef PRINT_CDS_MUST_MATCH_FLAG 147 } 148 149 // Fill in the fileMapInfo structure with data about this VM instance. 150 151 // This method copies the vm version info into header_version. If the version is too 152 // long then a truncated version, which has a hash code appended to it, is copied. 153 // 154 // Using a template enables this method to verify that header_version is an array of 155 // length JVM_IDENT_MAX. This ensures that the code that writes to the CDS file and 156 // the code that reads the CDS file will both use the same size buffer. Hence, will 157 // use identical truncation. This is necessary for matching of truncated versions. 158 template <int N> static void get_header_version(char (&header_version) [N]) { 159 assert(N == JVM_IDENT_MAX, "Bad header_version size"); 160 161 const char *vm_version = VM_Version::internal_vm_info_string(); 162 const int version_len = (int)strlen(vm_version); 163 164 memset(header_version, 0, JVM_IDENT_MAX); 165 166 if (version_len < (JVM_IDENT_MAX-1)) { 167 strcpy(header_version, vm_version); 168 169 } else { 170 // Get the hash value. Use a static seed because the hash needs to return the same 171 // value over multiple jvm invocations. 172 uint32_t hash = AltHashing::halfsiphash_32(8191, (const uint8_t*)vm_version, version_len); 173 174 // Truncate the ident, saving room for the 8 hex character hash value. 175 strncpy(header_version, vm_version, JVM_IDENT_MAX-9); 176 177 // Append the hash code as eight hex digits. 178 os::snprintf_checked(&header_version[JVM_IDENT_MAX-9], 9, "%08x", hash); 179 header_version[JVM_IDENT_MAX-1] = 0; // Null terminate. 180 } 181 182 assert(header_version[JVM_IDENT_MAX-1] == 0, "must be"); 183 } 184 185 FileMapInfo::FileMapInfo(const char* full_path, bool is_static) : 186 _is_static(is_static), _file_open(false), _is_mapped(false), _fd(-1), _file_offset(0), 187 _full_path(full_path), _base_archive_name(nullptr), _header(nullptr) { 188 if (_is_static) { 189 assert(_current_info == nullptr, "must be singleton"); // not thread safe 190 _current_info = this; 191 } else { 192 assert(_dynamic_archive_info == nullptr, "must be singleton"); // not thread safe 193 _dynamic_archive_info = this; 194 } 195 } 196 197 FileMapInfo::~FileMapInfo() { 198 if (_is_static) { 199 assert(_current_info == this, "must be singleton"); // not thread safe 200 _current_info = nullptr; 201 } else { 202 assert(_dynamic_archive_info == this, "must be singleton"); // not thread safe 203 _dynamic_archive_info = nullptr; 204 } 205 206 if (_header != nullptr) { 207 os::free(_header); 208 } 209 210 if (_file_open) { 211 ::close(_fd); 212 } 213 } 214 215 void FileMapInfo::populate_header(size_t core_region_alignment) { 216 assert(_header == nullptr, "Sanity check"); 217 size_t c_header_size; 218 size_t header_size; 219 size_t base_archive_name_size = 0; 220 size_t base_archive_name_offset = 0; 221 size_t longest_common_prefix_size = 0; 222 if (is_static()) { 223 c_header_size = sizeof(FileMapHeader); 224 header_size = c_header_size; 225 } else { 226 // dynamic header including base archive name for non-default base archive 227 c_header_size = sizeof(DynamicArchiveHeader); 228 header_size = c_header_size; 229 230 const char* default_base_archive_name = CDSConfig::default_archive_path(); 231 const char* current_base_archive_name = CDSConfig::static_archive_path(); 232 if (!os::same_files(current_base_archive_name, default_base_archive_name)) { 233 base_archive_name_size = strlen(current_base_archive_name) + 1; 234 header_size += base_archive_name_size; 235 base_archive_name_offset = c_header_size; 236 } 237 } 238 ResourceMark rm; 239 GrowableArray<const char*>* app_cp_array = create_dumptime_app_classpath_array(); 240 int len = app_cp_array->length(); 241 longest_common_prefix_size = longest_common_app_classpath_prefix_len(len, app_cp_array); 242 _header = (FileMapHeader*)os::malloc(header_size, mtInternal); 243 memset((void*)_header, 0, header_size); 244 _header->populate(this, 245 core_region_alignment, 246 header_size, 247 base_archive_name_size, 248 base_archive_name_offset, 249 longest_common_prefix_size); 250 } 251 252 void FileMapHeader::populate(FileMapInfo *info, size_t core_region_alignment, 253 size_t header_size, size_t base_archive_name_size, 254 size_t base_archive_name_offset, size_t common_app_classpath_prefix_size) { 255 // 1. We require _generic_header._magic to be at the beginning of the file 256 // 2. FileMapHeader also assumes that _generic_header is at the beginning of the file 257 assert(offset_of(FileMapHeader, _generic_header) == 0, "must be"); 258 set_header_size((unsigned int)header_size); 259 set_base_archive_name_offset((unsigned int)base_archive_name_offset); 260 set_base_archive_name_size((unsigned int)base_archive_name_size); 261 set_common_app_classpath_prefix_size((unsigned int)common_app_classpath_prefix_size); 262 set_magic(CDSConfig::is_dumping_dynamic_archive() ? CDS_DYNAMIC_ARCHIVE_MAGIC : CDS_ARCHIVE_MAGIC); 263 set_version(CURRENT_CDS_ARCHIVE_VERSION); 264 265 if (!info->is_static() && base_archive_name_size != 0) { 266 // copy base archive name 267 copy_base_archive_name(CDSConfig::static_archive_path()); 268 } 269 _core_region_alignment = core_region_alignment; 270 _obj_alignment = ObjectAlignmentInBytes; 271 _compact_strings = CompactStrings; 272 if (CDSConfig::is_dumping_heap()) { 273 _narrow_oop_mode = CompressedOops::mode(); 274 _narrow_oop_base = CompressedOops::base(); 275 _narrow_oop_shift = CompressedOops::shift(); 276 } 277 _compressed_oops = UseCompressedOops; 278 _compressed_class_ptrs = UseCompressedClassPointers; 279 _max_heap_size = MaxHeapSize; 280 _use_optimized_module_handling = MetaspaceShared::use_optimized_module_handling(); 281 _has_full_module_graph = CDSConfig::is_dumping_full_module_graph(); 282 _has_valhalla_patched_classes = CDSConfig::is_valhalla_preview(); 283 // The following fields are for sanity checks for whether this archive 284 // will function correctly with this JVM and the bootclasspath it's 285 // invoked with. 286 287 // JVM version string ... changes on each build. 288 get_header_version(_jvm_ident); 289 290 _app_class_paths_start_index = ClassLoaderExt::app_class_paths_start_index(); 291 _app_module_paths_start_index = ClassLoaderExt::app_module_paths_start_index(); 292 _max_used_path_index = ClassLoaderExt::max_used_path_index(); 293 _num_module_paths = ClassLoader::num_module_path_entries(); 294 295 _verify_local = BytecodeVerificationLocal; 296 _verify_remote = BytecodeVerificationRemote; 297 _has_platform_or_app_classes = ClassLoaderExt::has_platform_or_app_classes(); 298 _has_non_jar_in_classpath = ClassLoaderExt::has_non_jar_in_classpath(); 299 _requested_base_address = (char*)SharedBaseAddress; 300 _mapped_base_address = (char*)SharedBaseAddress; 301 _allow_archiving_with_java_agent = AllowArchivingWithJavaAgent; 302 _must_match.init(); 303 304 if (!CDSConfig::is_dumping_dynamic_archive()) { 305 set_shared_path_table(info->_shared_path_table); 306 } 307 } 308 309 void FileMapHeader::copy_base_archive_name(const char* archive) { 310 assert(base_archive_name_size() != 0, "_base_archive_name_size not set"); 311 assert(base_archive_name_offset() != 0, "_base_archive_name_offset not set"); 312 assert(header_size() > sizeof(*this), "_base_archive_name_size not included in header size?"); 313 memcpy((char*)this + base_archive_name_offset(), archive, base_archive_name_size()); 314 } 315 316 void FileMapHeader::print(outputStream* st) { 317 ResourceMark rm; 318 319 st->print_cr("- magic: 0x%08x", magic()); 320 st->print_cr("- crc: 0x%08x", crc()); 321 st->print_cr("- version: 0x%x", version()); 322 st->print_cr("- header_size: " UINT32_FORMAT, header_size()); 323 st->print_cr("- common_app_classpath_size: " UINT32_FORMAT, common_app_classpath_prefix_size()); 324 st->print_cr("- base_archive_name_offset: " UINT32_FORMAT, base_archive_name_offset()); 325 st->print_cr("- base_archive_name_size: " UINT32_FORMAT, base_archive_name_size()); 326 327 for (int i = 0; i < NUM_CDS_REGIONS; i++) { 328 FileMapRegion* r = region_at(i); 329 r->print(st, i); 330 } 331 st->print_cr("============ end regions ======== "); 332 333 st->print_cr("- core_region_alignment: " SIZE_FORMAT, _core_region_alignment); 334 st->print_cr("- obj_alignment: %d", _obj_alignment); 335 st->print_cr("- narrow_oop_base: " INTPTR_FORMAT, p2i(_narrow_oop_base)); 336 st->print_cr("- narrow_oop_base: " INTPTR_FORMAT, p2i(_narrow_oop_base)); 337 st->print_cr("- narrow_oop_shift %d", _narrow_oop_shift); 338 st->print_cr("- compact_strings: %d", _compact_strings); 339 st->print_cr("- max_heap_size: " UINTX_FORMAT, _max_heap_size); 340 st->print_cr("- narrow_oop_mode: %d", _narrow_oop_mode); 341 st->print_cr("- compressed_oops: %d", _compressed_oops); 342 st->print_cr("- compressed_class_ptrs: %d", _compressed_class_ptrs); 343 st->print_cr("- cloned_vtables_offset: " SIZE_FORMAT_X, _cloned_vtables_offset); 344 st->print_cr("- serialized_data_offset: " SIZE_FORMAT_X, _serialized_data_offset); 345 st->print_cr("- jvm_ident: %s", _jvm_ident); 346 st->print_cr("- shared_path_table_offset: " SIZE_FORMAT_X, _shared_path_table_offset); 347 st->print_cr("- app_class_paths_start_index: %d", _app_class_paths_start_index); 348 st->print_cr("- app_module_paths_start_index: %d", _app_module_paths_start_index); 349 st->print_cr("- num_module_paths: %d", _num_module_paths); 350 st->print_cr("- max_used_path_index: %d", _max_used_path_index); 351 st->print_cr("- verify_local: %d", _verify_local); 352 st->print_cr("- verify_remote: %d", _verify_remote); 353 st->print_cr("- has_platform_or_app_classes: %d", _has_platform_or_app_classes); 354 st->print_cr("- has_non_jar_in_classpath: %d", _has_non_jar_in_classpath); 355 st->print_cr("- requested_base_address: " INTPTR_FORMAT, p2i(_requested_base_address)); 356 st->print_cr("- mapped_base_address: " INTPTR_FORMAT, p2i(_mapped_base_address)); 357 st->print_cr("- heap_roots_offset: " SIZE_FORMAT, _heap_roots_offset); 358 st->print_cr("- allow_archiving_with_java_agent:%d", _allow_archiving_with_java_agent); 359 st->print_cr("- use_optimized_module_handling: %d", _use_optimized_module_handling); 360 st->print_cr("- has_full_module_graph %d", _has_full_module_graph); 361 st->print_cr("- has_valhalla_patched_classes %d", _has_valhalla_patched_classes); 362 st->print_cr("- ptrmap_size_in_bits: " SIZE_FORMAT, _ptrmap_size_in_bits); 363 _must_match.print(st); 364 } 365 366 void SharedClassPathEntry::init_as_non_existent(const char* path, TRAPS) { 367 _type = non_existent_entry; 368 set_name(path, CHECK); 369 } 370 371 void SharedClassPathEntry::init(bool is_modules_image, 372 bool is_module_path, 373 ClassPathEntry* cpe, TRAPS) { 374 assert(CDSConfig::is_dumping_archive(), "sanity"); 375 _timestamp = 0; 376 _filesize = 0; 377 _from_class_path_attr = false; 378 379 struct stat st; 380 if (os::stat(cpe->name(), &st) == 0) { 381 if ((st.st_mode & S_IFMT) == S_IFDIR) { 382 _type = dir_entry; 383 } else { 384 // The timestamp of the modules_image is not checked at runtime. 385 if (is_modules_image) { 386 _type = modules_image_entry; 387 } else { 388 _type = jar_entry; 389 _timestamp = st.st_mtime; 390 _from_class_path_attr = cpe->from_class_path_attr(); 391 } 392 _filesize = st.st_size; 393 _is_module_path = is_module_path; 394 } 395 } else { 396 // The file/dir must exist, or it would not have been added 397 // into ClassLoader::classpath_entry(). 398 // 399 // If we can't access a jar file in the boot path, then we can't 400 // make assumptions about where classes get loaded from. 401 log_error(cds)("Unable to open file %s.", cpe->name()); 402 MetaspaceShared::unrecoverable_loading_error(); 403 } 404 405 // No need to save the name of the module file, as it will be computed at run time 406 // to allow relocation of the JDK directory. 407 const char* name = is_modules_image ? "" : cpe->name(); 408 set_name(name, CHECK); 409 } 410 411 void SharedClassPathEntry::set_name(const char* name, TRAPS) { 412 size_t len = strlen(name) + 1; 413 _name = MetadataFactory::new_array<char>(ClassLoaderData::the_null_class_loader_data(), (int)len, CHECK); 414 strcpy(_name->data(), name); 415 } 416 417 void SharedClassPathEntry::copy_from(SharedClassPathEntry* ent, ClassLoaderData* loader_data, TRAPS) { 418 assert(ent != nullptr, "sanity"); 419 _type = ent->_type; 420 _is_module_path = ent->_is_module_path; 421 _timestamp = ent->_timestamp; 422 _filesize = ent->_filesize; 423 _from_class_path_attr = ent->_from_class_path_attr; 424 set_name(ent->name(), CHECK); 425 426 if (ent->is_jar() && ent->manifest() != nullptr) { 427 Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data, 428 ent->manifest_size(), 429 CHECK); 430 char* p = (char*)(buf->data()); 431 memcpy(p, ent->manifest(), ent->manifest_size()); 432 set_manifest(buf); 433 } 434 } 435 436 const char* SharedClassPathEntry::name() const { 437 if (UseSharedSpaces && is_modules_image()) { 438 // In order to validate the runtime modules image file size against the archived 439 // size information, we need to obtain the runtime modules image path. The recorded 440 // dump time modules image path in the archive may be different from the runtime path 441 // if the JDK image has beed moved after generating the archive. 442 return ClassLoader::get_jrt_entry()->name(); 443 } else { 444 return _name->data(); 445 } 446 } 447 448 bool SharedClassPathEntry::validate(bool is_class_path) const { 449 assert(UseSharedSpaces, "runtime only"); 450 451 struct stat st; 452 const char* name = this->name(); 453 454 bool ok = true; 455 log_info(class, path)("checking shared classpath entry: %s", name); 456 if (os::stat(name, &st) != 0 && is_class_path) { 457 // If the archived module path entry does not exist at runtime, it is not fatal 458 // (no need to invalid the shared archive) because the shared runtime visibility check 459 // filters out any archived module classes that do not have a matching runtime 460 // module path location. 461 log_warning(cds)("Required classpath entry does not exist: %s", name); 462 ok = false; 463 } else if (is_dir()) { 464 if (!os::dir_is_empty(name)) { 465 log_warning(cds)("directory is not empty: %s", name); 466 ok = false; 467 } 468 } else { 469 bool size_differs = _filesize != st.st_size; 470 bool time_differs = has_timestamp() && _timestamp != st.st_mtime; 471 if (time_differs || size_differs) { 472 ok = false; 473 if (PrintSharedArchiveAndExit) { 474 log_warning(cds)(time_differs ? "Timestamp mismatch" : "File size mismatch"); 475 } else { 476 const char* bad_file_msg = "This file is not the one used while building the shared archive file:"; 477 log_warning(cds)("%s %s", bad_file_msg, name); 478 if (!log_is_enabled(Info, cds)) { 479 log_warning(cds)("%s %s", bad_file_msg, name); 480 } 481 if (time_differs) { 482 log_warning(cds)("%s timestamp has changed.", name); 483 } 484 if (size_differs) { 485 log_warning(cds)("%s size has changed.", name); 486 } 487 } 488 } 489 } 490 491 if (PrintSharedArchiveAndExit && !ok) { 492 // If PrintSharedArchiveAndExit is enabled, don't report failure to the 493 // caller. Please see above comments for more details. 494 ok = true; 495 MetaspaceShared::set_archive_loading_failed(); 496 } 497 return ok; 498 } 499 500 bool SharedClassPathEntry::check_non_existent() const { 501 assert(_type == non_existent_entry, "must be"); 502 log_info(class, path)("should be non-existent: %s", name()); 503 struct stat st; 504 if (os::stat(name(), &st) != 0) { 505 log_info(class, path)("ok"); 506 return true; // file doesn't exist 507 } else { 508 return false; 509 } 510 } 511 512 void SharedClassPathEntry::metaspace_pointers_do(MetaspaceClosure* it) { 513 it->push(&_name); 514 it->push(&_manifest); 515 } 516 517 void SharedPathTable::metaspace_pointers_do(MetaspaceClosure* it) { 518 it->push(&_entries); 519 } 520 521 void SharedPathTable::dumptime_init(ClassLoaderData* loader_data, TRAPS) { 522 const int num_entries = 523 ClassLoader::num_boot_classpath_entries() + 524 ClassLoader::num_app_classpath_entries() + 525 ClassLoader::num_module_path_entries() + 526 FileMapInfo::num_non_existent_class_paths(); 527 _entries = MetadataFactory::new_array<SharedClassPathEntry*>(loader_data, num_entries, CHECK); 528 for (int i = 0; i < num_entries; i++) { 529 SharedClassPathEntry* ent = 530 new (loader_data, SharedClassPathEntry::size(), MetaspaceObj::SharedClassPathEntryType, THREAD) SharedClassPathEntry; 531 _entries->at_put(i, ent); 532 } 533 } 534 535 void FileMapInfo::allocate_shared_path_table(TRAPS) { 536 assert(CDSConfig::is_dumping_archive(), "sanity"); 537 538 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data(); 539 ClassPathEntry* jrt = ClassLoader::get_jrt_entry(); 540 541 assert(jrt != nullptr, 542 "No modular java runtime image present when allocating the CDS classpath entry table"); 543 544 _shared_path_table.dumptime_init(loader_data, CHECK); 545 546 // 1. boot class path 547 int i = 0; 548 i = add_shared_classpaths(i, "boot", jrt, CHECK); 549 i = add_shared_classpaths(i, "app", ClassLoader::app_classpath_entries(), CHECK); 550 i = add_shared_classpaths(i, "module", ClassLoader::module_path_entries(), CHECK); 551 552 for (int x = 0; x < num_non_existent_class_paths(); x++, i++) { 553 const char* path = _non_existent_class_paths->at(x); 554 shared_path(i)->init_as_non_existent(path, CHECK); 555 } 556 557 assert(i == _shared_path_table.size(), "number of shared path entry mismatch"); 558 } 559 560 int FileMapInfo::add_shared_classpaths(int i, const char* which, ClassPathEntry *cpe, TRAPS) { 561 while (cpe != nullptr) { 562 bool is_jrt = (cpe == ClassLoader::get_jrt_entry()); 563 bool is_module_path = i >= ClassLoaderExt::app_module_paths_start_index(); 564 const char* type = (is_jrt ? "jrt" : (cpe->is_jar_file() ? "jar" : "dir")); 565 log_info(class, path)("add %s shared path (%s) %s", which, type, cpe->name()); 566 SharedClassPathEntry* ent = shared_path(i); 567 ent->init(is_jrt, is_module_path, cpe, CHECK_0); 568 if (cpe->is_jar_file()) { 569 update_jar_manifest(cpe, ent, CHECK_0); 570 } 571 if (is_jrt) { 572 cpe = ClassLoader::get_next_boot_classpath_entry(cpe); 573 } else { 574 cpe = cpe->next(); 575 } 576 i++; 577 } 578 579 return i; 580 } 581 582 void FileMapInfo::check_nonempty_dir_in_shared_path_table() { 583 assert(CDSConfig::is_dumping_archive(), "sanity"); 584 585 bool has_nonempty_dir = false; 586 587 int last = _shared_path_table.size() - 1; 588 if (last > ClassLoaderExt::max_used_path_index()) { 589 // no need to check any path beyond max_used_path_index 590 last = ClassLoaderExt::max_used_path_index(); 591 } 592 593 for (int i = 0; i <= last; i++) { 594 SharedClassPathEntry *e = shared_path(i); 595 if (e->is_dir()) { 596 const char* path = e->name(); 597 if (!os::dir_is_empty(path)) { 598 log_error(cds)("Error: non-empty directory '%s'", path); 599 has_nonempty_dir = true; 600 } 601 } 602 } 603 604 if (has_nonempty_dir) { 605 ClassLoader::exit_with_path_failure("Cannot have non-empty directory in paths", nullptr); 606 } 607 } 608 609 void FileMapInfo::record_non_existent_class_path_entry(const char* path) { 610 assert(CDSConfig::is_dumping_archive(), "sanity"); 611 log_info(class, path)("non-existent Class-Path entry %s", path); 612 if (_non_existent_class_paths == nullptr) { 613 _non_existent_class_paths = new (mtClass) GrowableArray<const char*>(10, mtClass); 614 } 615 _non_existent_class_paths->append(os::strdup(path)); 616 } 617 618 int FileMapInfo::num_non_existent_class_paths() { 619 assert(CDSConfig::is_dumping_archive(), "sanity"); 620 if (_non_existent_class_paths != nullptr) { 621 return _non_existent_class_paths->length(); 622 } else { 623 return 0; 624 } 625 } 626 627 int FileMapInfo::get_module_shared_path_index(Symbol* location) { 628 if (location->starts_with("jrt:", 4) && get_number_of_shared_paths() > 0) { 629 assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image"); 630 return 0; 631 } 632 633 if (ClassLoaderExt::app_module_paths_start_index() >= get_number_of_shared_paths()) { 634 // The archive(s) were created without --module-path option 635 return -1; 636 } 637 638 if (!location->starts_with("file:", 5)) { 639 return -1; 640 } 641 642 // skip_uri_protocol was also called during dump time -- see ClassLoaderExt::process_module_table() 643 ResourceMark rm; 644 const char* file = ClassLoader::skip_uri_protocol(location->as_C_string()); 645 for (int i = ClassLoaderExt::app_module_paths_start_index(); i < get_number_of_shared_paths(); i++) { 646 SharedClassPathEntry* ent = shared_path(i); 647 assert(ent->in_named_module(), "must be"); 648 bool cond = strcmp(file, ent->name()) == 0; 649 log_debug(class, path)("get_module_shared_path_index (%d) %s : %s = %s", i, 650 location->as_C_string(), ent->name(), cond ? "same" : "different"); 651 if (cond) { 652 return i; 653 } 654 } 655 656 return -1; 657 } 658 659 class ManifestStream: public ResourceObj { 660 private: 661 u1* _buffer_start; // Buffer bottom 662 u1* _buffer_end; // Buffer top (one past last element) 663 u1* _current; // Current buffer position 664 665 public: 666 // Constructor 667 ManifestStream(u1* buffer, int length) : _buffer_start(buffer), 668 _current(buffer) { 669 _buffer_end = buffer + length; 670 } 671 672 static bool is_attr(u1* attr, const char* name) { 673 return strncmp((const char*)attr, name, strlen(name)) == 0; 674 } 675 676 static char* copy_attr(u1* value, size_t len) { 677 char* buf = NEW_RESOURCE_ARRAY(char, len + 1); 678 strncpy(buf, (char*)value, len); 679 buf[len] = 0; 680 return buf; 681 } 682 }; 683 684 void FileMapInfo::update_jar_manifest(ClassPathEntry *cpe, SharedClassPathEntry* ent, TRAPS) { 685 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data(); 686 ResourceMark rm(THREAD); 687 jint manifest_size; 688 689 assert(cpe->is_jar_file() && ent->is_jar(), "the shared class path entry is not a JAR file"); 690 char* manifest = ClassLoaderExt::read_manifest(THREAD, cpe, &manifest_size); 691 if (manifest != nullptr) { 692 ManifestStream* stream = new ManifestStream((u1*)manifest, 693 manifest_size); 694 // Copy the manifest into the shared archive 695 manifest = ClassLoaderExt::read_raw_manifest(THREAD, cpe, &manifest_size); 696 Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data, 697 manifest_size, 698 CHECK); 699 char* p = (char*)(buf->data()); 700 memcpy(p, manifest, manifest_size); 701 ent->set_manifest(buf); 702 } 703 } 704 705 char* FileMapInfo::skip_first_path_entry(const char* path) { 706 size_t path_sep_len = strlen(os::path_separator()); 707 char* p = strstr((char*)path, os::path_separator()); 708 if (p != nullptr) { 709 debug_only( { 710 size_t image_name_len = strlen(MODULES_IMAGE_NAME); 711 assert(strncmp(p - image_name_len, MODULES_IMAGE_NAME, image_name_len) == 0, 712 "first entry must be the modules image"); 713 } ); 714 p += path_sep_len; 715 } else { 716 debug_only( { 717 assert(ClassLoader::string_ends_with(path, MODULES_IMAGE_NAME), 718 "first entry must be the modules image"); 719 } ); 720 } 721 return p; 722 } 723 724 int FileMapInfo::num_paths(const char* path) { 725 if (path == nullptr) { 726 return 0; 727 } 728 int npaths = 1; 729 char* p = (char*)path; 730 while (p != nullptr) { 731 char* prev = p; 732 p = strstr((char*)p, os::path_separator()); 733 if (p != nullptr) { 734 p++; 735 // don't count empty path 736 if ((p - prev) > 1) { 737 npaths++; 738 } 739 } 740 } 741 return npaths; 742 } 743 744 // Returns true if a path within the paths exists and has non-zero size. 745 bool FileMapInfo::check_paths_existence(const char* paths) { 746 ClasspathStream cp_stream(paths); 747 bool exist = false; 748 struct stat st; 749 while (cp_stream.has_next()) { 750 const char* path = cp_stream.get_next(); 751 if (os::stat(path, &st) == 0 && st.st_size > 0) { 752 exist = true; 753 break; 754 } 755 } 756 return exist; 757 } 758 759 GrowableArray<const char*>* FileMapInfo::create_dumptime_app_classpath_array() { 760 assert(CDSConfig::is_dumping_archive(), "sanity"); 761 GrowableArray<const char*>* path_array = new GrowableArray<const char*>(10); 762 ClassPathEntry* cpe = ClassLoader::app_classpath_entries(); 763 while (cpe != nullptr) { 764 path_array->append(cpe->name()); 765 cpe = cpe->next(); 766 } 767 return path_array; 768 } 769 770 GrowableArray<const char*>* FileMapInfo::create_path_array(const char* paths) { 771 GrowableArray<const char*>* path_array = new GrowableArray<const char*>(10); 772 JavaThread* current = JavaThread::current(); 773 ClasspathStream cp_stream(paths); 774 bool non_jar_in_cp = header()->has_non_jar_in_classpath(); 775 while (cp_stream.has_next()) { 776 const char* path = cp_stream.get_next(); 777 if (!non_jar_in_cp) { 778 struct stat st; 779 if (os::stat(path, &st) == 0) { 780 path_array->append(path); 781 } 782 } else { 783 const char* canonical_path = ClassLoader::get_canonical_path(path, current); 784 if (canonical_path != nullptr) { 785 char* error_msg = nullptr; 786 jzfile* zip = ClassLoader::open_zip_file(canonical_path, &error_msg, current); 787 if (zip != nullptr && error_msg == nullptr) { 788 path_array->append(path); 789 } 790 } 791 } 792 } 793 return path_array; 794 } 795 796 bool FileMapInfo::classpath_failure(const char* msg, const char* name) { 797 ClassLoader::trace_class_path(msg, name); 798 if (PrintSharedArchiveAndExit) { 799 MetaspaceShared::set_archive_loading_failed(); 800 } 801 return false; 802 } 803 804 unsigned int FileMapInfo::longest_common_app_classpath_prefix_len(int num_paths, 805 GrowableArray<const char*>* rp_array) { 806 if (num_paths == 0) { 807 return 0; 808 } 809 unsigned int pos; 810 for (pos = 0; ; pos++) { 811 for (int i = 0; i < num_paths; i++) { 812 if (rp_array->at(i)[pos] != '\0' && rp_array->at(i)[pos] == rp_array->at(0)[pos]) { 813 continue; 814 } 815 // search backward for the pos before the file separator char 816 while (pos > 0) { 817 if (rp_array->at(0)[--pos] == *os::file_separator()) { 818 return pos + 1; 819 } 820 } 821 return 0; 822 } 823 } 824 return 0; 825 } 826 827 bool FileMapInfo::check_paths(int shared_path_start_idx, int num_paths, GrowableArray<const char*>* rp_array, 828 unsigned int dumptime_prefix_len, unsigned int runtime_prefix_len) { 829 int i = 0; 830 int j = shared_path_start_idx; 831 while (i < num_paths) { 832 while (shared_path(j)->from_class_path_attr()) { 833 // shared_path(j) was expanded from the JAR file attribute "Class-Path:" 834 // during dump time. It's not included in the -classpath VM argument. 835 j++; 836 } 837 assert(strlen(shared_path(j)->name()) > (size_t)dumptime_prefix_len, "sanity"); 838 const char* dumptime_path = shared_path(j)->name() + dumptime_prefix_len; 839 assert(strlen(rp_array->at(i)) > (size_t)runtime_prefix_len, "sanity"); 840 const char* runtime_path = rp_array->at(i) + runtime_prefix_len; 841 if (!os::same_files(dumptime_path, runtime_path)) { 842 return true; 843 } 844 i++; 845 j++; 846 } 847 return false; 848 } 849 850 bool FileMapInfo::validate_boot_class_paths() { 851 // 852 // - Archive contains boot classes only - relaxed boot path check: 853 // Extra path elements appended to the boot path at runtime are allowed. 854 // 855 // - Archive contains application or platform classes - strict boot path check: 856 // Validate the entire runtime boot path, which must be compatible 857 // with the dump time boot path. Appending boot path at runtime is not 858 // allowed. 859 // 860 861 // The first entry in boot path is the modules_image (guaranteed by 862 // ClassLoader::setup_boot_search_path()). Skip the first entry. The 863 // path of the runtime modules_image may be different from the dump 864 // time path (e.g. the JDK image is copied to a different location 865 // after generating the shared archive), which is acceptable. For most 866 // common cases, the dump time boot path might contain modules_image only. 867 char* runtime_boot_path = Arguments::get_boot_class_path(); 868 char* rp = skip_first_path_entry(runtime_boot_path); 869 assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image"); 870 int dp_len = header()->app_class_paths_start_index() - 1; // ignore the first path to the module image 871 bool mismatch = false; 872 873 bool relaxed_check = !header()->has_platform_or_app_classes(); 874 if (dp_len == 0 && rp == nullptr) { 875 return true; // ok, both runtime and dump time boot paths have modules_images only 876 } else if (dp_len == 0 && rp != nullptr) { 877 if (relaxed_check) { 878 return true; // ok, relaxed check, runtime has extra boot append path entries 879 } else { 880 ResourceMark rm; 881 if (check_paths_existence(rp)) { 882 // If a path exists in the runtime boot paths, it is considered a mismatch 883 // since there's no boot path specified during dump time. 884 mismatch = true; 885 } 886 } 887 } else if (dp_len > 0 && rp != nullptr) { 888 int num; 889 ResourceMark rm; 890 GrowableArray<const char*>* rp_array = create_path_array(rp); 891 int rp_len = rp_array->length(); 892 if (rp_len >= dp_len) { 893 if (relaxed_check) { 894 // only check the leading entries in the runtime boot path, up to 895 // the length of the dump time boot path 896 num = dp_len; 897 } else { 898 // check the full runtime boot path, must match with dump time 899 num = rp_len; 900 } 901 mismatch = check_paths(1, num, rp_array, 0, 0); 902 } else { 903 // create_path_array() ignores non-existing paths. Although the dump time and runtime boot classpath lengths 904 // are the same initially, after the call to create_path_array(), the runtime boot classpath length could become 905 // shorter. We consider boot classpath mismatch in this case. 906 mismatch = true; 907 } 908 } 909 910 if (mismatch) { 911 // The paths are different 912 return classpath_failure("[BOOT classpath mismatch, actual =", runtime_boot_path); 913 } 914 return true; 915 } 916 917 bool FileMapInfo::validate_app_class_paths(int shared_app_paths_len) { 918 const char *appcp = Arguments::get_appclasspath(); 919 assert(appcp != nullptr, "null app classpath"); 920 int rp_len = num_paths(appcp); 921 bool mismatch = false; 922 if (rp_len < shared_app_paths_len) { 923 return classpath_failure("Run time APP classpath is shorter than the one at dump time: ", appcp); 924 } 925 if (shared_app_paths_len != 0 && rp_len != 0) { 926 // Prefix is OK: E.g., dump with -cp foo.jar, but run with -cp foo.jar:bar.jar. 927 ResourceMark rm; 928 GrowableArray<const char*>* rp_array = create_path_array(appcp); 929 if (rp_array->length() == 0) { 930 // None of the jar file specified in the runtime -cp exists. 931 return classpath_failure("None of the jar file specified in the runtime -cp exists: -Djava.class.path=", appcp); 932 } 933 if (rp_array->length() < shared_app_paths_len) { 934 // create_path_array() ignores non-existing paths. Although the dump time and runtime app classpath lengths 935 // are the same initially, after the call to create_path_array(), the runtime app classpath length could become 936 // shorter. We consider app classpath mismatch in this case. 937 return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp); 938 } 939 940 // Handling of non-existent entries in the classpath: we eliminate all the non-existent 941 // entries from both the dump time classpath (ClassLoader::update_class_path_entry_list) 942 // and the runtime classpath (FileMapInfo::create_path_array), and check the remaining 943 // entries. E.g.: 944 // 945 // dump : -cp a.jar:NE1:NE2:b.jar -> a.jar:b.jar -> recorded in archive. 946 // run 1: -cp NE3:a.jar:NE4:b.jar -> a.jar:b.jar -> matched 947 // run 2: -cp x.jar:NE4:b.jar -> x.jar:b.jar -> mismatched 948 949 int j = header()->app_class_paths_start_index(); 950 mismatch = check_paths(j, shared_app_paths_len, rp_array, 0, 0); 951 if (mismatch) { 952 // To facilitate app deployment, we allow the JAR files to be moved *together* to 953 // a different location, as long as they are still stored under the same directory 954 // structure. E.g., the following is OK. 955 // java -Xshare:dump -cp /a/Foo.jar:/a/b/Bar.jar ... 956 // java -Xshare:auto -cp /x/y/Foo.jar:/x/y/b/Bar.jar ... 957 unsigned int dumptime_prefix_len = header()->common_app_classpath_prefix_size(); 958 unsigned int runtime_prefix_len = longest_common_app_classpath_prefix_len(shared_app_paths_len, rp_array); 959 if (dumptime_prefix_len != 0 || runtime_prefix_len != 0) { 960 log_info(class, path)("LCP length for app classpath (dumptime: %u, runtime: %u)", 961 dumptime_prefix_len, runtime_prefix_len); 962 mismatch = check_paths(j, shared_app_paths_len, rp_array, 963 dumptime_prefix_len, runtime_prefix_len); 964 } 965 if (mismatch) { 966 return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp); 967 } 968 } 969 } 970 return true; 971 } 972 973 void FileMapInfo::log_paths(const char* msg, int start_idx, int end_idx) { 974 LogTarget(Info, class, path) lt; 975 if (lt.is_enabled()) { 976 LogStream ls(lt); 977 ls.print("%s", msg); 978 const char* prefix = ""; 979 for (int i = start_idx; i < end_idx; i++) { 980 ls.print("%s%s", prefix, shared_path(i)->name()); 981 prefix = os::path_separator(); 982 } 983 ls.cr(); 984 } 985 } 986 987 bool FileMapInfo::check_module_paths() { 988 const char* rp = Arguments::get_property("jdk.module.path"); 989 int num_paths = CDSConfig::num_archives(rp); 990 if (num_paths != header()->num_module_paths()) { 991 return false; 992 } 993 ResourceMark rm; 994 GrowableArray<const char*>* rp_array = create_path_array(rp); 995 return check_paths(header()->app_module_paths_start_index(), num_paths, rp_array, 0, 0); 996 } 997 998 bool FileMapInfo::validate_shared_path_table() { 999 assert(UseSharedSpaces, "runtime only"); 1000 1001 _validating_shared_path_table = true; 1002 1003 // Load the shared path table info from the archive header 1004 _shared_path_table = header()->shared_path_table(); 1005 if (CDSConfig::is_dumping_dynamic_archive()) { 1006 // Only support dynamic dumping with the usage of the default CDS archive 1007 // or a simple base archive. 1008 // If the base layer archive contains additional path component besides 1009 // the runtime image and the -cp, dynamic dumping is disabled. 1010 // 1011 // When dynamic archiving is enabled, the _shared_path_table is overwritten 1012 // to include the application path and stored in the top layer archive. 1013 assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image"); 1014 if (header()->app_class_paths_start_index() > 1) { 1015 CDSConfig::disable_dumping_dynamic_archive(); 1016 log_warning(cds)( 1017 "Dynamic archiving is disabled because base layer archive has appended boot classpath"); 1018 } 1019 if (header()->num_module_paths() > 0) { 1020 if (!check_module_paths()) { 1021 CDSConfig::disable_dumping_dynamic_archive(); 1022 log_warning(cds)( 1023 "Dynamic archiving is disabled because base layer archive has a different module path"); 1024 } 1025 } 1026 } 1027 1028 log_paths("Expecting BOOT path=", 0, header()->app_class_paths_start_index()); 1029 log_paths("Expecting -Djava.class.path=", header()->app_class_paths_start_index(), header()->app_module_paths_start_index()); 1030 1031 int module_paths_start_index = header()->app_module_paths_start_index(); 1032 int shared_app_paths_len = 0; 1033 1034 // validate the path entries up to the _max_used_path_index 1035 for (int i=0; i < header()->max_used_path_index() + 1; i++) { 1036 if (i < module_paths_start_index) { 1037 if (shared_path(i)->validate()) { 1038 // Only count the app class paths not from the "Class-path" attribute of a jar manifest. 1039 if (!shared_path(i)->from_class_path_attr() && i >= header()->app_class_paths_start_index()) { 1040 shared_app_paths_len++; 1041 } 1042 log_info(class, path)("ok"); 1043 } else { 1044 if (_dynamic_archive_info != nullptr && _dynamic_archive_info->_is_static) { 1045 assert(!UseSharedSpaces, "UseSharedSpaces should be disabled"); 1046 } 1047 return false; 1048 } 1049 } else if (i >= module_paths_start_index) { 1050 if (shared_path(i)->validate(false /* not a class path entry */)) { 1051 log_info(class, path)("ok"); 1052 } else { 1053 if (_dynamic_archive_info != nullptr && _dynamic_archive_info->_is_static) { 1054 assert(!UseSharedSpaces, "UseSharedSpaces should be disabled"); 1055 } 1056 return false; 1057 } 1058 } 1059 } 1060 1061 if (header()->max_used_path_index() == 0) { 1062 // default archive only contains the module image in the bootclasspath 1063 assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image"); 1064 } else { 1065 if (!validate_boot_class_paths() || !validate_app_class_paths(shared_app_paths_len)) { 1066 const char* mismatch_msg = "shared class paths mismatch"; 1067 const char* hint_msg = log_is_enabled(Info, class, path) ? 1068 "" : " (hint: enable -Xlog:class+path=info to diagnose the failure)"; 1069 if (RequireSharedSpaces) { 1070 log_error(cds)("%s%s", mismatch_msg, hint_msg); 1071 MetaspaceShared::unrecoverable_loading_error(); 1072 } else { 1073 log_warning(cds)("%s%s", mismatch_msg, hint_msg); 1074 } 1075 return false; 1076 } 1077 } 1078 1079 validate_non_existent_class_paths(); 1080 1081 _validating_shared_path_table = false; 1082 1083 #if INCLUDE_JVMTI 1084 if (_classpath_entries_for_jvmti != nullptr) { 1085 os::free(_classpath_entries_for_jvmti); 1086 } 1087 size_t sz = sizeof(ClassPathEntry*) * get_number_of_shared_paths(); 1088 _classpath_entries_for_jvmti = (ClassPathEntry**)os::malloc(sz, mtClass); 1089 memset((void*)_classpath_entries_for_jvmti, 0, sz); 1090 #endif 1091 1092 return true; 1093 } 1094 1095 void FileMapInfo::validate_non_existent_class_paths() { 1096 // All of the recorded non-existent paths came from the Class-Path: attribute from the JAR 1097 // files on the app classpath. If any of these are found to exist during runtime, 1098 // it will change how classes are loading for the app loader. For safety, disable 1099 // loading of archived platform/app classes (currently there's no way to disable just the 1100 // app classes). 1101 1102 assert(UseSharedSpaces, "runtime only"); 1103 for (int i = header()->app_module_paths_start_index() + header()->num_module_paths(); 1104 i < get_number_of_shared_paths(); 1105 i++) { 1106 SharedClassPathEntry* ent = shared_path(i); 1107 if (!ent->check_non_existent()) { 1108 log_warning(cds)("Archived non-system classes are disabled because the " 1109 "file %s exists", ent->name()); 1110 header()->set_has_platform_or_app_classes(false); 1111 } 1112 } 1113 } 1114 1115 // A utility class for reading/validating the GenericCDSFileMapHeader portion of 1116 // a CDS archive's header. The file header of all CDS archives with versions from 1117 // CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION (12) are guaranteed to always start 1118 // with GenericCDSFileMapHeader. This makes it possible to read important information 1119 // from a CDS archive created by a different version of HotSpot, so that we can 1120 // automatically regenerate the archive as necessary (JDK-8261455). 1121 class FileHeaderHelper { 1122 int _fd; 1123 bool _is_valid; 1124 bool _is_static; 1125 GenericCDSFileMapHeader* _header; 1126 const char* _archive_name; 1127 const char* _base_archive_name; 1128 1129 public: 1130 FileHeaderHelper(const char* archive_name, bool is_static) { 1131 _fd = -1; 1132 _is_valid = false; 1133 _header = nullptr; 1134 _base_archive_name = nullptr; 1135 _archive_name = archive_name; 1136 _is_static = is_static; 1137 } 1138 1139 ~FileHeaderHelper() { 1140 if (_header != nullptr) { 1141 FREE_C_HEAP_ARRAY(char, _header); 1142 } 1143 if (_fd != -1) { 1144 ::close(_fd); 1145 } 1146 } 1147 1148 bool initialize() { 1149 assert(_archive_name != nullptr, "Archive name is null"); 1150 _fd = os::open(_archive_name, O_RDONLY | O_BINARY, 0); 1151 if (_fd < 0) { 1152 log_info(cds)("Specified shared archive not found (%s)", _archive_name); 1153 return false; 1154 } 1155 return initialize(_fd); 1156 } 1157 1158 // for an already opened file, do not set _fd 1159 bool initialize(int fd) { 1160 assert(_archive_name != nullptr, "Archive name is null"); 1161 assert(fd != -1, "Archive must be opened already"); 1162 // First read the generic header so we know the exact size of the actual header. 1163 GenericCDSFileMapHeader gen_header; 1164 size_t size = sizeof(GenericCDSFileMapHeader); 1165 os::lseek(fd, 0, SEEK_SET); 1166 size_t n = ::read(fd, (void*)&gen_header, (unsigned int)size); 1167 if (n != size) { 1168 log_warning(cds)("Unable to read generic CDS file map header from shared archive"); 1169 return false; 1170 } 1171 1172 if (gen_header._magic != CDS_ARCHIVE_MAGIC && 1173 gen_header._magic != CDS_DYNAMIC_ARCHIVE_MAGIC) { 1174 log_warning(cds)("The shared archive file has a bad magic number: %#x", gen_header._magic); 1175 return false; 1176 } 1177 1178 if (gen_header._version < CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION) { 1179 log_warning(cds)("Cannot handle shared archive file version 0x%x. Must be at least 0x%x.", 1180 gen_header._version, CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION); 1181 return false; 1182 } 1183 1184 if (gen_header._version != CURRENT_CDS_ARCHIVE_VERSION) { 1185 log_warning(cds)("The shared archive file version 0x%x does not match the required version 0x%x.", 1186 gen_header._version, CURRENT_CDS_ARCHIVE_VERSION); 1187 } 1188 1189 size_t filelen = os::lseek(fd, 0, SEEK_END); 1190 if (gen_header._header_size >= filelen) { 1191 log_warning(cds)("Archive file header larger than archive file"); 1192 return false; 1193 } 1194 1195 // Read the actual header and perform more checks 1196 size = gen_header._header_size; 1197 _header = (GenericCDSFileMapHeader*)NEW_C_HEAP_ARRAY(char, size, mtInternal); 1198 os::lseek(fd, 0, SEEK_SET); 1199 n = ::read(fd, (void*)_header, (unsigned int)size); 1200 if (n != size) { 1201 log_warning(cds)("Unable to read actual CDS file map header from shared archive"); 1202 return false; 1203 } 1204 1205 if (!check_header_crc()) { 1206 return false; 1207 } 1208 1209 if (!check_and_init_base_archive_name()) { 1210 return false; 1211 } 1212 1213 // All fields in the GenericCDSFileMapHeader has been validated. 1214 _is_valid = true; 1215 return true; 1216 } 1217 1218 GenericCDSFileMapHeader* get_generic_file_header() { 1219 assert(_header != nullptr && _is_valid, "must be a valid archive file"); 1220 return _header; 1221 } 1222 1223 const char* base_archive_name() { 1224 assert(_header != nullptr && _is_valid, "must be a valid archive file"); 1225 return _base_archive_name; 1226 } 1227 1228 private: 1229 bool check_header_crc() const { 1230 if (VerifySharedSpaces) { 1231 FileMapHeader* header = (FileMapHeader*)_header; 1232 int actual_crc = header->compute_crc(); 1233 if (actual_crc != header->crc()) { 1234 log_info(cds)("_crc expected: %d", header->crc()); 1235 log_info(cds)(" actual: %d", actual_crc); 1236 log_warning(cds)("Header checksum verification failed."); 1237 return false; 1238 } 1239 } 1240 return true; 1241 } 1242 1243 bool check_and_init_base_archive_name() { 1244 unsigned int name_offset = _header->_base_archive_name_offset; 1245 unsigned int name_size = _header->_base_archive_name_size; 1246 unsigned int header_size = _header->_header_size; 1247 1248 if (name_offset + name_size < name_offset) { 1249 log_warning(cds)("base_archive_name offset/size overflow: " UINT32_FORMAT "/" UINT32_FORMAT, 1250 name_offset, name_size); 1251 return false; 1252 } 1253 if (_header->_magic == CDS_ARCHIVE_MAGIC) { 1254 if (name_offset != 0) { 1255 log_warning(cds)("static shared archive must have zero _base_archive_name_offset"); 1256 return false; 1257 } 1258 if (name_size != 0) { 1259 log_warning(cds)("static shared archive must have zero _base_archive_name_size"); 1260 return false; 1261 } 1262 } else { 1263 assert(_header->_magic == CDS_DYNAMIC_ARCHIVE_MAGIC, "must be"); 1264 if ((name_size == 0 && name_offset != 0) || 1265 (name_size != 0 && name_offset == 0)) { 1266 // If either is zero, both must be zero. This indicates that we are using the default base archive. 1267 log_warning(cds)("Invalid base_archive_name offset/size: " UINT32_FORMAT "/" UINT32_FORMAT, 1268 name_offset, name_size); 1269 return false; 1270 } 1271 if (name_size > 0) { 1272 if (name_offset + name_size > header_size) { 1273 log_warning(cds)("Invalid base_archive_name offset/size (out of range): " 1274 UINT32_FORMAT " + " UINT32_FORMAT " > " UINT32_FORMAT , 1275 name_offset, name_size, header_size); 1276 return false; 1277 } 1278 const char* name = ((const char*)_header) + _header->_base_archive_name_offset; 1279 if (name[name_size - 1] != '\0' || strlen(name) != name_size - 1) { 1280 log_warning(cds)("Base archive name is damaged"); 1281 return false; 1282 } 1283 if (!os::file_exists(name)) { 1284 log_warning(cds)("Base archive %s does not exist", name); 1285 return false; 1286 } 1287 _base_archive_name = name; 1288 } 1289 } 1290 1291 return true; 1292 } 1293 }; 1294 1295 // Return value: 1296 // false: 1297 // <archive_name> is not a valid archive. *base_archive_name is set to null. 1298 // true && (*base_archive_name) == nullptr: 1299 // <archive_name> is a valid static archive. 1300 // true && (*base_archive_name) != nullptr: 1301 // <archive_name> is a valid dynamic archive. 1302 bool FileMapInfo::get_base_archive_name_from_header(const char* archive_name, 1303 char** base_archive_name) { 1304 FileHeaderHelper file_helper(archive_name, false); 1305 *base_archive_name = nullptr; 1306 1307 if (!file_helper.initialize()) { 1308 return false; 1309 } 1310 GenericCDSFileMapHeader* header = file_helper.get_generic_file_header(); 1311 if (header->_magic != CDS_DYNAMIC_ARCHIVE_MAGIC) { 1312 assert(header->_magic == CDS_ARCHIVE_MAGIC, "must be"); 1313 if (AutoCreateSharedArchive) { 1314 log_warning(cds)("AutoCreateSharedArchive is ignored because %s is a static archive", archive_name); 1315 } 1316 return true; 1317 } 1318 1319 const char* base = file_helper.base_archive_name(); 1320 if (base == nullptr) { 1321 *base_archive_name = CDSConfig::default_archive_path(); 1322 } else { 1323 *base_archive_name = os::strdup_check_oom(base); 1324 } 1325 1326 return true; 1327 } 1328 1329 // Read the FileMapInfo information from the file. 1330 1331 bool FileMapInfo::init_from_file(int fd) { 1332 FileHeaderHelper file_helper(_full_path, _is_static); 1333 if (!file_helper.initialize(fd)) { 1334 log_warning(cds)("Unable to read the file header."); 1335 return false; 1336 } 1337 GenericCDSFileMapHeader* gen_header = file_helper.get_generic_file_header(); 1338 1339 if (_is_static) { 1340 if (gen_header->_magic != CDS_ARCHIVE_MAGIC) { 1341 log_warning(cds)("Not a base shared archive: %s", _full_path); 1342 return false; 1343 } 1344 } else { 1345 if (gen_header->_magic != CDS_DYNAMIC_ARCHIVE_MAGIC) { 1346 log_warning(cds)("Not a top shared archive: %s", _full_path); 1347 return false; 1348 } 1349 } 1350 1351 _header = (FileMapHeader*)os::malloc(gen_header->_header_size, mtInternal); 1352 os::lseek(fd, 0, SEEK_SET); // reset to begin of the archive 1353 size_t size = gen_header->_header_size; 1354 size_t n = ::read(fd, (void*)_header, (unsigned int)size); 1355 if (n != size) { 1356 log_warning(cds)("Failed to read file header from the top archive file\n"); 1357 return false; 1358 } 1359 1360 if (header()->version() != CURRENT_CDS_ARCHIVE_VERSION) { 1361 log_info(cds)("_version expected: 0x%x", CURRENT_CDS_ARCHIVE_VERSION); 1362 log_info(cds)(" actual: 0x%x", header()->version()); 1363 log_warning(cds)("The shared archive file has the wrong version."); 1364 return false; 1365 } 1366 1367 int common_path_size = header()->common_app_classpath_prefix_size(); 1368 if (common_path_size < 0) { 1369 log_warning(cds)("common app classpath prefix len < 0"); 1370 return false; 1371 } 1372 1373 unsigned int base_offset = header()->base_archive_name_offset(); 1374 unsigned int name_size = header()->base_archive_name_size(); 1375 unsigned int header_size = header()->header_size(); 1376 if (base_offset != 0 && name_size != 0) { 1377 if (header_size != base_offset + name_size) { 1378 log_info(cds)("_header_size: " UINT32_FORMAT, header_size); 1379 log_info(cds)("common_app_classpath_size: " UINT32_FORMAT, header()->common_app_classpath_prefix_size()); 1380 log_info(cds)("base_archive_name_size: " UINT32_FORMAT, header()->base_archive_name_size()); 1381 log_info(cds)("base_archive_name_offset: " UINT32_FORMAT, header()->base_archive_name_offset()); 1382 log_warning(cds)("The shared archive file has an incorrect header size."); 1383 return false; 1384 } 1385 } 1386 1387 const char* actual_ident = header()->jvm_ident(); 1388 1389 if (actual_ident[JVM_IDENT_MAX-1] != 0) { 1390 log_warning(cds)("JVM version identifier is corrupted."); 1391 return false; 1392 } 1393 1394 char expected_ident[JVM_IDENT_MAX]; 1395 get_header_version(expected_ident); 1396 if (strncmp(actual_ident, expected_ident, JVM_IDENT_MAX-1) != 0) { 1397 log_info(cds)("_jvm_ident expected: %s", expected_ident); 1398 log_info(cds)(" actual: %s", actual_ident); 1399 log_warning(cds)("The shared archive file was created by a different" 1400 " version or build of HotSpot"); 1401 return false; 1402 } 1403 1404 _file_offset = header()->header_size(); // accounts for the size of _base_archive_name 1405 1406 size_t len = os::lseek(fd, 0, SEEK_END); 1407 1408 for (int i = 0; i < MetaspaceShared::n_regions; i++) { 1409 FileMapRegion* r = region_at(i); 1410 if (r->file_offset() > len || len - r->file_offset() < r->used()) { 1411 log_warning(cds)("The shared archive file has been truncated."); 1412 return false; 1413 } 1414 } 1415 1416 if (!header()->check_must_match_flags()) { 1417 return false; 1418 } 1419 1420 return true; 1421 } 1422 1423 void FileMapInfo::seek_to_position(size_t pos) { 1424 if (os::lseek(_fd, (long)pos, SEEK_SET) < 0) { 1425 log_error(cds)("Unable to seek to position " SIZE_FORMAT, pos); 1426 MetaspaceShared::unrecoverable_loading_error(); 1427 } 1428 } 1429 1430 // Read the FileMapInfo information from the file. 1431 bool FileMapInfo::open_for_read() { 1432 if (_file_open) { 1433 return true; 1434 } 1435 log_info(cds)("trying to map %s", _full_path); 1436 int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0); 1437 if (fd < 0) { 1438 if (errno == ENOENT) { 1439 log_info(cds)("Specified shared archive not found (%s)", _full_path); 1440 } else { 1441 log_warning(cds)("Failed to open shared archive file (%s)", 1442 os::strerror(errno)); 1443 } 1444 return false; 1445 } else { 1446 log_info(cds)("Opened archive %s.", _full_path); 1447 } 1448 1449 _fd = fd; 1450 _file_open = true; 1451 return true; 1452 } 1453 1454 // Write the FileMapInfo information to the file. 1455 1456 void FileMapInfo::open_for_write() { 1457 LogMessage(cds) msg; 1458 if (msg.is_info()) { 1459 msg.info("Dumping shared data to file: "); 1460 msg.info(" %s", _full_path); 1461 } 1462 1463 #ifdef _WINDOWS // On Windows, need WRITE permission to remove the file. 1464 chmod(_full_path, _S_IREAD | _S_IWRITE); 1465 #endif 1466 1467 // Use remove() to delete the existing file because, on Unix, this will 1468 // allow processes that have it open continued access to the file. 1469 remove(_full_path); 1470 int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444); 1471 if (fd < 0) { 1472 log_error(cds)("Unable to create shared archive file %s: (%s).", _full_path, 1473 os::strerror(errno)); 1474 MetaspaceShared::unrecoverable_writing_error(); 1475 } 1476 _fd = fd; 1477 _file_open = true; 1478 1479 // Seek past the header. We will write the header after all regions are written 1480 // and their CRCs computed. 1481 size_t header_bytes = header()->header_size(); 1482 1483 header_bytes = align_up(header_bytes, MetaspaceShared::core_region_alignment()); 1484 _file_offset = header_bytes; 1485 seek_to_position(_file_offset); 1486 } 1487 1488 // Write the header to the file, seek to the next allocation boundary. 1489 1490 void FileMapInfo::write_header() { 1491 _file_offset = 0; 1492 seek_to_position(_file_offset); 1493 assert(is_file_position_aligned(), "must be"); 1494 write_bytes(header(), header()->header_size()); 1495 } 1496 1497 size_t FileMapRegion::used_aligned() const { 1498 return align_up(used(), MetaspaceShared::core_region_alignment()); 1499 } 1500 1501 void FileMapRegion::init(int region_index, size_t mapping_offset, size_t size, bool read_only, 1502 bool allow_exec, int crc) { 1503 _is_heap_region = HeapShared::is_heap_region(region_index); 1504 _is_bitmap_region = (region_index == MetaspaceShared::bm); 1505 _mapping_offset = mapping_offset; 1506 _used = size; 1507 _read_only = read_only; 1508 _allow_exec = allow_exec; 1509 _crc = crc; 1510 _mapped_from_file = false; 1511 _mapped_base = nullptr; 1512 } 1513 1514 void FileMapRegion::init_oopmap(size_t offset, size_t size_in_bits) { 1515 _oopmap_offset = offset; 1516 _oopmap_size_in_bits = size_in_bits; 1517 } 1518 1519 void FileMapRegion::init_ptrmap(size_t offset, size_t size_in_bits) { 1520 _ptrmap_offset = offset; 1521 _ptrmap_size_in_bits = size_in_bits; 1522 } 1523 1524 BitMapView FileMapRegion::bitmap_view(bool is_oopmap) { 1525 char* bitmap_base = FileMapInfo::current_info()->map_bitmap_region(); 1526 bitmap_base += is_oopmap ? _oopmap_offset : _ptrmap_offset; 1527 size_t size_in_bits = is_oopmap ? _oopmap_size_in_bits : _ptrmap_size_in_bits; 1528 return BitMapView((BitMap::bm_word_t*)(bitmap_base), size_in_bits); 1529 } 1530 1531 BitMapView FileMapRegion::oopmap_view() { 1532 return bitmap_view(true); 1533 } 1534 1535 BitMapView FileMapRegion::ptrmap_view() { 1536 assert(has_ptrmap(), "must be"); 1537 return bitmap_view(false); 1538 } 1539 1540 bool FileMapRegion::check_region_crc() const { 1541 // This function should be called after the region has been properly 1542 // loaded into memory via FileMapInfo::map_region() or FileMapInfo::read_region(). 1543 // I.e., this->mapped_base() must be valid. 1544 size_t sz = used(); 1545 if (sz == 0) { 1546 return true; 1547 } 1548 1549 assert(mapped_base() != nullptr, "must be initialized"); 1550 int crc = ClassLoader::crc32(0, mapped_base(), (jint)sz); 1551 if (crc != this->crc()) { 1552 log_warning(cds)("Checksum verification failed."); 1553 return false; 1554 } 1555 return true; 1556 } 1557 1558 static const char* region_name(int region_index) { 1559 static const char* names[] = { 1560 "rw", "ro", "bm", "hp" 1561 }; 1562 const int num_regions = sizeof(names)/sizeof(names[0]); 1563 assert(0 <= region_index && region_index < num_regions, "sanity"); 1564 1565 return names[region_index]; 1566 } 1567 1568 void FileMapRegion::print(outputStream* st, int region_index) { 1569 st->print_cr("============ region ============= %d \"%s\"", region_index, region_name(region_index)); 1570 st->print_cr("- crc: 0x%08x", _crc); 1571 st->print_cr("- read_only: %d", _read_only); 1572 st->print_cr("- allow_exec: %d", _allow_exec); 1573 st->print_cr("- is_heap_region: %d", _is_heap_region); 1574 st->print_cr("- is_bitmap_region: %d", _is_bitmap_region); 1575 st->print_cr("- mapped_from_file: %d", _mapped_from_file); 1576 st->print_cr("- file_offset: " SIZE_FORMAT_X, _file_offset); 1577 st->print_cr("- mapping_offset: " SIZE_FORMAT_X, _mapping_offset); 1578 st->print_cr("- used: " SIZE_FORMAT, _used); 1579 st->print_cr("- oopmap_offset: " SIZE_FORMAT_X, _oopmap_offset); 1580 st->print_cr("- oopmap_size_in_bits: " SIZE_FORMAT, _oopmap_size_in_bits); 1581 st->print_cr("- mapped_base: " INTPTR_FORMAT, p2i(_mapped_base)); 1582 } 1583 1584 void FileMapInfo::write_region(int region, char* base, size_t size, 1585 bool read_only, bool allow_exec) { 1586 assert(CDSConfig::is_dumping_archive(), "sanity"); 1587 1588 FileMapRegion* r = region_at(region); 1589 char* requested_base; 1590 size_t mapping_offset = 0; 1591 1592 if (region == MetaspaceShared::bm) { 1593 requested_base = nullptr; // always null for bm region 1594 } else if (size == 0) { 1595 // This is an unused region (e.g., a heap region when !INCLUDE_CDS_JAVA_HEAP) 1596 requested_base = nullptr; 1597 } else if (HeapShared::is_heap_region(region)) { 1598 assert(HeapShared::can_write(), "sanity"); 1599 #if INCLUDE_CDS_JAVA_HEAP 1600 assert(!CDSConfig::is_dumping_dynamic_archive(), "must be"); 1601 requested_base = (char*)ArchiveHeapWriter::requested_address(); 1602 if (UseCompressedOops) { 1603 mapping_offset = (size_t)((address)requested_base - CompressedOops::base()); 1604 assert((mapping_offset >> CompressedOops::shift()) << CompressedOops::shift() == mapping_offset, "must be"); 1605 } else { 1606 mapping_offset = 0; // not used with !UseCompressedOops 1607 } 1608 #endif // INCLUDE_CDS_JAVA_HEAP 1609 } else { 1610 char* requested_SharedBaseAddress = (char*)MetaspaceShared::requested_base_address(); 1611 requested_base = ArchiveBuilder::current()->to_requested(base); 1612 assert(requested_base >= requested_SharedBaseAddress, "must be"); 1613 mapping_offset = requested_base - requested_SharedBaseAddress; 1614 } 1615 1616 r->set_file_offset(_file_offset); 1617 int crc = ClassLoader::crc32(0, base, (jint)size); 1618 if (size > 0) { 1619 log_info(cds)("Shared file region (%s) %d: " SIZE_FORMAT_W(8) 1620 " bytes, addr " INTPTR_FORMAT " file offset 0x%08" PRIxPTR 1621 " crc 0x%08x", 1622 region_name(region), region, size, p2i(requested_base), _file_offset, crc); 1623 } 1624 1625 r->init(region, mapping_offset, size, read_only, allow_exec, crc); 1626 1627 if (base != nullptr) { 1628 write_bytes_aligned(base, size); 1629 } 1630 } 1631 1632 static size_t write_bitmap(const CHeapBitMap* map, char* output, size_t offset) { 1633 size_t size_in_bytes = map->size_in_bytes(); 1634 map->write_to((BitMap::bm_word_t*)(output + offset), size_in_bytes); 1635 return offset + size_in_bytes; 1636 } 1637 1638 char* FileMapInfo::write_bitmap_region(const CHeapBitMap* ptrmap, ArchiveHeapInfo* heap_info, 1639 size_t &size_in_bytes) { 1640 size_in_bytes = ptrmap->size_in_bytes(); 1641 1642 if (heap_info->is_used()) { 1643 size_in_bytes += heap_info->oopmap()->size_in_bytes(); 1644 size_in_bytes += heap_info->ptrmap()->size_in_bytes(); 1645 } 1646 1647 // The bitmap region contains up to 3 parts: 1648 // ptrmap: metaspace pointers inside the ro/rw regions 1649 // heap_info->oopmap(): Java oop pointers in the heap region 1650 // heap_info->ptrmap(): metaspace pointers in the heap region 1651 char* buffer = NEW_C_HEAP_ARRAY(char, size_in_bytes, mtClassShared); 1652 size_t written = 0; 1653 written = write_bitmap(ptrmap, buffer, written); 1654 header()->set_ptrmap_size_in_bits(ptrmap->size()); 1655 1656 if (heap_info->is_used()) { 1657 FileMapRegion* r = region_at(MetaspaceShared::hp); 1658 1659 r->init_oopmap(written, heap_info->oopmap()->size()); 1660 written = write_bitmap(heap_info->oopmap(), buffer, written); 1661 1662 r->init_ptrmap(written, heap_info->ptrmap()->size()); 1663 written = write_bitmap(heap_info->ptrmap(), buffer, written); 1664 } 1665 1666 write_region(MetaspaceShared::bm, (char*)buffer, size_in_bytes, /*read_only=*/true, /*allow_exec=*/false); 1667 return buffer; 1668 } 1669 1670 size_t FileMapInfo::write_heap_region(ArchiveHeapInfo* heap_info) { 1671 char* buffer_start = heap_info->buffer_start(); 1672 size_t buffer_size = heap_info->buffer_byte_size(); 1673 write_region(MetaspaceShared::hp, buffer_start, buffer_size, false, false); 1674 header()->set_heap_roots_offset(heap_info->heap_roots_offset()); 1675 return buffer_size; 1676 } 1677 1678 // Dump bytes to file -- at the current file position. 1679 1680 void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) { 1681 assert(_file_open, "must be"); 1682 if (!os::write(_fd, buffer, nbytes)) { 1683 // If the shared archive is corrupted, close it and remove it. 1684 close(); 1685 remove(_full_path); 1686 MetaspaceShared::unrecoverable_writing_error("Unable to write to shared archive file."); 1687 } 1688 _file_offset += nbytes; 1689 } 1690 1691 bool FileMapInfo::is_file_position_aligned() const { 1692 return _file_offset == align_up(_file_offset, 1693 MetaspaceShared::core_region_alignment()); 1694 } 1695 1696 // Align file position to an allocation unit boundary. 1697 1698 void FileMapInfo::align_file_position() { 1699 assert(_file_open, "must be"); 1700 size_t new_file_offset = align_up(_file_offset, 1701 MetaspaceShared::core_region_alignment()); 1702 if (new_file_offset != _file_offset) { 1703 _file_offset = new_file_offset; 1704 // Seek one byte back from the target and write a byte to insure 1705 // that the written file is the correct length. 1706 _file_offset -= 1; 1707 seek_to_position(_file_offset); 1708 char zero = 0; 1709 write_bytes(&zero, 1); 1710 } 1711 } 1712 1713 1714 // Dump bytes to file -- at the current file position. 1715 1716 void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) { 1717 align_file_position(); 1718 write_bytes(buffer, nbytes); 1719 align_file_position(); 1720 } 1721 1722 // Close the shared archive file. This does NOT unmap mapped regions. 1723 1724 void FileMapInfo::close() { 1725 if (_file_open) { 1726 if (::close(_fd) < 0) { 1727 MetaspaceShared::unrecoverable_loading_error("Unable to close the shared archive file."); 1728 } 1729 _file_open = false; 1730 _fd = -1; 1731 } 1732 } 1733 1734 /* 1735 * Same as os::map_memory() but also pretouches if AlwaysPreTouch is enabled. 1736 */ 1737 char* map_memory(int fd, const char* file_name, size_t file_offset, 1738 char *addr, size_t bytes, bool read_only, 1739 bool allow_exec, MEMFLAGS flags = mtNone) { 1740 char* mem = os::map_memory(fd, file_name, file_offset, addr, bytes, 1741 AlwaysPreTouch ? false : read_only, 1742 allow_exec, flags); 1743 if (mem != nullptr && AlwaysPreTouch) { 1744 os::pretouch_memory(mem, mem + bytes); 1745 } 1746 return mem; 1747 } 1748 1749 // JVM/TI RedefineClasses() support: 1750 // Remap the shared readonly space to shared readwrite, private. 1751 bool FileMapInfo::remap_shared_readonly_as_readwrite() { 1752 int idx = MetaspaceShared::ro; 1753 FileMapRegion* r = region_at(idx); 1754 if (!r->read_only()) { 1755 // the space is already readwrite so we are done 1756 return true; 1757 } 1758 size_t size = r->used_aligned(); 1759 if (!open_for_read()) { 1760 return false; 1761 } 1762 char *addr = r->mapped_base(); 1763 char *base = os::remap_memory(_fd, _full_path, r->file_offset(), 1764 addr, size, false /* !read_only */, 1765 r->allow_exec()); 1766 close(); 1767 // These have to be errors because the shared region is now unmapped. 1768 if (base == nullptr) { 1769 log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno); 1770 vm_exit(1); 1771 } 1772 if (base != addr) { 1773 log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno); 1774 vm_exit(1); 1775 } 1776 r->set_read_only(false); 1777 return true; 1778 } 1779 1780 // Memory map a region in the address space. 1781 static const char* shared_region_name[] = { "ReadWrite", "ReadOnly", "Bitmap", "Heap" }; 1782 1783 MapArchiveResult FileMapInfo::map_regions(int regions[], int num_regions, char* mapped_base_address, ReservedSpace rs) { 1784 DEBUG_ONLY(FileMapRegion* last_region = nullptr); 1785 intx addr_delta = mapped_base_address - header()->requested_base_address(); 1786 1787 // Make sure we don't attempt to use header()->mapped_base_address() unless 1788 // it's been successfully mapped. 1789 DEBUG_ONLY(header()->set_mapped_base_address((char*)(uintptr_t)0xdeadbeef);) 1790 1791 for (int i = 0; i < num_regions; i++) { 1792 int idx = regions[i]; 1793 MapArchiveResult result = map_region(idx, addr_delta, mapped_base_address, rs); 1794 if (result != MAP_ARCHIVE_SUCCESS) { 1795 return result; 1796 } 1797 FileMapRegion* r = region_at(idx); 1798 DEBUG_ONLY(if (last_region != nullptr) { 1799 // Ensure that the OS won't be able to allocate new memory spaces between any mapped 1800 // regions, or else it would mess up the simple comparison in MetaspaceObj::is_shared(). 1801 assert(r->mapped_base() == last_region->mapped_end(), "must have no gaps"); 1802 } 1803 last_region = r;) 1804 log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)", is_static() ? "static " : "dynamic", 1805 idx, p2i(r->mapped_base()), p2i(r->mapped_end()), 1806 shared_region_name[idx]); 1807 1808 } 1809 1810 header()->set_mapped_base_address(header()->requested_base_address() + addr_delta); 1811 if (addr_delta != 0 && !relocate_pointers_in_core_regions(addr_delta)) { 1812 return MAP_ARCHIVE_OTHER_FAILURE; 1813 } 1814 1815 return MAP_ARCHIVE_SUCCESS; 1816 } 1817 1818 bool FileMapInfo::read_region(int i, char* base, size_t size, bool do_commit) { 1819 FileMapRegion* r = region_at(i); 1820 if (do_commit) { 1821 log_info(cds)("Commit %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)%s", 1822 is_static() ? "static " : "dynamic", i, p2i(base), p2i(base + size), 1823 shared_region_name[i], r->allow_exec() ? " exec" : ""); 1824 if (!os::commit_memory(base, size, r->allow_exec())) { 1825 log_error(cds)("Failed to commit %s region #%d (%s)", is_static() ? "static " : "dynamic", 1826 i, shared_region_name[i]); 1827 return false; 1828 } 1829 } 1830 if (os::lseek(_fd, (long)r->file_offset(), SEEK_SET) != (int)r->file_offset() || 1831 read_bytes(base, size) != size) { 1832 return false; 1833 } 1834 1835 r->set_mapped_from_file(false); 1836 r->set_mapped_base(base); 1837 1838 if (VerifySharedSpaces && !r->check_region_crc()) { 1839 return false; 1840 } 1841 1842 return true; 1843 } 1844 1845 MapArchiveResult FileMapInfo::map_region(int i, intx addr_delta, char* mapped_base_address, ReservedSpace rs) { 1846 assert(!HeapShared::is_heap_region(i), "sanity"); 1847 FileMapRegion* r = region_at(i); 1848 size_t size = r->used_aligned(); 1849 char *requested_addr = mapped_base_address + r->mapping_offset(); 1850 assert(r->mapped_base() == nullptr, "must be not mapped yet"); 1851 assert(requested_addr != nullptr, "must be specified"); 1852 1853 r->set_mapped_from_file(false); 1854 1855 if (MetaspaceShared::use_windows_memory_mapping()) { 1856 // Windows cannot remap read-only shared memory to read-write when required for 1857 // RedefineClasses, which is also used by JFR. Always map windows regions as RW. 1858 r->set_read_only(false); 1859 } else if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space() || 1860 Arguments::has_jfr_option()) { 1861 // If a tool agent is in use (debugging enabled), or JFR, we must map the address space RW 1862 r->set_read_only(false); 1863 } else if (addr_delta != 0) { 1864 r->set_read_only(false); // Need to patch the pointers 1865 } 1866 1867 if (MetaspaceShared::use_windows_memory_mapping() && rs.is_reserved()) { 1868 // This is the second time we try to map the archive(s). We have already created a ReservedSpace 1869 // that covers all the FileMapRegions to ensure all regions can be mapped. However, Windows 1870 // can't mmap into a ReservedSpace, so we just ::read() the data. We're going to patch all the 1871 // regions anyway, so there's no benefit for mmap anyway. 1872 if (!read_region(i, requested_addr, size, /* do_commit = */ true)) { 1873 log_info(cds)("Failed to read %s shared space into reserved space at " INTPTR_FORMAT, 1874 shared_region_name[i], p2i(requested_addr)); 1875 return MAP_ARCHIVE_OTHER_FAILURE; // oom or I/O error. 1876 } else { 1877 assert(r->mapped_base() != nullptr, "must be initialized"); 1878 } 1879 } else { 1880 // Note that this may either be a "fresh" mapping into unreserved address 1881 // space (Windows, first mapping attempt), or a mapping into pre-reserved 1882 // space (Posix). See also comment in MetaspaceShared::map_archives(). 1883 char* base = map_memory(_fd, _full_path, r->file_offset(), 1884 requested_addr, size, r->read_only(), 1885 r->allow_exec(), mtClassShared); 1886 if (base != requested_addr) { 1887 log_info(cds)("Unable to map %s shared space at " INTPTR_FORMAT, 1888 shared_region_name[i], p2i(requested_addr)); 1889 _memory_mapping_failed = true; 1890 return MAP_ARCHIVE_MMAP_FAILURE; 1891 } 1892 r->set_mapped_from_file(true); 1893 r->set_mapped_base(requested_addr); 1894 } 1895 1896 if (VerifySharedSpaces && !r->check_region_crc()) { 1897 return MAP_ARCHIVE_OTHER_FAILURE; 1898 } 1899 1900 return MAP_ARCHIVE_SUCCESS; 1901 } 1902 1903 // The return value is the location of the archive relocation bitmap. 1904 char* FileMapInfo::map_bitmap_region() { 1905 FileMapRegion* r = region_at(MetaspaceShared::bm); 1906 if (r->mapped_base() != nullptr) { 1907 return r->mapped_base(); 1908 } 1909 bool read_only = true, allow_exec = false; 1910 char* requested_addr = nullptr; // allow OS to pick any location 1911 char* bitmap_base = map_memory(_fd, _full_path, r->file_offset(), 1912 requested_addr, r->used_aligned(), read_only, allow_exec, mtClassShared); 1913 if (bitmap_base == nullptr) { 1914 log_info(cds)("failed to map relocation bitmap"); 1915 return nullptr; 1916 } 1917 1918 r->set_mapped_base(bitmap_base); 1919 if (VerifySharedSpaces && !r->check_region_crc()) { 1920 log_error(cds)("relocation bitmap CRC error"); 1921 if (!os::unmap_memory(bitmap_base, r->used_aligned())) { 1922 fatal("os::unmap_memory of relocation bitmap failed"); 1923 } 1924 return nullptr; 1925 } 1926 1927 r->set_mapped_from_file(true); 1928 log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)", 1929 is_static() ? "static " : "dynamic", 1930 MetaspaceShared::bm, p2i(r->mapped_base()), p2i(r->mapped_end()), 1931 shared_region_name[MetaspaceShared::bm]); 1932 return bitmap_base; 1933 } 1934 1935 // This is called when we cannot map the archive at the requested[ base address (usually 0x800000000). 1936 // We relocate all pointers in the 2 core regions (ro, rw). 1937 bool FileMapInfo::relocate_pointers_in_core_regions(intx addr_delta) { 1938 log_debug(cds, reloc)("runtime archive relocation start"); 1939 char* bitmap_base = map_bitmap_region(); 1940 1941 if (bitmap_base == nullptr) { 1942 return false; // OOM, or CRC check failure 1943 } else { 1944 size_t ptrmap_size_in_bits = header()->ptrmap_size_in_bits(); 1945 log_debug(cds, reloc)("mapped relocation bitmap @ " INTPTR_FORMAT " (" SIZE_FORMAT " bits)", 1946 p2i(bitmap_base), ptrmap_size_in_bits); 1947 1948 BitMapView ptrmap((BitMap::bm_word_t*)bitmap_base, ptrmap_size_in_bits); 1949 1950 // Patch all pointers in the mapped region that are marked by ptrmap. 1951 address patch_base = (address)mapped_base(); 1952 address patch_end = (address)mapped_end(); 1953 1954 // the current value of the pointers to be patched must be within this 1955 // range (i.e., must be between the requested base address and the address of the current archive). 1956 // Note: top archive may point to objects in the base archive, but not the other way around. 1957 address valid_old_base = (address)header()->requested_base_address(); 1958 address valid_old_end = valid_old_base + mapping_end_offset(); 1959 1960 // after patching, the pointers must point inside this range 1961 // (the requested location of the archive, as mapped at runtime). 1962 address valid_new_base = (address)header()->mapped_base_address(); 1963 address valid_new_end = (address)mapped_end(); 1964 1965 SharedDataRelocator patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end, 1966 valid_new_base, valid_new_end, addr_delta); 1967 ptrmap.iterate(&patcher); 1968 1969 // The MetaspaceShared::bm region will be unmapped in MetaspaceShared::initialize_shared_spaces(). 1970 1971 log_debug(cds, reloc)("runtime archive relocation done"); 1972 return true; 1973 } 1974 } 1975 1976 size_t FileMapInfo::read_bytes(void* buffer, size_t count) { 1977 assert(_file_open, "Archive file is not open"); 1978 size_t n = ::read(_fd, buffer, (unsigned int)count); 1979 if (n != count) { 1980 // Close the file if there's a problem reading it. 1981 close(); 1982 return 0; 1983 } 1984 _file_offset += count; 1985 return count; 1986 } 1987 1988 // Get the total size in bytes of a read only region 1989 size_t FileMapInfo::readonly_total() { 1990 size_t total = 0; 1991 if (current_info() != nullptr) { 1992 FileMapRegion* r = FileMapInfo::current_info()->region_at(MetaspaceShared::ro); 1993 if (r->read_only()) total += r->used(); 1994 } 1995 if (dynamic_info() != nullptr) { 1996 FileMapRegion* r = FileMapInfo::dynamic_info()->region_at(MetaspaceShared::ro); 1997 if (r->read_only()) total += r->used(); 1998 } 1999 return total; 2000 } 2001 2002 #if INCLUDE_CDS_JAVA_HEAP 2003 MemRegion FileMapInfo::_mapped_heap_memregion; 2004 2005 bool FileMapInfo::has_heap_region() { 2006 return (region_at(MetaspaceShared::hp)->used() > 0); 2007 } 2008 2009 // Returns the address range of the archived heap region computed using the 2010 // current oop encoding mode. This range may be different than the one seen at 2011 // dump time due to encoding mode differences. The result is used in determining 2012 // if/how these regions should be relocated at run time. 2013 MemRegion FileMapInfo::get_heap_region_requested_range() { 2014 FileMapRegion* r = region_at(MetaspaceShared::hp); 2015 size_t size = r->used(); 2016 assert(size > 0, "must have non-empty heap region"); 2017 2018 address start = heap_region_requested_address(); 2019 address end = start + size; 2020 log_info(cds)("Requested heap region [" INTPTR_FORMAT " - " INTPTR_FORMAT "] = " SIZE_FORMAT_W(8) " bytes", 2021 p2i(start), p2i(end), size); 2022 2023 return MemRegion((HeapWord*)start, (HeapWord*)end); 2024 } 2025 2026 void FileMapInfo::map_or_load_heap_region() { 2027 bool success = false; 2028 2029 if (can_use_heap_region()) { 2030 if (ArchiveHeapLoader::can_map()) { 2031 success = map_heap_region(); 2032 } else if (ArchiveHeapLoader::can_load()) { 2033 success = ArchiveHeapLoader::load_heap_region(this); 2034 } else { 2035 if (!UseCompressedOops && !ArchiveHeapLoader::can_map()) { 2036 // TODO - remove implicit knowledge of G1 2037 log_info(cds)("Cannot use CDS heap data. UseG1GC is required for -XX:-UseCompressedOops"); 2038 } else { 2039 log_info(cds)("Cannot use CDS heap data. UseEpsilonGC, UseG1GC, UseSerialGC or UseParallelGC are required."); 2040 } 2041 } 2042 } 2043 2044 if (!success) { 2045 CDSConfig::disable_loading_full_module_graph(); 2046 } 2047 } 2048 2049 bool FileMapInfo::can_use_heap_region() { 2050 if (!has_heap_region()) { 2051 return false; 2052 } 2053 if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) { 2054 ShouldNotReachHere(); // CDS should have been disabled. 2055 // The archived objects are mapped at JVM start-up, but we don't know if 2056 // j.l.String or j.l.Class might be replaced by the ClassFileLoadHook, 2057 // which would make the archived String or mirror objects invalid. Let's be safe and not 2058 // use the archived objects. These 2 classes are loaded during the JVMTI "early" stage. 2059 // 2060 // If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects 2061 // in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK 2062 // because we won't install an archived object subgraph if the klass of any of the 2063 // referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph(). 2064 } 2065 2066 // We pre-compute narrow Klass IDs with the runtime mapping start intended to be the base, and a shift of 2067 // ArchiveHeapWriter::precomputed_narrow_klass_shift. We enforce this encoding at runtime (see 2068 // CompressedKlassPointers::initialize_for_given_encoding()). Therefore, the following assertions must 2069 // hold: 2070 address archive_narrow_klass_base = (address)header()->mapped_base_address(); 2071 const int archive_narrow_klass_shift = ArchiveHeapWriter::precomputed_narrow_klass_shift; 2072 2073 log_info(cds)("CDS archive was created with max heap size = " SIZE_FORMAT "M, and the following configuration:", 2074 max_heap_size()/M); 2075 log_info(cds)(" narrow_klass_base at mapping start address, narrow_klass_shift = %d", 2076 archive_narrow_klass_shift); 2077 log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d", 2078 narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift()); 2079 log_info(cds)("The current max heap size = " SIZE_FORMAT "M, HeapRegion::GrainBytes = " SIZE_FORMAT, 2080 MaxHeapSize/M, HeapRegion::GrainBytes); 2081 log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d", 2082 p2i(CompressedKlassPointers::base()), CompressedKlassPointers::shift()); 2083 log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d", 2084 CompressedOops::mode(), p2i(CompressedOops::base()), CompressedOops::shift()); 2085 log_info(cds)(" heap range = [" PTR_FORMAT " - " PTR_FORMAT "]", 2086 UseCompressedOops ? p2i(CompressedOops::begin()) : 2087 UseG1GC ? p2i((address)G1CollectedHeap::heap()->reserved().start()) : 0L, 2088 UseCompressedOops ? p2i(CompressedOops::end()) : 2089 UseG1GC ? p2i((address)G1CollectedHeap::heap()->reserved().end()) : 0L); 2090 2091 assert(archive_narrow_klass_base == CompressedKlassPointers::base(), "Unexpected encoding base encountered " 2092 "(" PTR_FORMAT ", expected " PTR_FORMAT ")", p2i(CompressedKlassPointers::base()), p2i(archive_narrow_klass_base)); 2093 assert(archive_narrow_klass_shift == CompressedKlassPointers::shift(), "Unexpected encoding shift encountered " 2094 "(%d, expected %d)", CompressedKlassPointers::shift(), archive_narrow_klass_shift); 2095 2096 return true; 2097 } 2098 2099 // The actual address of this region during dump time. 2100 address FileMapInfo::heap_region_dumptime_address() { 2101 FileMapRegion* r = region_at(MetaspaceShared::hp); 2102 assert(UseSharedSpaces, "runtime only"); 2103 assert(is_aligned(r->mapping_offset(), sizeof(HeapWord)), "must be"); 2104 if (UseCompressedOops) { 2105 return /*dumptime*/ narrow_oop_base() + r->mapping_offset(); 2106 } else { 2107 return heap_region_requested_address(); 2108 } 2109 } 2110 2111 // The address where this region can be mapped into the runtime heap without 2112 // patching any of the pointers that are embedded in this region. 2113 address FileMapInfo::heap_region_requested_address() { 2114 assert(UseSharedSpaces, "runtime only"); 2115 FileMapRegion* r = region_at(MetaspaceShared::hp); 2116 assert(is_aligned(r->mapping_offset(), sizeof(HeapWord)), "must be"); 2117 assert(ArchiveHeapLoader::can_map(), "cannot be used by ArchiveHeapLoader::can_load() mode"); 2118 if (UseCompressedOops) { 2119 // We can avoid relocation if each region's offset from the runtime CompressedOops::base() 2120 // is the same as its offset from the CompressedOops::base() during dumptime. 2121 // Note that CompressedOops::base() may be different between dumptime and runtime. 2122 // 2123 // Example: 2124 // Dumptime base = 0x1000 and shift is 0. We have a region at address 0x2000. There's a 2125 // narrowOop P stored in this region that points to an object at address 0x2200. 2126 // P's encoded value is 0x1200. 2127 // 2128 // Runtime base = 0x4000 and shift is also 0. If we map this region at 0x5000, then 2129 // the value P can remain 0x1200. The decoded address = (0x4000 + (0x1200 << 0)) = 0x5200, 2130 // which is the runtime location of the referenced object. 2131 return /*runtime*/ CompressedOops::base() + r->mapping_offset(); 2132 } else { 2133 // This was the hard-coded requested base address used at dump time. With uncompressed oops, 2134 // the heap range is assigned by the OS so we will most likely have to relocate anyway, no matter 2135 // what base address was picked at duump time. 2136 return (address)ArchiveHeapWriter::NOCOOPS_REQUESTED_BASE; 2137 } 2138 } 2139 2140 bool FileMapInfo::map_heap_region() { 2141 if (map_heap_region_impl()) { 2142 #ifdef ASSERT 2143 // The "old" regions must be parsable -- we cannot have any unused space 2144 // at the start of the lowest G1 region that contains archived objects. 2145 assert(is_aligned(_mapped_heap_memregion.start(), HeapRegion::GrainBytes), "must be"); 2146 2147 // Make sure we map at the very top of the heap - see comments in 2148 // init_heap_region_relocation(). 2149 MemRegion heap_range = G1CollectedHeap::heap()->reserved(); 2150 assert(heap_range.contains(_mapped_heap_memregion), "must be"); 2151 2152 address heap_end = (address)heap_range.end(); 2153 address mapped_heap_region_end = (address)_mapped_heap_memregion.end(); 2154 assert(heap_end >= mapped_heap_region_end, "must be"); 2155 assert(heap_end - mapped_heap_region_end < (intx)(HeapRegion::GrainBytes), 2156 "must be at the top of the heap to avoid fragmentation"); 2157 #endif 2158 2159 ArchiveHeapLoader::set_mapped(); 2160 return true; 2161 } else { 2162 return false; 2163 } 2164 } 2165 2166 bool FileMapInfo::map_heap_region_impl() { 2167 assert(UseG1GC, "the following code assumes G1"); 2168 2169 FileMapRegion* r = region_at(MetaspaceShared::hp); 2170 size_t size = r->used(); 2171 if (size == 0) { 2172 return false; // no archived java heap data 2173 } 2174 2175 size_t word_size = size / HeapWordSize; 2176 address requested_start = heap_region_requested_address(); 2177 2178 log_info(cds)("Preferred address to map heap data (to avoid relocation) is " INTPTR_FORMAT, p2i(requested_start)); 2179 2180 // allocate from java heap 2181 HeapWord* start = G1CollectedHeap::heap()->alloc_archive_region(word_size, (HeapWord*)requested_start); 2182 if (start == nullptr) { 2183 log_info(cds)("UseSharedSpaces: Unable to allocate java heap region for archive heap."); 2184 return false; 2185 } 2186 2187 _mapped_heap_memregion = MemRegion(start, word_size); 2188 2189 // Map the archived heap data. No need to call MemTracker::record_virtual_memory_type() 2190 // for mapped region as it is part of the reserved java heap, which is already recorded. 2191 char* addr = (char*)_mapped_heap_memregion.start(); 2192 char* base = map_memory(_fd, _full_path, r->file_offset(), 2193 addr, _mapped_heap_memregion.byte_size(), r->read_only(), 2194 r->allow_exec()); 2195 if (base == nullptr || base != addr) { 2196 dealloc_heap_region(); 2197 log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap. " 2198 INTPTR_FORMAT ", size = " SIZE_FORMAT " bytes", 2199 p2i(addr), _mapped_heap_memregion.byte_size()); 2200 return false; 2201 } 2202 2203 r->set_mapped_base(base); 2204 if (VerifySharedSpaces && !r->check_region_crc()) { 2205 dealloc_heap_region(); 2206 log_info(cds)("UseSharedSpaces: mapped heap region is corrupt"); 2207 return false; 2208 } 2209 2210 // If the requested range is different from the range allocated by GC, then 2211 // the pointers need to be patched. 2212 address mapped_start = (address) _mapped_heap_memregion.start(); 2213 ptrdiff_t delta = mapped_start - requested_start; 2214 if (UseCompressedOops && 2215 (narrow_oop_mode() != CompressedOops::mode() || 2216 narrow_oop_shift() != CompressedOops::shift())) { 2217 _heap_pointers_need_patching = true; 2218 } 2219 if (delta != 0) { 2220 _heap_pointers_need_patching = true; 2221 } 2222 ArchiveHeapLoader::init_mapped_heap_info(mapped_start, delta, narrow_oop_shift()); 2223 2224 if (_heap_pointers_need_patching) { 2225 char* bitmap_base = map_bitmap_region(); 2226 if (bitmap_base == NULL) { 2227 log_info(cds)("CDS heap cannot be used because bitmap region cannot be mapped"); 2228 dealloc_heap_region(); 2229 unmap_region(MetaspaceShared::hp); 2230 _heap_pointers_need_patching = false; 2231 return false; 2232 } 2233 } 2234 log_info(cds)("Heap data mapped at " INTPTR_FORMAT ", size = " SIZE_FORMAT_W(8) " bytes", 2235 p2i(mapped_start), _mapped_heap_memregion.byte_size()); 2236 log_info(cds)("CDS heap data relocation delta = " INTX_FORMAT " bytes", delta); 2237 return true; 2238 } 2239 2240 narrowOop FileMapInfo::encoded_heap_region_dumptime_address() { 2241 assert(UseSharedSpaces, "runtime only"); 2242 assert(UseCompressedOops, "sanity"); 2243 FileMapRegion* r = region_at(MetaspaceShared::hp); 2244 return CompressedOops::narrow_oop_cast(r->mapping_offset() >> narrow_oop_shift()); 2245 } 2246 2247 void FileMapInfo::patch_heap_embedded_pointers() { 2248 if (!ArchiveHeapLoader::is_mapped() || !_heap_pointers_need_patching) { 2249 return; 2250 } 2251 2252 char* bitmap_base = map_bitmap_region(); 2253 assert(bitmap_base != nullptr, "must have already been mapped"); 2254 2255 FileMapRegion* r = region_at(MetaspaceShared::hp); 2256 ArchiveHeapLoader::patch_embedded_pointers( 2257 this, _mapped_heap_memregion, 2258 (address)(region_at(MetaspaceShared::bm)->mapped_base()) + r->oopmap_offset(), 2259 r->oopmap_size_in_bits()); 2260 } 2261 2262 void FileMapInfo::fixup_mapped_heap_region() { 2263 if (ArchiveHeapLoader::is_mapped()) { 2264 assert(!_mapped_heap_memregion.is_empty(), "sanity"); 2265 2266 // Populate the archive regions' G1BlockOffsetTableParts. That ensures 2267 // fast G1BlockOffsetTablePart::block_start operations for any given address 2268 // within the archive regions when trying to find start of an object 2269 // (e.g. during card table scanning). 2270 G1CollectedHeap::heap()->populate_archive_regions_bot_part(_mapped_heap_memregion); 2271 } 2272 } 2273 2274 // dealloc the archive regions from java heap 2275 void FileMapInfo::dealloc_heap_region() { 2276 G1CollectedHeap::heap()->dealloc_archive_regions(_mapped_heap_memregion); 2277 } 2278 #endif // INCLUDE_CDS_JAVA_HEAP 2279 2280 void FileMapInfo::unmap_regions(int regions[], int num_regions) { 2281 for (int r = 0; r < num_regions; r++) { 2282 int idx = regions[r]; 2283 unmap_region(idx); 2284 } 2285 } 2286 2287 // Unmap a memory region in the address space. 2288 2289 void FileMapInfo::unmap_region(int i) { 2290 FileMapRegion* r = region_at(i); 2291 char* mapped_base = r->mapped_base(); 2292 size_t size = r->used_aligned(); 2293 2294 if (mapped_base != nullptr) { 2295 if (size > 0 && r->mapped_from_file()) { 2296 log_info(cds)("Unmapping region #%d at base " INTPTR_FORMAT " (%s)", i, p2i(mapped_base), 2297 shared_region_name[i]); 2298 if (!os::unmap_memory(mapped_base, size)) { 2299 fatal("os::unmap_memory failed"); 2300 } 2301 } 2302 r->set_mapped_base(nullptr); 2303 } 2304 } 2305 2306 void FileMapInfo::assert_mark(bool check) { 2307 if (!check) { 2308 MetaspaceShared::unrecoverable_loading_error("Mark mismatch while restoring from shared file."); 2309 } 2310 } 2311 2312 FileMapInfo* FileMapInfo::_current_info = nullptr; 2313 FileMapInfo* FileMapInfo::_dynamic_archive_info = nullptr; 2314 bool FileMapInfo::_heap_pointers_need_patching = false; 2315 SharedPathTable FileMapInfo::_shared_path_table; 2316 bool FileMapInfo::_validating_shared_path_table = false; 2317 bool FileMapInfo::_memory_mapping_failed = false; 2318 GrowableArray<const char*>* FileMapInfo::_non_existent_class_paths = nullptr; 2319 2320 // Open the shared archive file, read and validate the header 2321 // information (version, boot classpath, etc.). If initialization 2322 // fails, shared spaces are disabled and the file is closed. 2323 // 2324 // Validation of the archive is done in two steps: 2325 // 2326 // [1] validate_header() - done here. 2327 // [2] validate_shared_path_table - this is done later, because the table is in the RW 2328 // region of the archive, which is not mapped yet. 2329 bool FileMapInfo::initialize() { 2330 assert(UseSharedSpaces, "UseSharedSpaces expected."); 2331 assert(Arguments::has_jimage(), "The shared archive file cannot be used with an exploded module build."); 2332 2333 if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) { 2334 // CDS assumes that no classes resolved in vmClasses::resolve_all() 2335 // are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved 2336 // during the JVMTI "early" stage, so we can still use CDS if 2337 // JvmtiExport::has_early_class_hook_env() is false. 2338 log_info(cds)("CDS is disabled because early JVMTI ClassFileLoadHook is in use."); 2339 return false; 2340 } 2341 2342 if (!open_for_read() || !init_from_file(_fd) || !validate_header()) { 2343 if (_is_static) { 2344 log_info(cds)("Initialize static archive failed."); 2345 return false; 2346 } else { 2347 log_info(cds)("Initialize dynamic archive failed."); 2348 if (AutoCreateSharedArchive) { 2349 CDSConfig::enable_dumping_dynamic_archive(); 2350 ArchiveClassesAtExit = CDSConfig::dynamic_archive_path(); 2351 } 2352 return false; 2353 } 2354 } 2355 2356 return true; 2357 } 2358 2359 // The 2 core spaces are RW->RO 2360 FileMapRegion* FileMapInfo::first_core_region() const { 2361 return region_at(MetaspaceShared::rw); 2362 } 2363 2364 FileMapRegion* FileMapInfo::last_core_region() const { 2365 return region_at(MetaspaceShared::ro); 2366 } 2367 2368 void FileMapInfo::print(outputStream* st) const { 2369 header()->print(st); 2370 if (!is_static()) { 2371 dynamic_header()->print(st); 2372 } 2373 } 2374 2375 void FileMapHeader::set_as_offset(char* p, size_t *offset) { 2376 *offset = ArchiveBuilder::current()->any_to_offset((address)p); 2377 } 2378 2379 int FileMapHeader::compute_crc() { 2380 char* start = (char*)this; 2381 // start computing from the field after _header_size to end of base archive name. 2382 char* buf = (char*)&(_generic_header._header_size) + sizeof(_generic_header._header_size); 2383 size_t sz = header_size() - (buf - start); 2384 int crc = ClassLoader::crc32(0, buf, (jint)sz); 2385 return crc; 2386 } 2387 2388 // This function should only be called during run time with UseSharedSpaces enabled. 2389 bool FileMapHeader::validate() { 2390 if (_obj_alignment != ObjectAlignmentInBytes) { 2391 log_info(cds)("The shared archive file's ObjectAlignmentInBytes of %d" 2392 " does not equal the current ObjectAlignmentInBytes of %d.", 2393 _obj_alignment, ObjectAlignmentInBytes); 2394 return false; 2395 } 2396 if (_compact_strings != CompactStrings) { 2397 log_info(cds)("The shared archive file's CompactStrings setting (%s)" 2398 " does not equal the current CompactStrings setting (%s).", 2399 _compact_strings ? "enabled" : "disabled", 2400 CompactStrings ? "enabled" : "disabled"); 2401 return false; 2402 } 2403 2404 // This must be done after header validation because it might change the 2405 // header data 2406 const char* prop = Arguments::get_property("java.system.class.loader"); 2407 if (prop != nullptr) { 2408 log_warning(cds)("Archived non-system classes are disabled because the " 2409 "java.system.class.loader property is specified (value = \"%s\"). " 2410 "To use archived non-system classes, this property must not be set", prop); 2411 _has_platform_or_app_classes = false; 2412 } 2413 2414 2415 if (!_verify_local && BytecodeVerificationLocal) { 2416 // we cannot load boot classes, so there's no point of using the CDS archive 2417 log_info(cds)("The shared archive file's BytecodeVerificationLocal setting (%s)" 2418 " does not equal the current BytecodeVerificationLocal setting (%s).", 2419 _verify_local ? "enabled" : "disabled", 2420 BytecodeVerificationLocal ? "enabled" : "disabled"); 2421 return false; 2422 } 2423 2424 // For backwards compatibility, we don't check the BytecodeVerificationRemote setting 2425 // if the archive only contains system classes. 2426 if (_has_platform_or_app_classes 2427 && !_verify_remote // we didn't verify the archived platform/app classes 2428 && BytecodeVerificationRemote) { // but we want to verify all loaded platform/app classes 2429 log_info(cds)("The shared archive file was created with less restrictive " 2430 "verification setting than the current setting."); 2431 // Pretend that we didn't have any archived platform/app classes, so they won't be loaded 2432 // by SystemDictionaryShared. 2433 _has_platform_or_app_classes = false; 2434 } 2435 2436 // Java agents are allowed during run time. Therefore, the following condition is not 2437 // checked: (!_allow_archiving_with_java_agent && AllowArchivingWithJavaAgent) 2438 // Note: _allow_archiving_with_java_agent is set in the shared archive during dump time 2439 // while AllowArchivingWithJavaAgent is set during the current run. 2440 if (_allow_archiving_with_java_agent && !AllowArchivingWithJavaAgent) { 2441 log_warning(cds)("The setting of the AllowArchivingWithJavaAgent is different " 2442 "from the setting in the shared archive."); 2443 return false; 2444 } 2445 2446 if (_allow_archiving_with_java_agent) { 2447 log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used " 2448 "for testing purposes only and should not be used in a production environment"); 2449 } 2450 2451 log_info(cds)("Archive was created with UseCompressedOops = %d, UseCompressedClassPointers = %d", 2452 compressed_oops(), compressed_class_pointers()); 2453 if (compressed_oops() != UseCompressedOops || compressed_class_pointers() != UseCompressedClassPointers) { 2454 log_info(cds)("Unable to use shared archive.\nThe saved state of UseCompressedOops and UseCompressedClassPointers is " 2455 "different from runtime, CDS will be disabled."); 2456 return false; 2457 } 2458 2459 if (is_static()) { 2460 const char* err = nullptr; 2461 if (CDSConfig::is_valhalla_preview()) { 2462 if (!_has_valhalla_patched_classes) { 2463 err = "not created"; 2464 } 2465 } else { 2466 if (_has_valhalla_patched_classes) { 2467 err = "created"; 2468 } 2469 } 2470 if (err != nullptr) { 2471 log_warning(cds)("This archive was %s with --enable-preview -XX:+EnableValhalla. It is " 2472 "incompatible with the current JVM setting", err); 2473 return false; 2474 } 2475 } 2476 2477 if (!_use_optimized_module_handling) { 2478 MetaspaceShared::disable_optimized_module_handling(); 2479 log_info(cds)("optimized module handling: disabled because archive was created without optimized module handling"); 2480 } 2481 2482 if (is_static() && !_has_full_module_graph) { 2483 // Only the static archive can contain the full module graph. 2484 CDSConfig::disable_loading_full_module_graph("archive was created without full module graph"); 2485 } 2486 2487 return true; 2488 } 2489 2490 bool FileMapInfo::validate_header() { 2491 if (!header()->validate()) { 2492 return false; 2493 } 2494 if (_is_static) { 2495 return true; 2496 } else { 2497 return DynamicArchive::validate(this); 2498 } 2499 } 2500 2501 #if INCLUDE_JVMTI 2502 ClassPathEntry** FileMapInfo::_classpath_entries_for_jvmti = nullptr; 2503 2504 ClassPathEntry* FileMapInfo::get_classpath_entry_for_jvmti(int i, TRAPS) { 2505 if (i == 0) { 2506 // index 0 corresponds to the ClassPathImageEntry which is a globally shared object 2507 // and should never be deleted. 2508 return ClassLoader::get_jrt_entry(); 2509 } 2510 ClassPathEntry* ent = _classpath_entries_for_jvmti[i]; 2511 if (ent == nullptr) { 2512 SharedClassPathEntry* scpe = shared_path(i); 2513 assert(scpe->is_jar(), "must be"); // other types of scpe will not produce archived classes 2514 2515 const char* path = scpe->name(); 2516 struct stat st; 2517 if (os::stat(path, &st) != 0) { 2518 char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128); 2519 jio_snprintf(msg, strlen(path) + 127, "error in finding JAR file %s", path); 2520 THROW_MSG_(vmSymbols::java_io_IOException(), msg, nullptr); 2521 } else { 2522 ent = ClassLoader::create_class_path_entry(THREAD, path, &st, false, false); 2523 if (ent == nullptr) { 2524 char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128); 2525 jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path); 2526 THROW_MSG_(vmSymbols::java_io_IOException(), msg, nullptr); 2527 } 2528 } 2529 2530 MutexLocker mu(THREAD, CDSClassFileStream_lock); 2531 if (_classpath_entries_for_jvmti[i] == nullptr) { 2532 _classpath_entries_for_jvmti[i] = ent; 2533 } else { 2534 // Another thread has beat me to creating this entry 2535 delete ent; 2536 ent = _classpath_entries_for_jvmti[i]; 2537 } 2538 } 2539 2540 return ent; 2541 } 2542 2543 ClassFileStream* FileMapInfo::open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS) { 2544 int path_index = ik->shared_classpath_index(); 2545 assert(path_index >= 0, "should be called for shared built-in classes only"); 2546 assert(path_index < (int)get_number_of_shared_paths(), "sanity"); 2547 2548 ClassPathEntry* cpe = get_classpath_entry_for_jvmti(path_index, CHECK_NULL); 2549 assert(cpe != nullptr, "must be"); 2550 2551 Symbol* name = ik->name(); 2552 const char* const class_name = name->as_C_string(); 2553 const char* const file_name = ClassLoader::file_name_for_class_name(class_name, 2554 name->utf8_length()); 2555 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader()); 2556 ClassFileStream* cfs = cpe->open_stream_for_loader(THREAD, file_name, loader_data); 2557 assert(cfs != nullptr, "must be able to read the classfile data of shared classes for built-in loaders."); 2558 log_debug(cds, jvmti)("classfile data for %s [%d: %s] = %d bytes", class_name, path_index, 2559 cfs->source(), cfs->length()); 2560 return cfs; 2561 } 2562 2563 #endif