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