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