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