src/share/vm/memory/filemap.cpp

Print this page
rev 6841 : mq
rev 6842 : mq


   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 "runtime/vm_version.hpp"
  34 #include "services/memTracker.hpp"
  35 #include "utilities/defaultStream.hpp"
  36 
  37 # include <sys/stat.h>
  38 # include <errno.h>
  39 
  40 #ifndef O_BINARY       // if defined (Win32) use binary files.
  41 #define O_BINARY 0     // otherwise do nothing.
  42 #endif
  43 
  44 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  45 
  46 extern address JVM_FunctionAtStart();
  47 extern address JVM_FunctionAtEnd();
  48 
  49 // Complain and stop. All error conditions occurring during the writing of
  50 // an archive file should stop the process.  Unrecoverable errors during
  51 // the reading of the archive file should stop the process.
  52 
  53 static void fail(const char *msg, va_list ap) {
  54   // This occurs very early during initialization: tty is not initialized.
  55   jio_fprintf(defaultStream::error_stream(),
  56               "An error has occurred while processing the"
  57               " shared archive file.\n");
  58   jio_vfprintf(defaultStream::error_stream(), msg, ap);
  59   jio_fprintf(defaultStream::error_stream(), "\n");
  60   // Do not change the text of the below message because some tests check for it.
  61   vm_exit_during_initialization("Unable to use shared archive.", NULL);
  62 }
  63 
  64 
  65 void FileMapInfo::fail_stop(const char *msg, ...) {
  66         va_list ap;
  67   va_start(ap, msg);
  68   fail(msg, ap);        // Never returns.
  69   va_end(ap);           // for completeness.
  70 }
  71 
  72 
  73 // Complain and continue.  Recoverable errors during the reading of the
  74 // archive file may continue (with sharing disabled).
  75 //
  76 // If we continue, then disable shared spaces and close the file.
  77 
  78 void FileMapInfo::fail_continue(const char *msg, ...) {
  79   va_list ap;
  80   va_start(ap, msg);









  81   if (RequireSharedSpaces) {
  82     fail(msg, ap);
  83   } else {
  84     if (PrintSharedSpaces) {
  85       tty->print_cr("UseSharedSpaces: %s", msg);
  86     }
  87   }

  88   va_end(ap);
  89   UseSharedSpaces = false;
  90   close();

  91 }
  92 
  93 // Fill in the fileMapInfo structure with data about this VM instance.
  94 
  95 // This method copies the vm version info into header_version.  If the version is too
  96 // long then a truncated version, which has a hash code appended to it, is copied.
  97 //
  98 // Using a template enables this method to verify that header_version is an array of
  99 // length JVM_IDENT_MAX.  This ensures that the code that writes to the CDS file and
 100 // the code that reads the CDS file will both use the same size buffer.  Hence, will
 101 // use identical truncation.  This is necessary for matching of truncated versions.
 102 template <int N> static void get_header_version(char (&header_version) [N]) {
 103   assert(N == JVM_IDENT_MAX, "Bad header_version size");
 104 
 105   const char *vm_version = VM_Version::internal_vm_info_string();
 106   const int version_len = (int)strlen(vm_version);
 107 
 108   if (version_len < (JVM_IDENT_MAX-1)) {
 109     strcpy(header_version, vm_version);
 110 
 111   } else {
 112     // Get the hash value.  Use a static seed because the hash needs to return the same
 113     // value over multiple jvm invocations.
 114     unsigned int hash = AltHashing::murmur3_32(8191, (const jbyte*)vm_version, version_len);
 115 
 116     // Truncate the ident, saving room for the 8 hex character hash value.
 117     strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
 118 
 119     // Append the hash code as eight hex digits.
 120     sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash);
 121     header_version[JVM_IDENT_MAX-1] = 0;  // Null terminate.
 122   }
 123 }
 124 















 125 void FileMapInfo::populate_header(size_t alignment) {
 126   _header._magic = 0xf00baba2;
 127   _header._version = _current_version;
 128   _header._alignment = alignment;
 129   _header._obj_alignment = ObjectAlignmentInBytes;











 130 
 131   // The following fields are for sanity checks for whether this archive
 132   // will function correctly with this JVM and the bootclasspath it's
 133   // invoked with.
 134 
 135   // JVM version string ... changes on each build.
 136   get_header_version(_header._jvm_ident);











 137 
 138   // Build checks on classpath and jar files
 139   _header._num_jars = 0;
 140   ClassPathEntry *cpe = ClassLoader::classpath_entry(0);
 141   for ( ; cpe != NULL; cpe = cpe->next()) {
 142 
 143     if (cpe->is_jar_file()) {
 144       if (_header._num_jars >= JVM_SHARED_JARS_MAX) {
 145         fail_stop("Too many jar files to share.", NULL);







 146       }
 147 
 148       // Jar file - record timestamp and file size.

 149       struct stat st;
 150       const char *path = cpe->name();
 151       if (os::stat(path, &st) != 0) {


 152         // If we can't access a jar file in the boot path, then we can't
 153         // make assumptions about where classes get loaded from.
 154         fail_stop("Unable to open jar file %s.", path);
 155       }
 156       _header._jar[_header._num_jars]._timestamp = st.st_mtime;
 157       _header._jar[_header._num_jars]._filesize = st.st_size;
 158       _header._num_jars++;
 159     } else {






















 160 
 161       // If directories appear in boot classpath, they must be empty to
 162       // avoid having to verify each individual class file.
 163       const char* name = ((ClassPathDirEntry*)cpe)->name();
























 164       if (!os::dir_is_empty(name)) {
 165         fail_stop("Boot classpath directory %s is not empty.", name);














 166       }
 167     }



 168   }









 169 }
 170 
 171 
 172 // Read the FileMapInfo information from the file.
 173 
 174 bool FileMapInfo::init_from_file(int fd) {
 175 
 176   size_t n = read(fd, &_header, sizeof(struct FileMapHeader));
 177   if (n != sizeof(struct FileMapHeader)) {

 178     fail_continue("Unable to read the file header.");
 179     return false;
 180   }
 181   if (_header._version != current_version()) {
 182     fail_continue("The shared archive file has the wrong version.");
 183     return false;
 184   }
 185   _file_offset = (long)n;
















 186   return true;
 187 }
 188 
 189 
 190 // Read the FileMapInfo information from the file.
 191 bool FileMapInfo::open_for_read() {
 192   _full_path = Arguments::GetSharedArchivePath();
 193   int fd = open(_full_path, O_RDONLY | O_BINARY, 0);
 194   if (fd < 0) {
 195     if (errno == ENOENT) {
 196       // Not locating the shared archive is ok.
 197       fail_continue("Specified shared archive not found.");
 198     } else {
 199       fail_continue("Failed to open shared archive file (%s).",
 200                     strerror(errno));
 201     }
 202     return false;
 203   }
 204 
 205   _fd = fd;


 220 #ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
 221   chmod(_full_path, _S_IREAD | _S_IWRITE);
 222 #endif
 223 
 224   // Use remove() to delete the existing file because, on Unix, this will
 225   // allow processes that have it open continued access to the file.
 226   remove(_full_path);
 227   int fd = open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
 228   if (fd < 0) {
 229     fail_stop("Unable to create shared archive file %s.", _full_path);
 230   }
 231   _fd = fd;
 232   _file_offset = 0;
 233   _file_open = true;
 234 }
 235 
 236 
 237 // Write the header to the file, seek to the next allocation boundary.
 238 
 239 void FileMapInfo::write_header() {
 240   write_bytes_aligned(&_header, sizeof(FileMapHeader));









 241 }
 242 
 243 
 244 // Dump shared spaces to file.
 245 
 246 void FileMapInfo::write_space(int i, Metaspace* space, bool read_only) {
 247   align_file_position();
 248   size_t used = space->used_bytes_slow(Metaspace::NonClassType);
 249   size_t capacity = space->capacity_bytes_slow(Metaspace::NonClassType);
 250   struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[i];
 251   write_region(i, (char*)space->bottom(), used, capacity, read_only, false);
 252 }
 253 
 254 
 255 // Dump region to file.
 256 
 257 void FileMapInfo::write_region(int region, char* base, size_t size,
 258                                size_t capacity, bool read_only,
 259                                bool allow_exec) {
 260   struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[region];
 261 
 262   if (_file_open) {
 263     guarantee(si->_file_offset == _file_offset, "file offset mismatch.");
 264     if (PrintSharedSpaces) {
 265       tty->print_cr("Shared file region %d: 0x%6x bytes, addr " INTPTR_FORMAT
 266                     " file offset 0x%6x", region, size, base, _file_offset);
 267     }
 268   } else {
 269     si->_file_offset = _file_offset;
 270   }
 271   si->_base = base;
 272   si->_used = size;
 273   si->_capacity = capacity;
 274   si->_read_only = read_only;
 275   si->_allow_exec = allow_exec;
 276   write_bytes_aligned(base, (int)size);
 277 }
 278 
 279 
 280 // Dump bytes to file -- at the current file position.


 322   align_file_position();
 323 }
 324 
 325 
 326 // Close the shared archive file.  This does NOT unmap mapped regions.
 327 
 328 void FileMapInfo::close() {
 329   if (_file_open) {
 330     if (::close(_fd) < 0) {
 331       fail_stop("Unable to close the shared archive file.");
 332     }
 333     _file_open = false;
 334     _fd = -1;
 335   }
 336 }
 337 
 338 
 339 // JVM/TI RedefineClasses() support:
 340 // Remap the shared readonly space to shared readwrite, private.
 341 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
 342   struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[0];
 343   if (!si->_read_only) {
 344     // the space is already readwrite so we are done
 345     return true;
 346   }
 347   size_t used = si->_used;
 348   size_t size = align_size_up(used, os::vm_allocation_granularity());
 349   if (!open_for_read()) {
 350     return false;
 351   }
 352   char *base = os::remap_memory(_fd, _full_path, si->_file_offset,
 353                                 si->_base, size, false /* !read_only */,
 354                                 si->_allow_exec);
 355   close();
 356   if (base == NULL) {
 357     fail_continue("Unable to remap shared readonly space (errno=%d).", errno);
 358     return false;
 359   }
 360   if (base != si->_base) {
 361     fail_continue("Unable to remap shared readonly space at required address.");
 362     return false;
 363   }
 364   si->_read_only = false;
 365   return true;
 366 }
 367 
 368 // Map the whole region at once, assumed to be allocated contiguously.
 369 ReservedSpace FileMapInfo::reserve_shared_memory() {
 370   struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[0];
 371   char* requested_addr = si->_base;
 372 
 373   size_t size = FileMapInfo::shared_spaces_size();
 374 
 375   // Reserve the space first, then map otherwise map will go right over some
 376   // other reserved memory (like the code cache).
 377   ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr);
 378   if (!rs.is_reserved()) {
 379     fail_continue(err_msg("Unable to reserve shared space at required address " INTPTR_FORMAT, requested_addr));
 380     return rs;
 381   }
 382   // the reserved virtual memory is for mapping class data sharing archive
 383   MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared);
 384 
 385   return rs;
 386 }
 387 
 388 // Memory map a region in the address space.
 389 static const char* shared_region_name[] = { "ReadOnly", "ReadWrite", "MiscData", "MiscCode"};
 390 
 391 char* FileMapInfo::map_region(int i) {
 392   struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[i];
 393   size_t used = si->_used;
 394   size_t alignment = os::vm_allocation_granularity();
 395   size_t size = align_size_up(used, alignment);
 396   char *requested_addr = si->_base;
 397 
 398   // map the contents of the CDS archive in this memory
 399   char *base = os::map_memory(_fd, _full_path, si->_file_offset,
 400                               requested_addr, size, si->_read_only,
 401                               si->_allow_exec);
 402   if (base == NULL || base != si->_base) {
 403     fail_continue(err_msg("Unable to map %s shared space at required address.", shared_region_name[i]));
 404     return NULL;
 405   }
 406 #ifdef _WINDOWS
 407   // This call is Windows-only because the memory_type gets recorded for the other platforms
 408   // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows.
 409   MemTracker::record_virtual_memory_type((address)base, mtClassShared);
 410 #endif
 411   return base;
 412 }
 413 
 414 
 415 // Unmap a memory region in the address space.
 416 
 417 void FileMapInfo::unmap_region(int i) {
 418   struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[i];
 419   size_t used = si->_used;
 420   size_t size = align_size_up(used, os::vm_allocation_granularity());
 421   if (!os::unmap_memory(si->_base, size)) {
 422     fail_stop("Unable to unmap shared space.");
 423   }
 424 }
 425 
 426 
 427 void FileMapInfo::assert_mark(bool check) {
 428   if (!check) {
 429     fail_stop("Mark mismatch while restoring from shared file.", NULL);
 430   }
 431 }
 432 
 433 
 434 FileMapInfo* FileMapInfo::_current_info = NULL;
 435 



 436 
 437 // Open the shared archive file, read and validate the header
 438 // information (version, boot classpath, etc.).  If initialization
 439 // fails, shared spaces are disabled and the file is closed. [See
 440 // fail_continue.]






 441 bool FileMapInfo::initialize() {
 442   assert(UseSharedSpaces, "UseSharedSpaces expected.");
 443 
 444   if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space()) {
 445     fail_continue("Tool agent requires sharing to be disabled.");
 446     return false;
 447   }
 448 
 449   if (!open_for_read()) {
 450     return false;
 451   }
 452 
 453   init_from_file(_fd);
 454   if (!validate()) {
 455     return false;
 456   }
 457 
 458   SharedReadOnlySize =  _header._space[0]._capacity;
 459   SharedReadWriteSize = _header._space[1]._capacity;
 460   SharedMiscDataSize =  _header._space[2]._capacity;
 461   SharedMiscCodeSize =  _header._space[3]._capacity;
 462   return true;
 463 }
 464 
 465 
 466 bool FileMapInfo::validate() {
 467   if (_header._version != current_version()) {
 468     fail_continue("The shared archive file is the wrong version.");
 469     return false;
 470   }
 471   if (_header._magic != (int)0xf00baba2) {
 472     fail_continue("The shared archive file has a bad magic number.");
 473     return false;
 474   }
 475   char header_version[JVM_IDENT_MAX];
 476   get_header_version(header_version);
 477   if (strncmp(_header._jvm_ident, header_version, JVM_IDENT_MAX-1) != 0) {
 478     fail_continue("The shared archive file was created by a different"
 479                   " version or build of HotSpot.");
 480     return false;
 481   }
 482   if (_header._obj_alignment != ObjectAlignmentInBytes) {
 483     fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"
 484                   " does not equal the current ObjectAlignmentInBytes of %d.",
 485                   _header._obj_alignment, ObjectAlignmentInBytes);
 486     return false;
 487   }
 488 
 489   // Cannot verify interpreter yet, as it can only be created after the GC
 490   // heap has been initialized.
 491 
 492   if (_header._num_jars >= JVM_SHARED_JARS_MAX) {
 493     fail_continue("Too many jar files to share.");
 494     return false;
 495   }
 496 
 497   // Build checks on classpath and jar files
 498   int num_jars_now = 0;
 499   ClassPathEntry *cpe = ClassLoader::classpath_entry(0);
 500   for ( ; cpe != NULL; cpe = cpe->next()) {
 501 
 502     if (cpe->is_jar_file()) {
 503       if (num_jars_now < _header._num_jars) {
 504 
 505         // Jar file - verify timestamp and file size.
 506         struct stat st;
 507         const char *path = cpe->name();
 508         if (os::stat(path, &st) != 0) {
 509           fail_continue("Unable to open jar file %s.", path);
 510           return false;
 511         }
 512         if (_header._jar[num_jars_now]._timestamp != st.st_mtime ||
 513             _header._jar[num_jars_now]._filesize != st.st_size) {
 514           fail_continue("A jar file is not the one used while building"
 515                         " the shared archive file.");
 516           return false;
 517         }
 518       }
 519       ++num_jars_now;
 520     } else {
 521 
 522       // If directories appear in boot classpath, they must be empty to
 523       // avoid having to verify each individual class file.
 524       const char* name = ((ClassPathDirEntry*)cpe)->name();
 525       if (!os::dir_is_empty(name)) {
 526         fail_continue("Boot classpath directory %s is not empty.", name);
 527         return false;
 528       }
 529     }
 530   }
 531   if (num_jars_now < _header._num_jars) {
 532     fail_continue("The number of jar files in the boot classpath is"
 533                   " less than the number the shared archive was created with.");
 534     return false;
 535   }
 536 
 537   return true;
 538 }
 539 
 540 // The following method is provided to see whether a given pointer
 541 // falls in the mapped shared space.
 542 // Param:
 543 // p, The given pointer
 544 // Return:
 545 // True if the p is within the mapped shared space, otherwise, false.
 546 bool FileMapInfo::is_in_shared_space(const void* p) {
 547   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
 548     if (p >= _header._space[i]._base &&
 549         p < _header._space[i]._base + _header._space[i]._used) {
 550       return true;
 551     }
 552   }
 553 
 554   return false;
 555 }
 556 
 557 void FileMapInfo::print_shared_spaces() {
 558   gclog_or_tty->print_cr("Shared Spaces:");
 559   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
 560     struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[i];
 561     gclog_or_tty->print("  %s " INTPTR_FORMAT "-" INTPTR_FORMAT,
 562                         shared_region_name[i],
 563                         si->_base, si->_base + si->_used);
 564   }
 565 }
 566 
 567 // Unmap mapped regions of shared space.
 568 void FileMapInfo::stop_sharing_and_unmap(const char* msg) {
 569   FileMapInfo *map_info = FileMapInfo::current_info();
 570   if (map_info) {
 571     map_info->fail_continue(msg);
 572     for (int i = 0; i < MetaspaceShared::n_regions; i++) {
 573       if (map_info->_header._space[i]._base != NULL) {
 574         map_info->unmap_region(i);
 575         map_info->_header._space[i]._base = NULL;
 576       }
 577     }
 578   } else if (DumpSharedSpaces) {
 579     fail_stop(msg, NULL);
 580   }
 581 }


   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/sharedClassUtil.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/systemDictionaryShared.hpp"
  30 #include "classfile/altHashing.hpp"
  31 #include "memory/filemap.hpp"
  32 #include "memory/metadataFactory.hpp"
  33 #include "memory/oopFactory.hpp"
  34 #include "oops/objArrayOop.hpp"
  35 #include "runtime/arguments.hpp"
  36 #include "runtime/java.hpp"
  37 #include "runtime/os.hpp"
  38 #include "runtime/vm_version.hpp"
  39 #include "services/memTracker.hpp"
  40 #include "utilities/defaultStream.hpp"
  41 
  42 # include <sys/stat.h>
  43 # include <errno.h>
  44 
  45 #ifndef O_BINARY       // if defined (Win32) use binary files.
  46 #define O_BINARY 0     // otherwise do nothing.
  47 #endif
  48 
  49 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC

  50 extern address JVM_FunctionAtStart();
  51 extern address JVM_FunctionAtEnd();
  52 
  53 // Complain and stop. All error conditions occurring during the writing of
  54 // an archive file should stop the process.  Unrecoverable errors during
  55 // the reading of the archive file should stop the process.
  56 
  57 static void fail(const char *msg, va_list ap) {
  58   // This occurs very early during initialization: tty is not initialized.
  59   jio_fprintf(defaultStream::error_stream(),
  60               "An error has occurred while processing the"
  61               " shared archive file.\n");
  62   jio_vfprintf(defaultStream::error_stream(), msg, ap);
  63   jio_fprintf(defaultStream::error_stream(), "\n");
  64   // Do not change the text of the below message because some tests check for it.
  65   vm_exit_during_initialization("Unable to use shared archive.", NULL);
  66 }
  67 
  68 
  69 void FileMapInfo::fail_stop(const char *msg, ...) {
  70         va_list ap;
  71   va_start(ap, msg);
  72   fail(msg, ap);        // Never returns.
  73   va_end(ap);           // for completeness.
  74 }
  75 
  76 
  77 // Complain and continue.  Recoverable errors during the reading of the
  78 // archive file may continue (with sharing disabled).
  79 //
  80 // If we continue, then disable shared spaces and close the file.
  81 
  82 void FileMapInfo::fail_continue(const char *msg, ...) {
  83   va_list ap;
  84   va_start(ap, msg);
  85   MetaspaceShared::set_archive_loading_failed();
  86   if (PrintSharedArchiveAndExit && _validating_classpath_entry_table) {
  87     // If we are doing PrintSharedArchiveAndExit and some of the classpath entries
  88     // do not validate, we can still continue "limping" to validate the remaining
  89     // entries. No need to quit.
  90     tty->print("[");
  91     tty->vprint(msg, ap);
  92     tty->print_cr("]");
  93   } else {
  94     if (RequireSharedSpaces) {
  95       fail(msg, ap);
  96     } else {
  97       if (PrintSharedSpaces) {
  98         tty->print_cr("UseSharedSpaces: %s", msg);
  99       }
 100     }
 101   }
 102   va_end(ap);
 103   UseSharedSpaces = false;
 104   assert(current_info() != NULL, "singleton must be registered");
 105   current_info()->close();
 106 }
 107 
 108 // Fill in the fileMapInfo structure with data about this VM instance.
 109 
 110 // This method copies the vm version info into header_version.  If the version is too
 111 // long then a truncated version, which has a hash code appended to it, is copied.
 112 //
 113 // Using a template enables this method to verify that header_version is an array of
 114 // length JVM_IDENT_MAX.  This ensures that the code that writes to the CDS file and
 115 // the code that reads the CDS file will both use the same size buffer.  Hence, will
 116 // use identical truncation.  This is necessary for matching of truncated versions.
 117 template <int N> static void get_header_version(char (&header_version) [N]) {
 118   assert(N == JVM_IDENT_MAX, "Bad header_version size");
 119 
 120   const char *vm_version = VM_Version::internal_vm_info_string();
 121   const int version_len = (int)strlen(vm_version);
 122 
 123   if (version_len < (JVM_IDENT_MAX-1)) {
 124     strcpy(header_version, vm_version);
 125 
 126   } else {
 127     // Get the hash value.  Use a static seed because the hash needs to return the same
 128     // value over multiple jvm invocations.
 129     unsigned int hash = AltHashing::murmur3_32(8191, (const jbyte*)vm_version, version_len);
 130 
 131     // Truncate the ident, saving room for the 8 hex character hash value.
 132     strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
 133 
 134     // Append the hash code as eight hex digits.
 135     sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash);
 136     header_version[JVM_IDENT_MAX-1] = 0;  // Null terminate.
 137   }
 138 }
 139 
 140 FileMapInfo::FileMapInfo() {
 141   assert(_current_info == NULL, "must be singleton"); // not thread safe
 142   _current_info = this;
 143   memset(this, 0, sizeof(FileMapInfo));
 144   _file_offset = 0;
 145   _file_open = false;
 146   _header = SharedClassUtil::allocate_file_map_header();
 147   _header->_version = _invalid_version;
 148 }
 149 
 150 FileMapInfo::~FileMapInfo() {
 151   assert(_current_info == this, "must be singleton"); // not thread safe
 152   _current_info = NULL;
 153 }
 154 
 155 void FileMapInfo::populate_header(size_t alignment) {
 156   _header->populate(this, alignment);
 157 }
 158 
 159 size_t FileMapInfo::FileMapHeader::data_size() {
 160   return SharedClassUtil::file_map_header_size() - sizeof(FileMapInfo::FileMapHeaderBase);
 161 }
 162 
 163 void FileMapInfo::FileMapHeader::populate(FileMapInfo* mapinfo, size_t alignment) {
 164   _magic = 0xf00baba2;
 165   _version = _current_version;
 166   _alignment = alignment;
 167   _obj_alignment = ObjectAlignmentInBytes;
 168   _classpath_entry_table_size = mapinfo->_classpath_entry_table_size;
 169   _classpath_entry_table = mapinfo->_classpath_entry_table;
 170   _classpath_entry_size = mapinfo->_classpath_entry_size;
 171 
 172   // The following fields are for sanity checks for whether this archive
 173   // will function correctly with this JVM and the bootclasspath it's
 174   // invoked with.
 175 
 176   // JVM version string ... changes on each build.
 177   get_header_version(_jvm_ident);
 178 }
 179 
 180 void FileMapInfo::allocate_classpath_entry_table() {
 181   int bytes = 0;
 182   int count = 0;
 183   char* strptr = NULL;
 184   char* strptr_max = NULL;
 185   Thread* THREAD = Thread::current();
 186 
 187   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 188   size_t entry_size = SharedClassUtil::shared_class_path_entry_size();
 189 
 190   for (int pass=0; pass<2; pass++) {

 191     ClassPathEntry *cpe = ClassLoader::classpath_entry(0);

 192 
 193     for (int cur_entry = 0 ; cpe != NULL; cpe = cpe->next(), cur_entry++) {
 194       const char *name = cpe->name();
 195       int name_bytes = (int)(strlen(name) + 1);
 196 
 197       if (pass == 0) {
 198         count ++;
 199         bytes += (int)entry_size;
 200         bytes += name_bytes;
 201         if (TraceClassPaths || (TraceClassLoading && Verbose)) {
 202           tty->print_cr("[Add main shared path (%s) %s]", (cpe->is_jar_file() ? "jar" : "dir"), name);
 203         }
 204       } else {
 205         SharedClassPathEntry* ent = shared_classpath(cur_entry);
 206         if (cpe->is_jar_file()) {
 207           struct stat st;
 208           if (os::stat(name, &st) != 0) {
 209             // The file/dir must exist, or else it would not have been added
 210             // into ClassLoader::classpath_entry().
 211             //
 212             // If we can't access a jar file in the boot path, then we can't
 213             // make assumptions about where classes get loaded from.
 214             FileMapInfo::fail_stop("Unable to open jar file %s.", name);
 215           }
 216 
 217           EXCEPTION_MARK; // The following call should never throw, but would exit VM on error.
 218           SharedClassUtil::update_shared_classpath(cpe, ent, st.st_mtime, st.st_size, THREAD);
 219         } else {
 220           ent->_filesize  = -1;
 221           if (!os::dir_is_empty(name)) {
 222             ClassLoader::exit_with_path_failure("Cannot have non-empty directory in archived classpaths", name);
 223           }
 224         }
 225         ent->_name = strptr;
 226         if (strptr + name_bytes <= strptr_max) {
 227           strncpy(strptr, name, (size_t)name_bytes); // name_bytes includes trailing 0.
 228           strptr += name_bytes;
 229         } else {
 230           assert(0, "miscalculated buffer size");
 231         }
 232       }
 233     }
 234 
 235     if (pass == 0) {
 236       EXCEPTION_MARK; // The following call should never throw, but would exit VM on error.
 237       Array<u8>* arr = MetadataFactory::new_array<u8>(loader_data, (bytes + 7)/8, THREAD);
 238       strptr = (char*)(arr->data());
 239       strptr_max = strptr + bytes;
 240       SharedClassPathEntry* table = (SharedClassPathEntry*)strptr;
 241       strptr += entry_size * count;
 242 
 243       _classpath_entry_table_size = count;
 244       _classpath_entry_table = table;
 245       _classpath_entry_size = entry_size;
 246     }
 247   }
 248 }
 249 
 250 bool FileMapInfo::validate_classpath_entry_table() {
 251   _validating_classpath_entry_table = true;
 252 
 253   int count = _header->_classpath_entry_table_size;
 254 
 255   _classpath_entry_table = _header->_classpath_entry_table;
 256   _classpath_entry_size = _header->_classpath_entry_size;
 257 
 258   for (int i=0; i<count; i++) {
 259     SharedClassPathEntry* ent = shared_classpath(i);
 260     struct stat st;
 261     const char* name = ent->_name;
 262     bool ok = true;
 263     if (TraceClassPaths || (TraceClassLoading && Verbose)) {
 264       tty->print_cr("[Checking shared classpath entry: %s]", name);
 265     }
 266     if (os::stat(name, &st) != 0) {
 267       fail_continue("Required classpath entry does not exist: %s", name);
 268       ok = false;
 269     } else if (ent->is_dir()) {
 270       if (!os::dir_is_empty(name)) {
 271         fail_continue("directory is not empty: %s", name);
 272         ok = false;
 273       }
 274     } else {
 275       if (ent->_timestamp != st.st_mtime ||
 276           ent->_filesize != st.st_size) {
 277         ok = false;
 278         if (PrintSharedArchiveAndExit) {
 279           fail_continue(ent->_timestamp != st.st_mtime ?
 280                         "Timestamp mismatch" :
 281                         "File size mismatch");
 282         } else {
 283           fail_continue("A jar file is not the one used while building"
 284                         " the shared archive file: %s", name);
 285         }
 286       }
 287     }
 288     if (ok) {
 289       if (TraceClassPaths || (TraceClassLoading && Verbose)) {
 290         tty->print_cr("[ok]");
 291       }
 292     } else if (!PrintSharedArchiveAndExit) {
 293       _validating_classpath_entry_table = false;
 294       return false;
 295     }
 296   }
 297 
 298   _classpath_entry_table_size = _header->_classpath_entry_table_size;
 299   _validating_classpath_entry_table = false;
 300   return true;
 301 }
 302 
 303 
 304 // Read the FileMapInfo information from the file.
 305 
 306 bool FileMapInfo::init_from_file(int fd) {
 307   size_t sz = _header->data_size();
 308   char* addr = _header->data();
 309   size_t n = os::read(fd, addr, (unsigned int)sz);
 310   if (n != sz) {
 311     fail_continue("Unable to read the file header.");
 312     return false;
 313   }
 314   if (_header->_version != current_version()) {
 315     fail_continue("The shared archive file has the wrong version.");
 316     return false;
 317   }
 318   _file_offset = (long)n;
 319 
 320   size_t info_size = _header->_paths_misc_info_size;
 321   _paths_misc_info = NEW_C_HEAP_ARRAY_RETURN_NULL(char, info_size, mtClass);
 322   if (_paths_misc_info == NULL) {
 323     fail_continue("Unable to read the file header.");
 324     return false;
 325   }
 326   n = os::read(fd, _paths_misc_info, (unsigned int)info_size);
 327   if (n != info_size) {
 328     fail_continue("Unable to read the shared path info header.");
 329     FREE_C_HEAP_ARRAY(char, _paths_misc_info, mtClass);
 330     _paths_misc_info = NULL;
 331     return false;
 332   }
 333 
 334   _file_offset += (long)n;
 335   return true;
 336 }
 337 
 338 
 339 // Read the FileMapInfo information from the file.
 340 bool FileMapInfo::open_for_read() {
 341   _full_path = Arguments::GetSharedArchivePath();
 342   int fd = open(_full_path, O_RDONLY | O_BINARY, 0);
 343   if (fd < 0) {
 344     if (errno == ENOENT) {
 345       // Not locating the shared archive is ok.
 346       fail_continue("Specified shared archive not found.");
 347     } else {
 348       fail_continue("Failed to open shared archive file (%s).",
 349                     strerror(errno));
 350     }
 351     return false;
 352   }
 353 
 354   _fd = fd;


 369 #ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
 370   chmod(_full_path, _S_IREAD | _S_IWRITE);
 371 #endif
 372 
 373   // Use remove() to delete the existing file because, on Unix, this will
 374   // allow processes that have it open continued access to the file.
 375   remove(_full_path);
 376   int fd = open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
 377   if (fd < 0) {
 378     fail_stop("Unable to create shared archive file %s.", _full_path);
 379   }
 380   _fd = fd;
 381   _file_offset = 0;
 382   _file_open = true;
 383 }
 384 
 385 
 386 // Write the header to the file, seek to the next allocation boundary.
 387 
 388 void FileMapInfo::write_header() {
 389   int info_size = ClassLoader::get_shared_paths_misc_info_size();
 390 
 391   _header->_paths_misc_info_size = info_size;
 392 
 393   align_file_position();
 394   size_t sz = _header->data_size();
 395   char* addr = _header->data();
 396   write_bytes(addr, (int)sz); // skip the C++ vtable
 397   write_bytes(ClassLoader::get_shared_paths_misc_info(), info_size);
 398   align_file_position();
 399 }
 400 
 401 
 402 // Dump shared spaces to file.
 403 
 404 void FileMapInfo::write_space(int i, Metaspace* space, bool read_only) {
 405   align_file_position();
 406   size_t used = space->used_bytes_slow(Metaspace::NonClassType);
 407   size_t capacity = space->capacity_bytes_slow(Metaspace::NonClassType);
 408   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 409   write_region(i, (char*)space->bottom(), used, capacity, read_only, false);
 410 }
 411 
 412 
 413 // Dump region to file.
 414 
 415 void FileMapInfo::write_region(int region, char* base, size_t size,
 416                                size_t capacity, bool read_only,
 417                                bool allow_exec) {
 418   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[region];
 419 
 420   if (_file_open) {
 421     guarantee(si->_file_offset == _file_offset, "file offset mismatch.");
 422     if (PrintSharedSpaces) {
 423       tty->print_cr("Shared file region %d: 0x%6x bytes, addr " INTPTR_FORMAT
 424                     " file offset 0x%6x", region, size, base, _file_offset);
 425     }
 426   } else {
 427     si->_file_offset = _file_offset;
 428   }
 429   si->_base = base;
 430   si->_used = size;
 431   si->_capacity = capacity;
 432   si->_read_only = read_only;
 433   si->_allow_exec = allow_exec;
 434   write_bytes_aligned(base, (int)size);
 435 }
 436 
 437 
 438 // Dump bytes to file -- at the current file position.


 480   align_file_position();
 481 }
 482 
 483 
 484 // Close the shared archive file.  This does NOT unmap mapped regions.
 485 
 486 void FileMapInfo::close() {
 487   if (_file_open) {
 488     if (::close(_fd) < 0) {
 489       fail_stop("Unable to close the shared archive file.");
 490     }
 491     _file_open = false;
 492     _fd = -1;
 493   }
 494 }
 495 
 496 
 497 // JVM/TI RedefineClasses() support:
 498 // Remap the shared readonly space to shared readwrite, private.
 499 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
 500   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[0];
 501   if (!si->_read_only) {
 502     // the space is already readwrite so we are done
 503     return true;
 504   }
 505   size_t used = si->_used;
 506   size_t size = align_size_up(used, os::vm_allocation_granularity());
 507   if (!open_for_read()) {
 508     return false;
 509   }
 510   char *base = os::remap_memory(_fd, _full_path, si->_file_offset,
 511                                 si->_base, size, false /* !read_only */,
 512                                 si->_allow_exec);
 513   close();
 514   if (base == NULL) {
 515     fail_continue("Unable to remap shared readonly space (errno=%d).", errno);
 516     return false;
 517   }
 518   if (base != si->_base) {
 519     fail_continue("Unable to remap shared readonly space at required address.");
 520     return false;
 521   }
 522   si->_read_only = false;
 523   return true;
 524 }
 525 
 526 // Map the whole region at once, assumed to be allocated contiguously.
 527 ReservedSpace FileMapInfo::reserve_shared_memory() {
 528   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[0];
 529   char* requested_addr = si->_base;
 530 
 531   size_t size = FileMapInfo::shared_spaces_size();
 532 
 533   // Reserve the space first, then map otherwise map will go right over some
 534   // other reserved memory (like the code cache).
 535   ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr);
 536   if (!rs.is_reserved()) {
 537     fail_continue(err_msg("Unable to reserve shared space at required address " INTPTR_FORMAT, requested_addr));
 538     return rs;
 539   }
 540   // the reserved virtual memory is for mapping class data sharing archive
 541   MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared);
 542 
 543   return rs;
 544 }
 545 
 546 // Memory map a region in the address space.
 547 static const char* shared_region_name[] = { "ReadOnly", "ReadWrite", "MiscData", "MiscCode"};
 548 
 549 char* FileMapInfo::map_region(int i) {
 550   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 551   size_t used = si->_used;
 552   size_t alignment = os::vm_allocation_granularity();
 553   size_t size = align_size_up(used, alignment);
 554   char *requested_addr = si->_base;
 555 
 556   // map the contents of the CDS archive in this memory
 557   char *base = os::map_memory(_fd, _full_path, si->_file_offset,
 558                               requested_addr, size, si->_read_only,
 559                               si->_allow_exec);
 560   if (base == NULL || base != si->_base) {
 561     fail_continue(err_msg("Unable to map %s shared space at required address.", shared_region_name[i]));
 562     return NULL;
 563   }
 564 #ifdef _WINDOWS
 565   // This call is Windows-only because the memory_type gets recorded for the other platforms
 566   // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows.
 567   MemTracker::record_virtual_memory_type((address)base, mtClassShared);
 568 #endif
 569   return base;
 570 }
 571 
 572 
 573 // Unmap a memory region in the address space.
 574 
 575 void FileMapInfo::unmap_region(int i) {
 576   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 577   size_t used = si->_used;
 578   size_t size = align_size_up(used, os::vm_allocation_granularity());
 579   if (!os::unmap_memory(si->_base, size)) {
 580     fail_stop("Unable to unmap shared space.");
 581   }
 582 }
 583 
 584 
 585 void FileMapInfo::assert_mark(bool check) {
 586   if (!check) {
 587     fail_stop("Mark mismatch while restoring from shared file.", NULL);
 588   }
 589 }
 590 
 591 
 592 FileMapInfo* FileMapInfo::_current_info = NULL;
 593 SharedClassPathEntry* FileMapInfo::_classpath_entry_table = NULL;
 594 int FileMapInfo::_classpath_entry_table_size = 0;
 595 size_t FileMapInfo::_classpath_entry_size = 0x1234baad;
 596 bool FileMapInfo::_validating_classpath_entry_table = false;
 597 
 598 // Open the shared archive file, read and validate the header
 599 // information (version, boot classpath, etc.).  If initialization
 600 // fails, shared spaces are disabled and the file is closed. [See
 601 // fail_continue.]
 602 //
 603 // Validation of the archive is done in two steps:
 604 //
 605 // [1] validate_header() - done here. This checks the header, including _paths_misc_info.
 606 // [2] validate_classpath_entry_table - this is done later, because the table is in the RW
 607 //     region of the archive, which is not mapped yet.
 608 bool FileMapInfo::initialize() {
 609   assert(UseSharedSpaces, "UseSharedSpaces expected.");
 610 
 611   if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space()) {
 612     fail_continue("Tool agent requires sharing to be disabled.");
 613     return false;
 614   }
 615 
 616   if (!open_for_read()) {
 617     return false;
 618   }
 619 
 620   init_from_file(_fd);
 621   if (!validate_header()) {
 622     return false;
 623   }
 624 
 625   SharedReadOnlySize =  _header->_space[0]._capacity;
 626   SharedReadWriteSize = _header->_space[1]._capacity;
 627   SharedMiscDataSize =  _header->_space[2]._capacity;
 628   SharedMiscCodeSize =  _header->_space[3]._capacity;
 629   return true;
 630 }
 631 
 632 bool FileMapInfo::FileMapHeader::validate() {
 633   if (_version != current_version()) {
 634     FileMapInfo::fail_continue("The shared archive file is the wrong version.");

 635     return false;
 636   }
 637   if (_magic != (int)0xf00baba2) {
 638     FileMapInfo::fail_continue("The shared archive file has a bad magic number.");
 639     return false;
 640   }
 641   char header_version[JVM_IDENT_MAX];
 642   get_header_version(header_version);
 643   if (strncmp(_jvm_ident, header_version, JVM_IDENT_MAX-1) != 0) {
 644     if (TraceClassPaths) {
 645       tty->print_cr("Expected: %s", header_version);
 646       tty->print_cr("Actual:   %s", _jvm_ident);
 647     }
 648     FileMapInfo::fail_continue("The shared archive file was created by a different"
 649                   " version or build of HotSpot");


 650     return false;
 651   }
 652   if (_obj_alignment != ObjectAlignmentInBytes) {
 653     FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"
 654                   " does not equal the current ObjectAlignmentInBytes of %d.",
 655                   _obj_alignment, ObjectAlignmentInBytes);


 656     return false;
 657   }
 658 
 659   return true;
 660 }


 661 
 662 bool FileMapInfo::validate_header() {
 663   bool status = _header->validate();
 664 
 665   if (status) {
 666     if (!ClassLoader::check_shared_paths_misc_info(_paths_misc_info, _header->_paths_misc_info_size)) {
 667       if (!PrintSharedArchiveAndExit) {
 668         fail_continue("shared class paths mismatch (hint: enable -XX:+TraceClassPaths to diagnose the failure)");
 669         status = false;

 670       }





 671     }
 672   }


 673 
 674   if (_paths_misc_info != NULL) {
 675     FREE_C_HEAP_ARRAY(char, _paths_misc_info, mtClass);
 676     _paths_misc_info = NULL;




 677   }
 678   return status;







 679 }
 680 
 681 // The following method is provided to see whether a given pointer
 682 // falls in the mapped shared space.
 683 // Param:
 684 // p, The given pointer
 685 // Return:
 686 // True if the p is within the mapped shared space, otherwise, false.
 687 bool FileMapInfo::is_in_shared_space(const void* p) {
 688   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
 689     if (p >= _header->_space[i]._base &&
 690         p < _header->_space[i]._base + _header->_space[i]._used) {
 691       return true;
 692     }
 693   }
 694 
 695   return false;
 696 }
 697 
 698 void FileMapInfo::print_shared_spaces() {
 699   gclog_or_tty->print_cr("Shared Spaces:");
 700   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
 701     struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 702     gclog_or_tty->print("  %s " INTPTR_FORMAT "-" INTPTR_FORMAT,
 703                         shared_region_name[i],
 704                         si->_base, si->_base + si->_used);
 705   }
 706 }
 707 
 708 // Unmap mapped regions of shared space.
 709 void FileMapInfo::stop_sharing_and_unmap(const char* msg) {
 710   FileMapInfo *map_info = FileMapInfo::current_info();
 711   if (map_info) {
 712     map_info->fail_continue(msg);
 713     for (int i = 0; i < MetaspaceShared::n_regions; i++) {
 714       if (map_info->_header->_space[i]._base != NULL) {
 715         map_info->unmap_region(i);
 716         map_info->_header->_space[i]._base = NULL;
 717       }
 718     }
 719   } else if (DumpSharedSpaces) {
 720     fail_stop(msg, NULL);
 721   }
 722 }