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