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