1 /*
   2  * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "classfile/classLoader.inline.hpp"
  28 #include "classfile/classLoaderExt.hpp"
  29 #include "classfile/symbolTable.hpp"
  30 #include "classfile/systemDictionaryShared.hpp"
  31 #include "classfile/altHashing.hpp"
  32 #include "logging/log.hpp"
  33 #include "logging/logStream.hpp"
  34 #include "logging/logMessage.hpp"
  35 #include "memory/filemap.hpp"
  36 #include "memory/heapShared.inline.hpp"
  37 #include "memory/iterator.inline.hpp"
  38 #include "memory/metadataFactory.hpp"
  39 #include "memory/metaspaceClosure.hpp"
  40 #include "memory/metaspaceShared.hpp"
  41 #include "memory/oopFactory.hpp"
  42 #include "oops/compressedOops.inline.hpp"
  43 #include "oops/objArrayOop.hpp"
  44 #include "oops/oop.inline.hpp"
  45 #include "prims/jvmtiExport.hpp"
  46 #include "runtime/arguments.hpp"
  47 #include "runtime/java.hpp"
  48 #include "runtime/os.inline.hpp"
  49 #include "runtime/vm_version.hpp"
  50 #include "services/memTracker.hpp"
  51 #include "utilities/align.hpp"
  52 #include "utilities/defaultStream.hpp"
  53 #if INCLUDE_G1GC
  54 #include "gc/g1/g1CollectedHeap.hpp"
  55 #include "gc/g1/heapRegion.hpp"
  56 #endif
  57 
  58 # include <sys/stat.h>
  59 # include <errno.h>
  60 
  61 #ifndef O_BINARY       // if defined (Win32) use binary files.
  62 #define O_BINARY 0     // otherwise do nothing.
  63 #endif
  64 
  65 extern address JVM_FunctionAtStart();
  66 extern address JVM_FunctionAtEnd();
  67 
  68 // Complain and stop. All error conditions occurring during the writing of
  69 // an archive file should stop the process.  Unrecoverable errors during
  70 // the reading of the archive file should stop the process.
  71 
  72 static void fail(const char *msg, va_list ap) {
  73   // This occurs very early during initialization: tty is not initialized.
  74   jio_fprintf(defaultStream::error_stream(),
  75               "An error has occurred while processing the"
  76               " shared archive file.\n");
  77   jio_vfprintf(defaultStream::error_stream(), msg, ap);
  78   jio_fprintf(defaultStream::error_stream(), "\n");
  79   // Do not change the text of the below message because some tests check for it.
  80   vm_exit_during_initialization("Unable to use shared archive.", NULL);
  81 }
  82 
  83 
  84 void FileMapInfo::fail_stop(const char *msg, ...) {
  85         va_list ap;
  86   va_start(ap, msg);
  87   fail(msg, ap);        // Never returns.
  88   va_end(ap);           // for completeness.
  89 }
  90 
  91 
  92 // Complain and continue.  Recoverable errors during the reading of the
  93 // archive file may continue (with sharing disabled).
  94 //
  95 // If we continue, then disable shared spaces and close the file.
  96 
  97 void FileMapInfo::fail_continue(const char *msg, ...) {
  98   va_list ap;
  99   va_start(ap, msg);
 100   MetaspaceShared::set_archive_loading_failed();
 101   if (PrintSharedArchiveAndExit && _validating_shared_path_table) {
 102     // If we are doing PrintSharedArchiveAndExit and some of the classpath entries
 103     // do not validate, we can still continue "limping" to validate the remaining
 104     // entries. No need to quit.
 105     tty->print("[");
 106     tty->vprint(msg, ap);
 107     tty->print_cr("]");
 108   } else {
 109     if (RequireSharedSpaces) {
 110       fail(msg, ap);
 111     } else {
 112       if (log_is_enabled(Info, cds)) {
 113         ResourceMark rm;
 114         LogStream ls(Log(cds)::info());
 115         ls.print("UseSharedSpaces: ");
 116         ls.vprint_cr(msg, ap);
 117       }
 118     }
 119     UseSharedSpaces = false;
 120     assert(current_info() != NULL, "singleton must be registered");
 121     current_info()->close();
 122   }
 123   va_end(ap);
 124 }
 125 
 126 // Fill in the fileMapInfo structure with data about this VM instance.
 127 
 128 // This method copies the vm version info into header_version.  If the version is too
 129 // long then a truncated version, which has a hash code appended to it, is copied.
 130 //
 131 // Using a template enables this method to verify that header_version is an array of
 132 // length JVM_IDENT_MAX.  This ensures that the code that writes to the CDS file and
 133 // the code that reads the CDS file will both use the same size buffer.  Hence, will
 134 // use identical truncation.  This is necessary for matching of truncated versions.
 135 template <int N> static void get_header_version(char (&header_version) [N]) {
 136   assert(N == JVM_IDENT_MAX, "Bad header_version size");
 137 
 138   const char *vm_version = VM_Version::internal_vm_info_string();
 139   const int version_len = (int)strlen(vm_version);
 140 
 141   if (version_len < (JVM_IDENT_MAX-1)) {
 142     strcpy(header_version, vm_version);
 143 
 144   } else {
 145     // Get the hash value.  Use a static seed because the hash needs to return the same
 146     // value over multiple jvm invocations.
 147     unsigned int hash = AltHashing::murmur3_32(8191, (const jbyte*)vm_version, version_len);
 148 
 149     // Truncate the ident, saving room for the 8 hex character hash value.
 150     strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
 151 
 152     // Append the hash code as eight hex digits.
 153     sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash);
 154     header_version[JVM_IDENT_MAX-1] = 0;  // Null terminate.
 155   }
 156 }
 157 
 158 FileMapInfo::FileMapInfo() {
 159   assert(_current_info == NULL, "must be singleton"); // not thread safe
 160   _current_info = this;
 161   memset((void*)this, 0, sizeof(FileMapInfo));
 162   _file_offset = 0;
 163   _file_open = false;
 164   _header = (FileMapHeader*)os::malloc(sizeof(FileMapHeader), mtInternal);
 165   _header->_version = INVALID_CDS_ARCHIVE_VERSION;
 166   _header->_has_platform_or_app_classes = true;
 167 }
 168 
 169 FileMapInfo::~FileMapInfo() {
 170   assert(_current_info == this, "must be singleton"); // not thread safe
 171   _current_info = NULL;
 172 }
 173 
 174 void FileMapInfo::populate_header(size_t alignment) {
 175   _header->populate(this, alignment);
 176 }
 177 
 178 void FileMapHeader::populate(FileMapInfo* mapinfo, size_t alignment) {
 179   _magic = CDS_ARCHIVE_MAGIC;
 180   _version = CURRENT_CDS_ARCHIVE_VERSION;
 181   _alignment = alignment;
 182   _obj_alignment = ObjectAlignmentInBytes;
 183   _compact_strings = CompactStrings;
 184   _narrow_oop_mode = Universe::narrow_oop_mode();
 185   _narrow_oop_base = Universe::narrow_oop_base();
 186   _narrow_oop_shift = Universe::narrow_oop_shift();
 187   _max_heap_size = MaxHeapSize;
 188   _narrow_klass_base = Universe::narrow_klass_base();
 189   _narrow_klass_shift = Universe::narrow_klass_shift();
 190   _shared_path_table_size = mapinfo->_shared_path_table_size;
 191   _shared_path_table = mapinfo->_shared_path_table;
 192   _shared_path_entry_size = mapinfo->_shared_path_entry_size;
 193   if (HeapShared::is_heap_object_archiving_allowed()) {
 194     _heap_reserved = Universe::heap()->reserved_region();
 195   }
 196 
 197   // The following fields are for sanity checks for whether this archive
 198   // will function correctly with this JVM and the bootclasspath it's
 199   // invoked with.
 200 
 201   // JVM version string ... changes on each build.
 202   get_header_version(_jvm_ident);
 203 
 204   ClassLoaderExt::finalize_shared_paths_misc_info();
 205   _app_class_paths_start_index = ClassLoaderExt::app_class_paths_start_index();
 206   _app_module_paths_start_index = ClassLoaderExt::app_module_paths_start_index();
 207   _max_used_path_index = ClassLoaderExt::max_used_path_index();
 208 
 209   _verify_local = BytecodeVerificationLocal;
 210   _verify_remote = BytecodeVerificationRemote;
 211   _has_platform_or_app_classes = ClassLoaderExt::has_platform_or_app_classes();
 212   _shared_base_address = SharedBaseAddress;
 213   _allow_archiving_with_java_agent = AllowArchivingWithJavaAgent;
 214 }
 215 
 216 void SharedClassPathEntry::init(const char* name, bool is_modules_image, TRAPS) {
 217   assert(DumpSharedSpaces, "dump time only");
 218   _timestamp = 0;
 219   _filesize  = 0;
 220 
 221   struct stat st;
 222   if (os::stat(name, &st) == 0) {
 223     if ((st.st_mode & S_IFMT) == S_IFDIR) {
 224       _type = dir_entry;
 225     } else {
 226       // The timestamp of the modules_image is not checked at runtime.
 227       if (is_modules_image) {
 228         _type = modules_image_entry;
 229       } else {
 230         _type = jar_entry;
 231         _timestamp = st.st_mtime;
 232       }
 233       _filesize = st.st_size;
 234     }
 235   } else {
 236     // The file/dir must exist, or it would not have been added
 237     // into ClassLoader::classpath_entry().
 238     //
 239     // If we can't access a jar file in the boot path, then we can't
 240     // make assumptions about where classes get loaded from.
 241     FileMapInfo::fail_stop("Unable to open file %s.", name);
 242   }
 243 
 244   size_t len = strlen(name) + 1;
 245   _name = MetadataFactory::new_array<char>(ClassLoaderData::the_null_class_loader_data(), (int)len, THREAD);
 246   strcpy(_name->data(), name);
 247 }
 248 
 249 bool SharedClassPathEntry::validate(bool is_class_path) {
 250   assert(UseSharedSpaces, "runtime only");
 251 
 252   struct stat st;
 253   const char* name;
 254 
 255   // In order to validate the runtime modules image file size against the archived
 256   // size information, we need to obtain the runtime modules image path. The recorded
 257   // dump time modules image path in the archive may be different from the runtime path
 258   // if the JDK image has beed moved after generating the archive.
 259   if (is_modules_image()) {
 260     name = ClassLoader::get_jrt_entry()->name();
 261   } else {
 262     name = this->name();
 263   }
 264 
 265   bool ok = true;
 266   log_info(class, path)("checking shared classpath entry: %s", name);
 267   if (os::stat(name, &st) != 0 && is_class_path) {
 268     // If the archived module path entry does not exist at runtime, it is not fatal
 269     // (no need to invalid the shared archive) because the shared runtime visibility check
 270     // filters out any archived module classes that do not have a matching runtime
 271     // module path location.
 272     FileMapInfo::fail_continue("Required classpath entry does not exist: %s", name);
 273     ok = false;
 274   } else if (is_dir()) {
 275     if (!os::dir_is_empty(name)) {
 276       FileMapInfo::fail_continue("directory is not empty: %s", name);
 277       ok = false;
 278     }
 279   } else if ((has_timestamp() && _timestamp != st.st_mtime) ||
 280              _filesize != st.st_size) {
 281     ok = false;
 282     if (PrintSharedArchiveAndExit) {
 283       FileMapInfo::fail_continue(_timestamp != st.st_mtime ?
 284                                  "Timestamp mismatch" :
 285                                  "File size mismatch");
 286     } else {
 287       FileMapInfo::fail_continue("A jar file is not the one used while building"
 288                                  " the shared archive file: %s", name);
 289     }
 290   }
 291 
 292   if (PrintSharedArchiveAndExit && !ok) {
 293     // If PrintSharedArchiveAndExit is enabled, don't report failure to the
 294     // caller. Please see above comments for more details.
 295     ok = true;
 296   }
 297   return ok;
 298 }
 299 
 300 void SharedClassPathEntry::metaspace_pointers_do(MetaspaceClosure* it) {
 301   it->push(&_name);
 302   it->push(&_manifest);
 303 }
 304 
 305 void FileMapInfo::allocate_shared_path_table() {
 306   assert(DumpSharedSpaces, "Sanity");
 307 
 308   Thread* THREAD = Thread::current();
 309   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 310   ClassPathEntry* jrt = ClassLoader::get_jrt_entry();
 311 
 312   assert(jrt != NULL,
 313          "No modular java runtime image present when allocating the CDS classpath entry table");
 314 
 315   size_t entry_size = sizeof(SharedClassPathEntry); // assert ( should be 8 byte aligned??)
 316   int num_boot_classpath_entries = ClassLoader::num_boot_classpath_entries();
 317   int num_app_classpath_entries = ClassLoader::num_app_classpath_entries();
 318   int num_module_path_entries = ClassLoader::num_module_path_entries();
 319   int num_entries = num_boot_classpath_entries + num_app_classpath_entries + num_module_path_entries;
 320   size_t bytes = entry_size * num_entries;
 321 
 322   _shared_path_table = MetadataFactory::new_array<u8>(loader_data, (int)(bytes + 7 / 8), THREAD);
 323   _shared_path_table_size = num_entries;
 324   _shared_path_entry_size = entry_size;
 325 
 326   // 1. boot class path
 327   int i = 0;
 328   ClassPathEntry* cpe = jrt;
 329   while (cpe != NULL) {
 330     bool is_jrt = (cpe == jrt);
 331     const char* type = (is_jrt ? "jrt" : (cpe->is_jar_file() ? "jar" : "dir"));
 332     log_info(class, path)("add main shared path (%s) %s", type, cpe->name());
 333     SharedClassPathEntry* ent = shared_path(i);
 334     ent->init(cpe->name(), is_jrt, THREAD);
 335     if (!is_jrt) {    // No need to do the modules image.
 336       EXCEPTION_MARK; // The following call should never throw, but would exit VM on error.
 337       update_shared_classpath(cpe, ent, THREAD);
 338     }
 339     cpe = ClassLoader::get_next_boot_classpath_entry(cpe);
 340     i++;
 341   }
 342   assert(i == num_boot_classpath_entries,
 343          "number of boot class path entry mismatch");
 344 
 345   // 2. app class path
 346   ClassPathEntry *acpe = ClassLoader::app_classpath_entries();
 347   while (acpe != NULL) {
 348     log_info(class, path)("add app shared path %s", acpe->name());
 349     SharedClassPathEntry* ent = shared_path(i);
 350     ent->init(acpe->name(), false, THREAD);
 351     EXCEPTION_MARK;
 352     update_shared_classpath(acpe, ent, THREAD);
 353     acpe = acpe->next();
 354     i++;
 355   }
 356 
 357   // 3. module path
 358   ClassPathEntry *mpe = ClassLoader::module_path_entries();
 359   while (mpe != NULL) {
 360     log_info(class, path)("add module path %s",mpe->name());
 361     SharedClassPathEntry* ent = shared_path(i);
 362     ent->init(mpe->name(), false, THREAD);
 363     EXCEPTION_MARK;
 364     update_shared_classpath(mpe, ent, THREAD);
 365     mpe = mpe->next();
 366     i++;
 367   }
 368   assert(i == num_entries, "number of shared path entry mismatch");
 369 }
 370 
 371 void FileMapInfo::check_nonempty_dir_in_shared_path_table() {
 372   assert(DumpSharedSpaces, "dump time only");
 373 
 374   bool has_nonempty_dir = false;
 375 
 376   int last = _shared_path_table_size - 1;
 377   if (last > ClassLoaderExt::max_used_path_index()) {
 378      // no need to check any path beyond max_used_path_index
 379      last = ClassLoaderExt::max_used_path_index();
 380   }
 381 
 382   for (int i = 0; i <= last; i++) {
 383     SharedClassPathEntry *e = shared_path(i);
 384     if (e->is_dir()) {
 385       const char* path = e->name();
 386       if (!os::dir_is_empty(path)) {
 387         tty->print_cr("Error: non-empty directory '%s'", path);
 388         has_nonempty_dir = true;
 389       }
 390     }
 391   }
 392 
 393   if (has_nonempty_dir) {
 394     ClassLoader::exit_with_path_failure("Cannot have non-empty directory in paths", NULL);
 395   }
 396 }
 397 
 398 class ManifestStream: public ResourceObj {
 399   private:
 400   u1*   _buffer_start; // Buffer bottom
 401   u1*   _buffer_end;   // Buffer top (one past last element)
 402   u1*   _current;      // Current buffer position
 403 
 404  public:
 405   // Constructor
 406   ManifestStream(u1* buffer, int length) : _buffer_start(buffer),
 407                                            _current(buffer) {
 408     _buffer_end = buffer + length;
 409   }
 410 
 411   static bool is_attr(u1* attr, const char* name) {
 412     return strncmp((const char*)attr, name, strlen(name)) == 0;
 413   }
 414 
 415   static char* copy_attr(u1* value, size_t len) {
 416     char* buf = NEW_RESOURCE_ARRAY(char, len + 1);
 417     strncpy(buf, (char*)value, len);
 418     buf[len] = 0;
 419     return buf;
 420   }
 421 
 422   // The return value indicates if the JAR is signed or not
 423   bool check_is_signed() {
 424     u1* attr = _current;
 425     bool isSigned = false;
 426     while (_current < _buffer_end) {
 427       if (*_current == '\n') {
 428         *_current = '\0';
 429         u1* value = (u1*)strchr((char*)attr, ':');
 430         if (value != NULL) {
 431           assert(*(value+1) == ' ', "Unrecognized format" );
 432           if (strstr((char*)attr, "-Digest") != NULL) {
 433             isSigned = true;
 434             break;
 435           }
 436         }
 437         *_current = '\n'; // restore
 438         attr = _current + 1;
 439       }
 440       _current ++;
 441     }
 442     return isSigned;
 443   }
 444 };
 445 
 446 void FileMapInfo::update_shared_classpath(ClassPathEntry *cpe, SharedClassPathEntry* ent, TRAPS) {
 447   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 448   ResourceMark rm(THREAD);
 449   jint manifest_size;
 450 
 451   if (cpe->is_jar_file()) {
 452     assert(ent->is_jar(), "the shared class path entry is not a JAR file");
 453     char* manifest = ClassLoaderExt::read_manifest(cpe, &manifest_size, CHECK);
 454     if (manifest != NULL) {
 455       ManifestStream* stream = new ManifestStream((u1*)manifest,
 456                                                   manifest_size);
 457       if (stream->check_is_signed()) {
 458         ent->set_is_signed();
 459       } else {
 460         // Copy the manifest into the shared archive
 461         manifest = ClassLoaderExt::read_raw_manifest(cpe, &manifest_size, CHECK);
 462         Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,
 463                                                         manifest_size,
 464                                                         THREAD);
 465         char* p = (char*)(buf->data());
 466         memcpy(p, manifest, manifest_size);
 467         ent->set_manifest(buf);
 468       }
 469     }
 470   }
 471 }
 472 
 473 
 474 bool FileMapInfo::validate_shared_path_table() {
 475   assert(UseSharedSpaces, "runtime only");
 476 
 477   _validating_shared_path_table = true;
 478   _shared_path_table = _header->_shared_path_table;
 479   _shared_path_entry_size = _header->_shared_path_entry_size;
 480   _shared_path_table_size = _header->_shared_path_table_size;
 481 
 482   int module_paths_start_index = _header->_app_module_paths_start_index;
 483 
 484   // validate the path entries up to the _max_used_path_index
 485   for (int i=0; i < _header->_max_used_path_index + 1; i++) {
 486     if (i < module_paths_start_index) {
 487       if (shared_path(i)->validate()) {
 488         log_info(class, path)("ok");
 489       } else {
 490         assert(!UseSharedSpaces, "UseSharedSpaces should be disabled");
 491         return false;
 492       }
 493     } else if (i >= module_paths_start_index) {
 494       if (shared_path(i)->validate(false /* not a class path entry */)) {
 495         log_info(class, path)("ok");
 496       } else {
 497         assert(!UseSharedSpaces, "UseSharedSpaces should be disabled");
 498         return false;
 499       }
 500     }
 501   }
 502 
 503   _validating_shared_path_table = false;
 504   return true;
 505 }
 506 
 507 // Read the FileMapInfo information from the file.
 508 
 509 bool FileMapInfo::init_from_file(int fd) {
 510   size_t sz = sizeof(FileMapHeader);
 511   size_t n = os::read(fd, _header, (unsigned int)sz);
 512   if (n != sz) {
 513     fail_continue("Unable to read the file header.");
 514     return false;
 515   }
 516   if (_header->_version != CURRENT_CDS_ARCHIVE_VERSION) {
 517     fail_continue("The shared archive file has the wrong version.");
 518     return false;
 519   }
 520   _file_offset = (long)n;
 521 
 522   size_t info_size = _header->_paths_misc_info_size;
 523   _paths_misc_info = NEW_C_HEAP_ARRAY_RETURN_NULL(char, info_size, mtClass);
 524   if (_paths_misc_info == NULL) {
 525     fail_continue("Unable to read the file header.");
 526     return false;
 527   }
 528   n = os::read(fd, _paths_misc_info, (unsigned int)info_size);
 529   if (n != info_size) {
 530     fail_continue("Unable to read the shared path info header.");
 531     FREE_C_HEAP_ARRAY(char, _paths_misc_info);
 532     _paths_misc_info = NULL;
 533     return false;
 534   }
 535 
 536   size_t len = lseek(fd, 0, SEEK_END);
 537   CDSFileMapRegion* si = space_at(MetaspaceShared::last_valid_region);
 538   // The last space might be empty
 539   if (si->_file_offset > len || len - si->_file_offset < si->_used) {
 540     fail_continue("The shared archive file has been truncated.");
 541     return false;
 542   }
 543 
 544   _file_offset += (long)n;
 545   SharedBaseAddress = _header->_shared_base_address;
 546   return true;
 547 }
 548 
 549 
 550 // Read the FileMapInfo information from the file.
 551 bool FileMapInfo::open_for_read() {
 552   _full_path = Arguments::GetSharedArchivePath();
 553   int fd = open(_full_path, O_RDONLY | O_BINARY, 0);
 554   if (fd < 0) {
 555     if (errno == ENOENT) {
 556       // Not locating the shared archive is ok.
 557       fail_continue("Specified shared archive not found.");
 558     } else {
 559       fail_continue("Failed to open shared archive file (%s).",
 560                     os::strerror(errno));
 561     }
 562     return false;
 563   }
 564 
 565   _fd = fd;
 566   _file_open = true;
 567   return true;
 568 }
 569 
 570 
 571 // Write the FileMapInfo information to the file.
 572 
 573 void FileMapInfo::open_for_write() {
 574   _full_path = Arguments::GetSharedArchivePath();
 575   LogMessage(cds) msg;
 576   if (msg.is_info()) {
 577     msg.info("Dumping shared data to file: ");
 578     msg.info("   %s", _full_path);
 579   }
 580 
 581 #ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
 582   chmod(_full_path, _S_IREAD | _S_IWRITE);
 583 #endif
 584 
 585   // Use remove() to delete the existing file because, on Unix, this will
 586   // allow processes that have it open continued access to the file.
 587   remove(_full_path);
 588   int fd = open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
 589   if (fd < 0) {
 590     fail_stop("Unable to create shared archive file %s: (%s).", _full_path,
 591               os::strerror(errno));
 592   }
 593   _fd = fd;
 594   _file_offset = 0;
 595   _file_open = true;
 596 }
 597 
 598 
 599 // Write the header to the file, seek to the next allocation boundary.
 600 
 601 void FileMapInfo::write_header() {
 602   int info_size = ClassLoader::get_shared_paths_misc_info_size();
 603 
 604   _header->_paths_misc_info_size = info_size;
 605 
 606   align_file_position();
 607   write_bytes(_header, sizeof(FileMapHeader));
 608   write_bytes(ClassLoader::get_shared_paths_misc_info(), (size_t)info_size);
 609   align_file_position();
 610 }
 611 
 612 
 613 // Dump region to file.
 614 
 615 void FileMapInfo::write_region(int region, char* base, size_t size,
 616                                bool read_only, bool allow_exec) {
 617   CDSFileMapRegion* si = space_at(region);
 618 
 619   if (_file_open) {
 620     guarantee(si->_file_offset == _file_offset, "file offset mismatch.");
 621     log_info(cds)("Shared file region %d: " SIZE_FORMAT_HEX_W(08)
 622                   " bytes, addr " INTPTR_FORMAT " file offset " SIZE_FORMAT_HEX_W(08),
 623                   region, size, p2i(base), _file_offset);
 624   } else {
 625     si->_file_offset = _file_offset;
 626   }
 627   if (HeapShared::is_heap_region(region)) {
 628     assert((base - (char*)Universe::narrow_oop_base()) % HeapWordSize == 0, "Sanity");
 629     if (base != NULL) {
 630       si->_addr._offset = (intx)CompressedOops::encode_not_null((oop)base);
 631     } else {
 632       si->_addr._offset = 0;
 633     }
 634   } else {
 635     si->_addr._base = base;
 636   }
 637   si->_used = size;
 638   si->_read_only = read_only;
 639   si->_allow_exec = allow_exec;
 640   si->_crc = ClassLoader::crc32(0, base, (jint)size);
 641   if (base != NULL) {
 642     write_bytes_aligned(base, size);
 643   }
 644 }
 645 
 646 // Write out the given archive heap memory regions.  GC code combines multiple
 647 // consecutive archive GC regions into one MemRegion whenever possible and
 648 // produces the 'heap_mem' array.
 649 //
 650 // If the archive heap memory size is smaller than a single dump time GC region
 651 // size, there is only one MemRegion in the array.
 652 //
 653 // If the archive heap memory size is bigger than one dump time GC region size,
 654 // the 'heap_mem' array may contain more than one consolidated MemRegions. When
 655 // the first/bottom archive GC region is a partial GC region (with the empty
 656 // portion at the higher address within the region), one MemRegion is used for
 657 // the bottom partial archive GC region. The rest of the consecutive archive
 658 // GC regions are combined into another MemRegion.
 659 //
 660 // Here's the mapping from (archive heap GC regions) -> (GrowableArray<MemRegion> *regions).
 661 //   + We have 1 or more archive heap regions: ah0, ah1, ah2 ..... ahn
 662 //   + We have 1 or 2 consolidated heap memory regions: r0 and r1
 663 //
 664 // If there's a single archive GC region (ah0), then r0 == ah0, and r1 is empty.
 665 // Otherwise:
 666 //
 667 // "X" represented space that's occupied by heap objects.
 668 // "_" represented unused spaced in the heap region.
 669 //
 670 //
 671 //    |ah0       | ah1 | ah2| ...... | ahn|
 672 //    |XXXXXX|__ |XXXXX|XXXX|XXXXXXXX|XXXX|
 673 //    |<-r0->|   |<- r1 ----------------->|
 674 //            ^^^
 675 //             |
 676 //             +-- gap
 677 size_t FileMapInfo::write_archive_heap_regions(GrowableArray<MemRegion> *heap_mem,
 678                                                GrowableArray<ArchiveHeapOopmapInfo> *oopmaps,
 679                                                int first_region_id, int max_num_regions,
 680                                                bool print_log) {
 681   assert(max_num_regions <= 2, "Only support maximum 2 memory regions");
 682 
 683   int arr_len = heap_mem == NULL ? 0 : heap_mem->length();
 684   if(arr_len > max_num_regions) {
 685     fail_stop("Unable to write archive heap memory regions: "
 686               "number of memory regions exceeds maximum due to fragmentation");
 687   }
 688 
 689   size_t total_size = 0;
 690   for (int i = first_region_id, arr_idx = 0;
 691            i < first_region_id + max_num_regions;
 692            i++, arr_idx++) {
 693     char* start = NULL;
 694     size_t size = 0;
 695     if (arr_idx < arr_len) {
 696       start = (char*)heap_mem->at(arr_idx).start();
 697       size = heap_mem->at(arr_idx).byte_size();
 698       total_size += size;
 699     }
 700 
 701     if (print_log) {
 702       log_info(cds)("Archive heap region %d " INTPTR_FORMAT " - " INTPTR_FORMAT " = " SIZE_FORMAT_W(8) " bytes",
 703                     i, p2i(start), p2i(start + size), size);
 704     }
 705     write_region(i, start, size, false, false);
 706     if (size > 0) {
 707       space_at(i)->_oopmap = oopmaps->at(arr_idx)._oopmap;
 708       space_at(i)->_oopmap_size_in_bits = oopmaps->at(arr_idx)._oopmap_size_in_bits;
 709     }
 710   }
 711   return total_size;
 712 }
 713 
 714 // Dump bytes to file -- at the current file position.
 715 
 716 void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) {
 717   if (_file_open) {
 718     size_t n = os::write(_fd, buffer, (unsigned int)nbytes);
 719     if (n != nbytes) {
 720       // It is dangerous to leave the corrupted shared archive file around,
 721       // close and remove the file. See bug 6372906.
 722       close();
 723       remove(_full_path);
 724       fail_stop("Unable to write to shared archive file.");
 725     }
 726   }
 727   _file_offset += nbytes;
 728 }
 729 
 730 
 731 // Align file position to an allocation unit boundary.
 732 
 733 void FileMapInfo::align_file_position() {
 734   size_t new_file_offset = align_up(_file_offset,
 735                                          os::vm_allocation_granularity());
 736   if (new_file_offset != _file_offset) {
 737     _file_offset = new_file_offset;
 738     if (_file_open) {
 739       // Seek one byte back from the target and write a byte to insure
 740       // that the written file is the correct length.
 741       _file_offset -= 1;
 742       if (lseek(_fd, (long)_file_offset, SEEK_SET) < 0) {
 743         fail_stop("Unable to seek.");
 744       }
 745       char zero = 0;
 746       write_bytes(&zero, 1);
 747     }
 748   }
 749 }
 750 
 751 
 752 // Dump bytes to file -- at the current file position.
 753 
 754 void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) {
 755   align_file_position();
 756   write_bytes(buffer, nbytes);
 757   align_file_position();
 758 }
 759 
 760 
 761 // Close the shared archive file.  This does NOT unmap mapped regions.
 762 
 763 void FileMapInfo::close() {
 764   if (_file_open) {
 765     if (::close(_fd) < 0) {
 766       fail_stop("Unable to close the shared archive file.");
 767     }
 768     _file_open = false;
 769     _fd = -1;
 770   }
 771 }
 772 
 773 
 774 // JVM/TI RedefineClasses() support:
 775 // Remap the shared readonly space to shared readwrite, private.
 776 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
 777   int idx = MetaspaceShared::ro;
 778   CDSFileMapRegion* si = space_at(idx);
 779   if (!si->_read_only) {
 780     // the space is already readwrite so we are done
 781     return true;
 782   }
 783   size_t used = si->_used;
 784   size_t size = align_up(used, os::vm_allocation_granularity());
 785   if (!open_for_read()) {
 786     return false;
 787   }
 788   char *addr = region_addr(idx);
 789   char *base = os::remap_memory(_fd, _full_path, si->_file_offset,
 790                                 addr, size, false /* !read_only */,
 791                                 si->_allow_exec);
 792   close();
 793   if (base == NULL) {
 794     fail_continue("Unable to remap shared readonly space (errno=%d).", errno);
 795     return false;
 796   }
 797   if (base != addr) {
 798     fail_continue("Unable to remap shared readonly space at required address.");
 799     return false;
 800   }
 801   si->_read_only = false;
 802   return true;
 803 }
 804 
 805 // Map the whole region at once, assumed to be allocated contiguously.
 806 ReservedSpace FileMapInfo::reserve_shared_memory() {
 807   char* requested_addr = region_addr(0);
 808   size_t size = FileMapInfo::core_spaces_size();
 809 
 810   // Reserve the space first, then map otherwise map will go right over some
 811   // other reserved memory (like the code cache).
 812   ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr);
 813   if (!rs.is_reserved()) {
 814     fail_continue("Unable to reserve shared space at required address "
 815                   INTPTR_FORMAT, p2i(requested_addr));
 816     return rs;
 817   }
 818   // the reserved virtual memory is for mapping class data sharing archive
 819   MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared);
 820 
 821   return rs;
 822 }
 823 
 824 // Memory map a region in the address space.
 825 static const char* shared_region_name[] = { "MiscData", "ReadWrite", "ReadOnly", "MiscCode", "OptionalData",
 826                                             "String1", "String2", "OpenArchive1", "OpenArchive2" };
 827 
 828 char* FileMapInfo::map_region(int i, char** top_ret) {
 829   assert(!HeapShared::is_heap_region(i), "sanity");
 830   CDSFileMapRegion* si = space_at(i);
 831   size_t used = si->_used;
 832   size_t alignment = os::vm_allocation_granularity();
 833   size_t size = align_up(used, alignment);
 834   char *requested_addr = region_addr(i);
 835 
 836   // If a tool agent is in use (debugging enabled), we must map the address space RW
 837   if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space()) {
 838     si->_read_only = false;
 839   }
 840 
 841   // map the contents of the CDS archive in this memory
 842   char *base = os::map_memory(_fd, _full_path, si->_file_offset,
 843                               requested_addr, size, si->_read_only,
 844                               si->_allow_exec);
 845   if (base == NULL || base != requested_addr) {
 846     fail_continue("Unable to map %s shared space at required address.", shared_region_name[i]);
 847     return NULL;
 848   }
 849 #ifdef _WINDOWS
 850   // This call is Windows-only because the memory_type gets recorded for the other platforms
 851   // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows.
 852   MemTracker::record_virtual_memory_type((address)base, mtClassShared);
 853 #endif
 854 
 855 
 856   if (!verify_region_checksum(i)) {
 857     return NULL;
 858   }
 859 
 860   *top_ret = base + size;
 861   return base;
 862 }
 863 
 864 address FileMapInfo::decode_start_address(CDSFileMapRegion* spc, bool with_current_oop_encoding_mode) {
 865   if (with_current_oop_encoding_mode) {
 866     return (address)CompressedOops::decode_not_null(offset_of_space(spc));
 867   } else {
 868     return (address)HeapShared::decode_from_archive(offset_of_space(spc));
 869   }
 870 }
 871 
 872 static MemRegion *closed_archive_heap_ranges = NULL;
 873 static MemRegion *open_archive_heap_ranges = NULL;
 874 static int num_closed_archive_heap_ranges = 0;
 875 static int num_open_archive_heap_ranges = 0;
 876 
 877 #if INCLUDE_CDS_JAVA_HEAP
 878 bool FileMapInfo::has_heap_regions() {
 879   return (_header->_space[MetaspaceShared::first_closed_archive_heap_region]._used > 0);
 880 }
 881 
 882 // Returns the address range of the archived heap regions computed using the
 883 // current oop encoding mode. This range may be different than the one seen at
 884 // dump time due to encoding mode differences. The result is used in determining
 885 // if/how these regions should be relocated at run time.
 886 MemRegion FileMapInfo::get_heap_regions_range_with_current_oop_encoding_mode() {
 887   address start = (address) max_uintx;
 888   address end   = NULL;
 889 
 890   for (int i = MetaspaceShared::first_closed_archive_heap_region;
 891            i <= MetaspaceShared::last_valid_region;
 892            i++) {
 893     CDSFileMapRegion* si = space_at(i);
 894     size_t size = si->_used;
 895     if (size > 0) {
 896       address s = start_address_as_decoded_with_current_oop_encoding_mode(si);
 897       address e = s + size;
 898       if (start > s) {
 899         start = s;
 900       }
 901       if (end < e) {
 902         end = e;
 903       }
 904     }
 905   }
 906   assert(end != NULL, "must have at least one used heap region");
 907   return MemRegion((HeapWord*)start, (HeapWord*)end);
 908 }
 909 
 910 //
 911 // Map the closed and open archive heap objects to the runtime java heap.
 912 //
 913 // The shared objects are mapped at (or close to ) the java heap top in
 914 // closed archive regions. The mapped objects contain no out-going
 915 // references to any other java heap regions. GC does not write into the
 916 // mapped closed archive heap region.
 917 //
 918 // The open archive heap objects are mapped below the shared objects in
 919 // the runtime java heap. The mapped open archive heap data only contains
 920 // references to the shared objects and open archive objects initially.
 921 // During runtime execution, out-going references to any other java heap
 922 // regions may be added. GC may mark and update references in the mapped
 923 // open archive objects.
 924 void FileMapInfo::map_heap_regions_impl() {
 925   if (!HeapShared::is_heap_object_archiving_allowed()) {
 926     log_info(cds)("CDS heap data is being ignored. UseG1GC, "
 927                   "UseCompressedOops and UseCompressedClassPointers are required.");
 928     return;
 929   }
 930 
 931   if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
 932     ShouldNotReachHere(); // CDS should have been disabled.
 933     // The archived objects are mapped at JVM start-up, but we don't know if
 934     // j.l.String or j.l.Class might be replaced by the ClassFileLoadHook,
 935     // which would make the archived String or mirror objects invalid. Let's be safe and not
 936     // use the archived objects. These 2 classes are loaded during the JVMTI "early" stage.
 937     //
 938     // If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects
 939     // in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK
 940     // because we won't install an archived object subgraph if the klass of any of the
 941     // referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph().
 942   }
 943 
 944   MemRegion heap_reserved = Universe::heap()->reserved_region();
 945 
 946   log_info(cds)("CDS archive was created with max heap size = " SIZE_FORMAT "M, and the following configuration:",
 947                 max_heap_size()/M);
 948   log_info(cds)("    narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
 949                 p2i(narrow_klass_base()), narrow_klass_shift());
 950   log_info(cds)("    narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
 951                 narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift());
 952 
 953   log_info(cds)("The current max heap size = " SIZE_FORMAT "M, HeapRegion::GrainBytes = " SIZE_FORMAT,
 954                 heap_reserved.byte_size()/M, HeapRegion::GrainBytes);
 955   log_info(cds)("    narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
 956                 p2i(Universe::narrow_klass_base()), Universe::narrow_klass_shift());
 957   log_info(cds)("    narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
 958                 Universe::narrow_oop_mode(), p2i(Universe::narrow_oop_base()), Universe::narrow_oop_shift());
 959 
 960   if (narrow_klass_base() != Universe::narrow_klass_base() ||
 961       narrow_klass_shift() != Universe::narrow_klass_shift()) {
 962     log_info(cds)("CDS heap data cannot be used because the archive was created with an incompatible narrow klass encoding mode.");
 963     return;
 964   }
 965 
 966   if (narrow_oop_mode() != Universe::narrow_oop_mode() ||
 967       narrow_oop_base() != Universe::narrow_oop_base() ||
 968       narrow_oop_shift() != Universe::narrow_oop_shift()) {
 969     log_info(cds)("CDS heap data need to be relocated because the archive was created with an incompatible oop encoding mode.");
 970     _heap_pointers_need_patching = true;
 971   } else {
 972     MemRegion range = get_heap_regions_range_with_current_oop_encoding_mode();
 973     if (!heap_reserved.contains(range)) {
 974       log_info(cds)("CDS heap data need to be relocated because");
 975       log_info(cds)("the desired range " PTR_FORMAT " - "  PTR_FORMAT, p2i(range.start()), p2i(range.end()));
 976       log_info(cds)("is outside of the heap " PTR_FORMAT " - "  PTR_FORMAT, p2i(heap_reserved.start()), p2i(heap_reserved.end()));
 977       _heap_pointers_need_patching = true;
 978     }
 979   }
 980 
 981   ptrdiff_t delta = 0;
 982   if (_heap_pointers_need_patching) {
 983     //   dumptime heap end  ------------v
 984     //   [      |archived heap regions| ]         runtime heap end ------v
 985     //                                       [   |archived heap regions| ]
 986     //                                  |<-----delta-------------------->|
 987     //
 988     // At dump time, the archived heap regions were near the top of the heap.
 989     // At run time, they may not be inside the heap, so we move them so
 990     // that they are now near the top of the runtime time. This can be done by
 991     // the simple math of adding the delta as shown above.
 992     address dumptime_heap_end = (address)_header->_heap_reserved.end();
 993     address runtime_heap_end = (address)heap_reserved.end();
 994     delta = runtime_heap_end - dumptime_heap_end;
 995   }
 996 
 997   log_info(cds)("CDS heap data relocation delta = " INTX_FORMAT " bytes", delta);
 998   HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());
 999 
