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