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