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