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