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