1 /* 2 * Copyright (c) 2003, 2013, 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/symbolTable.hpp" 28 #include "classfile/altHashing.hpp" 29 #include "memory/filemap.hpp" 30 #include "runtime/arguments.hpp" 31 #include "runtime/java.hpp" 32 #include "runtime/os.hpp" 33 #include "services/memTracker.hpp" 34 #include "utilities/defaultStream.hpp" 35 36 # include <sys/stat.h> 37 # include <errno.h> 38 39 #ifndef O_BINARY // if defined (Win32) use binary files. 40 #define O_BINARY 0 // otherwise do nothing. 41 #endif 42 43 44 extern address JVM_FunctionAtStart(); 45 extern address JVM_FunctionAtEnd(); 46 47 // Complain and stop. All error conditions occurring during the writing of 48 // an archive file should stop the process. Unrecoverable errors during 49 // the reading of the archive file should stop the process. 50 51 static void fail(const char *msg, va_list ap) { 52 // This occurs very early during initialization: tty is not initialized. 53 jio_fprintf(defaultStream::error_stream(), 54 "An error has occurred while processing the" 55 " shared archive file.\n"); 56 jio_vfprintf(defaultStream::error_stream(), msg, ap); 57 jio_fprintf(defaultStream::error_stream(), "\n"); 58 // Do not change the text of the below message because some tests check for it. 59 vm_exit_during_initialization("Unable to use shared archive.", NULL); 60 } 61 62 63 void FileMapInfo::fail_stop(const char *msg, ...) { 64 va_list ap; 65 va_start(ap, msg); 66 fail(msg, ap); // Never returns. 67 va_end(ap); // for completeness. 68 } 69 70 71 // Complain and continue. Recoverable errors during the reading of the 72 // archive file may continue (with sharing disabled). 73 // 74 // If we continue, then disable shared spaces and close the file. 75 76 void FileMapInfo::fail_continue(const char *msg, ...) { 77 va_list ap; 78 va_start(ap, msg); 79 if (RequireSharedSpaces) { 80 fail(msg, ap); 81 } else { 82 if (PrintSharedSpaces) { 83 tty->print_cr("UseSharedSpaces: %s", msg); 84 } 85 } 86 va_end(ap); 87 UseSharedSpaces = false; 88 close(); 89 } 90 91 // Fill in the fileMapInfo structure with data about this VM instance. 92 93 // This method copies the vm version info into header_version. If the version is too 94 // long then a truncated version, which has a hash code appended to it, is copied. 95 // 96 // Using a template enables this method to verify that header_version is an array of 97 // length JVM_IDENT_MAX. This ensures that the code that writes to the CDS file and 98 // the code that reads the CDS file will both use the same size buffer. Hence, will 99 // use identical truncation. This is necessary for matching of truncated versions. 100 template <int N> static void get_header_version(char (&header_version) [N]) { 101 assert(N == JVM_IDENT_MAX, "Bad header_version size"); 102 103 const char *vm_version = VM_Version::internal_vm_info_string(); 104 const int version_len = (int)strlen(vm_version); 105 106 if (version_len < (JVM_IDENT_MAX-1)) { 107 strcpy(header_version, vm_version); 108 109 } else { 110 // Get the hash value. Use a static seed because the hash needs to return the same 111 // value over multiple jvm invocations. 112 unsigned int hash = AltHashing::murmur3_32(8191, (const jbyte*)vm_version, version_len); 113 114 // Truncate the ident, saving room for the 8 hex character hash value. 115 strncpy(header_version, vm_version, JVM_IDENT_MAX-9); 116 117 // Append the hash code as eight hex digits. 118 sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash); 119 header_version[JVM_IDENT_MAX-1] = 0; // Null terminate. 120 } 121 } 122 123 void FileMapInfo::populate_header(size_t alignment) { 124 _header._magic = 0xf00baba2; 125 _header._version = _current_version; 126 _header._alignment = alignment; 127 _header._obj_alignment = ObjectAlignmentInBytes; 128 129 // The following fields are for sanity checks for whether this archive 130 // will function correctly with this JVM and the bootclasspath it's 131 // invoked with. 132 133 // JVM version string ... changes on each build. 134 get_header_version(_header._jvm_ident); 135 136 // Build checks on classpath and jar files 137 _header._num_jars = 0; 138 ClassPathEntry *cpe = ClassLoader::classpath_entry(0); 139 for ( ; cpe != NULL; cpe = cpe->next()) { 140 141 if (cpe->is_jar_file()) { 142 if (_header._num_jars >= JVM_SHARED_JARS_MAX) { 143 fail_stop("Too many jar files to share.", NULL); 144 } 145 146 // Jar file - record timestamp and file size. 147 struct stat st; 148 const char *path = cpe->name(); 149 if (os::stat(path, &st) != 0) { 150 // If we can't access a jar file in the boot path, then we can't 151 // make assumptions about where classes get loaded from. 152 fail_stop("Unable to open jar file %s.", path); 153 } 154 _header._jar[_header._num_jars]._timestamp = st.st_mtime; 155 _header._jar[_header._num_jars]._filesize = st.st_size; 156 _header._num_jars++; 157 } else { 158 159 // If directories appear in boot classpath, they must be empty to 160 // avoid having to verify each individual class file. 161 const char* name = ((ClassPathDirEntry*)cpe)->name(); 162 if (!os::dir_is_empty(name)) { 163 fail_stop("Boot classpath directory %s is not empty.", name); 164 } 165 } 166 } 167 } 168 169 170 // Read the FileMapInfo information from the file. 171 172 bool FileMapInfo::init_from_file(int fd) { 173 174 size_t n = read(fd, &_header, sizeof(struct FileMapHeader)); 175 if (n != sizeof(struct FileMapHeader)) { 176 fail_continue("Unable to read the file header."); 177 return false; 178 } 179 if (_header._version != current_version()) { 180 fail_continue("The shared archive file has the wrong version."); 181 return false; 182 } 183 _file_offset = (long)n; 184 return true; 185 } 186 187 188 // Read the FileMapInfo information from the file. 189 bool FileMapInfo::open_for_read() { 190 _full_path = Arguments::GetSharedArchivePath(); 191 int fd = open(_full_path, O_RDONLY | O_BINARY, 0); 192 if (fd < 0) { 193 if (errno == ENOENT) { 194 // Not locating the shared archive is ok. 195 fail_continue("Specified shared archive not found."); 196 } else { 197 fail_continue("Failed to open shared archive file (%s).", 198 strerror(errno)); 199 } 200 return false; 201 } 202 203 _fd = fd; 204 _file_open = true; 205 return true; 206 } 207 208 209 // Write the FileMapInfo information to the file. 210 211 void FileMapInfo::open_for_write() { 212 _full_path = Arguments::GetSharedArchivePath(); 213 if (PrintSharedSpaces) { 214 tty->print_cr("Dumping shared data to file: "); 215 tty->print_cr(" %s", _full_path); 216 } 217 218 #ifdef _WINDOWS // On Windows, need WRITE permission to remove the file. 219 chmod(_full_path, _S_IREAD | _S_IWRITE); 220 #endif 221 222 // Use remove() to delete the existing file because, on Unix, this will 223 // allow processes that have it open continued access to the file. 224 remove(_full_path); 225 int fd = open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444); 226 if (fd < 0) { 227 fail_stop("Unable to create shared archive file %s.", _full_path); 228 } 229 _fd = fd; 230 _file_offset = 0; 231 _file_open = true; 232 } 233 234 235 // Write the header to the file, seek to the next allocation boundary. 236 237 void FileMapInfo::write_header() { 238 write_bytes_aligned(&_header, sizeof(FileMapHeader)); 239 } 240 241 242 // Dump shared spaces to file. 243 244 void FileMapInfo::write_space(int i, Metaspace* space, bool read_only) { 245 align_file_position(); 246 size_t used = space->used_bytes_slow(Metaspace::NonClassType); 247 size_t capacity = space->capacity_bytes_slow(Metaspace::NonClassType); 248 struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[i]; 249 write_region(i, (char*)space->bottom(), used, capacity, read_only, false); 250 } 251 252 253 // Dump region to file. 254 255 void FileMapInfo::write_region(int region, char* base, size_t size, 256 size_t capacity, bool read_only, 257 bool allow_exec) { 258 struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[region]; 259 260 if (_file_open) { 261 guarantee(si->_file_offset == _file_offset, "file offset mismatch."); 262 if (PrintSharedSpaces) { 263 tty->print_cr("Shared file region %d: 0x%6x bytes, addr " INTPTR_FORMAT 264 " file offset 0x%6x", region, size, base, _file_offset); 265 } 266 } else { 267 si->_file_offset = _file_offset; 268 } 269 si->_base = base; 270 si->_used = size; 271 si->_capacity = capacity; 272 si->_read_only = read_only; 273 si->_allow_exec = allow_exec; 274 write_bytes_aligned(base, (int)size); 275 } 276 277 278 // Dump bytes to file -- at the current file position. 279 280 void FileMapInfo::write_bytes(const void* buffer, int nbytes) { 281 if (_file_open) { 282 int n = ::write(_fd, buffer, nbytes); 283 if (n != nbytes) { 284 // It is dangerous to leave the corrupted shared archive file around, 285 // close and remove the file. See bug 6372906. 286 close(); 287 remove(_full_path); 288 fail_stop("Unable to write to shared archive file.", NULL); 289 } 290 } 291 _file_offset += nbytes; 292 } 293 294 295 // Align file position to an allocation unit boundary. 296 297 void FileMapInfo::align_file_position() { 298 long new_file_offset = align_size_up(_file_offset, os::vm_allocation_granularity()); 299 if (new_file_offset != _file_offset) { 300 _file_offset = new_file_offset; 301 if (_file_open) { 302 // Seek one byte back from the target and write a byte to insure 303 // that the written file is the correct length. 304 _file_offset -= 1; 305 if (lseek(_fd, _file_offset, SEEK_SET) < 0) { 306 fail_stop("Unable to seek.", NULL); 307 } 308 char zero = 0; 309 write_bytes(&zero, 1); 310 } 311 } 312 } 313 314 315 // Dump bytes to file -- at the current file position. 316 317 void FileMapInfo::write_bytes_aligned(const void* buffer, int nbytes) { 318 align_file_position(); 319 write_bytes(buffer, nbytes); 320 align_file_position(); 321 } 322 323 324 // Close the shared archive file. This does NOT unmap mapped regions. 325 326 void FileMapInfo::close() { 327 if (_file_open) { 328 if (::close(_fd) < 0) { 329 fail_stop("Unable to close the shared archive file."); 330 } 331 _file_open = false; 332 _fd = -1; 333 } 334 } 335 336 337 // JVM/TI RedefineClasses() support: 338 // Remap the shared readonly space to shared readwrite, private. 339 bool FileMapInfo::remap_shared_readonly_as_readwrite() { 340 struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[0]; 341 if (!si->_read_only) { 342 // the space is already readwrite so we are done 343 return true; 344 } 345 size_t used = si->_used; 346 size_t size = align_size_up(used, os::vm_allocation_granularity()); 347 if (!open_for_read()) { 348 return false; 349 } 350 char *base = os::remap_memory(_fd, _full_path, si->_file_offset, 351 si->_base, size, false /* !read_only */, 352 si->_allow_exec); 353 close(); 354 if (base == NULL) { 355 fail_continue("Unable to remap shared readonly space (errno=%d).", errno); 356 return false; 357 } 358 if (base != si->_base) { 359 fail_continue("Unable to remap shared readonly space at required address."); 360 return false; 361 } 362 si->_read_only = false; 363 return true; 364 } 365 366 // Map the whole region at once, assumed to be allocated contiguously. 367 ReservedSpace FileMapInfo::reserve_shared_memory() { 368 struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[0]; 369 char* requested_addr = si->_base; 370 371 size_t size = FileMapInfo::shared_spaces_size(); 372 373 // Reserve the space first, then map otherwise map will go right over some 374 // other reserved memory (like the code cache). 375 ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr); 376 if (!rs.is_reserved()) { 377 fail_continue(err_msg("Unable to reserve shared space at required address " INTPTR_FORMAT, requested_addr)); 378 return rs; 379 } 380 // the reserved virtual memory is for mapping class data sharing archive 381 MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared); 382 383 return rs; 384 } 385 386 // Memory map a region in the address space. 387 static const char* shared_region_name[] = { "ReadOnly", "ReadWrite", "MiscData", "MiscCode"}; 388 389 char* FileMapInfo::map_region(int i) { 390 struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[i]; 391 size_t used = si->_used; 392 size_t alignment = os::vm_allocation_granularity(); 393 size_t size = align_size_up(used, alignment); 394 char *requested_addr = si->_base; 395 396 // map the contents of the CDS archive in this memory 397 char *base = os::map_memory(_fd, _full_path, si->_file_offset, 398 requested_addr, size, si->_read_only, 399 si->_allow_exec); 400 if (base == NULL || base != si->_base) { 401 fail_continue(err_msg("Unable to map %s shared space at required address.", shared_region_name[i])); 402 return NULL; 403 } 404 #ifdef _WINDOWS 405 // This call is Windows-only because the memory_type gets recorded for the other platforms 406 // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows. 407 MemTracker::record_virtual_memory_type((address)base, mtClassShared); 408 #endif 409 return base; 410 } 411 412 413 // Unmap a memory region in the address space. 414 415 void FileMapInfo::unmap_region(int i) { 416 struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[i]; 417 size_t used = si->_used; 418 size_t size = align_size_up(used, os::vm_allocation_granularity()); 419 if (!os::unmap_memory(si->_base, size)) { 420 fail_stop("Unable to unmap shared space."); 421 } 422 } 423 424 425 void FileMapInfo::assert_mark(bool check) { 426 if (!check) { 427 fail_stop("Mark mismatch while restoring from shared file.", NULL); 428 } 429 } 430 431 432 FileMapInfo* FileMapInfo::_current_info = NULL; 433 434 435 // Open the shared archive file, read and validate the header 436 // information (version, boot classpath, etc.). If initialization 437 // fails, shared spaces are disabled and the file is closed. [See 438 // fail_continue.] 439 bool FileMapInfo::initialize() { 440 assert(UseSharedSpaces, "UseSharedSpaces expected."); 441 442 if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space()) { 443 fail_continue("Tool agent requires sharing to be disabled."); 444 return false; 445 } 446 447 if (!open_for_read()) { 448 return false; 449 } 450 451 init_from_file(_fd); 452 if (!validate()) { 453 return false; 454 } 455 456 SharedReadOnlySize = _header._space[0]._capacity; 457 SharedReadWriteSize = _header._space[1]._capacity; 458 SharedMiscDataSize = _header._space[2]._capacity; 459 SharedMiscCodeSize = _header._space[3]._capacity; 460 return true; 461 } 462 463 464 bool FileMapInfo::validate() { 465 if (_header._version != current_version()) { 466 fail_continue("The shared archive file is the wrong version."); 467 return false; 468 } 469 if (_header._magic != (int)0xf00baba2) { 470 fail_continue("The shared archive file has a bad magic number."); 471 return false; 472 } 473 char header_version[JVM_IDENT_MAX]; 474 get_header_version(header_version); 475 if (strncmp(_header._jvm_ident, header_version, JVM_IDENT_MAX-1) != 0) { 476 fail_continue("The shared archive file was created by a different" 477 " version or build of HotSpot."); 478 return false; 479 } 480 if (_header._obj_alignment != ObjectAlignmentInBytes) { 481 fail_continue("The shared archive file's ObjectAlignmentInBytes of %d" 482 " does not equal the current ObjectAlignmentInBytes of %d.", 483 _header._obj_alignment, ObjectAlignmentInBytes); 484 return false; 485 } 486 487 // Cannot verify interpreter yet, as it can only be created after the GC 488 // heap has been initialized. 489 490 if (_header._num_jars >= JVM_SHARED_JARS_MAX) { 491 fail_continue("Too many jar files to share."); 492 return false; 493 } 494 495 // Build checks on classpath and jar files 496 int num_jars_now = 0; 497 ClassPathEntry *cpe = ClassLoader::classpath_entry(0); 498 for ( ; cpe != NULL; cpe = cpe->next()) { 499 500 if (cpe->is_jar_file()) { 501 if (num_jars_now < _header._num_jars) { 502 503 // Jar file - verify timestamp and file size. 504 struct stat st; 505 const char *path = cpe->name(); 506 if (os::stat(path, &st) != 0) { 507 fail_continue("Unable to open jar file %s.", path); 508 return false; 509 } 510 if (_header._jar[num_jars_now]._timestamp != st.st_mtime || 511 _header._jar[num_jars_now]._filesize != st.st_size) { 512 fail_continue("A jar file is not the one used while building" 513 " the shared archive file."); 514 return false; 515 } 516 } 517 ++num_jars_now; 518 } else { 519 520 // If directories appear in boot classpath, they must be empty to 521 // avoid having to verify each individual class file. 522 const char* name = ((ClassPathDirEntry*)cpe)->name(); 523 if (!os::dir_is_empty(name)) { 524 fail_continue("Boot classpath directory %s is not empty.", name); 525 return false; 526 } 527 } 528 } 529 if (num_jars_now < _header._num_jars) { 530 fail_continue("The number of jar files in the boot classpath is" 531 " less than the number the shared archive was created with."); 532 return false; 533 } 534 535 return true; 536 } 537 538 // The following method is provided to see whether a given pointer 539 // falls in the mapped shared space. 540 // Param: 541 // p, The given pointer 542 // Return: 543 // True if the p is within the mapped shared space, otherwise, false. 544 bool FileMapInfo::is_in_shared_space(const void* p) { 545 for (int i = 0; i < MetaspaceShared::n_regions; i++) { 546 if (p >= _header._space[i]._base && 547 p < _header._space[i]._base + _header._space[i]._used) { 548 return true; 549 } 550 } 551 552 return false; 553 } 554 555 void FileMapInfo::print_shared_spaces() { 556 gclog_or_tty->print_cr("Shared Spaces:"); 557 for (int i = 0; i < MetaspaceShared::n_regions; i++) { 558 struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[i]; 559 gclog_or_tty->print(" %s " INTPTR_FORMAT "-" INTPTR_FORMAT, 560 shared_region_name[i], 561 si->_base, si->_base + si->_used); 562 } 563 } 564 565 // Unmap mapped regions of shared space. 566 void FileMapInfo::stop_sharing_and_unmap(const char* msg) { 567 FileMapInfo *map_info = FileMapInfo::current_info(); 568 if (map_info) { 569 map_info->fail_continue(msg); 570 for (int i = 0; i < MetaspaceShared::n_regions; i++) { 571 if (map_info->_header._space[i]._base != NULL) { 572 map_info->unmap_region(i); 573 map_info->_header._space[i]._base = NULL; 574 } 575 } 576 } else if (DumpSharedSpaces) { 577 fail_stop(msg, NULL); 578 } 579 }