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