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