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