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