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