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