1 /*
   2  * Copyright (c) 2003, 2014, 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/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 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);
 330     _paths_misc_info = NULL;
 331     return false;
 332   }
 333 
 334   size_t len = lseek(fd, 0, SEEK_END);
 335   struct FileMapInfo::FileMapHeader::space_info* si =
 336     &_header->_space[MetaspaceShared::mc];
 337   if (si->_file_offset >= len || len - si->_file_offset < si->_used) {
 338     fail_continue("The shared archive file has been truncated.");
 339     return false;
 340   }
 341 
 342   _file_offset += (long)n;
 343   return true;
 344 }
 345 
 346 
 347 // Read the FileMapInfo information from the file.
 348 bool FileMapInfo::open_for_read() {
 349   _full_path = Arguments::GetSharedArchivePath();
 350   int fd = open(_full_path, O_RDONLY | O_BINARY, 0);
 351   if (fd < 0) {
 352     if (errno == ENOENT) {
 353       // Not locating the shared archive is ok.
 354       fail_continue("Specified shared archive not found.");
 355     } else {
 356       fail_continue("Failed to open shared archive file (%s).",
 357                     strerror(errno));
 358     }
 359     return false;
 360   }
 361 
 362   _fd = fd;
 363   _file_open = true;
 364   return true;
 365 }
 366 
 367 
 368 // Write the FileMapInfo information to the file.
 369 
 370 void FileMapInfo::open_for_write() {
 371  _full_path = Arguments::GetSharedArchivePath();
 372   if (PrintSharedSpaces) {
 373     tty->print_cr("Dumping shared data to file: ");
 374     tty->print_cr("   %s", _full_path);
 375   }
 376 
 377 #ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
 378   chmod(_full_path, _S_IREAD | _S_IWRITE);
 379 #endif
 380 
 381   // Use remove() to delete the existing file because, on Unix, this will
 382   // allow processes that have it open continued access to the file.
 383   remove(_full_path);
 384   int fd = open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
 385   if (fd < 0) {
 386     fail_stop("Unable to create shared archive file %s.", _full_path);
 387   }
 388   _fd = fd;
 389   _file_offset = 0;
 390   _file_open = true;
 391 }
 392 
 393 
 394 // Write the header to the file, seek to the next allocation boundary.
 395 
 396 void FileMapInfo::write_header() {
 397   int info_size = ClassLoader::get_shared_paths_misc_info_size();
 398 
 399   _header->_paths_misc_info_size = info_size;
 400 
 401   align_file_position();
 402   size_t sz = _header->data_size();
 403   char* addr = _header->data();
 404   write_bytes(addr, (int)sz); // skip the C++ vtable
 405   write_bytes(ClassLoader::get_shared_paths_misc_info(), info_size);
 406   align_file_position();
 407 }
 408 
 409 
 410 // Dump shared spaces to file.
 411 
 412 void FileMapInfo::write_space(int i, Metaspace* space, bool read_only) {
 413   align_file_position();
 414   size_t used = space->used_bytes_slow(Metaspace::NonClassType);
 415   size_t capacity = space->capacity_bytes_slow(Metaspace::NonClassType);
 416   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 417   write_region(i, (char*)space->bottom(), used, capacity, read_only, false);
 418 }
 419 
 420 
 421 // Dump region to file.
 422 
 423 void FileMapInfo::write_region(int region, char* base, size_t size,
 424                                size_t capacity, bool read_only,
 425                                bool allow_exec) {
 426   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[region];
 427 
 428   if (_file_open) {
 429     guarantee(si->_file_offset == _file_offset, "file offset mismatch.");
 430     if (PrintSharedSpaces) {
 431       tty->print_cr("Shared file region %d: 0x%6x bytes, addr " INTPTR_FORMAT
 432                     " file offset 0x%6x", region, size, base, _file_offset);
 433     }
 434   } else {
 435     si->_file_offset = _file_offset;
 436   }
 437   si->_base = base;
 438   si->_used = size;
 439   si->_capacity = capacity;
 440   si->_read_only = read_only;
 441   si->_allow_exec = allow_exec;
 442   si->_crc = ClassLoader::crc32(0, base, (jint)size);
 443   write_bytes_aligned(base, (int)size);
 444 }
 445 
 446 
 447 // Dump bytes to file -- at the current file position.
 448 
 449 void FileMapInfo::write_bytes(const void* buffer, int nbytes) {
 450   if (_file_open) {
 451     int n = ::write(_fd, buffer, nbytes);
 452     if (n != nbytes) {
 453       // It is dangerous to leave the corrupted shared archive file around,
 454       // close and remove the file. See bug 6372906.
 455       close();
 456       remove(_full_path);
 457       fail_stop("Unable to write to shared archive file.");
 458     }
 459   }
 460   _file_offset += nbytes;
 461 }
 462 
 463 
 464 // Align file position to an allocation unit boundary.
 465 
 466 void FileMapInfo::align_file_position() {
 467   size_t new_file_offset = align_size_up(_file_offset,
 468                                          os::vm_allocation_granularity());
 469   if (new_file_offset != _file_offset) {
 470     _file_offset = new_file_offset;
 471     if (_file_open) {
 472       // Seek one byte back from the target and write a byte to insure
 473       // that the written file is the correct length.
 474       _file_offset -= 1;
 475       if (lseek(_fd, (long)_file_offset, SEEK_SET) < 0) {
 476         fail_stop("Unable to seek.");
 477       }
 478       char zero = 0;
 479       write_bytes(&zero, 1);
 480     }
 481   }
 482 }
 483 
 484 
 485 // Dump bytes to file -- at the current file position.
 486 
 487 void FileMapInfo::write_bytes_aligned(const void* buffer, int nbytes) {
 488   align_file_position();
 489   write_bytes(buffer, nbytes);
 490   align_file_position();
 491 }
 492 
 493 
 494 // Close the shared archive file.  This does NOT unmap mapped regions.
 495 
 496 void FileMapInfo::close() {
 497   if (_file_open) {
 498     if (::close(_fd) < 0) {
 499       fail_stop("Unable to close the shared archive file.");
 500     }
 501     _file_open = false;
 502     _fd = -1;
 503   }
 504 }
 505 
 506 
 507 // JVM/TI RedefineClasses() support:
 508 // Remap the shared readonly space to shared readwrite, private.
 509 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
 510   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[0];
 511   if (!si->_read_only) {
 512     // the space is already readwrite so we are done
 513     return true;
 514   }
 515   size_t used = si->_used;
 516   size_t size = align_size_up(used, os::vm_allocation_granularity());
 517   if (!open_for_read()) {
 518     return false;
 519   }
 520   char *base = os::remap_memory(_fd, _full_path, si->_file_offset,
 521                                 si->_base, size, false /* !read_only */,
 522                                 si->_allow_exec);
 523   close();
 524   if (base == NULL) {
 525     fail_continue("Unable to remap shared readonly space (errno=%d).", errno);
 526     return false;
 527   }
 528   if (base != si->_base) {
 529     fail_continue("Unable to remap shared readonly space at required address.");
 530     return false;
 531   }
 532   si->_read_only = false;
 533   return true;
 534 }
 535 
 536 // Map the whole region at once, assumed to be allocated contiguously.
 537 ReservedSpace FileMapInfo::reserve_shared_memory() {
 538   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[0];
 539   char* requested_addr = si->_base;
 540 
 541   size_t size = FileMapInfo::shared_spaces_size();
 542 
 543   // Reserve the space first, then map otherwise map will go right over some
 544   // other reserved memory (like the code cache).
 545   ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr);
 546   if (!rs.is_reserved()) {
 547     fail_continue("Unable to reserve shared space at required address " INTPTR_FORMAT, requested_addr);
 548     return rs;
 549   }
 550   // the reserved virtual memory is for mapping class data sharing archive
 551   MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared);
 552 
 553   return rs;
 554 }
 555 
 556 // Memory map a region in the address space.
 557 static const char* shared_region_name[] = { "ReadOnly", "ReadWrite", "MiscData", "MiscCode"};
 558 
 559 char* FileMapInfo::map_region(int i) {
 560   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 561   size_t used = si->_used;
 562   size_t alignment = os::vm_allocation_granularity();
 563   size_t size = align_size_up(used, alignment);
 564   char *requested_addr = si->_base;
 565 
 566   // map the contents of the CDS archive in this memory
 567   char *base = os::map_memory(_fd, _full_path, si->_file_offset,
 568                               requested_addr, size, si->_read_only,
 569                               si->_allow_exec);
 570   if (base == NULL || base != si->_base) {
 571     fail_continue("Unable to map %s shared space at required address.", shared_region_name[i]);
 572     return NULL;
 573   }
 574 #ifdef _WINDOWS
 575   // This call is Windows-only because the memory_type gets recorded for the other platforms
 576   // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows.
 577   MemTracker::record_virtual_memory_type((address)base, mtClassShared);
 578 #endif
 579   return base;
 580 }
 581 
 582 bool FileMapInfo::verify_region_checksum(int i) {
 583   if (!VerifySharedSpaces) {
 584     return true;
 585   }
 586   const char* buf = _header->_space[i]._base;
 587   size_t sz = _header->_space[i]._used;
 588   int crc = ClassLoader::crc32(0, buf, (jint)sz);
 589   if (crc != _header->_space[i]._crc) {
 590     fail_continue("Checksum verification failed.");
 591     return false;
 592   }
 593   return true;
 594 }
 595 
 596 // Unmap a memory region in the address space.
 597 
 598 void FileMapInfo::unmap_region(int i) {
 599   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 600   size_t used = si->_used;
 601   size_t size = align_size_up(used, os::vm_allocation_granularity());
 602   if (!os::unmap_memory(si->_base, size)) {
 603     fail_stop("Unable to unmap shared space.");
 604   }
 605 }
 606 
 607 
 608 void FileMapInfo::assert_mark(bool check) {
 609   if (!check) {
 610     fail_stop("Mark mismatch while restoring from shared file.");
 611   }
 612 }
 613 
 614 
 615 FileMapInfo* FileMapInfo::_current_info = NULL;
 616 SharedClassPathEntry* FileMapInfo::_classpath_entry_table = NULL;
 617 int FileMapInfo::_classpath_entry_table_size = 0;
 618 size_t FileMapInfo::_classpath_entry_size = 0x1234baad;
 619 bool FileMapInfo::_validating_classpath_entry_table = false;
 620 
 621 // Open the shared archive file, read and validate the header
 622 // information (version, boot classpath, etc.).  If initialization
 623 // fails, shared spaces are disabled and the file is closed. [See
 624 // fail_continue.]
 625 //
 626 // Validation of the archive is done in two steps:
 627 //
 628 // [1] validate_header() - done here. This checks the header, including _paths_misc_info.
 629 // [2] validate_classpath_entry_table - this is done later, because the table is in the RW
 630 //     region of the archive, which is not mapped yet.
 631 bool FileMapInfo::initialize() {
 632   assert(UseSharedSpaces, "UseSharedSpaces expected.");
 633 
 634   if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space()) {
 635     fail_continue("Tool agent requires sharing to be disabled.");
 636     return false;
 637   }
 638 
 639   if (!open_for_read()) {
 640     return false;
 641   }
 642 
 643   init_from_file(_fd);
 644   if (!validate_header()) {
 645     return false;
 646   }
 647 
 648   SharedReadOnlySize =  _header->_space[0]._capacity;
 649   SharedReadWriteSize = _header->_space[1]._capacity;
 650   SharedMiscDataSize =  _header->_space[2]._capacity;
 651   SharedMiscCodeSize =  _header->_space[3]._capacity;
 652   return true;
 653 }
 654 
 655 int FileMapInfo::FileMapHeader::compute_crc() {
 656   char* header = data();
 657   // start computing from the field after _crc
 658   char* buf = (char*)&_crc + sizeof(int);
 659   size_t sz = data_size() - (buf - header);
 660   int crc = ClassLoader::crc32(0, buf, (jint)sz);
 661   return crc;
 662 }
 663 
 664 bool FileMapInfo::FileMapHeader::validate() {
 665   if (VerifySharedSpaces && compute_crc() != _crc) {
 666     fail_continue("Header checksum verification failed.");
 667     return false;
 668   }
 669 
 670   if (_version != current_version()) {
 671     FileMapInfo::fail_continue("The shared archive file is the wrong version.");
 672     return false;
 673   }
 674   if (_magic != (int)0xf00baba2) {
 675     FileMapInfo::fail_continue("The shared archive file has a bad magic number.");
 676     return false;
 677   }
 678   char header_version[JVM_IDENT_MAX];
 679   get_header_version(header_version);
 680   if (strncmp(_jvm_ident, header_version, JVM_IDENT_MAX-1) != 0) {
 681     if (TraceClassPaths) {
 682       tty->print_cr("Expected: %s", header_version);
 683       tty->print_cr("Actual:   %s", _jvm_ident);
 684     }
 685     FileMapInfo::fail_continue("The shared archive file was created by a different"
 686                   " version or build of HotSpot");
 687     return false;
 688   }
 689   if (_obj_alignment != ObjectAlignmentInBytes) {
 690     FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"
 691                   " does not equal the current ObjectAlignmentInBytes of %d.",
 692                   _obj_alignment, ObjectAlignmentInBytes);
 693     return false;
 694   }
 695 
 696   return true;
 697 }
 698 
 699 bool FileMapInfo::validate_header() {
 700   bool status = _header->validate();
 701 
 702   if (status) {
 703     if (!ClassLoader::check_shared_paths_misc_info(_paths_misc_info, _header->_paths_misc_info_size)) {
 704       if (!PrintSharedArchiveAndExit) {
 705         fail_continue("shared class paths mismatch (hint: enable -XX:+TraceClassPaths to diagnose the failure)");
 706         status = false;
 707       }
 708     }
 709   }
 710 
 711   if (_paths_misc_info != NULL) {
 712     FREE_C_HEAP_ARRAY(char, _paths_misc_info);
 713     _paths_misc_info = NULL;
 714   }
 715   return status;
 716 }
 717 
 718 // The following method is provided to see whether a given pointer
 719 // falls in the mapped shared space.
 720 // Param:
 721 // p, The given pointer
 722 // Return:
 723 // True if the p is within the mapped shared space, otherwise, false.
 724 bool FileMapInfo::is_in_shared_space(const void* p) {
 725   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
 726     if (p >= _header->_space[i]._base &&
 727         p < _header->_space[i]._base + _header->_space[i]._used) {
 728       return true;
 729     }
 730   }
 731 
 732   return false;
 733 }
 734 
 735 void FileMapInfo::print_shared_spaces() {
 736   gclog_or_tty->print_cr("Shared Spaces:");
 737   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
 738     struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 739     gclog_or_tty->print("  %s " INTPTR_FORMAT "-" INTPTR_FORMAT,
 740                         shared_region_name[i],
 741                         si->_base, si->_base + si->_used);
 742   }
 743 }
 744 
 745 // Unmap mapped regions of shared space.
 746 void FileMapInfo::stop_sharing_and_unmap(const char* msg) {
 747   FileMapInfo *map_info = FileMapInfo::current_info();
 748   if (map_info) {
 749     map_info->fail_continue("%s", msg);
 750     for (int i = 0; i < MetaspaceShared::n_regions; i++) {
 751       if (map_info->_header->_space[i]._base != NULL) {
 752         map_info->unmap_region(i);
 753         map_info->_header->_space[i]._base = NULL;
 754       }
 755     }
 756   } else if (DumpSharedSpaces) {
 757     fail_stop("%s", msg);
 758   }
 759 }