1000   CDSFileMapRegion* si = space_at(MetaspaceShared::first_closed_archive_heap_region);
1001   address relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si);
1002   if (!is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes)) {
1003     // Align the bottom of the closed archive heap regions at G1 region boundary.
1004     // This will avoid the situation where the highest open region and the lowest
1005     // closed region sharing the same G1 region. Otherwise we will fail to map the
1006     // open regions.
1007     size_t align = size_t(relocated_closed_heap_region_bottom) % HeapRegion::GrainBytes;
1008     delta -= align;
1009     log_info(cds)("CDS heap data need to be relocated lower by a further " SIZE_FORMAT
1010                   " bytes to " INTX_FORMAT " to be aligned with HeapRegion::GrainBytes",
1011                   align, delta);
1012     HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());
1013     _heap_pointers_need_patching = true;
1014     relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si);
1015   }
1016   assert(is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes),
1017          "must be");
1018 
1019   // Map the closed_archive_heap regions, GC does not write into the regions.
1020   if (map_heap_data(&closed_archive_heap_ranges,
1021                     MetaspaceShared::first_closed_archive_heap_region,
1022                     MetaspaceShared::max_closed_archive_heap_region,
1023                     &num_closed_archive_heap_ranges)) {
1024     HeapShared::set_closed_archive_heap_region_mapped();
1025 
1026     // Now, map open_archive heap regions, GC can write into the regions.
1027     if (map_heap_data(&open_archive_heap_ranges,
1028                       MetaspaceShared::first_open_archive_heap_region,
1029                       MetaspaceShared::max_open_archive_heap_region,
1030                       &num_open_archive_heap_ranges,
1031                       true /* open */)) {
1032       HeapShared::set_open_archive_heap_region_mapped();
1033     }
1034   }
1035 }
1036 
1037 void FileMapInfo::map_heap_regions() {
1038   if (has_heap_regions()) {
1039     map_heap_regions_impl();
1040   }
1041 
1042   if (!HeapShared::closed_archive_heap_region_mapped()) {
1043     assert(closed_archive_heap_ranges == NULL &&
1044            num_closed_archive_heap_ranges == 0, "sanity");
1045   }
1046 
1047   if (!HeapShared::open_archive_heap_region_mapped()) {
1048     assert(open_archive_heap_ranges == NULL && num_open_archive_heap_ranges == 0, "sanity");
1049   }
1050 }
1051 
1052 bool FileMapInfo::map_heap_data(MemRegion **heap_mem, int first,
1053                                 int max, int* num, bool is_open_archive) {
1054   MemRegion * regions = new MemRegion[max];
1055   CDSFileMapRegion* si;
1056   int region_num = 0;
1057 
1058   for (int i = first;
1059            i < first + max; i++) {
1060     si = space_at(i);
1061     size_t size = si->_used;
1062     if (size > 0) {
1063       HeapWord* start = (HeapWord*)start_address_as_decoded_from_archive(si);
1064       regions[region_num] = MemRegion(start, size / HeapWordSize);
1065       region_num ++;
1066       log_info(cds)("Trying to map heap data: region[%d] at " INTPTR_FORMAT ", size = " SIZE_FORMAT_W(8) " bytes",
1067                     i, p2i(start), size);
1068     }
1069   }
1070 
1071   if (region_num == 0) {
1072     return false; // no archived java heap data
1073   }
1074 
1075   // Check that ranges are within the java heap
1076   if (!G1CollectedHeap::heap()->check_archive_addresses(regions, region_num)) {
1077     log_info(cds)("UseSharedSpaces: Unable to allocate region, range is not within java heap.");
1078     return false;
1079   }
1080 
1081   // allocate from java heap
1082   if (!G1CollectedHeap::heap()->alloc_archive_regions(
1083              regions, region_num, is_open_archive)) {
1084     log_info(cds)("UseSharedSpaces: Unable to allocate region, java heap range is already in use.");
1085     return false;
1086   }
1087 
1088   // Map the archived heap data. No need to call MemTracker::record_virtual_memory_type()
1089   // for mapped regions as they are part of the reserved java heap, which is
1090   // already recorded.
1091   for (int i = 0; i < region_num; i++) {
1092     si = space_at(first + i);
1093     char* addr = (char*)regions[i].start();
1094     char* base = os::map_memory(_fd, _full_path, si->_file_offset,
1095                                 addr, regions[i].byte_size(), si->_read_only,
1096                                 si->_allow_exec);
1097     if (base == NULL || base != addr) {
1098       // dealloc the regions from java heap
1099       dealloc_archive_heap_regions(regions, region_num, is_open_archive);
1100       log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap. "
1101                     INTPTR_FORMAT ", size = " SIZE_FORMAT " bytes",
1102                     p2i(addr), regions[i].byte_size());
1103       return false;
1104     }
1105   }
1106 
1107   if (!verify_mapped_heap_regions(first, region_num)) {
1108     // dealloc the regions from java heap
1109     dealloc_archive_heap_regions(regions, region_num, is_open_archive);
1110     log_info(cds)("UseSharedSpaces: mapped heap regions are corrupt");
1111     return false;
1112   }
1113 
1114   // the shared heap data is mapped successfully
1115   *heap_mem = regions;
1116   *num = region_num;
1117   return true;
1118 }
1119 
1120 bool FileMapInfo::verify_mapped_heap_regions(int first, int num) {
1121   assert(num > 0, "sanity");
1122   for (int i = first; i < first + num; i++) {
1123     if (!verify_region_checksum(i)) {
1124       return false;
1125     }
1126   }
1127   return true;
1128 }
1129 
1130 void FileMapInfo::patch_archived_heap_embedded_pointers() {
1131   if (!_heap_pointers_need_patching) {
1132     return;
1133   }
1134 
1135   patch_archived_heap_embedded_pointers(closed_archive_heap_ranges,
1136                                         num_closed_archive_heap_ranges,
1137                                         MetaspaceShared::first_closed_archive_heap_region);
1138 
1139   patch_archived_heap_embedded_pointers(open_archive_heap_ranges,
1140                                         num_open_archive_heap_ranges,
1141                                         MetaspaceShared::first_open_archive_heap_region);
1142 }
1143 
1144 void FileMapInfo::patch_archived_heap_embedded_pointers(MemRegion* ranges, int num_ranges,
1145                                                         int first_region_idx) {
1146   for (int i=0; i<num_ranges; i++) {
1147     CDSFileMapRegion* si = space_at(i + first_region_idx);
1148     HeapShared::patch_archived_heap_embedded_pointers(ranges[i], (address)si->_oopmap,
1149                                                       si->_oopmap_size_in_bits);
1150   }
1151 }
1152 
1153 // This internally allocates objects using SystemDictionary::Object_klass(), so it
1154 // must be called after the well-known classes are resolved.
1155 void FileMapInfo::fixup_mapped_heap_regions() {
1156   // If any closed regions were found, call the fill routine to make them parseable.
1157   // Note that closed_archive_heap_ranges may be non-NULL even if no ranges were found.
1158   if (num_closed_archive_heap_ranges != 0) {
1159     assert(closed_archive_heap_ranges != NULL,
1160            "Null closed_archive_heap_ranges array with non-zero count");
1161     G1CollectedHeap::heap()->fill_archive_regions(closed_archive_heap_ranges,
1162                                                   num_closed_archive_heap_ranges);
1163   }
1164 
1165   // do the same for mapped open archive heap regions
1166   if (num_open_archive_heap_ranges != 0) {
1167     assert(open_archive_heap_ranges != NULL, "NULL open_archive_heap_ranges array with non-zero count");
1168     G1CollectedHeap::heap()->fill_archive_regions(open_archive_heap_ranges,
1169                                                   num_open_archive_heap_ranges);
1170   }
1171 }
1172 
1173 // dealloc the archive regions from java heap
1174 void FileMapInfo::dealloc_archive_heap_regions(MemRegion* regions, int num, bool is_open) {
1175   if (num > 0) {
1176     assert(regions != NULL, "Null archive ranges array with non-zero count");
1177     G1CollectedHeap::heap()->dealloc_archive_regions(regions, num, is_open);
1178   }
1179 }
1180 #endif // INCLUDE_CDS_JAVA_HEAP
1181 
1182 bool FileMapInfo::verify_region_checksum(int i) {
1183   if (!VerifySharedSpaces) {
1184     return true;
1185   }
1186 
1187   size_t sz = space_at(i)->_used;
1188 
1189   if (sz == 0) {
1190     return true; // no data
1191   }
1192   if ((HeapShared::is_closed_archive_heap_region(i) &&
1193        !HeapShared::closed_archive_heap_region_mapped()) ||
1194       (HeapShared::is_open_archive_heap_region(i) &&
1195        !HeapShared::open_archive_heap_region_mapped())) {
1196     return true; // archived heap data is not mapped
1197   }
1198   const char* buf = region_addr(i);
1199   int crc = ClassLoader::crc32(0, buf, (jint)sz);
1200   if (crc != space_at(i)->_crc) {
1201     fail_continue("Checksum verification failed.");
1202     return false;
1203   }
1204   return true;
1205 }
1206 
1207 // Unmap a memory region in the address space.
1208 
1209 void FileMapInfo::unmap_region(int i) {
1210   assert(!HeapShared::is_heap_region(i), "sanity");
1211   CDSFileMapRegion* si = space_at(i);
1212   size_t used = si->_used;
1213   size_t size = align_up(used, os::vm_allocation_granularity());
1214 
1215   if (used == 0) {
1216     return;
1217   }
1218 
1219   char* addr = region_addr(i);
1220   if (!os::unmap_memory(addr, size)) {
1221     fail_stop("Unable to unmap shared space.");
1222   }
1223 }
1224 
1225 void FileMapInfo::assert_mark(bool check) {
1226   if (!check) {
1227     fail_stop("Mark mismatch while restoring from shared file.");
1228   }
1229 }
1230 
1231 void FileMapInfo::metaspace_pointers_do(MetaspaceClosure* it) {
1232   it->push(&_shared_path_table);
1233   for (int i=0; i<_shared_path_table_size; i++) {
1234     shared_path(i)->metaspace_pointers_do(it);
1235   }
1236 }
1237 
1238 
1239 FileMapInfo* FileMapInfo::_current_info = NULL;
1240 bool FileMapInfo::_heap_pointers_need_patching = false;
1241 Array<u8>* FileMapInfo::_shared_path_table = NULL;
1242 int FileMapInfo::_shared_path_table_size = 0;
1243 size_t FileMapInfo::_shared_path_entry_size = 0x1234baad;
1244 bool FileMapInfo::_validating_shared_path_table = false;
1245 
1246 // Open the shared archive file, read and validate the header
1247 // information (version, boot classpath, etc.).  If initialization
1248 // fails, shared spaces are disabled and the file is closed. [See
1249 // fail_continue.]
1250 //
1251 // Validation of the archive is done in two steps:
1252 //
1253 // [1] validate_header() - done here. This checks the header, including _paths_misc_info.
1254 // [2] validate_shared_path_table - this is done later, because the table is in the RW
1255 //     region of the archive, which is not mapped yet.
1256 bool FileMapInfo::initialize() {
1257   assert(UseSharedSpaces, "UseSharedSpaces expected.");
1258 
1259   if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
1260     // CDS assumes that no classes resolved in SystemDictionary::resolve_well_known_classes
1261     // are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved
1262     // during the JVMTI "early" stage, so we can still use CDS if
1263     // JvmtiExport::has_early_class_hook_env() is false.
1264     FileMapInfo::fail_continue("CDS is disabled because early JVMTI ClassFileLoadHook is in use.");
1265     return false;
1266   }
1267 
1268   if (!open_for_read()) {
1269     return false;
1270   }
1271 
1272   init_from_file(_fd);
1273   if (!validate_header()) {
1274     return false;
1275   }
1276   return true;
1277 }
1278 
1279 char* FileMapInfo::region_addr(int idx) {
1280   CDSFileMapRegion* si = space_at(idx);
1281   if (HeapShared::is_heap_region(idx)) {
1282     assert(DumpSharedSpaces, "The following doesn't work at runtime");
1283     return si->_used > 0 ?
1284           (char*)start_address_as_decoded_with_current_oop_encoding_mode(si) : NULL;
1285   } else {
1286     return si->_addr._base;
1287   }
1288 }
1289 
1290 int FileMapHeader::compute_crc() {
1291   char* start = (char*)this;
1292   // start computing from the field after _crc
1293   char* buf = (char*)&_crc + sizeof(_crc);
1294   size_t sz = sizeof(FileMapHeader) - (buf - start);
1295   int crc = ClassLoader::crc32(0, buf, (jint)sz);
1296   return crc;
1297 }
1298 
1299 // This function should only be called during run time with UseSharedSpaces enabled.
1300 bool FileMapHeader::validate() {
1301   if (VerifySharedSpaces && compute_crc() != _crc) {
1302     FileMapInfo::fail_continue("Header checksum verification failed.");
1303     return false;
1304   }
1305 
1306   if (!Arguments::has_jimage()) {
1307     FileMapInfo::fail_continue("The shared archive file cannot be used with an exploded module build.");
1308     return false;
1309   }
1310 
1311   if (_version != CURRENT_CDS_ARCHIVE_VERSION) {
1312     FileMapInfo::fail_continue("The shared archive file is the wrong version.");
1313     return false;
1314   }
1315   if (_magic != CDS_ARCHIVE_MAGIC) {
1316     FileMapInfo::fail_continue("The shared archive file has a bad magic number.");
1317     return false;
1318   }
1319   char header_version[JVM_IDENT_MAX];
1320   get_header_version(header_version);
1321   if (strncmp(_jvm_ident, header_version, JVM_IDENT_MAX-1) != 0) {
1322     log_info(class, path)("expected: %s", header_version);
1323     log_info(class, path)("actual:   %s", _jvm_ident);
1324     FileMapInfo::fail_continue("The shared archive file was created by a different"
1325                   " version or build of HotSpot");
1326     return false;
1327   }
1328   if (_obj_alignment != ObjectAlignmentInBytes) {
1329     FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"
1330                   " does not equal the current ObjectAlignmentInBytes of " INTX_FORMAT ".",
1331                   _obj_alignment, ObjectAlignmentInBytes);
1332     return false;
1333   }
1334   if (_compact_strings != CompactStrings) {
1335     FileMapInfo::fail_continue("The shared archive file's CompactStrings setting (%s)"
1336                   " does not equal the current CompactStrings setting (%s).",
1337                   _compact_strings ? "enabled" : "disabled",
1338                   CompactStrings   ? "enabled" : "disabled");
1339     return false;
1340   }
1341 
1342   // This must be done after header validation because it might change the
1343   // header data
1344   const char* prop = Arguments::get_property("java.system.class.loader");
1345   if (prop != NULL) {
1346     warning("Archived non-system classes are disabled because the "
1347             "java.system.class.loader property is specified (value = \"%s\"). "
1348             "To use archived non-system classes, this property must not be set", prop);
1349     _has_platform_or_app_classes = false;
1350   }
1351 
1352   // For backwards compatibility, we don't check the verification setting
1353   // if the archive only contains system classes.
1354   if (_has_platform_or_app_classes &&
1355       ((!_verify_local && BytecodeVerificationLocal) ||
1356        (!_verify_remote && BytecodeVerificationRemote))) {
1357     FileMapInfo::fail_continue("The shared archive file was created with less restrictive "
1358                   "verification setting than the current setting.");
1359     return false;
1360   }
1361 
1362   // Java agents are allowed during run time. Therefore, the following condition is not
1363   // checked: (!_allow_archiving_with_java_agent && AllowArchivingWithJavaAgent)
1364   // Note: _allow_archiving_with_java_agent is set in the shared archive during dump time
1365   // while AllowArchivingWithJavaAgent is set during the current run.
1366   if (_allow_archiving_with_java_agent && !AllowArchivingWithJavaAgent) {
1367     FileMapInfo::fail_continue("The setting of the AllowArchivingWithJavaAgent is different "
1368                                "from the setting in the shared archive.");
1369     return false;
1370   }
1371 
1372   if (_allow_archiving_with_java_agent) {
1373     warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1374             "for testing purposes only and should not be used in a production environment");
1375   }
1376 
1377   return true;
1378 }
1379 
1380 bool FileMapInfo::validate_header() {
1381   bool status = _header->validate();
1382 
1383   if (status) {
1384     if (!ClassLoader::check_shared_paths_misc_info(_paths_misc_info, _header->_paths_misc_info_size)) {
1385       if (!PrintSharedArchiveAndExit) {
1386         fail_continue("shared class paths mismatch (hint: enable -Xlog:class+path=info to diagnose the failure)");
1387         status = false;
1388       }
1389     }
1390   }
1391 
1392   if (_paths_misc_info != NULL) {
1393     FREE_C_HEAP_ARRAY(char, _paths_misc_info);
1394     _paths_misc_info = NULL;
1395   }
1396   return status;
1397 }
1398 
1399 // Check if a given address is within one of the shared regions
1400 bool FileMapInfo::is_in_shared_region(const void* p, int idx) {
1401   assert(idx == MetaspaceShared::ro ||
1402          idx == MetaspaceShared::rw ||
1403          idx == MetaspaceShared::mc ||
1404          idx == MetaspaceShared::md, "invalid region index");
1405   char* base = region_addr(idx);
1406   if (p >= base && p < base + space_at(idx)->_used) {
1407     return true;
1408   }
1409   return false;
1410 }
1411 
1412 // Unmap mapped regions of shared space.
1413 void FileMapInfo::stop_sharing_and_unmap(const char* msg) {
1414   MetaspaceObj::set_shared_metaspace_range(NULL, NULL);
1415 
1416   FileMapInfo *map_info = FileMapInfo::current_info();
1417   if (map_info) {
1418     map_info->fail_continue("%s", msg);
1419     for (int i = 0; i < MetaspaceShared::num_non_heap_spaces; i++) {
1420       if (!HeapShared::is_heap_region(i)) {
1421         char *addr = map_info->region_addr(i);
1422         if (addr != NULL) {
1423           map_info->unmap_region(i);
1424           map_info->space_at(i)->_addr._base = NULL;
1425         }
1426       }
1427     }
1428     // Dealloc the archive heap regions only without unmapping. The regions are part
1429     // of the java heap. Unmapping of the heap regions are managed by GC.
1430     map_info->dealloc_archive_heap_regions(open_archive_heap_ranges,
1431                                            num_open_archive_heap_ranges,
1432                                            true);
1433     map_info->dealloc_archive_heap_regions(closed_archive_heap_ranges,
1434                                            num_closed_archive_heap_ranges,
1435                                            false);
1436   } else if (DumpSharedSpaces) {
1437     fail_stop("%s", msg);
1438   }
1439 }