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