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