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