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