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