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