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