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