1 /* 2 * Copyright (c) 2003, 2018, 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 "classfile/classLoader.inline.hpp" 28 #include "classfile/classLoaderExt.hpp" 29 #include "classfile/compactHashtable.inline.hpp" 30 #include "classfile/stringTable.hpp" 31 #include "classfile/symbolTable.hpp" 32 #include "classfile/systemDictionaryShared.hpp" 33 #include "classfile/altHashing.hpp" 34 #include "logging/log.hpp" 35 #include "logging/logStream.hpp" 36 #include "logging/logMessage.hpp" 37 #include "memory/filemap.hpp" 38 #include "memory/heapShared.inline.hpp" 39 #include "memory/iterator.inline.hpp" 40 #include "memory/metadataFactory.hpp" 41 #include "memory/metaspaceClosure.hpp" 42 #include "memory/metaspaceShared.hpp" 43 #include "memory/oopFactory.hpp" 44 #include "oops/compressedOops.inline.hpp" 45 #include "oops/objArrayOop.hpp" 46 #include "oops/oop.inline.hpp" 47 #include "prims/jvmtiExport.hpp" 48 #include "runtime/arguments.hpp" 49 #include "runtime/java.hpp" 50 #include "runtime/os.hpp" 51 #include "runtime/vm_version.hpp" 52 #include "services/memTracker.hpp" 53 #include "utilities/align.hpp" 54 #include "utilities/defaultStream.hpp" 55 #if INCLUDE_G1GC 56 #include "gc/g1/g1CollectedHeap.hpp" 57 #include "gc/g1/heapRegion.hpp" 58 #endif 59 60 # include <sys/stat.h> 61 # include <errno.h> 62 63 #ifndef O_BINARY // if defined (Win32) use binary files. 64 #define O_BINARY 0 // otherwise do nothing. 65 #endif 66 67 extern address JVM_FunctionAtStart(); 68 extern address JVM_FunctionAtEnd(); 69 70 // Complain and stop. All error conditions occurring during the writing of 71 // an archive file should stop the process. Unrecoverable errors during 72 // the reading of the archive file should stop the process. 73 74 static void fail(const char *msg, va_list ap) { 75 // This occurs very early during initialization: tty is not initialized. 76 jio_fprintf(defaultStream::error_stream(), 77 "An error has occurred while processing the" 78 " shared archive file.\n"); 79 jio_vfprintf(defaultStream::error_stream(), msg, ap); 80 jio_fprintf(defaultStream::error_stream(), "\n"); 81 // Do not change the text of the below message because some tests check for it. 82 vm_exit_during_initialization("Unable to use shared archive.", NULL); 83 } 84 85 86 void FileMapInfo::fail_stop(const char *msg, ...) { 87 va_list ap; 88 va_start(ap, msg); 89 fail(msg, ap); // Never returns. 90 va_end(ap); // for completeness. 91 } 92 93 94 // Complain and continue. Recoverable errors during the reading of the 95 // archive file may continue (with sharing disabled). 96 // 97 // If we continue, then disable shared spaces and close the file. 98 99 void FileMapInfo::fail_continue(const char *msg, ...) { 100 va_list ap; 101 va_start(ap, msg); 102 MetaspaceShared::set_archive_loading_failed(); 103 if (PrintSharedArchiveAndExit && _validating_shared_path_table) { 104 // If we are doing PrintSharedArchiveAndExit and some of the classpath entries 105 // do not validate, we can still continue "limping" to validate the remaining 106 // entries. No need to quit. 107 tty->print("["); 108 tty->vprint(msg, ap); 109 tty->print_cr("]"); 110 } else { 111 if (RequireSharedSpaces) { 112 fail(msg, ap); 113 } else { 114 if (log_is_enabled(Info, cds)) { 115 ResourceMark rm; 116 LogStream ls(Log(cds)::info()); 117 ls.print("UseSharedSpaces: "); 118 ls.vprint_cr(msg, ap); 119 } 120 } 121 UseSharedSpaces = false; 122 assert(current_info() != NULL, "singleton must be registered"); 123 current_info()->close(); 124 } 125 va_end(ap); 126 } 127 128 // Fill in the fileMapInfo structure with data about this VM instance. 129 130 // This method copies the vm version info into header_version. If the version is too 131 // long then a truncated version, which has a hash code appended to it, is copied. 132 // 133 // Using a template enables this method to verify that header_version is an array of 134 // length JVM_IDENT_MAX. This ensures that the code that writes to the CDS file and 135 // the code that reads the CDS file will both use the same size buffer. Hence, will 136 // use identical truncation. This is necessary for matching of truncated versions. 137 template <int N> static void get_header_version(char (&header_version) [N]) { 138 assert(N == JVM_IDENT_MAX, "Bad header_version size"); 139 140 const char *vm_version = VM_Version::internal_vm_info_string(); 141 const int version_len = (int)strlen(vm_version); 142 143 if (version_len < (JVM_IDENT_MAX-1)) { 144 strcpy(header_version, vm_version); 145 146 } else { 147 // Get the hash value. Use a static seed because the hash needs to return the same 148 // value over multiple jvm invocations. 149 unsigned int hash = AltHashing::murmur3_32(8191, (const jbyte*)vm_version, version_len); 150 151 // Truncate the ident, saving room for the 8 hex character hash value. 152 strncpy(header_version, vm_version, JVM_IDENT_MAX-9); 153 154 // Append the hash code as eight hex digits. 155 sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash); 156 header_version[JVM_IDENT_MAX-1] = 0; // Null terminate. 157 } 158 } 159 160 FileMapInfo::FileMapInfo() { 161 assert(_current_info == NULL, "must be singleton"); // not thread safe 162 _current_info = this; 163 memset((void*)this, 0, sizeof(FileMapInfo)); 164 _file_offset = 0; 165 _file_open = false; 166 _header = new FileMapHeader(); 167 _header->_version = _invalid_version; 168 _header->_has_platform_or_app_classes = true; 169 } 170 171 FileMapInfo::~FileMapInfo() { 172 assert(_current_info == this, "must be singleton"); // not thread safe 173 _current_info = NULL; 174 } 175 176 void FileMapInfo::populate_header(size_t alignment) { 177 _header->populate(this, alignment); 178 } 179 180 void FileMapInfo::FileMapHeader::populate(FileMapInfo* mapinfo, size_t alignment) { 181 _magic = 0xf00baba2; 182 _version = _current_version; 183 _alignment = alignment; 184 _obj_alignment = ObjectAlignmentInBytes; 185 _compact_strings = CompactStrings; 186 _narrow_oop_mode = Universe::narrow_oop_mode(); 187 _narrow_oop_base = Universe::narrow_oop_base(); 188 _narrow_oop_shift = Universe::narrow_oop_shift(); 189 _max_heap_size = MaxHeapSize; 190 _narrow_klass_base = Universe::narrow_klass_base(); 191 _narrow_klass_shift = Universe::narrow_klass_shift(); 192 _shared_path_table_size = mapinfo->_shared_path_table_size; 193 _shared_path_table = mapinfo->_shared_path_table; 194 _shared_path_entry_size = mapinfo->_shared_path_entry_size; 195 if (MetaspaceShared::is_heap_object_archiving_allowed()) { 196 _g1_reserved = G1CollectedHeap::heap()->g1_reserved(); 197 } 198 199 // The following fields are for sanity checks for whether this archive 200 // will function correctly with this JVM and the bootclasspath it's 201 // invoked with. 202 203 // JVM version string ... changes on each build. 204 get_header_version(_jvm_ident); 205 206 ClassLoaderExt::finalize_shared_paths_misc_info(); 207 _app_class_paths_start_index = ClassLoaderExt::app_class_paths_start_index(); 208 _app_module_paths_start_index = ClassLoaderExt::app_module_paths_start_index(); 209 210 _verify_local = BytecodeVerificationLocal; 211 _verify_remote = BytecodeVerificationRemote; 212 _has_platform_or_app_classes = ClassLoaderExt::has_platform_or_app_classes(); 213 } 214 215 void SharedClassPathEntry::init(const char* name, bool is_modules_image, TRAPS) { 216 assert(DumpSharedSpaces, "dump time only"); 217 _timestamp = 0; 218 _filesize = 0; 219 220 struct stat st; 221 if (os::stat(name, &st) == 0) { 222 if ((st.st_mode & S_IFMT) == S_IFDIR) { 223 _type = dir_entry; 224 } else { 225 // The timestamp of the modules_image is not checked at runtime. 226 if (is_modules_image) { 227 _type = modules_image_entry; 228 } else { 229 _type = jar_entry; 230 _timestamp = st.st_mtime; 231 } 232 _filesize = st.st_size; 233 } 234 } else { 235 // The file/dir must exist, or it would not have been added 236 // into ClassLoader::classpath_entry(). 237 // 238 // If we can't access a jar file in the boot path, then we can't 239 // make assumptions about where classes get loaded from. 240 FileMapInfo::fail_stop("Unable to open file %s.", name); 241 } 242 243 size_t len = strlen(name) + 1; 244 _name = MetadataFactory::new_array<char>(ClassLoaderData::the_null_class_loader_data(), (int)len, THREAD); 245 strcpy(_name->data(), name); 246 } 247 248 bool SharedClassPathEntry::validate(bool is_class_path) { 249 assert(UseSharedSpaces, "runtime only"); 250 251 struct stat st; 252 const char* name; 253 254 // In order to validate the runtime modules image file size against the archived 255 // size information, we need to obtain the runtime modules image path. The recorded 256 // dump time modules image path in the archive may be different from the runtime path 257 // if the JDK image has beed moved after generating the archive. 258 if (is_modules_image()) { 259 name = ClassLoader::get_jrt_entry()->name(); 260 } else { 261 name = this->name(); 262 } 263 264 bool ok = true; 265 log_info(class, path)("checking shared classpath entry: %s", name); 266 if (os::stat(name, &st) != 0 && is_class_path) { 267 // If the archived module path entry does not exist at runtime, it is not fatal 268 // (no need to invalid the shared archive) because the shared runtime visibility check 269 // filters out any archived module classes that do not have a matching runtime 270 // module path location. 271 FileMapInfo::fail_continue("Required classpath entry does not exist: %s", name); 272 ok = false; 273 } else if (is_dir()) { 274 if (!os::dir_is_empty(name)) { 275 FileMapInfo::fail_continue("directory is not empty: %s", name); 276 ok = false; 277 } 278 } else if ((has_timestamp() && _timestamp != st.st_mtime) || 279 _filesize != st.st_size) { 280 ok = false; 281 if (PrintSharedArchiveAndExit) { 282 FileMapInfo::fail_continue(_timestamp != st.st_mtime ? 283 "Timestamp mismatch" : 284 "File size mismatch"); 285 } else { 286 FileMapInfo::fail_continue("A jar file is not the one used while building" 287 " the shared archive file: %s", name); 288 } 289 } 290 return ok; 291 } 292 293 void SharedClassPathEntry::metaspace_pointers_do(MetaspaceClosure* it) { 294 it->push(&_name); 295 it->push(&_manifest); 296 } 297 298 void FileMapInfo::allocate_shared_path_table() { 299 assert(DumpSharedSpaces, "Sanity"); 300 301 Thread* THREAD = Thread::current(); 302 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data(); 303 ClassPathEntry* jrt = ClassLoader::get_jrt_entry(); 304 305 assert(jrt != NULL, 306 "No modular java runtime image present when allocating the CDS classpath entry table"); 307 308 size_t entry_size = sizeof(SharedClassPathEntry); // assert ( should be 8 byte aligned??) 309 int num_boot_classpath_entries = ClassLoader::num_boot_classpath_entries(); 310 int num_app_classpath_entries = ClassLoader::num_app_classpath_entries(); 311 int num_module_path_entries = ClassLoader::num_module_path_entries(); 312 int num_entries = num_boot_classpath_entries + num_app_classpath_entries + num_module_path_entries; 313 size_t bytes = entry_size * num_entries; 314 315 _shared_path_table = MetadataFactory::new_array<u8>(loader_data, (int)(bytes + 7 / 8), THREAD); 316 _shared_path_table_size = num_entries; 317 _shared_path_entry_size = entry_size; 318 319 // 1. boot class path 320 int i = 0; 321 ClassPathEntry* cpe = jrt; 322 while (cpe != NULL) { 323 bool is_jrt = (cpe == jrt); 324 const char* type = (is_jrt ? "jrt" : (cpe->is_jar_file() ? "jar" : "dir")); 325 log_info(class, path)("add main shared path (%s) %s", type, cpe->name()); 326 SharedClassPathEntry* ent = shared_path(i); 327 ent->init(cpe->name(), is_jrt, THREAD); 328 if (!is_jrt) { // No need to do the modules image. 329 EXCEPTION_MARK; // The following call should never throw, but would exit VM on error. 330 update_shared_classpath(cpe, ent, THREAD); 331 } 332 cpe = ClassLoader::get_next_boot_classpath_entry(cpe); 333 i++; 334 } 335 assert(i == num_boot_classpath_entries, 336 "number of boot class path entry mismatch"); 337 338 // 2. app class path 339 ClassPathEntry *acpe = ClassLoader::app_classpath_entries(); 340 while (acpe != NULL) { 341 log_info(class, path)("add app shared path %s", acpe->name()); 342 SharedClassPathEntry* ent = shared_path(i); 343 ent->init(acpe->name(), false, THREAD); 344 EXCEPTION_MARK; 345 update_shared_classpath(acpe, ent, THREAD); 346 acpe = acpe->next(); 347 i++; 348 } 349 350 // 3. module path 351 ClassPathEntry *mpe = ClassLoader::module_path_entries(); 352 while (mpe != NULL) { 353 log_info(class, path)("add module path %s",mpe->name()); 354 SharedClassPathEntry* ent = shared_path(i); 355 ent->init(mpe->name(), false, THREAD); 356 EXCEPTION_MARK; 357 update_shared_classpath(mpe, ent, THREAD); 358 mpe = mpe->next(); 359 i++; 360 } 361 assert(i == num_entries, "number of shared path entry mismatch"); 362 } 363 364 void FileMapInfo::check_nonempty_dir_in_shared_path_table() { 365 assert(DumpSharedSpaces, "dump time only"); 366 367 bool has_nonempty_dir = false; 368 369 int end = _shared_path_table_size; 370 if (!ClassLoaderExt::has_platform_or_app_classes()) { 371 // only check the boot path if no app class is loaded 372 end = ClassLoaderExt::app_class_paths_start_index(); 373 } 374 375 for (int i = 0; i < end; i++) { 376 SharedClassPathEntry *e = shared_path(i); 377 if (e->is_dir()) { 378 const char* path = e->name(); 379 if (!os::dir_is_empty(path)) { 380 tty->print_cr("Error: non-empty directory '%s'", path); 381 has_nonempty_dir = true; 382 } 383 } 384 } 385 386 if (has_nonempty_dir) { 387 ClassLoader::exit_with_path_failure("Cannot have non-empty directory in paths", NULL); 388 } 389 } 390 391 class ManifestStream: public ResourceObj { 392 private: 393 u1* _buffer_start; // Buffer bottom 394 u1* _buffer_end; // Buffer top (one past last element) 395 u1* _current; // Current buffer position 396 397 public: 398 // Constructor 399 ManifestStream(u1* buffer, int length) : _buffer_start(buffer), 400 _current(buffer) { 401 _buffer_end = buffer + length; 402 } 403 404 static bool is_attr(u1* attr, const char* name) { 405 return strncmp((const char*)attr, name, strlen(name)) == 0; 406 } 407 408 static char* copy_attr(u1* value, size_t len) { 409 char* buf = NEW_RESOURCE_ARRAY(char, len + 1); 410 strncpy(buf, (char*)value, len); 411 buf[len] = 0; 412 return buf; 413 } 414 415 // The return value indicates if the JAR is signed or not 416 bool check_is_signed() { 417 u1* attr = _current; 418 bool isSigned = false; 419 while (_current < _buffer_end) { 420 if (*_current == '\n') { 421 *_current = '\0'; 422 u1* value = (u1*)strchr((char*)attr, ':'); 423 if (value != NULL) { 424 assert(*(value+1) == ' ', "Unrecognized format" ); 425 if (strstr((char*)attr, "-Digest") != NULL) { 426 isSigned = true; 427 break; 428 } 429 } 430 *_current = '\n'; // restore 431 attr = _current + 1; 432 } 433 _current ++; 434 } 435 return isSigned; 436 } 437 }; 438 439 void FileMapInfo::update_shared_classpath(ClassPathEntry *cpe, SharedClassPathEntry* ent, TRAPS) { 440 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data(); 441 ResourceMark rm(THREAD); 442 jint manifest_size; 443 444 if (cpe->is_jar_file()) { 445 assert(ent->is_jar(), "the shared class path entry is not a JAR file"); 446 char* manifest = ClassLoaderExt::read_manifest(cpe, &manifest_size, CHECK); 447 if (manifest != NULL) { 448 ManifestStream* stream = new ManifestStream((u1*)manifest, 449 manifest_size); 450 if (stream->check_is_signed()) { 451 ent->set_is_signed(); 452 } else { 453 // Copy the manifest into the shared archive 454 manifest = ClassLoaderExt::read_raw_manifest(cpe, &manifest_size, CHECK); 455 Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data, 456 manifest_size, 457 THREAD); 458 char* p = (char*)(buf->data()); 459 memcpy(p, manifest, manifest_size); 460 ent->set_manifest(buf); 461 } 462 } 463 } 464 } 465 466 467 bool FileMapInfo::validate_shared_path_table() { 468 assert(UseSharedSpaces, "runtime only"); 469 470 _validating_shared_path_table = true; 471 _shared_path_table = _header->_shared_path_table; 472 _shared_path_entry_size = _header->_shared_path_entry_size; 473 _shared_path_table_size = _header->_shared_path_table_size; 474 475 int module_paths_start_index = _header->_app_module_paths_start_index; 476 477 // If the shared archive contain app or platform classes, validate all entries 478 // in the shared path table. Otherwise, only validate the boot path entries (with 479 // entry index < _app_class_paths_start_index). 480 int count = _header->has_platform_or_app_classes() ? 481 _shared_path_table_size : _header->_app_class_paths_start_index; 482 483 for (int i=0; i<count; i++) { 484 if (i < module_paths_start_index) { 485 if (shared_path(i)->validate()) { 486 log_info(class, path)("ok"); 487 } 488 } else if (i >= module_paths_start_index) { 489 if (shared_path(i)->validate(false /* not a class path entry */)) { 490 log_info(class, path)("ok"); 491 } 492 } else if (!PrintSharedArchiveAndExit) { 493 _validating_shared_path_table = false; 494 _shared_path_table = NULL; 495 _shared_path_table_size = 0; 496 return false; 497 } 498 } 499 500 _validating_shared_path_table = false; 501 return true; 502 } 503 504 // Read the FileMapInfo information from the file. 505 506 bool FileMapInfo::init_from_file(int fd) { 507 size_t sz = _header->data_size(); 508 char* addr = _header->data(); 509 size_t n = os::read(fd, addr, (unsigned int)sz); 510 if (n != sz) { 511 fail_continue("Unable to read the file header."); 512 return false; 513 } 514 if (_header->_version != current_version()) { 515 fail_continue("The shared archive file has the wrong version."); 516 return false; 517 } 518 _file_offset = (long)n; 519 520 size_t info_size = _header->_paths_misc_info_size; 521 _paths_misc_info = NEW_C_HEAP_ARRAY_RETURN_NULL(char, info_size, mtClass); 522 if (_paths_misc_info == NULL) { 523 fail_continue("Unable to read the file header."); 524 return false; 525 } 526 n = os::read(fd, _paths_misc_info, (unsigned int)info_size); 527 if (n != info_size) { 528 fail_continue("Unable to read the shared path info header."); 529 FREE_C_HEAP_ARRAY(char, _paths_misc_info); 530 _paths_misc_info = NULL; 531 return false; 532 } 533 534 size_t len = lseek(fd, 0, SEEK_END); 535 FileMapHeader::space_info* si = space_at(MetaspaceShared::last_valid_region); 536 // The last space might be empty 537 if (si->_file_offset > len || len - si->_file_offset < si->_used) { 538 fail_continue("The shared archive file has been truncated."); 539 return false; 540 } 541 542 _file_offset += (long)n; 543 return true; 544 } 545 546 547 // Read the FileMapInfo information from the file. 548 bool FileMapInfo::open_for_read() { 549 _full_path = Arguments::GetSharedArchivePath(); 550 int fd = open(_full_path, O_RDONLY | O_BINARY, 0); 551 if (fd < 0) { 552 if (errno == ENOENT) { 553 // Not locating the shared archive is ok. 554 fail_continue("Specified shared archive not found."); 555 } else { 556 fail_continue("Failed to open shared archive file (%s).", 557 os::strerror(errno)); 558 } 559 return false; 560 } 561 562 _fd = fd; 563 _file_open = true; 564 return true; 565 } 566 567 568 // Write the FileMapInfo information to the file. 569 570 void FileMapInfo::open_for_write() { 571 _full_path = Arguments::GetSharedArchivePath(); 572 LogMessage(cds) msg; 573 if (msg.is_info()) { 574 msg.info("Dumping shared data to file: "); 575 msg.info(" %s", _full_path); 576 } 577 578 #ifdef _WINDOWS // On Windows, need WRITE permission to remove the file. 579 chmod(_full_path, _S_IREAD | _S_IWRITE); 580 #endif 581 582 // Use remove() to delete the existing file because, on Unix, this will 583 // allow processes that have it open continued access to the file. 584 remove(_full_path); 585 int fd = open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444); 586 if (fd < 0) { 587 fail_stop("Unable to create shared archive file %s: (%s).", _full_path, 588 os::strerror(errno)); 589 } 590 _fd = fd; 591 _file_offset = 0; 592 _file_open = true; 593 } 594 595 596 // Write the header to the file, seek to the next allocation boundary. 597 598 void FileMapInfo::write_header() { 599 int info_size = ClassLoader::get_shared_paths_misc_info_size(); 600 601 _header->_paths_misc_info_size = info_size; 602 603 align_file_position(); 604 size_t sz = _header->data_size(); 605 char* addr = _header->data(); 606 write_bytes(addr, (int)sz); // skip the C++ vtable 607 write_bytes(ClassLoader::get_shared_paths_misc_info(), info_size); 608 align_file_position(); 609 } 610 611 612 // Dump region to file. 613 614 void FileMapInfo::write_region(int region, char* base, size_t size, 615 bool read_only, bool allow_exec) { 616 FileMapHeader::space_info* si = space_at(region); 617 618 if (_file_open) { 619 guarantee(si->_file_offset == _file_offset, "file offset mismatch."); 620 log_info(cds)("Shared file region %d: " SIZE_FORMAT_HEX_W(08) 621 " bytes, addr " INTPTR_FORMAT " file offset " SIZE_FORMAT_HEX_W(08), 622 region, size, p2i(base), _file_offset); 623 } else { 624 si->_file_offset = _file_offset; 625 } 626 if (MetaspaceShared::is_heap_region(region)) { 627 assert((base - (char*)Universe::narrow_oop_base()) % HeapWordSize == 0, "Sanity"); 628 if (base != NULL) { 629 si->_addr._offset = (intx)CompressedOops::encode_not_null((oop)base); 630 } else { 631 si->_addr._offset = 0; 632 } 633 } else { 634 si->_addr._base = base; 635 } 636 si->_used = size; 637 si->_read_only = read_only; 638 si->_allow_exec = allow_exec; 639 si->_crc = ClassLoader::crc32(0, base, (jint)size); 640 if (base != NULL) { 641 write_bytes_aligned(base, (int)size); 642 } 643 } 644 645 // Write out the given archive heap memory regions. GC code combines multiple 646 // consecutive archive GC regions into one MemRegion whenever possible and 647 // produces the 'heap_mem' array. 648 // 649 // If the archive heap memory size is smaller than a single dump time GC region 650 // size, there is only one MemRegion in the array. 651 // 652 // If the archive heap memory size is bigger than one dump time GC region size, 653 // the 'heap_mem' array may contain more than one consolidated MemRegions. When 654 // the first/bottom archive GC region is a partial GC region (with the empty 655 // portion at the higher address within the region), one MemRegion is used for 656 // the bottom partial archive GC region. The rest of the consecutive archive 657 // GC regions are combined into another MemRegion. 658 // 659 // Here's the mapping from (archive heap GC regions) -> (GrowableArray<MemRegion> *regions). 660 // + We have 1 or more archive heap regions: ah0, ah1, ah2 ..... ahn 661 // + We have 1 or 2 consolidated heap memory regions: r0 and r1 662 // 663 // If there's a single archive GC region (ah0), then r0 == ah0, and r1 is empty. 664 // Otherwise: 665 // 666 // "X" represented space that's occupied by heap objects. 667 // "_" represented unused spaced in the heap region. 668 // 669 // 670 // |ah0 | ah1 | ah2| ...... | ahn| 671 // |XXXXXX|__ |XXXXX|XXXX|XXXXXXXX|XXXX| 672 // |<-r0->| |<- r1 ----------------->| 673 // ^^^ 674 // | 675 // +-- gap 676 size_t FileMapInfo::write_archive_heap_regions(GrowableArray<MemRegion> *heap_mem, 677 GrowableArray<ArchiveHeapOopmapInfo> *oopmaps, 678 int first_region_id, int max_num_regions) { 679 assert(max_num_regions <= 2, "Only support maximum 2 memory regions"); 680 681 int arr_len = heap_mem == NULL ? 0 : heap_mem->length(); 682 if(arr_len > max_num_regions) { 683 fail_stop("Unable to write archive heap memory regions: " 684 "number of memory regions exceeds maximum due to fragmentation"); 685 } 686 687 size_t total_size = 0; 688 for (int i = first_region_id, arr_idx = 0; 689 i < first_region_id + max_num_regions; 690 i++, arr_idx++) { 691 char* start = NULL; 692 size_t size = 0; 693 if (arr_idx < arr_len) { 694 start = (char*)heap_mem->at(arr_idx).start(); 695 size = heap_mem->at(arr_idx).byte_size(); 696 total_size += size; 697 } 698 699 log_info(cds)("Archive heap region %d " INTPTR_FORMAT " - " INTPTR_FORMAT " = " SIZE_FORMAT_W(8) " bytes", 700 i, p2i(start), p2i(start + size), size); 701 write_region(i, start, size, false, false); 702 if (size > 0) { 703 space_at(i)->_oopmap = oopmaps->at(arr_idx)._oopmap; 704 space_at(i)->_oopmap_size_in_bits = oopmaps->at(arr_idx)._oopmap_size_in_bits; 705 } 706 } 707 return total_size; 708 } 709 710 // Dump bytes to file -- at the current file position. 711 712 void FileMapInfo::write_bytes(const void* buffer, int nbytes) { 713 if (_file_open) { 714 int n = ::write(_fd, buffer, nbytes); 715 if (n != nbytes) { 716 // It is dangerous to leave the corrupted shared archive file around, 717 // close and remove the file. See bug 6372906. 718 close(); 719 remove(_full_path); 720 fail_stop("Unable to write to shared archive file."); 721 } 722 } 723 _file_offset += nbytes; 724 } 725 726 727 // Align file position to an allocation unit boundary. 728 729 void FileMapInfo::align_file_position() { 730 size_t new_file_offset = align_up(_file_offset, 731 os::vm_allocation_granularity()); 732 if (new_file_offset != _file_offset) { 733 _file_offset = new_file_offset; 734 if (_file_open) { 735 // Seek one byte back from the target and write a byte to insure 736 // that the written file is the correct length. 737 _file_offset -= 1; 738 if (lseek(_fd, (long)_file_offset, SEEK_SET) < 0) { 739 fail_stop("Unable to seek."); 740 } 741 char zero = 0; 742 write_bytes(&zero, 1); 743 } 744 } 745 } 746 747 748 // Dump bytes to file -- at the current file position. 749 750 void FileMapInfo::write_bytes_aligned(const void* buffer, int nbytes) { 751 align_file_position(); 752 write_bytes(buffer, nbytes); 753 align_file_position(); 754 } 755 756 757 // Close the shared archive file. This does NOT unmap mapped regions. 758 759 void FileMapInfo::close() { 760 if (_file_open) { 761 if (::close(_fd) < 0) { 762 fail_stop("Unable to close the shared archive file."); 763 } 764 _file_open = false; 765 _fd = -1; 766 } 767 } 768 769 770 // JVM/TI RedefineClasses() support: 771 // Remap the shared readonly space to shared readwrite, private. 772 bool FileMapInfo::remap_shared_readonly_as_readwrite() { 773 int idx = MetaspaceShared::ro; 774 FileMapHeader::space_info* si = space_at(idx); 775 if (!si->_read_only) { 776 // the space is already readwrite so we are done 777 return true; 778 } 779 size_t used = si->_used; 780 size_t size = align_up(used, os::vm_allocation_granularity()); 781 if (!open_for_read()) { 782 return false; 783 } 784 char *addr = _header->region_addr(idx); 785 char *base = os::remap_memory(_fd, _full_path, si->_file_offset, 786 addr, size, false /* !read_only */, 787 si->_allow_exec); 788 close(); 789 if (base == NULL) { 790 fail_continue("Unable to remap shared readonly space (errno=%d).", errno); 791 return false; 792 } 793 if (base != addr) { 794 fail_continue("Unable to remap shared readonly space at required address."); 795 return false; 796 } 797 si->_read_only = false; 798 return true; 799 } 800 801 // Map the whole region at once, assumed to be allocated contiguously. 802 ReservedSpace FileMapInfo::reserve_shared_memory() { 803 char* requested_addr = _header->region_addr(0); 804 size_t size = FileMapInfo::core_spaces_size(); 805 806 // Reserve the space first, then map otherwise map will go right over some 807 // other reserved memory (like the code cache). 808 ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr); 809 if (!rs.is_reserved()) { 810 fail_continue("Unable to reserve shared space at required address " 811 INTPTR_FORMAT, p2i(requested_addr)); 812 return rs; 813 } 814 // the reserved virtual memory is for mapping class data sharing archive 815 MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared); 816 817 return rs; 818 } 819 820 // Memory map a region in the address space. 821 static const char* shared_region_name[] = { "MiscData", "ReadWrite", "ReadOnly", "MiscCode", "OptionalData", 822 "String1", "String2", "OpenArchive1", "OpenArchive2" }; 823 824 char* FileMapInfo::map_region(int i, char** top_ret) { 825 assert(!MetaspaceShared::is_heap_region(i), "sanity"); 826 FileMapHeader::space_info* si = space_at(i); 827 size_t used = si->_used; 828 size_t alignment = os::vm_allocation_granularity(); 829 size_t size = align_up(used, alignment); 830 char *requested_addr = _header->region_addr(i); 831 832 // If a tool agent is in use (debugging enabled), we must map the address space RW 833 if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space()) { 834 si->_read_only = false; 835 } 836 837 // map the contents of the CDS archive in this memory 838 char *base = os::map_memory(_fd, _full_path, si->_file_offset, 839 requested_addr, size, si->_read_only, 840 si->_allow_exec); 841 if (base == NULL || base != requested_addr) { 842 fail_continue("Unable to map %s shared space at required address.", shared_region_name[i]); 843 return NULL; 844 } 845 #ifdef _WINDOWS 846 // This call is Windows-only because the memory_type gets recorded for the other platforms 847 // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows. 848 MemTracker::record_virtual_memory_type((address)base, mtClassShared); 849 #endif 850 851 852 if (!verify_region_checksum(i)) { 853 return NULL; 854 } 855 856 *top_ret = base + size; 857 return base; 858 } 859 860 861 address FileMapInfo::FileMapHeader::space_info::decode_start_address(bool with_current_oop_encoding_mode) { 862 if (with_current_oop_encoding_mode) { 863 return (address)CompressedOops::decode_not_null(offset()); 864 } else { 865 return (address)HeapShared::decode_with_archived_oop_encoding_mode(offset()); 866 } 867 } 868 869 static MemRegion *string_ranges = NULL; 870 static MemRegion *open_archive_heap_ranges = NULL; 871 static int num_string_ranges = 0; 872 static int num_open_archive_heap_ranges = 0; 873 874 #if INCLUDE_CDS_JAVA_HEAP 875 bool FileMapInfo::has_heap_regions() { 876 return (_header->_space[MetaspaceShared::first_string]._used > 0); 877 } 878 879 // Returns the address range where the heap regions would occupy using the 880 // current oop encoding mode. 881 MemRegion FileMapInfo::get_heap_regions_range_with_current_oop_encoding_mode() { 882 address start = (address) max_uintx; 883 address end = NULL; 884 885 for (int i = MetaspaceShared::first_string; i <= MetaspaceShared::last_valid_region; i++) { 886 FileMapHeader::space_info* si = space_at(i); 887 size_t size = si->_used; 888 if (size > 0) { 889 address s = si->start_address_with_current_oop_encoding_mode(); 890 address e = s + size; 891 if (start > s) { 892 start = s; 893 } 894 if (end < e) { 895 end = e; 896 } 897 } 898 } 899 assert(end != NULL, "must have at least one used heap region"); 900 return MemRegion((HeapWord*)start, (HeapWord*)end); 901 } 902 903 // 904 // Map the shared string objects and open archive heap objects to the runtime 905 // java heap. 906 // 907 // The shared strings are mapped near the runtime java heap top. The 908 // mapped strings contain no out-going references to any other java heap 909 // regions. GC does not write into the mapped shared strings. 910 // 911 // The open archive heap objects are mapped below the shared strings in 912 // the runtime java heap. The mapped open archive heap data only contain 913 // references to the shared strings and open archive objects initially. 914 // During runtime execution, out-going references to any other java heap 915 // regions may be added. GC may mark and update references in the mapped 916 // open archive objects. 917 void FileMapInfo::map_heap_regions_impl() { 918 if (!MetaspaceShared::is_heap_object_archiving_allowed()) { 919 log_info(cds)("CDS heap data is being ignored. UseG1GC, " 920 "UseCompressedOops and UseCompressedClassPointers are required."); 921 return; 922 } 923 924 MemRegion g1_reserved = G1CollectedHeap::heap()->g1_reserved(); 925 926 log_info(cds)("CDS archive was created with max heap size = " UINTX_FORMAT "M, and the following configuration:", 927 max_heap_size()/M); 928 log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d", 929 p2i(narrow_klass_base()), narrow_klass_shift()); 930 log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d", 931 narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift()); 932 933 log_info(cds)("The current max heap size = " UINTX_FORMAT "M, HeapRegion::GrainBytes = " UINTX_FORMAT, 934 g1_reserved.byte_size()/M, HeapRegion::GrainBytes); 935 log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d", 936 p2i(Universe::narrow_klass_base()), Universe::narrow_klass_shift()); 937 log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d", 938 Universe::narrow_oop_mode(), p2i(Universe::narrow_oop_base()), Universe::narrow_oop_shift()); 939 940 if (narrow_klass_base() != Universe::narrow_klass_base() || 941 narrow_klass_shift() != Universe::narrow_klass_shift()) { 942 log_info(cds)("CDS heap data cannot be used because the archive was created with an incompatible heap size."); 943 return; 944 } 945 946 if (narrow_oop_mode() != Universe::narrow_oop_mode() || 947 narrow_oop_base() != Universe::narrow_oop_base() || 948 narrow_oop_shift() != Universe::narrow_oop_shift()) { 949 log_info(cds)("CDS heap data need to be relocated because the archive was created with an incompatible heap size."); 950 _heap_pointers_need_patching = true; 951 } else { 952 MemRegion range = get_heap_regions_range_with_current_oop_encoding_mode(); 953 if (!g1_reserved.contains(range)) { 954 log_info(cds)("CDS heap data need to be relocated because"); 955 log_info(cds)("the desired range " PTR_FORMAT " - " PTR_FORMAT, p2i(range.start()), p2i(range.end())); 956 log_info(cds)("is outside of the heap " PTR_FORMAT " - " PTR_FORMAT, p2i(g1_reserved.start()), p2i(g1_reserved.end())); 957 _heap_pointers_need_patching = true; 958 } 959 } 960 961 ptrdiff_t delta = 0; 962 if (_heap_pointers_need_patching) { 963 // dumptime heap end ------------v 964 // [ |archived heap regions| ] runtime heap end ------v 965 // [ |archived heap regions| ] 966 // |<-----delta-------------------->| 967 // 968 // At dump time, the archived heap regions were near the top of the heap. 969 // At run time, they may not be inside the heap, so we move them so 970 // that they are now near the top of the runtime time. This can be done by 971 // the simple math of adding the delta as shown above. 972 address dumptime_heap_end = (address)_header->_g1_reserved.end(); 973 address runtime_heap_end = (address)g1_reserved.end(); 974 delta = runtime_heap_end - dumptime_heap_end; 975 } 976 977 log_info(cds)("CDS heap data relocation delta = " INTX_FORMAT " bytes", delta); 978 HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift()); 979 980 FileMapHeader::space_info* si = space_at(MetaspaceShared::first_string); 981 address relocated_strings_bottom = si->start_address_with_archived_oop_encoding_mode(); 982 if (!is_aligned(relocated_strings_bottom + delta, HeapRegion::GrainBytes)) { 983 // Align the bottom of the string regions at G1 region boundary. This will avoid 984 // the situation where the highest open region and the lowest string region sharing 985 // the same G1 region. Otherwise we will fail to map the open regions. 986 size_t align = size_t(relocated_strings_bottom) % HeapRegion::GrainBytes; 987 delta -= align; 988 assert(is_aligned(relocated_strings_bottom + delta, HeapRegion::GrainBytes), "must be"); 989 990 log_info(cds)("CDS heap data need to be relocated lower by a further " UINTX_FORMAT 991 " bytes to be aligned with HeapRegion::GrainBytes", align); 992 993 HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift()); 994 _heap_pointers_need_patching = true; 995 } 996 997 // First, map string regions as closed archive heap regions. 998 // GC does not write into the regions. 999 if (map_heap_data(&string_ranges, 1000 MetaspaceShared::first_string, 1001 MetaspaceShared::max_strings, 1002 &num_string_ranges)) { 1003 StringTable::set_shared_string_mapped(); 1004 1005 // Now, map open_archive heap regions, GC can write into the regions. 1006 if (map_heap_data(&open_archive_heap_ranges, 1007 MetaspaceShared::first_open_archive_heap_region, 1008 MetaspaceShared::max_open_archive_heap_region, 1009 &num_open_archive_heap_ranges, 1010 true /* open */)) { 1011 MetaspaceShared::set_open_archive_heap_region_mapped(); 1012 } 1013 } 1014 } 1015 1016 void FileMapInfo::map_heap_regions() { 1017 if (has_heap_regions()) { 1018 map_heap_regions_impl(); 1019 } 1020 1021 if (!StringTable::shared_string_mapped()) { 1022 assert(string_ranges == NULL && num_string_ranges == 0, "sanity"); 1023 } 1024 1025 if (!MetaspaceShared::open_archive_heap_region_mapped()) { 1026 assert(open_archive_heap_ranges == NULL && num_open_archive_heap_ranges == 0, "sanity"); 1027 } 1028 } 1029 1030 bool FileMapInfo::map_heap_data(MemRegion **heap_mem, int first, 1031 int max, int* num, bool is_open_archive) { 1032 MemRegion * regions = new MemRegion[max]; 1033 FileMapHeader::space_info* si; 1034 int region_num = 0; 1035 1036 for (int i = first; 1037 i < first + max; i++) { 1038 si = space_at(i); 1039 size_t size = si->_used; 1040 if (size > 0) { 1041 HeapWord* start = (HeapWord*)si->start_address_with_archived_oop_encoding_mode(); 1042 regions[region_num] = MemRegion(start, size / HeapWordSize); 1043 region_num ++; 1044 log_info(cds)("Trying to map heap data: region[%d] at " INTPTR_FORMAT ", size = %8d bytes", 1045 i, p2i(start), int(size)); 1046 } 1047 } 1048 1049 if (region_num == 0) { 1050 return false; // no archived java heap data 1051 } 1052 1053 // Check that ranges are within the java heap 1054 if (!G1CollectedHeap::heap()->check_archive_addresses(regions, region_num)) { 1055 log_info(cds)("UseSharedSpaces: Unable to allocate region, range is not within java heap."); 1056 return false; 1057 } 1058 1059 // allocate from java heap 1060 if (!G1CollectedHeap::heap()->alloc_archive_regions( 1061 regions, region_num, is_open_archive)) { 1062 log_info(cds)("UseSharedSpaces: Unable to allocate region, java heap range is already in use."); 1063 return false; 1064 } 1065 1066 // Map the archived heap data. No need to call MemTracker::record_virtual_memory_type() 1067 // for mapped regions as they are part of the reserved java heap, which is 1068 // already recorded. 1069 for (int i = 0; i < region_num; i++) { 1070 si = space_at(first + i); 1071 char* addr = (char*)regions[i].start(); 1072 char* base = os::map_memory(_fd, _full_path, si->_file_offset, 1073 addr, regions[i].byte_size(), si->_read_only, 1074 si->_allow_exec); 1075 if (base == NULL || base != addr) { 1076 // dealloc the regions from java heap 1077 dealloc_archive_heap_regions(regions, region_num); 1078 log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap. " 1079 INTPTR_FORMAT ", size = " UINTX_FORMAT " bytes", 1080 p2i(addr), regions[i].byte_size()); 1081 return false; 1082 } 1083 } 1084 1085 if (!verify_mapped_heap_regions(first, region_num)) { 1086 // dealloc the regions from java heap 1087 dealloc_archive_heap_regions(regions, region_num); 1088 log_info(cds)("UseSharedSpaces: mapped heap regions are corrupt"); 1089 return false; 1090 } 1091 1092 // the shared heap data is mapped successfully 1093 *heap_mem = regions; 1094 *num = region_num; 1095 return true; 1096 } 1097 1098 bool FileMapInfo::verify_mapped_heap_regions(int first, int num) { 1099 for (int i = first; 1100 i <= first + num; i++) { 1101 if (!verify_region_checksum(i)) { 1102 return false; 1103 } 1104 } 1105 return true; 1106 } 1107 1108 void FileMapInfo::patch_archived_heap_embedded_pointers() { 1109 if (!_heap_pointers_need_patching) { 1110 return; 1111 } 1112 1113 patch_archived_heap_embedded_pointers(string_ranges, 1114 num_string_ranges, 1115 MetaspaceShared::first_string); 1116 1117 patch_archived_heap_embedded_pointers(open_archive_heap_ranges, 1118 num_open_archive_heap_ranges, 1119 MetaspaceShared::first_open_archive_heap_region); 1120 } 1121 1122 void FileMapInfo::patch_archived_heap_embedded_pointers(MemRegion* ranges, int num_ranges, 1123 int first_region_idx) { 1124 for (int i=0; i<num_ranges; i++) { 1125 FileMapHeader::space_info* si = space_at(i + first_region_idx); 1126 HeapShared::patch_archived_heap_embedded_pointers(ranges[i], si->_oopmap, 1127 si->_oopmap_size_in_bits); 1128 } 1129 } 1130 1131 // This internally allocates objects using SystemDictionary::Object_klass(), so it 1132 // must be called after the well-known classes are resolved. 1133 void FileMapInfo::fixup_mapped_heap_regions() { 1134 // If any string regions were found, call the fill routine to make them parseable. 1135 // Note that string_ranges may be non-NULL even if no ranges were found. 1136 if (num_string_ranges != 0) { 1137 assert(string_ranges != NULL, "Null string_ranges array with non-zero count"); 1138 G1CollectedHeap::heap()->fill_archive_regions(string_ranges, num_string_ranges); 1139 } 1140 1141 // do the same for mapped open archive heap regions 1142 if (num_open_archive_heap_ranges != 0) { 1143 assert(open_archive_heap_ranges != NULL, "NULL open_archive_heap_ranges array with non-zero count"); 1144 G1CollectedHeap::heap()->fill_archive_regions(open_archive_heap_ranges, 1145 num_open_archive_heap_ranges); 1146 } 1147 } 1148 1149 // dealloc the archive regions from java heap 1150 void FileMapInfo::dealloc_archive_heap_regions(MemRegion* regions, int num) { 1151 if (num > 0) { 1152 assert(regions != NULL, "Null archive ranges array with non-zero count"); 1153 G1CollectedHeap::heap()->dealloc_archive_regions(regions, num); 1154 } 1155 } 1156 #endif // INCLUDE_CDS_JAVA_HEAP 1157 1158 bool FileMapInfo::verify_region_checksum(int i) { 1159 if (!VerifySharedSpaces) { 1160 return true; 1161 } 1162 1163 size_t sz = _header->_space[i]._used; 1164 1165 if (sz == 0) { 1166 return true; // no data 1167 } 1168 if ((MetaspaceShared::is_string_region(i) && 1169 !StringTable::shared_string_mapped()) || 1170 (MetaspaceShared::is_open_archive_heap_region(i) && 1171 !MetaspaceShared::open_archive_heap_region_mapped())) { 1172 return true; // archived heap data is not mapped 1173 } 1174 const char* buf = _header->region_addr(i); 1175 int crc = ClassLoader::crc32(0, buf, (jint)sz); 1176 if (crc != _header->_space[i]._crc) { 1177 fail_continue("Checksum verification failed."); 1178 return false; 1179 } 1180 return true; 1181 } 1182 1183 // Unmap a memory region in the address space. 1184 1185 void FileMapInfo::unmap_region(int i) { 1186 assert(!MetaspaceShared::is_heap_region(i), "sanity"); 1187 FileMapHeader::space_info* si = space_at(i); 1188 size_t used = si->_used; 1189 size_t size = align_up(used, os::vm_allocation_granularity()); 1190 1191 if (used == 0) { 1192 return; 1193 } 1194 1195 char* addr = _header->region_addr(i); 1196 if (!os::unmap_memory(addr, size)) { 1197 fail_stop("Unable to unmap shared space."); 1198 } 1199 } 1200 1201 void FileMapInfo::assert_mark(bool check) { 1202 if (!check) { 1203 fail_stop("Mark mismatch while restoring from shared file."); 1204 } 1205 } 1206 1207 void FileMapInfo::metaspace_pointers_do(MetaspaceClosure* it) { 1208 it->push(&_shared_path_table); 1209 for (int i=0; i<_shared_path_table_size; i++) { 1210 shared_path(i)->metaspace_pointers_do(it); 1211 } 1212 } 1213 1214 1215 FileMapInfo* FileMapInfo::_current_info = NULL; 1216 bool FileMapInfo::_heap_pointers_need_patching = false; 1217 Array<u8>* FileMapInfo::_shared_path_table = NULL; 1218 int FileMapInfo::_shared_path_table_size = 0; 1219 size_t FileMapInfo::_shared_path_entry_size = 0x1234baad; 1220 bool FileMapInfo::_validating_shared_path_table = false; 1221 1222 // Open the shared archive file, read and validate the header 1223 // information (version, boot classpath, etc.). If initialization 1224 // fails, shared spaces are disabled and the file is closed. [See 1225 // fail_continue.] 1226 // 1227 // Validation of the archive is done in two steps: 1228 // 1229 // [1] validate_header() - done here. This checks the header, including _paths_misc_info. 1230 // [2] validate_shared_path_table - this is done later, because the table is in the RW 1231 // region of the archive, which is not mapped yet. 1232 bool FileMapInfo::initialize() { 1233 assert(UseSharedSpaces, "UseSharedSpaces expected."); 1234 1235 if (!open_for_read()) { 1236 return false; 1237 } 1238 1239 init_from_file(_fd); 1240 if (!validate_header()) { 1241 return false; 1242 } 1243 return true; 1244 } 1245 1246 char* FileMapInfo::FileMapHeader::region_addr(int idx) { 1247 if (MetaspaceShared::is_heap_region(idx)) { 1248 assert(DumpSharedSpaces, "The following doesn't work at runtime"); 1249 return _space[idx]._used > 0 ? 1250 (char*)_space[idx].start_address_with_current_oop_encoding_mode() : NULL; 1251 } else { 1252 return _space[idx]._addr._base; 1253 } 1254 } 1255 1256 int FileMapInfo::FileMapHeader::compute_crc() { 1257 char* header = data(); 1258 // start computing from the field after _crc 1259 char* buf = (char*)&_crc + sizeof(int); 1260 size_t sz = data_size() - (buf - header); 1261 int crc = ClassLoader::crc32(0, buf, (jint)sz); 1262 return crc; 1263 } 1264 1265 // This function should only be called during run time with UseSharedSpaces enabled. 1266 bool FileMapInfo::FileMapHeader::validate() { 1267 if (VerifySharedSpaces && compute_crc() != _crc) { 1268 fail_continue("Header checksum verification failed."); 1269 return false; 1270 } 1271 1272 if (!Arguments::has_jimage()) { 1273 FileMapInfo::fail_continue("The shared archive file cannot be used with an exploded module build."); 1274 return false; 1275 } 1276 1277 if (_version != current_version()) { 1278 FileMapInfo::fail_continue("The shared archive file is the wrong version."); 1279 return false; 1280 } 1281 if (_magic != (int)0xf00baba2) { 1282 FileMapInfo::fail_continue("The shared archive file has a bad magic number."); 1283 return false; 1284 } 1285 char header_version[JVM_IDENT_MAX]; 1286 get_header_version(header_version); 1287 if (strncmp(_jvm_ident, header_version, JVM_IDENT_MAX-1) != 0) { 1288 log_info(class, path)("expected: %s", header_version); 1289 log_info(class, path)("actual: %s", _jvm_ident); 1290 FileMapInfo::fail_continue("The shared archive file was created by a different" 1291 " version or build of HotSpot"); 1292 return false; 1293 } 1294 if (_obj_alignment != ObjectAlignmentInBytes) { 1295 FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d" 1296 " does not equal the current ObjectAlignmentInBytes of " INTX_FORMAT ".", 1297 _obj_alignment, ObjectAlignmentInBytes); 1298 return false; 1299 } 1300 if (_compact_strings != CompactStrings) { 1301 FileMapInfo::fail_continue("The shared archive file's CompactStrings setting (%s)" 1302 " does not equal the current CompactStrings setting (%s).", 1303 _compact_strings ? "enabled" : "disabled", 1304 CompactStrings ? "enabled" : "disabled"); 1305 return false; 1306 } 1307 1308 // This must be done after header validation because it might change the 1309 // header data 1310 const char* prop = Arguments::get_property("java.system.class.loader"); 1311 if (prop != NULL) { 1312 warning("Archived non-system classes are disabled because the " 1313 "java.system.class.loader property is specified (value = \"%s\"). " 1314 "To use archived non-system classes, this property must be not be set", prop); 1315 _has_platform_or_app_classes = false; 1316 } 1317 1318 // For backwards compatibility, we don't check the verification setting 1319 // if the archive only contains system classes. 1320 if (_has_platform_or_app_classes && 1321 ((!_verify_local && BytecodeVerificationLocal) || 1322 (!_verify_remote && BytecodeVerificationRemote))) { 1323 FileMapInfo::fail_continue("The shared archive file was created with less restrictive " 1324 "verification setting than the current setting."); 1325 return false; 1326 } 1327 1328 return true; 1329 } 1330 1331 bool FileMapInfo::validate_header() { 1332 bool status = _header->validate(); 1333 1334 if (status) { 1335 if (!ClassLoader::check_shared_paths_misc_info(_paths_misc_info, _header->_paths_misc_info_size)) { 1336 if (!PrintSharedArchiveAndExit) { 1337 fail_continue("shared class paths mismatch (hint: enable -Xlog:class+path=info to diagnose the failure)"); 1338 status = false; 1339 } 1340 } 1341 } 1342 1343 if (_paths_misc_info != NULL) { 1344 FREE_C_HEAP_ARRAY(char, _paths_misc_info); 1345 _paths_misc_info = NULL; 1346 } 1347 return status; 1348 } 1349 1350 // Check if a given address is within one of the shared regions 1351 bool FileMapInfo::is_in_shared_region(const void* p, int idx) { 1352 assert(idx == MetaspaceShared::ro || 1353 idx == MetaspaceShared::rw || 1354 idx == MetaspaceShared::mc || 1355 idx == MetaspaceShared::md, "invalid region index"); 1356 char* base = _header->region_addr(idx); 1357 if (p >= base && p < base + _header->_space[idx]._used) { 1358 return true; 1359 } 1360 return false; 1361 } 1362 1363 // Unmap mapped regions of shared space. 1364 void FileMapInfo::stop_sharing_and_unmap(const char* msg) { 1365 FileMapInfo *map_info = FileMapInfo::current_info(); 1366 if (map_info) { 1367 map_info->fail_continue("%s", msg); 1368 for (int i = 0; i < MetaspaceShared::num_non_heap_spaces; i++) { 1369 if (!MetaspaceShared::is_heap_region(i)) { 1370 char *addr = map_info->_header->region_addr(i); 1371 if (addr != NULL) { 1372 map_info->unmap_region(i); 1373 map_info->_header->_space[i]._addr._base = NULL; 1374 } 1375 } 1376 } 1377 // Dealloc the archive heap regions only without unmapping. The regions are part 1378 // of the java heap. Unmapping of the heap regions are managed by GC. 1379 map_info->dealloc_archive_heap_regions(open_archive_heap_ranges, 1380 num_open_archive_heap_ranges); 1381 map_info->dealloc_archive_heap_regions(string_ranges, num_string_ranges); 1382 } else if (DumpSharedSpaces) { 1383 fail_stop("%s", msg); 1384 } 1385 }