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