1 /* 2 * Copyright (c) 2003, 2019, 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/classLoaderData.inline.hpp" 29 #include "classfile/classLoaderExt.hpp" 30 #include "classfile/symbolTable.hpp" 31 #include "classfile/systemDictionaryShared.hpp" 32 #include "classfile/altHashing.hpp" 33 #include "logging/log.hpp" 34 #include "logging/logStream.hpp" 35 #include "logging/logMessage.hpp" 36 #include "memory/filemap.hpp" 37 #include "memory/heapShared.inline.hpp" 38 #include "memory/iterator.inline.hpp" 39 #include "memory/metadataFactory.hpp" 40 #include "memory/metaspaceClosure.hpp" 41 #include "memory/metaspaceShared.hpp" 42 #include "memory/oopFactory.hpp" 43 #include "oops/compressedOops.inline.hpp" 44 #include "oops/objArrayOop.hpp" 45 #include "oops/oop.inline.hpp" 46 #include "prims/jvmtiExport.hpp" 47 #include "runtime/arguments.hpp" 48 #include "runtime/java.hpp" 49 #include "runtime/mutexLocker.hpp" 50 #include "runtime/os.inline.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 = (FileMapHeader*)os::malloc(sizeof(FileMapHeader), mtInternal); 167 _header->_version = INVALID_CDS_ARCHIVE_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 FileMapHeader::populate(FileMapInfo* mapinfo, size_t alignment) { 181 _magic = CDS_ARCHIVE_MAGIC; 182 _version = CURRENT_CDS_ARCHIVE_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 (HeapShared::is_heap_object_archiving_allowed()) { 196 _heap_reserved = Universe::heap()->reserved_region(); 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 _max_used_path_index = ClassLoaderExt::max_used_path_index(); 210 211 _verify_local = BytecodeVerificationLocal; 212 _verify_remote = BytecodeVerificationRemote; 213 _has_platform_or_app_classes = ClassLoaderExt::has_platform_or_app_classes(); 214 _shared_base_address = SharedBaseAddress; 215 _allow_archiving_with_java_agent = AllowArchivingWithJavaAgent; 216 } 217 218 void SharedClassPathEntry::init(const char* name, bool is_modules_image, TRAPS) { 219 assert(DumpSharedSpaces, "dump time only"); 220 _timestamp = 0; 221 _filesize = 0; 222 223 struct stat st; 224 if (os::stat(name, &st) == 0) { 225 if ((st.st_mode & S_IFMT) == S_IFDIR) { 226 _type = dir_entry; 227 } else { 228 // The timestamp of the modules_image is not checked at runtime. 229 if (is_modules_image) { 230 _type = modules_image_entry; 231 } else { 232 _type = jar_entry; 233 _timestamp = st.st_mtime; 234 } 235 _filesize = st.st_size; 236 } 237 } else { 238 // The file/dir must exist, or it would not have been added 239 // into ClassLoader::classpath_entry(). 240 // 241 // If we can't access a jar file in the boot path, then we can't 242 // make assumptions about where classes get loaded from. 243 FileMapInfo::fail_stop("Unable to open file %s.", name); 244 } 245 246 size_t len = strlen(name) + 1; 247 _name = MetadataFactory::new_array<char>(ClassLoaderData::the_null_class_loader_data(), (int)len, THREAD); 248 strcpy(_name->data(), name); 249 } 250 251 bool SharedClassPathEntry::validate(bool is_class_path) { 252 assert(UseSharedSpaces, "runtime only"); 253 254 struct stat st; 255 const char* name; 256 257 // In order to validate the runtime modules image file size against the archived 258 // size information, we need to obtain the runtime modules image path. The recorded 259 // dump time modules image path in the archive may be different from the runtime path 260 // if the JDK image has beed moved after generating the archive. 261 if (is_modules_image()) { 262 name = ClassLoader::get_jrt_entry()->name(); 263 } else { 264 name = this->name(); 265 } 266 267 bool ok = true; 268 log_info(class, path)("checking shared classpath entry: %s", name); 269 if (os::stat(name, &st) != 0 && is_class_path) { 270 // If the archived module path entry does not exist at runtime, it is not fatal 271 // (no need to invalid the shared archive) because the shared runtime visibility check 272 // filters out any archived module classes that do not have a matching runtime 273 // module path location. 274 FileMapInfo::fail_continue("Required classpath entry does not exist: %s", name); 275 ok = false; 276 } else if (is_dir()) { 277 if (!os::dir_is_empty(name)) { 278 FileMapInfo::fail_continue("directory is not empty: %s", name); 279 ok = false; 280 } 281 } else if ((has_timestamp() && _timestamp != st.st_mtime) || 282 _filesize != st.st_size) { 283 ok = false; 284 if (PrintSharedArchiveAndExit) { 285 FileMapInfo::fail_continue(_timestamp != st.st_mtime ? 286 "Timestamp mismatch" : 287 "File size mismatch"); 288 } else { 289 FileMapInfo::fail_continue("A jar file is not the one used while building" 290 " the shared archive file: %s", name); 291 } 292 } 293 294 if (PrintSharedArchiveAndExit && !ok) { 295 // If PrintSharedArchiveAndExit is enabled, don't report failure to the 296 // caller. Please see above comments for more details. 297 ok = true; 298 } 299 return ok; 300 } 301 302 void SharedClassPathEntry::metaspace_pointers_do(MetaspaceClosure* it) { 303 it->push(&_name); 304 it->push(&_manifest); 305 } 306 307 void FileMapInfo::allocate_shared_path_table() { 308 assert(DumpSharedSpaces, "Sanity"); 309 310 Thread* THREAD = Thread::current(); 311 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data(); 312 ClassPathEntry* jrt = ClassLoader::get_jrt_entry(); 313 314 assert(jrt != NULL, 315 "No modular java runtime image present when allocating the CDS classpath entry table"); 316 317 size_t entry_size = sizeof(SharedClassPathEntry); // assert ( should be 8 byte aligned??) 318 int num_boot_classpath_entries = ClassLoader::num_boot_classpath_entries(); 319 int num_app_classpath_entries = ClassLoader::num_app_classpath_entries(); 320 int num_module_path_entries = ClassLoader::num_module_path_entries(); 321 int num_entries = num_boot_classpath_entries + num_app_classpath_entries + num_module_path_entries; 322 size_t bytes = entry_size * num_entries; 323 324 _shared_path_table = MetadataFactory::new_array<u8>(loader_data, (int)(bytes + 7 / 8), THREAD); 325 _shared_path_table_size = num_entries; 326 _shared_path_entry_size = entry_size; 327 328 // 1. boot class path 329 int i = 0; 330 ClassPathEntry* cpe = jrt; 331 while (cpe != NULL) { 332 bool is_jrt = (cpe == jrt); 333 const char* type = (is_jrt ? "jrt" : (cpe->is_jar_file() ? "jar" : "dir")); 334 log_info(class, path)("add main shared path (%s) %s", type, cpe->name()); 335 SharedClassPathEntry* ent = shared_path(i); 336 ent->init(cpe->name(), is_jrt, THREAD); 337 if (!is_jrt) { // No need to do the modules image. 338 EXCEPTION_MARK; // The following call should never throw, but would exit VM on error. 339 update_shared_classpath(cpe, ent, THREAD); 340 } 341 cpe = ClassLoader::get_next_boot_classpath_entry(cpe); 342 i++; 343 } 344 assert(i == num_boot_classpath_entries, 345 "number of boot class path entry mismatch"); 346 347 // 2. app class path 348 ClassPathEntry *acpe = ClassLoader::app_classpath_entries(); 349 while (acpe != NULL) { 350 log_info(class, path)("add app shared path %s", acpe->name()); 351 SharedClassPathEntry* ent = shared_path(i); 352 ent->init(acpe->name(), false, THREAD); 353 EXCEPTION_MARK; 354 update_shared_classpath(acpe, ent, THREAD); 355 acpe = acpe->next(); 356 i++; 357 } 358 359 // 3. module path 360 ClassPathEntry *mpe = ClassLoader::module_path_entries(); 361 while (mpe != NULL) { 362 log_info(class, path)("add module path %s",mpe->name()); 363 SharedClassPathEntry* ent = shared_path(i); 364 ent->init(mpe->name(), false, THREAD); 365 EXCEPTION_MARK; 366 update_shared_classpath(mpe, ent, THREAD); 367 mpe = mpe->next(); 368 i++; 369 } 370 assert(i == num_entries, "number of shared path entry mismatch"); 371 } 372 373 void FileMapInfo::check_nonempty_dir_in_shared_path_table() { 374 assert(DumpSharedSpaces, "dump time only"); 375 376 bool has_nonempty_dir = false; 377 378 int last = _shared_path_table_size - 1; 379 if (last > ClassLoaderExt::max_used_path_index()) { 380 // no need to check any path beyond max_used_path_index 381 last = ClassLoaderExt::max_used_path_index(); 382 } 383 384 for (int i = 0; i <= last; i++) { 385 SharedClassPathEntry *e = shared_path(i); 386 if (e->is_dir()) { 387 const char* path = e->name(); 388 if (!os::dir_is_empty(path)) { 389 tty->print_cr("Error: non-empty directory '%s'", path); 390 has_nonempty_dir = true; 391 } 392 } 393 } 394 395 if (has_nonempty_dir) { 396 ClassLoader::exit_with_path_failure("Cannot have non-empty directory in paths", NULL); 397 } 398 } 399 400 class ManifestStream: public ResourceObj { 401 private: 402 u1* _buffer_start; // Buffer bottom 403 u1* _buffer_end; // Buffer top (one past last element) 404 u1* _current; // Current buffer position 405 406 public: 407 // Constructor 408 ManifestStream(u1* buffer, int length) : _buffer_start(buffer), 409 _current(buffer) { 410 _buffer_end = buffer + length; 411 } 412 413 static bool is_attr(u1* attr, const char* name) { 414 return strncmp((const char*)attr, name, strlen(name)) == 0; 415 } 416 417 static char* copy_attr(u1* value, size_t len) { 418 char* buf = NEW_RESOURCE_ARRAY(char, len + 1); 419 strncpy(buf, (char*)value, len); 420 buf[len] = 0; 421 return buf; 422 } 423 424 // The return value indicates if the JAR is signed or not 425 bool check_is_signed() { 426 u1* attr = _current; 427 bool isSigned = false; 428 while (_current < _buffer_end) { 429 if (*_current == '\n') { 430 *_current = '\0'; 431 u1* value = (u1*)strchr((char*)attr, ':'); 432 if (value != NULL) { 433 assert(*(value+1) == ' ', "Unrecognized format" ); 434 if (strstr((char*)attr, "-Digest") != NULL) { 435 isSigned = true; 436 break; 437 } 438 } 439 *_current = '\n'; // restore 440 attr = _current + 1; 441 } 442 _current ++; 443 } 444 return isSigned; 445 } 446 }; 447 448 void FileMapInfo::update_shared_classpath(ClassPathEntry *cpe, SharedClassPathEntry* ent, TRAPS) { 449 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data(); 450 ResourceMark rm(THREAD); 451 jint manifest_size; 452 453 if (cpe->is_jar_file()) { 454 assert(ent->is_jar(), "the shared class path entry is not a JAR file"); 455 char* manifest = ClassLoaderExt::read_manifest(cpe, &manifest_size, CHECK); 456 if (manifest != NULL) { 457 ManifestStream* stream = new ManifestStream((u1*)manifest, 458 manifest_size); 459 if (stream->check_is_signed()) { 460 ent->set_is_signed(); 461 } else { 462 // Copy the manifest into the shared archive 463 manifest = ClassLoaderExt::read_raw_manifest(cpe, &manifest_size, CHECK); 464 Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data, 465 manifest_size, 466 THREAD); 467 char* p = (char*)(buf->data()); 468 memcpy(p, manifest, manifest_size); 469 ent->set_manifest(buf); 470 } 471 } 472 } 473 } 474 475 476 bool FileMapInfo::validate_shared_path_table() { 477 assert(UseSharedSpaces, "runtime only"); 478 479 _validating_shared_path_table = true; 480 _shared_path_table = _header->_shared_path_table; 481 _shared_path_entry_size = _header->_shared_path_entry_size; 482 _shared_path_table_size = _header->_shared_path_table_size; 483 484 int module_paths_start_index = _header->_app_module_paths_start_index; 485 486 // validate the path entries up to the _max_used_path_index 487 for (int i=0; i < _header->_max_used_path_index + 1; i++) { 488 if (i < module_paths_start_index) { 489 if (shared_path(i)->validate()) { 490 log_info(class, path)("ok"); 491 } else { 492 assert(!UseSharedSpaces, "UseSharedSpaces should be disabled"); 493 return false; 494 } 495 } else if (i >= module_paths_start_index) { 496 if (shared_path(i)->validate(false /* not a class path entry */)) { 497 log_info(class, path)("ok"); 498 } else { 499 assert(!UseSharedSpaces, "UseSharedSpaces should be disabled"); 500 return false; 501 } 502 } 503 } 504 505 _validating_shared_path_table = false; 506 507 #if INCLUDE_JVMTI 508 if (_classpath_entries_for_jvmti != NULL) { 509 os::free(_classpath_entries_for_jvmti); 510 } 511 size_t sz = sizeof(ClassPathEntry*) * _shared_path_table_size; 512 _classpath_entries_for_jvmti = (ClassPathEntry**)os::malloc(sz, mtClass); 513 memset(_classpath_entries_for_jvmti, 0, sz); 514 #endif 515 516 return true; 517 } 518 519 // Read the FileMapInfo information from the file. 520 521 bool FileMapInfo::init_from_file(int fd) { 522 size_t sz = sizeof(FileMapHeader); 523 size_t n = os::read(fd, _header, (unsigned int)sz); 524 if (n != sz) { 525 fail_continue("Unable to read the file header."); 526 return false; 527 } 528 if (_header->_version != CURRENT_CDS_ARCHIVE_VERSION) { 529 fail_continue("The shared archive file has the wrong version."); 530 return false; 531 } 532 _file_offset = (long)n; 533 534 size_t info_size = _header->_paths_misc_info_size; 535 _paths_misc_info = NEW_C_HEAP_ARRAY_RETURN_NULL(char, info_size, mtClass); 536 if (_paths_misc_info == NULL) { 537 fail_continue("Unable to read the file header."); 538 return false; 539 } 540 n = os::read(fd, _paths_misc_info, (unsigned int)info_size); 541 if (n != info_size) { 542 fail_continue("Unable to read the shared path info header."); 543 FREE_C_HEAP_ARRAY(char, _paths_misc_info); 544 _paths_misc_info = NULL; 545 return false; 546 } 547 548 size_t len = lseek(fd, 0, SEEK_END); 549 CDSFileMapRegion* si = space_at(MetaspaceShared::last_valid_region); 550 // The last space might be empty 551 if (si->_file_offset > len || len - si->_file_offset < si->_used) { 552 fail_continue("The shared archive file has been truncated."); 553 return false; 554 } 555 556 _file_offset += (long)n; 557 SharedBaseAddress = _header->_shared_base_address; 558 return true; 559 } 560 561 562 // Read the FileMapInfo information from the file. 563 bool FileMapInfo::open_for_read() { 564 _full_path = Arguments::GetSharedArchivePath(); 565 int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0); 566 if (fd < 0) { 567 if (errno == ENOENT) { 568 // Not locating the shared archive is ok. 569 fail_continue("Specified shared archive not found."); 570 } else { 571 fail_continue("Failed to open shared archive file (%s).", 572 os::strerror(errno)); 573 } 574 return false; 575 } 576 577 _fd = fd; 578 _file_open = true; 579 return true; 580 } 581 582 583 // Write the FileMapInfo information to the file. 584 585 void FileMapInfo::open_for_write() { 586 _full_path = Arguments::GetSharedArchivePath(); 587 LogMessage(cds) msg; 588 if (msg.is_info()) { 589 msg.info("Dumping shared data to file: "); 590 msg.info(" %s", _full_path); 591 } 592 593 #ifdef _WINDOWS // On Windows, need WRITE permission to remove the file. 594 chmod(_full_path, _S_IREAD | _S_IWRITE); 595 #endif 596 597 // Use remove() to delete the existing file because, on Unix, this will 598 // allow processes that have it open continued access to the file. 599 remove(_full_path); 600 int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444); 601 if (fd < 0) { 602 fail_stop("Unable to create shared archive file %s: (%s).", _full_path, 603 os::strerror(errno)); 604 } 605 _fd = fd; 606 _file_offset = 0; 607 _file_open = true; 608 } 609 610 611 // Write the header to the file, seek to the next allocation boundary. 612 613 void FileMapInfo::write_header() { 614 int info_size = ClassLoader::get_shared_paths_misc_info_size(); 615 616 _header->_paths_misc_info_size = info_size; 617 618 align_file_position(); 619 write_bytes(_header, sizeof(FileMapHeader)); 620 write_bytes(ClassLoader::get_shared_paths_misc_info(), (size_t)info_size); 621 align_file_position(); 622 } 623 624 625 // Dump region to file. 626 627 void FileMapInfo::write_region(int region, char* base, size_t size, 628 bool read_only, bool allow_exec) { 629 CDSFileMapRegion* si = space_at(region); 630 631 if (_file_open) { 632 guarantee(si->_file_offset == _file_offset, "file offset mismatch."); 633 log_info(cds)("Shared file region %d: " SIZE_FORMAT_HEX_W(08) 634 " bytes, addr " INTPTR_FORMAT " file offset " SIZE_FORMAT_HEX_W(08), 635 region, size, p2i(base), _file_offset); 636 } else { 637 si->_file_offset = _file_offset; 638 } 639 if (HeapShared::is_heap_region(region)) { 640 assert((base - (char*)Universe::narrow_oop_base()) % HeapWordSize == 0, "Sanity"); 641 if (base != NULL) { 642 si->_addr._offset = (intx)CompressedOops::encode_not_null((oop)base); 643 } else { 644 si->_addr._offset = 0; 645 } 646 } else { 647 si->_addr._base = base; 648 } 649 si->_used = size; 650 si->_read_only = read_only; 651 si->_allow_exec = allow_exec; 652 si->_crc = ClassLoader::crc32(0, base, (jint)size); 653 if (base != NULL) { 654 write_bytes_aligned(base, size); 655 } 656 } 657 658 // Write out the given archive heap memory regions. GC code combines multiple 659 // consecutive archive GC regions into one MemRegion whenever possible and 660 // produces the 'heap_mem' array. 661 // 662 // If the archive heap memory size is smaller than a single dump time GC region 663 // size, there is only one MemRegion in the array. 664 // 665 // If the archive heap memory size is bigger than one dump time GC region size, 666 // the 'heap_mem' array may contain more than one consolidated MemRegions. When 667 // the first/bottom archive GC region is a partial GC region (with the empty 668 // portion at the higher address within the region), one MemRegion is used for 669 // the bottom partial archive GC region. The rest of the consecutive archive 670 // GC regions are combined into another MemRegion. 671 // 672 // Here's the mapping from (archive heap GC regions) -> (GrowableArray<MemRegion> *regions). 673 // + We have 1 or more archive heap regions: ah0, ah1, ah2 ..... ahn 674 // + We have 1 or 2 consolidated heap memory regions: r0 and r1 675 // 676 // If there's a single archive GC region (ah0), then r0 == ah0, and r1 is empty. 677 // Otherwise: 678 // 679 // "X" represented space that's occupied by heap objects. 680 // "_" represented unused spaced in the heap region. 681 // 682 // 683 // |ah0 | ah1 | ah2| ...... | ahn| 684 // |XXXXXX|__ |XXXXX|XXXX|XXXXXXXX|XXXX| 685 // |<-r0->| |<- r1 ----------------->| 686 // ^^^ 687 // | 688 // +-- gap 689 size_t FileMapInfo::write_archive_heap_regions(GrowableArray<MemRegion> *heap_mem, 690 GrowableArray<ArchiveHeapOopmapInfo> *oopmaps, 691 int first_region_id, int max_num_regions, 692 bool print_log) { 693 assert(max_num_regions <= 2, "Only support maximum 2 memory regions"); 694 695 int arr_len = heap_mem == NULL ? 0 : heap_mem->length(); 696 if(arr_len > max_num_regions) { 697 fail_stop("Unable to write archive heap memory regions: " 698 "number of memory regions exceeds maximum due to fragmentation. " 699 "Please increase java heap size " 700 "(current MaxHeapSize is " SIZE_FORMAT ", InitialHeapSize is " SIZE_FORMAT ").", 701 MaxHeapSize, InitialHeapSize); 702 } 703 704 size_t total_size = 0; 705 for (int i = first_region_id, arr_idx = 0; 706 i < first_region_id + max_num_regions; 707 i++, arr_idx++) { 708 char* start = NULL; 709 size_t size = 0; 710 if (arr_idx < arr_len) { 711 start = (char*)heap_mem->at(arr_idx).start(); 712 size = heap_mem->at(arr_idx).byte_size(); 713 total_size += size; 714 } 715 716 if (print_log) { 717 log_info(cds)("Archive heap region %d " INTPTR_FORMAT " - " INTPTR_FORMAT " = " SIZE_FORMAT_W(8) " bytes", 718 i, p2i(start), p2i(start + size), size); 719 } 720 write_region(i, start, size, false, false); 721 if (size > 0) { 722 space_at(i)->_oopmap = oopmaps->at(arr_idx)._oopmap; 723 space_at(i)->_oopmap_size_in_bits = oopmaps->at(arr_idx)._oopmap_size_in_bits; 724 } 725 } 726 return total_size; 727 } 728 729 // Dump bytes to file -- at the current file position. 730 731 void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) { 732 if (_file_open) { 733 size_t n = os::write(_fd, buffer, (unsigned int)nbytes); 734 if (n != nbytes) { 735 // It is dangerous to leave the corrupted shared archive file around, 736 // close and remove the file. See bug 6372906. 737 close(); 738 remove(_full_path); 739 fail_stop("Unable to write to shared archive file."); 740 } 741 } 742 _file_offset += nbytes; 743 } 744 745 746 // Align file position to an allocation unit boundary. 747 748 void FileMapInfo::align_file_position() { 749 size_t new_file_offset = align_up(_file_offset, 750 os::vm_allocation_granularity()); 751 if (new_file_offset != _file_offset) { 752 _file_offset = new_file_offset; 753 if (_file_open) { 754 // Seek one byte back from the target and write a byte to insure 755 // that the written file is the correct length. 756 _file_offset -= 1; 757 if (lseek(_fd, (long)_file_offset, SEEK_SET) < 0) { 758 fail_stop("Unable to seek."); 759 } 760 char zero = 0; 761 write_bytes(&zero, 1); 762 } 763 } 764 } 765 766 767 // Dump bytes to file -- at the current file position. 768 769 void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) { 770 align_file_position(); 771 write_bytes(buffer, nbytes); 772 align_file_position(); 773 } 774 775 776 // Close the shared archive file. This does NOT unmap mapped regions. 777 778 void FileMapInfo::close() { 779 if (_file_open) { 780 if (::close(_fd) < 0) { 781 fail_stop("Unable to close the shared archive file."); 782 } 783 _file_open = false; 784 _fd = -1; 785 } 786 } 787 788 789 // JVM/TI RedefineClasses() support: 790 // Remap the shared readonly space to shared readwrite, private. 791 bool FileMapInfo::remap_shared_readonly_as_readwrite() { 792 int idx = MetaspaceShared::ro; 793 CDSFileMapRegion* si = space_at(idx); 794 if (!si->_read_only) { 795 // the space is already readwrite so we are done 796 return true; 797 } 798 size_t used = si->_used; 799 size_t size = align_up(used, os::vm_allocation_granularity()); 800 if (!open_for_read()) { 801 return false; 802 } 803 char *addr = region_addr(idx); 804 char *base = os::remap_memory(_fd, _full_path, si->_file_offset, 805 addr, size, false /* !read_only */, 806 si->_allow_exec); 807 close(); 808 if (base == NULL) { 809 fail_continue("Unable to remap shared readonly space (errno=%d).", errno); 810 return false; 811 } 812 if (base != addr) { 813 fail_continue("Unable to remap shared readonly space at required address."); 814 return false; 815 } 816 si->_read_only = false; 817 return true; 818 } 819 820 // Map the whole region at once, assumed to be allocated contiguously. 821 ReservedSpace FileMapInfo::reserve_shared_memory() { 822 char* requested_addr = region_addr(0); 823 size_t size = FileMapInfo::core_spaces_size(); 824 825 // Reserve the space first, then map otherwise map will go right over some 826 // other reserved memory (like the code cache). 827 ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr); 828 if (!rs.is_reserved()) { 829 fail_continue("Unable to reserve shared space at required address " 830 INTPTR_FORMAT, p2i(requested_addr)); 831 return rs; 832 } 833 // the reserved virtual memory is for mapping class data sharing archive 834 MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared); 835 836 return rs; 837 } 838 839 // Memory map a region in the address space. 840 static const char* shared_region_name[] = { "MiscData", "ReadWrite", "ReadOnly", "MiscCode", "OptionalData", 841 "String1", "String2", "OpenArchive1", "OpenArchive2" }; 842 843 char* FileMapInfo::map_region(int i, char** top_ret) { 844 assert(!HeapShared::is_heap_region(i), "sanity"); 845 CDSFileMapRegion* si = space_at(i); 846 size_t used = si->_used; 847 size_t alignment = os::vm_allocation_granularity(); 848 size_t size = align_up(used, alignment); 849 char *requested_addr = region_addr(i); 850 851 // If a tool agent is in use (debugging enabled), we must map the address space RW 852 if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space()) { 853 si->_read_only = false; 854 } 855 856 // map the contents of the CDS archive in this memory 857 char *base = os::map_memory(_fd, _full_path, si->_file_offset, 858 requested_addr, size, si->_read_only, 859 si->_allow_exec); 860 if (base == NULL || base != requested_addr) { 861 fail_continue("Unable to map %s shared space at required address.", shared_region_name[i]); 862 return NULL; 863 } 864 #ifdef _WINDOWS 865 // This call is Windows-only because the memory_type gets recorded for the other platforms 866 // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows. 867 MemTracker::record_virtual_memory_type((address)base, mtClassShared); 868 #endif 869 870 871 if (!verify_region_checksum(i)) { 872 return NULL; 873 } 874 875 *top_ret = base + size; 876 return base; 877 } 878 879 address FileMapInfo::decode_start_address(CDSFileMapRegion* spc, bool with_current_oop_encoding_mode) { 880 if (with_current_oop_encoding_mode) { 881 return (address)CompressedOops::decode_not_null(offset_of_space(spc)); 882 } else { 883 return (address)HeapShared::decode_from_archive(offset_of_space(spc)); 884 } 885 } 886 887 static MemRegion *closed_archive_heap_ranges = NULL; 888 static MemRegion *open_archive_heap_ranges = NULL; 889 static int num_closed_archive_heap_ranges = 0; 890 static int num_open_archive_heap_ranges = 0; 891 892 #if INCLUDE_CDS_JAVA_HEAP 893 bool FileMapInfo::has_heap_regions() { 894 return (_header->_space[MetaspaceShared::first_closed_archive_heap_region]._used > 0); 895 } 896 897 // Returns the address range of the archived heap regions computed using the 898 // current oop encoding mode. This range may be different than the one seen at 899 // dump time due to encoding mode differences. The result is used in determining 900 // if/how these regions should be relocated at run time. 901 MemRegion FileMapInfo::get_heap_regions_range_with_current_oop_encoding_mode() { 902 address start = (address) max_uintx; 903 address end = NULL; 904 905 for (int i = MetaspaceShared::first_closed_archive_heap_region; 906 i <= MetaspaceShared::last_valid_region; 907 i++) { 908 CDSFileMapRegion* si = space_at(i); 909 size_t size = si->_used; 910 if (size > 0) { 911 address s = start_address_as_decoded_with_current_oop_encoding_mode(si); 912 address e = s + size; 913 if (start > s) { 914 start = s; 915 } 916 if (end < e) { 917 end = e; 918 } 919 } 920 } 921 assert(end != NULL, "must have at least one used heap region"); 922 return MemRegion((HeapWord*)start, (HeapWord*)end); 923 } 924 925 // 926 // Map the closed and open archive heap objects to the runtime java heap. 927 // 928 // The shared objects are mapped at (or close to ) the java heap top in 929 // closed archive regions. The mapped objects contain no out-going 930 // references to any other java heap regions. GC does not write into the 931 // mapped closed archive heap region. 932 // 933 // The open archive heap objects are mapped below the shared objects in 934 // the runtime java heap. The mapped open archive heap data only contains 935 // references to the shared objects and open archive objects initially. 936 // During runtime execution, out-going references to any other java heap 937 // regions may be added. GC may mark and update references in the mapped 938 // open archive objects. 939 void FileMapInfo::map_heap_regions_impl() { 940 if (!HeapShared::is_heap_object_archiving_allowed()) { 941 log_info(cds)("CDS heap data is being ignored. UseG1GC, " 942 "UseCompressedOops and UseCompressedClassPointers are required."); 943 return; 944 } 945 946 if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) { 947 ShouldNotReachHere(); // CDS should have been disabled. 948 // The archived objects are mapped at JVM start-up, but we don't know if 949 // j.l.String or j.l.Class might be replaced by the ClassFileLoadHook, 950 // which would make the archived String or mirror objects invalid. Let's be safe and not 951 // use the archived objects. These 2 classes are loaded during the JVMTI "early" stage. 952 // 953 // If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects 954 // in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK 955 // because we won't install an archived object subgraph if the klass of any of the 956 // referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph(). 957 } 958 959 MemRegion heap_reserved = Universe::heap()->reserved_region(); 960 961 log_info(cds)("CDS archive was created with max heap size = " SIZE_FORMAT "M, and the following configuration:", 962 max_heap_size()/M); 963 log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d", 964 p2i(narrow_klass_base()), narrow_klass_shift()); 965 log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d", 966 narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift()); 967 968 log_info(cds)("The current max heap size = " SIZE_FORMAT "M, HeapRegion::GrainBytes = " SIZE_FORMAT, 969 heap_reserved.byte_size()/M, HeapRegion::GrainBytes); 970 log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d", 971 p2i(Universe::narrow_klass_base()), Universe::narrow_klass_shift()); 972 log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d", 973 Universe::narrow_oop_mode(), p2i(Universe::narrow_oop_base()), Universe::narrow_oop_shift()); 974 975 if (narrow_klass_base() != Universe::narrow_klass_base() || 976 narrow_klass_shift() != Universe::narrow_klass_shift()) { 977 log_info(cds)("CDS heap data cannot be used because the archive was created with an incompatible narrow klass encoding mode."); 978 return; 979 } 980 981 if (narrow_oop_mode() != Universe::narrow_oop_mode() || 982 narrow_oop_base() != Universe::narrow_oop_base() || 983 narrow_oop_shift() != Universe::narrow_oop_shift()) { 984 log_info(cds)("CDS heap data need to be relocated because the archive was created with an incompatible oop encoding mode."); 985 _heap_pointers_need_patching = true; 986 } else { 987 MemRegion range = get_heap_regions_range_with_current_oop_encoding_mode(); 988 if (!heap_reserved.contains(range)) { 989 log_info(cds)("CDS heap data need to be relocated because"); 990 log_info(cds)("the desired range " PTR_FORMAT " - " PTR_FORMAT, p2i(range.start()), p2i(range.end())); 991 log_info(cds)("is outside of the heap " PTR_FORMAT " - " PTR_FORMAT, p2i(heap_reserved.start()), p2i(heap_reserved.end())); 992 _heap_pointers_need_patching = true; 993 } 994 } 995 996 ptrdiff_t delta = 0; 997 if (_heap_pointers_need_patching) { 998 // dumptime heap end ------------v 999 // [ |archived heap regions| ] runtime heap end ------v 1000 // [ |archived heap regions| ] 1001 // |<-----delta-------------------->| 1002 // 1003 // At dump time, the archived heap regions were near the top of the heap. 1004 // At run time, they may not be inside the heap, so we move them so 1005 // that they are now near the top of the runtime time. This can be done by 1006 // the simple math of adding the delta as shown above. 1007 address dumptime_heap_end = (address)_header->_heap_reserved.end(); 1008 address runtime_heap_end = (address)heap_reserved.end(); 1009 delta = runtime_heap_end - dumptime_heap_end; 1010 } 1011 1012 log_info(cds)("CDS heap data relocation delta = " INTX_FORMAT " bytes", delta); 1013 HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift()); 1014 1015 CDSFileMapRegion* si = space_at(MetaspaceShared::first_closed_archive_heap_region); 1016 address relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si); 1017 if (!is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes)) { 1018 // Align the bottom of the closed archive heap regions at G1 region boundary. 1019 // This will avoid the situation where the highest open region and the lowest 1020 // closed region sharing the same G1 region. Otherwise we will fail to map the 1021 // open regions. 1022 size_t align = size_t(relocated_closed_heap_region_bottom) % HeapRegion::GrainBytes; 1023 delta -= align; 1024 log_info(cds)("CDS heap data need to be relocated lower by a further " SIZE_FORMAT 1025 " bytes to " INTX_FORMAT " to be aligned with HeapRegion::GrainBytes", 1026 align, delta); 1027 HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift()); 1028 _heap_pointers_need_patching = true; 1029 relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si); 1030 } 1031 assert(is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes), 1032 "must be"); 1033 1034 // Map the closed_archive_heap regions, GC does not write into the regions. 1035 if (map_heap_data(&closed_archive_heap_ranges, 1036 MetaspaceShared::first_closed_archive_heap_region, 1037 MetaspaceShared::max_closed_archive_heap_region, 1038 &num_closed_archive_heap_ranges)) { 1039 HeapShared::set_closed_archive_heap_region_mapped(); 1040 1041 // Now, map open_archive heap regions, GC can write into the regions. 1042 if (map_heap_data(&open_archive_heap_ranges, 1043 MetaspaceShared::first_open_archive_heap_region, 1044 MetaspaceShared::max_open_archive_heap_region, 1045 &num_open_archive_heap_ranges, 1046 true /* open */)) { 1047 HeapShared::set_open_archive_heap_region_mapped(); 1048 } 1049 } 1050 } 1051 1052 void FileMapInfo::map_heap_regions() { 1053 if (has_heap_regions()) { 1054 map_heap_regions_impl(); 1055 } 1056 1057 if (!HeapShared::closed_archive_heap_region_mapped()) { 1058 assert(closed_archive_heap_ranges == NULL && 1059 num_closed_archive_heap_ranges == 0, "sanity"); 1060 } 1061 1062 if (!HeapShared::open_archive_heap_region_mapped()) { 1063 assert(open_archive_heap_ranges == NULL && num_open_archive_heap_ranges == 0, "sanity"); 1064 } 1065 } 1066 1067 bool FileMapInfo::map_heap_data(MemRegion **heap_mem, int first, 1068 int max, int* num, bool is_open_archive) { 1069 MemRegion * regions = new MemRegion[max]; 1070 CDSFileMapRegion* si; 1071 int region_num = 0; 1072 1073 for (int i = first; 1074 i < first + max; i++) { 1075 si = space_at(i); 1076 size_t size = si->_used; 1077 if (size > 0) { 1078 HeapWord* start = (HeapWord*)start_address_as_decoded_from_archive(si); 1079 regions[region_num] = MemRegion(start, size / HeapWordSize); 1080 region_num ++; 1081 log_info(cds)("Trying to map heap data: region[%d] at " INTPTR_FORMAT ", size = " SIZE_FORMAT_W(8) " bytes", 1082 i, p2i(start), size); 1083 } 1084 } 1085 1086 if (region_num == 0) { 1087 return false; // no archived java heap data 1088 } 1089 1090 // Check that ranges are within the java heap 1091 if (!G1CollectedHeap::heap()->check_archive_addresses(regions, region_num)) { 1092 log_info(cds)("UseSharedSpaces: Unable to allocate region, range is not within java heap."); 1093 return false; 1094 } 1095 1096 // allocate from java heap 1097 if (!G1CollectedHeap::heap()->alloc_archive_regions( 1098 regions, region_num, is_open_archive)) { 1099 log_info(cds)("UseSharedSpaces: Unable to allocate region, java heap range is already in use."); 1100 return false; 1101 } 1102 1103 // Map the archived heap data. No need to call MemTracker::record_virtual_memory_type() 1104 // for mapped regions as they are part of the reserved java heap, which is 1105 // already recorded. 1106 for (int i = 0; i < region_num; i++) { 1107 si = space_at(first + i); 1108 char* addr = (char*)regions[i].start(); 1109 char* base = os::map_memory(_fd, _full_path, si->_file_offset, 1110 addr, regions[i].byte_size(), si->_read_only, 1111 si->_allow_exec); 1112 if (base == NULL || base != addr) { 1113 // dealloc the regions from java heap 1114 dealloc_archive_heap_regions(regions, region_num, is_open_archive); 1115 log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap. " 1116 INTPTR_FORMAT ", size = " SIZE_FORMAT " bytes", 1117 p2i(addr), regions[i].byte_size()); 1118 return false; 1119 } 1120 } 1121 1122 if (!verify_mapped_heap_regions(first, region_num)) { 1123 // dealloc the regions from java heap 1124 dealloc_archive_heap_regions(regions, region_num, is_open_archive); 1125 log_info(cds)("UseSharedSpaces: mapped heap regions are corrupt"); 1126 return false; 1127 } 1128 1129 // the shared heap data is mapped successfully 1130 *heap_mem = regions; 1131 *num = region_num; 1132 return true; 1133 } 1134 1135 bool FileMapInfo::verify_mapped_heap_regions(int first, int num) { 1136 assert(num > 0, "sanity"); 1137 for (int i = first; i < first + num; i++) { 1138 if (!verify_region_checksum(i)) { 1139 return false; 1140 } 1141 } 1142 return true; 1143 } 1144 1145 void FileMapInfo::patch_archived_heap_embedded_pointers() { 1146 if (!_heap_pointers_need_patching) { 1147 return; 1148 } 1149 1150 patch_archived_heap_embedded_pointers(closed_archive_heap_ranges, 1151 num_closed_archive_heap_ranges, 1152 MetaspaceShared::first_closed_archive_heap_region); 1153 1154 patch_archived_heap_embedded_pointers(open_archive_heap_ranges, 1155 num_open_archive_heap_ranges, 1156 MetaspaceShared::first_open_archive_heap_region); 1157 } 1158 1159 void FileMapInfo::patch_archived_heap_embedded_pointers(MemRegion* ranges, int num_ranges, 1160 int first_region_idx) { 1161 for (int i=0; i<num_ranges; i++) { 1162 CDSFileMapRegion* si = space_at(i + first_region_idx); 1163 HeapShared::patch_archived_heap_embedded_pointers(ranges[i], (address)si->_oopmap, 1164 si->_oopmap_size_in_bits); 1165 } 1166 } 1167 1168 // This internally allocates objects using SystemDictionary::Object_klass(), so it 1169 // must be called after the well-known classes are resolved. 1170 void FileMapInfo::fixup_mapped_heap_regions() { 1171 // If any closed regions were found, call the fill routine to make them parseable. 1172 // Note that closed_archive_heap_ranges may be non-NULL even if no ranges were found. 1173 if (num_closed_archive_heap_ranges != 0) { 1174 assert(closed_archive_heap_ranges != NULL, 1175 "Null closed_archive_heap_ranges array with non-zero count"); 1176 G1CollectedHeap::heap()->fill_archive_regions(closed_archive_heap_ranges, 1177 num_closed_archive_heap_ranges); 1178 } 1179 1180 // do the same for mapped open archive heap regions 1181 if (num_open_archive_heap_ranges != 0) { 1182 assert(open_archive_heap_ranges != NULL, "NULL open_archive_heap_ranges array with non-zero count"); 1183 G1CollectedHeap::heap()->fill_archive_regions(open_archive_heap_ranges, 1184 num_open_archive_heap_ranges); 1185 } 1186 } 1187 1188 // dealloc the archive regions from java heap 1189 void FileMapInfo::dealloc_archive_heap_regions(MemRegion* regions, int num, bool is_open) { 1190 if (num > 0) { 1191 assert(regions != NULL, "Null archive ranges array with non-zero count"); 1192 G1CollectedHeap::heap()->dealloc_archive_regions(regions, num, is_open); 1193 } 1194 } 1195 #endif // INCLUDE_CDS_JAVA_HEAP 1196 1197 bool FileMapInfo::verify_region_checksum(int i) { 1198 if (!VerifySharedSpaces) { 1199 return true; 1200 } 1201 1202 size_t sz = space_at(i)->_used; 1203 1204 if (sz == 0) { 1205 return true; // no data 1206 } 1207 if ((HeapShared::is_closed_archive_heap_region(i) && 1208 !HeapShared::closed_archive_heap_region_mapped()) || 1209 (HeapShared::is_open_archive_heap_region(i) && 1210 !HeapShared::open_archive_heap_region_mapped())) { 1211 return true; // archived heap data is not mapped 1212 } 1213 const char* buf = region_addr(i); 1214 int crc = ClassLoader::crc32(0, buf, (jint)sz); 1215 if (crc != space_at(i)->_crc) { 1216 fail_continue("Checksum verification failed."); 1217 return false; 1218 } 1219 return true; 1220 } 1221 1222 // Unmap a memory region in the address space. 1223 1224 void FileMapInfo::unmap_region(int i) { 1225 assert(!HeapShared::is_heap_region(i), "sanity"); 1226 CDSFileMapRegion* si = space_at(i); 1227 size_t used = si->_used; 1228 size_t size = align_up(used, os::vm_allocation_granularity()); 1229 1230 if (used == 0) { 1231 return; 1232 } 1233 1234 char* addr = region_addr(i); 1235 if (!os::unmap_memory(addr, size)) { 1236 fail_stop("Unable to unmap shared space."); 1237 } 1238 } 1239 1240 void FileMapInfo::assert_mark(bool check) { 1241 if (!check) { 1242 fail_stop("Mark mismatch while restoring from shared file."); 1243 } 1244 } 1245 1246 void FileMapInfo::metaspace_pointers_do(MetaspaceClosure* it) { 1247 it->push(&_shared_path_table); 1248 for (int i=0; i<_shared_path_table_size; i++) { 1249 shared_path(i)->metaspace_pointers_do(it); 1250 } 1251 } 1252 1253 1254 FileMapInfo* FileMapInfo::_current_info = NULL; 1255 bool FileMapInfo::_heap_pointers_need_patching = false; 1256 Array<u8>* FileMapInfo::_shared_path_table = NULL; 1257 int FileMapInfo::_shared_path_table_size = 0; 1258 size_t FileMapInfo::_shared_path_entry_size = 0x1234baad; 1259 bool FileMapInfo::_validating_shared_path_table = false; 1260 1261 // Open the shared archive file, read and validate the header 1262 // information (version, boot classpath, etc.). If initialization 1263 // fails, shared spaces are disabled and the file is closed. [See 1264 // fail_continue.] 1265 // 1266 // Validation of the archive is done in two steps: 1267 // 1268 // [1] validate_header() - done here. This checks the header, including _paths_misc_info. 1269 // [2] validate_shared_path_table - this is done later, because the table is in the RW 1270 // region of the archive, which is not mapped yet. 1271 bool FileMapInfo::initialize() { 1272 assert(UseSharedSpaces, "UseSharedSpaces expected."); 1273 1274 if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) { 1275 // CDS assumes that no classes resolved in SystemDictionary::resolve_well_known_classes 1276 // are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved 1277 // during the JVMTI "early" stage, so we can still use CDS if 1278 // JvmtiExport::has_early_class_hook_env() is false. 1279 FileMapInfo::fail_continue("CDS is disabled because early JVMTI ClassFileLoadHook is in use."); 1280 return false; 1281 } 1282 1283 if (!open_for_read()) { 1284 return false; 1285 } 1286 1287 init_from_file(_fd); 1288 if (!validate_header()) { 1289 return false; 1290 } 1291 return true; 1292 } 1293 1294 char* FileMapInfo::region_addr(int idx) { 1295 CDSFileMapRegion* si = space_at(idx); 1296 if (HeapShared::is_heap_region(idx)) { 1297 assert(DumpSharedSpaces, "The following doesn't work at runtime"); 1298 return si->_used > 0 ? 1299 (char*)start_address_as_decoded_with_current_oop_encoding_mode(si) : NULL; 1300 } else { 1301 return si->_addr._base; 1302 } 1303 } 1304 1305 int FileMapHeader::compute_crc() { 1306 char* start = (char*)this; 1307 // start computing from the field after _crc 1308 char* buf = (char*)&_crc + sizeof(_crc); 1309 size_t sz = sizeof(FileMapHeader) - (buf - start); 1310 int crc = ClassLoader::crc32(0, buf, (jint)sz); 1311 return crc; 1312 } 1313 1314 // This function should only be called during run time with UseSharedSpaces enabled. 1315 bool FileMapHeader::validate() { 1316 if (VerifySharedSpaces && compute_crc() != _crc) { 1317 FileMapInfo::fail_continue("Header checksum verification failed."); 1318 return false; 1319 } 1320 1321 if (!Arguments::has_jimage()) { 1322 FileMapInfo::fail_continue("The shared archive file cannot be used with an exploded module build."); 1323 return false; 1324 } 1325 1326 if (_version != CURRENT_CDS_ARCHIVE_VERSION) { 1327 FileMapInfo::fail_continue("The shared archive file is the wrong version."); 1328 return false; 1329 } 1330 if (_magic != CDS_ARCHIVE_MAGIC) { 1331 FileMapInfo::fail_continue("The shared archive file has a bad magic number."); 1332 return false; 1333 } 1334 char header_version[JVM_IDENT_MAX]; 1335 get_header_version(header_version); 1336 if (strncmp(_jvm_ident, header_version, JVM_IDENT_MAX-1) != 0) { 1337 log_info(class, path)("expected: %s", header_version); 1338 log_info(class, path)("actual: %s", _jvm_ident); 1339 FileMapInfo::fail_continue("The shared archive file was created by a different" 1340 " version or build of HotSpot"); 1341 return false; 1342 } 1343 if (_obj_alignment != ObjectAlignmentInBytes) { 1344 FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d" 1345 " does not equal the current ObjectAlignmentInBytes of " INTX_FORMAT ".", 1346 _obj_alignment, ObjectAlignmentInBytes); 1347 return false; 1348 } 1349 if (_compact_strings != CompactStrings) { 1350 FileMapInfo::fail_continue("The shared archive file's CompactStrings setting (%s)" 1351 " does not equal the current CompactStrings setting (%s).", 1352 _compact_strings ? "enabled" : "disabled", 1353 CompactStrings ? "enabled" : "disabled"); 1354 return false; 1355 } 1356 1357 // This must be done after header validation because it might change the 1358 // header data 1359 const char* prop = Arguments::get_property("java.system.class.loader"); 1360 if (prop != NULL) { 1361 warning("Archived non-system classes are disabled because the " 1362 "java.system.class.loader property is specified (value = \"%s\"). " 1363 "To use archived non-system classes, this property must not be set", prop); 1364 _has_platform_or_app_classes = false; 1365 } 1366 1367 // For backwards compatibility, we don't check the verification setting 1368 // if the archive only contains system classes. 1369 if (_has_platform_or_app_classes && 1370 ((!_verify_local && BytecodeVerificationLocal) || 1371 (!_verify_remote && BytecodeVerificationRemote))) { 1372 FileMapInfo::fail_continue("The shared archive file was created with less restrictive " 1373 "verification setting than the current setting."); 1374 return false; 1375 } 1376 1377 // Java agents are allowed during run time. Therefore, the following condition is not 1378 // checked: (!_allow_archiving_with_java_agent && AllowArchivingWithJavaAgent) 1379 // Note: _allow_archiving_with_java_agent is set in the shared archive during dump time 1380 // while AllowArchivingWithJavaAgent is set during the current run. 1381 if (_allow_archiving_with_java_agent && !AllowArchivingWithJavaAgent) { 1382 FileMapInfo::fail_continue("The setting of the AllowArchivingWithJavaAgent is different " 1383 "from the setting in the shared archive."); 1384 return false; 1385 } 1386 1387 if (_allow_archiving_with_java_agent) { 1388 warning("This archive was created with AllowArchivingWithJavaAgent. It should be used " 1389 "for testing purposes only and should not be used in a production environment"); 1390 } 1391 1392 return true; 1393 } 1394 1395 bool FileMapInfo::validate_header() { 1396 bool status = _header->validate(); 1397 1398 if (status) { 1399 if (!ClassLoader::check_shared_paths_misc_info(_paths_misc_info, _header->_paths_misc_info_size)) { 1400 if (!PrintSharedArchiveAndExit) { 1401 fail_continue("shared class paths mismatch (hint: enable -Xlog:class+path=info to diagnose the failure)"); 1402 status = false; 1403 } 1404 } 1405 } 1406 1407 if (_paths_misc_info != NULL) { 1408 FREE_C_HEAP_ARRAY(char, _paths_misc_info); 1409 _paths_misc_info = NULL; 1410 } 1411 return status; 1412 } 1413 1414 // Check if a given address is within one of the shared regions 1415 bool FileMapInfo::is_in_shared_region(const void* p, int idx) { 1416 assert(idx == MetaspaceShared::ro || 1417 idx == MetaspaceShared::rw || 1418 idx == MetaspaceShared::mc || 1419 idx == MetaspaceShared::md, "invalid region index"); 1420 char* base = region_addr(idx); 1421 if (p >= base && p < base + space_at(idx)->_used) { 1422 return true; 1423 } 1424 return false; 1425 } 1426 1427 // Unmap mapped regions of shared space. 1428 void FileMapInfo::stop_sharing_and_unmap(const char* msg) { 1429 MetaspaceObj::set_shared_metaspace_range(NULL, NULL); 1430 1431 FileMapInfo *map_info = FileMapInfo::current_info(); 1432 if (map_info) { 1433 map_info->fail_continue("%s", msg); 1434 for (int i = 0; i < MetaspaceShared::num_non_heap_spaces; i++) { 1435 if (!HeapShared::is_heap_region(i)) { 1436 char *addr = map_info->region_addr(i); 1437 if (addr != NULL) { 1438 map_info->unmap_region(i); 1439 map_info->space_at(i)->_addr._base = NULL; 1440 } 1441 } 1442 } 1443 // Dealloc the archive heap regions only without unmapping. The regions are part 1444 // of the java heap. Unmapping of the heap regions are managed by GC. 1445 map_info->dealloc_archive_heap_regions(open_archive_heap_ranges, 1446 num_open_archive_heap_ranges, 1447 true); 1448 map_info->dealloc_archive_heap_regions(closed_archive_heap_ranges, 1449 num_closed_archive_heap_ranges, 1450 false); 1451 } else if (DumpSharedSpaces) { 1452 fail_stop("%s", msg); 1453 } 1454 } 1455 1456 #if INCLUDE_JVMTI 1457 ClassPathEntry** FileMapInfo::_classpath_entries_for_jvmti = NULL; 1458 1459 ClassPathEntry* FileMapInfo::get_classpath_entry_for_jvmti(int i, TRAPS) { 1460 ClassPathEntry* ent = _classpath_entries_for_jvmti[i]; 1461 if (ent == NULL) { 1462 if (i == 0) { 1463 ent = ClassLoader:: get_jrt_entry(); 1464 assert(ent != NULL, "must be"); 1465 } else { 1466 SharedClassPathEntry* scpe = shared_path(i); 1467 assert(scpe->is_jar(), "must be"); // other types of scpe will not produce archived classes 1468 1469 const char* path = scpe->name(); 1470 struct stat st; 1471 if (os::stat(path, &st) != 0) { 1472 char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128); ; 1473 jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path); 1474 THROW_MSG_(vmSymbols::java_io_IOException(), msg, NULL); 1475 } else { 1476 ent = ClassLoader::create_class_path_entry(path, &st, /*throw_exception=*/true, false, CHECK_NULL); 1477 } 1478 } 1479 1480 MutexLocker mu(CDSClassFileStream_lock, THREAD); 1481 if (_classpath_entries_for_jvmti[i] == NULL) { 1482 _classpath_entries_for_jvmti[i] = ent; 1483 } else { 1484 // Another thread has beat me to creating this entry 1485 delete ent; 1486 ent = _classpath_entries_for_jvmti[i]; 1487 } 1488 } 1489 1490 return ent; 1491 } 1492 1493 ClassFileStream* FileMapInfo::open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS) { 1494 int path_index = ik->shared_classpath_index(); 1495 assert(path_index >= 0, "should be called for shared built-in classes only"); 1496 assert(path_index < (int)_shared_path_table_size, "sanity"); 1497 1498 ClassPathEntry* cpe = get_classpath_entry_for_jvmti(path_index, CHECK_NULL); 1499 assert(cpe != NULL, "must be"); 1500 1501 Symbol* name = ik->name(); 1502 const char* const class_name = name->as_C_string(); 1503 const char* const file_name = ClassLoader::file_name_for_class_name(class_name, 1504 name->utf8_length()); 1505 return cpe->open_stream_for_loader(file_name, ClassLoaderData::class_loader_data(class_loader()), THREAD); 1506 } 1507 1508 #endif