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