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/dynamicArchive.hpp"
  38 #include "memory/filemap.hpp"
  39 #include "memory/heapShared.inline.hpp"
  40 #include "memory/iterator.inline.hpp"
  41 #include "memory/metadataFactory.hpp"
  42 #include "memory/metaspaceClosure.hpp"
  43 #include "memory/metaspaceShared.hpp"
  44 #include "memory/oopFactory.hpp"
  45 #include "memory/universe.hpp"
  46 #include "oops/compressedOops.hpp"
  47 #include "oops/compressedOops.inline.hpp"
  48 #include "oops/objArrayOop.hpp"
  49 #include "oops/oop.inline.hpp"
  50 #include "prims/jvmtiExport.hpp"
  51 #include "runtime/arguments.hpp"
  52 #include "runtime/java.hpp"
  53 #include "runtime/mutexLocker.hpp"
  54 #include "runtime/os.inline.hpp"
  55 #include "runtime/vm_version.hpp"
  56 #include "services/memTracker.hpp"
  57 #include "utilities/align.hpp"
  58 #include "utilities/classpathStream.hpp"
  59 #include "utilities/defaultStream.hpp"
  60 #if INCLUDE_G1GC
  61 #include "gc/g1/g1CollectedHeap.hpp"
  62 #include "gc/g1/heapRegion.hpp"
  63 #endif
  64 
  65 # include <sys/stat.h>
  66 # include <errno.h>
  67 
  68 #ifndef O_BINARY       // if defined (Win32) use binary files.
  69 #define O_BINARY 0     // otherwise do nothing.
  70 #endif
  71 
  72 extern address JVM_FunctionAtStart();
  73 extern address JVM_FunctionAtEnd();
  74 
  75 // Complain and stop. All error conditions occurring during the writing of
  76 // an archive file should stop the process.  Unrecoverable errors during
  77 // the reading of the archive file should stop the process.
  78 
  79 static void fail_exit(const char *msg, va_list ap) {
  80   // This occurs very early during initialization: tty is not initialized.
  81   jio_fprintf(defaultStream::error_stream(),
  82               "An error has occurred while processing the"
  83               " shared archive file.\n");
  84   jio_vfprintf(defaultStream::error_stream(), msg, ap);
  85   jio_fprintf(defaultStream::error_stream(), "\n");
  86   // Do not change the text of the below message because some tests check for it.
  87   vm_exit_during_initialization("Unable to use shared archive.", NULL);
  88 }
  89 
  90 
  91 void FileMapInfo::fail_stop(const char *msg, ...) {
  92         va_list ap;
  93   va_start(ap, msg);
  94   fail_exit(msg, ap);   // Never returns.
  95   va_end(ap);           // for completeness.
  96 }
  97 
  98 
  99 // Complain and continue.  Recoverable errors during the reading of the
 100 // archive file may continue (with sharing disabled).
 101 //
 102 // If we continue, then disable shared spaces and close the file.
 103 
 104 void FileMapInfo::fail_continue(const char *msg, ...) {
 105   va_list ap;
 106   va_start(ap, msg);
 107   if (_dynamic_archive_info == NULL) {
 108     MetaspaceShared::set_archive_loading_failed();
 109   } else {
 110     // _dynamic_archive_info has been setup after mapping the base archive
 111     DynamicArchive::disable();
 112   }
 113   if (PrintSharedArchiveAndExit && _validating_shared_path_table) {
 114     // If we are doing PrintSharedArchiveAndExit and some of the classpath entries
 115     // do not validate, we can still continue "limping" to validate the remaining
 116     // entries. No need to quit.
 117     tty->print("[");
 118     tty->vprint(msg, ap);
 119     tty->print_cr("]");
 120   } else {
 121     if (RequireSharedSpaces) {
 122       fail_exit(msg, ap);
 123     } else {
 124       if (log_is_enabled(Info, cds)) {
 125         ResourceMark rm;
 126         LogStream ls(Log(cds)::info());
 127         ls.print("UseSharedSpaces: ");
 128         ls.vprint_cr(msg, ap);
 129       }
 130     }
 131     if (_dynamic_archive_info == NULL) {
 132       UseSharedSpaces = false;
 133       assert(current_info() != NULL, "singleton must be registered");
 134       current_info()->close();
 135     } else {
 136       // We are failing when loading the top archive, but the base archive should
 137       // continue to work.
 138       log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s", _dynamic_archive_info->_full_path);
 139     }
 140   }
 141   va_end(ap);
 142 }
 143 
 144 // Fill in the fileMapInfo structure with data about this VM instance.
 145 
 146 // This method copies the vm version info into header_version.  If the version is too
 147 // long then a truncated version, which has a hash code appended to it, is copied.
 148 //
 149 // Using a template enables this method to verify that header_version is an array of
 150 // length JVM_IDENT_MAX.  This ensures that the code that writes to the CDS file and
 151 // the code that reads the CDS file will both use the same size buffer.  Hence, will
 152 // use identical truncation.  This is necessary for matching of truncated versions.
 153 template <int N> static void get_header_version(char (&header_version) [N]) {
 154   assert(N == JVM_IDENT_MAX, "Bad header_version size");
 155 
 156   const char *vm_version = VM_Version::internal_vm_info_string();
 157   const int version_len = (int)strlen(vm_version);
 158 
 159   memset(header_version, 0, JVM_IDENT_MAX);
 160 
 161   if (version_len < (JVM_IDENT_MAX-1)) {
 162     strcpy(header_version, vm_version);
 163 
 164   } else {
 165     // Get the hash value.  Use a static seed because the hash needs to return the same
 166     // value over multiple jvm invocations.
 167     unsigned int hash = AltHashing::murmur3_32(8191, (const jbyte*)vm_version, version_len);
 168 
 169     // Truncate the ident, saving room for the 8 hex character hash value.
 170     strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
 171 
 172     // Append the hash code as eight hex digits.
 173     sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash);
 174     header_version[JVM_IDENT_MAX-1] = 0;  // Null terminate.
 175   }
 176 
 177   assert(header_version[JVM_IDENT_MAX-1] == 0, "must be");
 178 }
 179 
 180 FileMapInfo::FileMapInfo(bool is_static) {
 181   memset((void*)this, 0, sizeof(FileMapInfo));
 182   _is_static = is_static;
 183   size_t header_size;
 184   if (is_static) {
 185     assert(_current_info == NULL, "must be singleton"); // not thread safe
 186     _current_info = this;
 187     header_size = sizeof(FileMapHeader);
 188   } else {
 189     assert(_dynamic_archive_info == NULL, "must be singleton"); // not thread safe
 190     _dynamic_archive_info = this;
 191     header_size = sizeof(DynamicArchiveHeader);
 192   }
 193   _header = (FileMapHeader*)os::malloc(header_size, mtInternal);
 194   memset((void*)_header, 0, header_size);
 195   _header->_header_size = header_size;
 196   _header->_version = INVALID_CDS_ARCHIVE_VERSION;
 197   _header->_has_platform_or_app_classes = true;
 198   _file_offset = 0;
 199   _file_open = false;
 200 }
 201 
 202 FileMapInfo::~FileMapInfo() {
 203   if (_is_static) {
 204     assert(_current_info == this, "must be singleton"); // not thread safe
 205     _current_info = NULL;
 206   } else {
 207     assert(_dynamic_archive_info == this, "must be singleton"); // not thread safe
 208     _dynamic_archive_info = NULL;
 209   }
 210 }
 211 
 212 void FileMapInfo::populate_header(size_t alignment) {
 213   _header->populate(this, alignment);
 214 }
 215 
 216 void FileMapHeader::populate(FileMapInfo* mapinfo, size_t alignment) {
 217   if (DynamicDumpSharedSpaces) {
 218     _magic = CDS_DYNAMIC_ARCHIVE_MAGIC;
 219   } else {
 220     _magic = CDS_ARCHIVE_MAGIC;
 221   }
 222   _version = CURRENT_CDS_ARCHIVE_VERSION;
 223   _alignment = alignment;
 224   _obj_alignment = ObjectAlignmentInBytes;
 225   _compact_strings = CompactStrings;
 226   _narrow_oop_mode = CompressedOops::mode();
 227   _narrow_oop_base = CompressedOops::base();
 228   _narrow_oop_shift = CompressedOops::shift();
 229   _max_heap_size = MaxHeapSize;
 230   _narrow_klass_base = CompressedKlassPointers::base();
 231   _narrow_klass_shift = CompressedKlassPointers::shift();
 232   _shared_path_table = mapinfo->_shared_path_table;
 233   if (HeapShared::is_heap_object_archiving_allowed()) {
 234     _heap_reserved = Universe::heap()->reserved_region();
 235   }
 236 
 237   // The following fields are for sanity checks for whether this archive
 238   // will function correctly with this JVM and the bootclasspath it's
 239   // invoked with.
 240 
 241   // JVM version string ... changes on each build.
 242   get_header_version(_jvm_ident);
 243 
 244   _app_class_paths_start_index = ClassLoaderExt::app_class_paths_start_index();
 245   _app_module_paths_start_index = ClassLoaderExt::app_module_paths_start_index();
 246   _num_module_paths = ClassLoader::num_module_path_entries();
 247   _max_used_path_index = ClassLoaderExt::max_used_path_index();
 248 
 249   _verify_local = BytecodeVerificationLocal;
 250   _verify_remote = BytecodeVerificationRemote;
 251   _has_platform_or_app_classes = ClassLoaderExt::has_platform_or_app_classes();
 252   _shared_base_address = SharedBaseAddress;
 253   _allow_archiving_with_java_agent = AllowArchivingWithJavaAgent;
 254   // the following 2 fields will be set in write_header for dynamic archive header
 255   _base_archive_name_size = 0;
 256   _base_archive_is_default = false;
 257 }
 258 
 259 void SharedClassPathEntry::init_as_non_existent(const char* path, TRAPS) {
 260   _type = non_existent_entry;
 261   set_name(path, THREAD);
 262 }
 263 
 264 void SharedClassPathEntry::init(bool is_modules_image,
 265                                 ClassPathEntry* cpe, TRAPS) {
 266   assert(DumpSharedSpaces || DynamicDumpSharedSpaces, "dump time only");
 267   _timestamp = 0;
 268   _filesize  = 0;
 269   _from_class_path_attr = false;
 270 
 271   struct stat st;
 272   if (os::stat(cpe->name(), &st) == 0) {
 273     if ((st.st_mode & S_IFMT) == S_IFDIR) {
 274       _type = dir_entry;
 275     } else {
 276       // The timestamp of the modules_image is not checked at runtime.
 277       if (is_modules_image) {
 278         _type = modules_image_entry;
 279       } else {
 280         _type = jar_entry;
 281         _timestamp = st.st_mtime;
 282         _from_class_path_attr = cpe->from_class_path_attr();
 283       }
 284       _filesize = st.st_size;
 285     }
 286   } else {
 287     // The file/dir must exist, or it would not have been added
 288     // into ClassLoader::classpath_entry().
 289     //
 290     // If we can't access a jar file in the boot path, then we can't
 291     // make assumptions about where classes get loaded from.
 292     FileMapInfo::fail_stop("Unable to open file %s.", cpe->name());
 293   }
 294 
 295   // No need to save the name of the module file, as it will be computed at run time
 296   // to allow relocation of the JDK directory.
 297   const char* name = is_modules_image  ? "" : cpe->name();
 298   set_name(name, THREAD);
 299 }
 300 
 301 void SharedClassPathEntry::set_name(const char* name, TRAPS) {
 302   size_t len = strlen(name) + 1;
 303   _name = MetadataFactory::new_array<char>(ClassLoaderData::the_null_class_loader_data(), (int)len, THREAD);
 304   strcpy(_name->data(), name);
 305 }
 306 
 307 const char* SharedClassPathEntry::name() const {
 308   if (UseSharedSpaces && is_modules_image()) {
 309     // In order to validate the runtime modules image file size against the archived
 310     // size information, we need to obtain the runtime modules image path. The recorded
 311     // dump time modules image path in the archive may be different from the runtime path
 312     // if the JDK image has beed moved after generating the archive.
 313     return ClassLoader::get_jrt_entry()->name();
 314   } else {
 315     return _name->data();
 316   }
 317 }
 318 
 319 bool SharedClassPathEntry::validate(bool is_class_path) const {
 320   assert(UseSharedSpaces, "runtime only");
 321 
 322   struct stat st;
 323   const char* name = this->name();
 324 
 325   bool ok = true;
 326   log_info(class, path)("checking shared classpath entry: %s", name);
 327   if (os::stat(name, &st) != 0 && is_class_path) {
 328     // If the archived module path entry does not exist at runtime, it is not fatal
 329     // (no need to invalid the shared archive) because the shared runtime visibility check
 330     // filters out any archived module classes that do not have a matching runtime
 331     // module path location.
 332     FileMapInfo::fail_continue("Required classpath entry does not exist: %s", name);
 333     ok = false;
 334   } else if (is_dir()) {
 335     if (!os::dir_is_empty(name)) {
 336       FileMapInfo::fail_continue("directory is not empty: %s", name);
 337       ok = false;
 338     }
 339   } else if ((has_timestamp() && _timestamp != st.st_mtime) ||
 340              _filesize != st.st_size) {
 341     ok = false;
 342     if (PrintSharedArchiveAndExit) {
 343       FileMapInfo::fail_continue(_timestamp != st.st_mtime ?
 344                                  "Timestamp mismatch" :
 345                                  "File size mismatch");
 346     } else {
 347       FileMapInfo::fail_continue("A jar file is not the one used while building"
 348                                  " the shared archive file: %s", name);
 349     }
 350   }
 351 
 352   if (PrintSharedArchiveAndExit && !ok) {
 353     // If PrintSharedArchiveAndExit is enabled, don't report failure to the
 354     // caller. Please see above comments for more details.
 355     ok = true;
 356     MetaspaceShared::set_archive_loading_failed();
 357   }
 358   return ok;
 359 }
 360 
 361 bool SharedClassPathEntry::check_non_existent() const {
 362   assert(_type == non_existent_entry, "must be");
 363   log_info(class, path)("should be non-existent: %s", name());
 364   struct stat st;
 365   if (os::stat(name(), &st) != 0) {
 366     log_info(class, path)("ok");
 367     return true; // file doesn't exist
 368   } else {
 369     return false;
 370   }
 371 }
 372 
 373 
 374 void SharedClassPathEntry::metaspace_pointers_do(MetaspaceClosure* it) {
 375   it->push(&_name);
 376   it->push(&_manifest);
 377 }
 378 
 379 void SharedPathTable::metaspace_pointers_do(MetaspaceClosure* it) {
 380   it->push(&_table);
 381   for (int i=0; i<_size; i++) {
 382     path_at(i)->metaspace_pointers_do(it);
 383   }
 384 }
 385 
 386 void SharedPathTable::dumptime_init(ClassLoaderData* loader_data, Thread* THREAD) {
 387   size_t entry_size = sizeof(SharedClassPathEntry);
 388   int num_entries = 0;
 389   num_entries += ClassLoader::num_boot_classpath_entries();
 390   num_entries += ClassLoader::num_app_classpath_entries();
 391   num_entries += ClassLoader::num_module_path_entries();
 392   num_entries += FileMapInfo::num_non_existent_class_paths();
 393   size_t bytes = entry_size * num_entries;
 394 
 395   _table = MetadataFactory::new_array<u8>(loader_data, (int)(bytes + 7 / 8), THREAD);
 396   _size = num_entries;
 397 }
 398 
 399 void FileMapInfo::allocate_shared_path_table() {
 400   assert(DumpSharedSpaces || DynamicDumpSharedSpaces, "Sanity");
 401 
 402   EXCEPTION_MARK; // The following calls should never throw, but would exit VM on error.
 403   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 404   ClassPathEntry* jrt = ClassLoader::get_jrt_entry();
 405 
 406   assert(jrt != NULL,
 407          "No modular java runtime image present when allocating the CDS classpath entry table");
 408 
 409   _shared_path_table.dumptime_init(loader_data, THREAD);
 410 
 411   // 1. boot class path
 412   int i = 0;
 413   i = add_shared_classpaths(i, "boot",   jrt, THREAD);
 414   i = add_shared_classpaths(i, "app",    ClassLoader::app_classpath_entries(), THREAD);
 415   i = add_shared_classpaths(i, "module", ClassLoader::module_path_entries(), THREAD);
 416 
 417   for (int x = 0; x < num_non_existent_class_paths(); x++, i++) {
 418     const char* path = _non_existent_class_paths->at(x);
 419     shared_path(i)->init_as_non_existent(path, THREAD);
 420   }
 421 
 422   assert(i == _shared_path_table.size(), "number of shared path entry mismatch");
 423 }
 424 
 425 int FileMapInfo::add_shared_classpaths(int i, const char* which, ClassPathEntry *cpe, TRAPS) {
 426   while (cpe != NULL) {
 427     bool is_jrt = (cpe == ClassLoader::get_jrt_entry());
 428     const char* type = (is_jrt ? "jrt" : (cpe->is_jar_file() ? "jar" : "dir"));
 429     log_info(class, path)("add %s shared path (%s) %s", which, type, cpe->name());
 430     SharedClassPathEntry* ent = shared_path(i);
 431     ent->init(is_jrt, cpe, THREAD);
 432     if (cpe->is_jar_file()) {
 433       update_jar_manifest(cpe, ent, THREAD);
 434     }
 435     if (is_jrt) {
 436       cpe = ClassLoader::get_next_boot_classpath_entry(cpe);
 437     } else {
 438       cpe = cpe->next();
 439     }
 440     i++;
 441   }
 442 
 443   return i;
 444 }
 445 
 446 void FileMapInfo::check_nonempty_dir_in_shared_path_table() {
 447   assert(DumpSharedSpaces || DynamicDumpSharedSpaces, "dump time only");
 448 
 449   bool has_nonempty_dir = false;
 450 
 451   int last = _shared_path_table.size() - 1;
 452   if (last > ClassLoaderExt::max_used_path_index()) {
 453      // no need to check any path beyond max_used_path_index
 454      last = ClassLoaderExt::max_used_path_index();
 455   }
 456 
 457   for (int i = 0; i <= last; i++) {
 458     SharedClassPathEntry *e = shared_path(i);
 459     if (e->is_dir()) {
 460       const char* path = e->name();
 461       if (!os::dir_is_empty(path)) {
 462         tty->print_cr("Error: non-empty directory '%s'", path);
 463         has_nonempty_dir = true;
 464       }
 465     }
 466   }
 467 
 468   if (has_nonempty_dir) {
 469     ClassLoader::exit_with_path_failure("Cannot have non-empty directory in paths", NULL);
 470   }
 471 }
 472 
 473 void FileMapInfo::record_non_existent_class_path_entry(const char* path) {
 474   assert(DumpSharedSpaces || DynamicDumpSharedSpaces, "dump time only");
 475   log_info(class, path)("non-existent Class-Path entry %s", path);
 476   if (_non_existent_class_paths == NULL) {
 477     _non_existent_class_paths = new (ResourceObj::C_HEAP, mtInternal)GrowableArray<const char*>(10, true);
 478   }
 479   _non_existent_class_paths->append(os::strdup(path));
 480 }
 481 
 482 int FileMapInfo::num_non_existent_class_paths() {
 483   assert(DumpSharedSpaces || DynamicDumpSharedSpaces, "dump time only");
 484   if (_non_existent_class_paths != NULL) {
 485     return _non_existent_class_paths->length();
 486   } else {
 487     return 0;
 488   }
 489 }
 490 
 491 class ManifestStream: public ResourceObj {
 492   private:
 493   u1*   _buffer_start; // Buffer bottom
 494   u1*   _buffer_end;   // Buffer top (one past last element)
 495   u1*   _current;      // Current buffer position
 496 
 497  public:
 498   // Constructor
 499   ManifestStream(u1* buffer, int length) : _buffer_start(buffer),
 500                                            _current(buffer) {
 501     _buffer_end = buffer + length;
 502   }
 503 
 504   static bool is_attr(u1* attr, const char* name) {
 505     return strncmp((const char*)attr, name, strlen(name)) == 0;
 506   }
 507 
 508   static char* copy_attr(u1* value, size_t len) {
 509     char* buf = NEW_RESOURCE_ARRAY(char, len + 1);
 510     strncpy(buf, (char*)value, len);
 511     buf[len] = 0;
 512     return buf;
 513   }
 514 
 515   // The return value indicates if the JAR is signed or not
 516   bool check_is_signed() {
 517     u1* attr = _current;
 518     bool isSigned = false;
 519     while (_current < _buffer_end) {
 520       if (*_current == '\n') {
 521         *_current = '\0';
 522         u1* value = (u1*)strchr((char*)attr, ':');
 523         if (value != NULL) {
 524           assert(*(value+1) == ' ', "Unrecognized format" );
 525           if (strstr((char*)attr, "-Digest") != NULL) {
 526             isSigned = true;
 527             break;
 528           }
 529         }
 530         *_current = '\n'; // restore
 531         attr = _current + 1;
 532       }
 533       _current ++;
 534     }
 535     return isSigned;
 536   }
 537 };
 538 
 539 void FileMapInfo::update_jar_manifest(ClassPathEntry *cpe, SharedClassPathEntry* ent, TRAPS) {
 540   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 541   ResourceMark rm(THREAD);
 542   jint manifest_size;
 543 
 544   assert(cpe->is_jar_file() && ent->is_jar(), "the shared class path entry is not a JAR file");
 545   char* manifest = ClassLoaderExt::read_manifest(cpe, &manifest_size, CHECK);
 546   if (manifest != NULL) {
 547     ManifestStream* stream = new ManifestStream((u1*)manifest,
 548                                                 manifest_size);
 549     if (stream->check_is_signed()) {
 550       ent->set_is_signed();
 551     } else {
 552       // Copy the manifest into the shared archive
 553       manifest = ClassLoaderExt::read_raw_manifest(cpe, &manifest_size, CHECK);
 554       Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,
 555                                                       manifest_size,
 556                                                       THREAD);
 557       char* p = (char*)(buf->data());
 558       memcpy(p, manifest, manifest_size);
 559       ent->set_manifest(buf);
 560     }
 561   }
 562 }
 563 
 564 char* FileMapInfo::skip_first_path_entry(const char* path) {
 565   size_t path_sep_len = strlen(os::path_separator());
 566   char* p = strstr((char*)path, os::path_separator());
 567   if (p != NULL) {
 568     debug_only( {
 569       size_t image_name_len = strlen(MODULES_IMAGE_NAME);
 570       assert(strncmp(p - image_name_len, MODULES_IMAGE_NAME, image_name_len) == 0,
 571              "first entry must be the modules image");
 572     } );
 573     p += path_sep_len;
 574   } else {
 575     debug_only( {
 576       assert(ClassLoader::string_ends_with(path, MODULES_IMAGE_NAME),
 577              "first entry must be the modules image");
 578     } );
 579   }
 580   return p;
 581 }
 582 
 583 int FileMapInfo::num_paths(const char* path) {
 584   if (path == NULL) {
 585     return 0;
 586   }
 587   int npaths = 1;
 588   char* p = (char*)path;
 589   while (p != NULL) {
 590     char* prev = p;
 591     p = strstr((char*)p, os::path_separator());
 592     if (p != NULL) {
 593       p++;
 594       // don't count empty path
 595       if ((p - prev) > 1) {
 596        npaths++;
 597       }
 598     }
 599   }
 600   return npaths;
 601 }
 602 
 603 GrowableArray<const char*>* FileMapInfo::create_path_array(const char* paths) {
 604   GrowableArray<const char*>* path_array =  new(ResourceObj::RESOURCE_AREA, mtInternal)
 605       GrowableArray<const char*>(10);
 606 
 607   ClasspathStream cp_stream(paths);
 608   while (cp_stream.has_next()) {
 609     const char* path = cp_stream.get_next();
 610     struct stat st;
 611     if (os::stat(path, &st) == 0) {
 612       path_array->append(path);
 613     }
 614   }
 615   return path_array;
 616 }
 617 
 618 bool FileMapInfo::fail(const char* msg, const char* name) {
 619   ClassLoader::trace_class_path(msg, name);
 620   MetaspaceShared::set_archive_loading_failed();
 621   return false;
 622 }
 623 
 624 bool FileMapInfo::check_paths(int shared_path_start_idx, int num_paths, GrowableArray<const char*>* rp_array) {
 625   int i = 0;
 626   int j = shared_path_start_idx;
 627   bool mismatch = false;
 628   while (i < num_paths && !mismatch) {
 629     while (shared_path(j)->from_class_path_attr()) {
 630       // shared_path(j) was expanded from the JAR file attribute "Class-Path:"
 631       // during dump time. It's not included in the -classpath VM argument.
 632       j++;
 633     }
 634     if (!os::same_files(shared_path(j)->name(), rp_array->at(i))) {
 635       mismatch = true;
 636     }
 637     i++;
 638     j++;
 639   }
 640   return mismatch;
 641 }
 642 
 643 bool FileMapInfo::validate_boot_class_paths() {
 644   //
 645   // - Archive contains boot classes only - relaxed boot path check:
 646   //   Extra path elements appended to the boot path at runtime are allowed.
 647   //
 648   // - Archive contains application or platform classes - strict boot path check:
 649   //   Validate the entire runtime boot path, which must be compatible
 650   //   with the dump time boot path. Appending boot path at runtime is not
 651   //   allowed.
 652   //
 653 
 654   // The first entry in boot path is the modules_image (guaranteed by
 655   // ClassLoader::setup_boot_search_path()). Skip the first entry. The
 656   // path of the runtime modules_image may be different from the dump
 657   // time path (e.g. the JDK image is copied to a different location
 658   // after generating the shared archive), which is acceptable. For most
 659   // common cases, the dump time boot path might contain modules_image only.
 660   char* runtime_boot_path = Arguments::get_sysclasspath();
 661   char* rp = skip_first_path_entry(runtime_boot_path);
 662   assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
 663   int dp_len = _header->_app_class_paths_start_index - 1; // ignore the first path to the module image
 664   bool mismatch = false;
 665 
 666   bool relaxed_check = !header()->has_platform_or_app_classes();
 667   if (dp_len == 0 && rp == NULL) {
 668     return true;   // ok, both runtime and dump time boot paths have modules_images only
 669   } else if (dp_len == 0 && rp != NULL) {
 670     if (relaxed_check) {
 671       return true;   // ok, relaxed check, runtime has extra boot append path entries
 672     } else {
 673       mismatch = true;
 674     }
 675   } else if (dp_len > 0 && rp != NULL) {
 676     int num;
 677     ResourceMark rm;
 678     GrowableArray<const char*>* rp_array = create_path_array(rp);
 679     int rp_len = rp_array->length();
 680     if (rp_len >= dp_len) {
 681       if (relaxed_check) {
 682         // only check the leading entries in the runtime boot path, up to
 683         // the length of the dump time boot path
 684         num = dp_len;
 685       } else {
 686         // check the full runtime boot path, must match with dump time
 687         num = rp_len;
 688       }
 689       mismatch = check_paths(1, num, rp_array);
 690     }
 691   }
 692 
 693   if (mismatch) {
 694     // The paths are different
 695     return fail("[BOOT classpath mismatch, actual =", runtime_boot_path);
 696   }
 697   return true;
 698 }
 699 
 700 bool FileMapInfo::validate_app_class_paths(int shared_app_paths_len) {
 701   const char *appcp = Arguments::get_appclasspath();
 702   assert(appcp != NULL, "NULL app classpath");
 703   int rp_len = num_paths(appcp);
 704   bool mismatch = false;
 705   if (rp_len < shared_app_paths_len) {
 706     return fail("Run time APP classpath is shorter than the one at dump time: ", appcp);
 707   }
 708   if (shared_app_paths_len != 0 && rp_len != 0) {
 709     // Prefix is OK: E.g., dump with -cp foo.jar, but run with -cp foo.jar:bar.jar.
 710     ResourceMark rm;
 711     GrowableArray<const char*>* rp_array = create_path_array(appcp);
 712     if (rp_array->length() == 0) {
 713       // None of the jar file specified in the runtime -cp exists.
 714       return fail("None of the jar file specified in the runtime -cp exists: -Djava.class.path=", appcp);
 715     }
 716 
 717     // Handling of non-existent entries in the classpath: we eliminate all the non-existent
 718     // entries from both the dump time classpath (ClassLoader::update_class_path_entry_list)
 719     // and the runtime classpath (FileMapInfo::create_path_array), and check the remaining
 720     // entries. E.g.:
 721     //
 722     // dump : -cp a.jar:NE1:NE2:b.jar  -> a.jar:b.jar -> recorded in archive.
 723     // run 1: -cp NE3:a.jar:NE4:b.jar  -> a.jar:b.jar -> matched
 724     // run 2: -cp x.jar:NE4:b.jar      -> x.jar:b.jar -> mismatched
 725 
 726     int j = _header->_app_class_paths_start_index;
 727     mismatch = check_paths(j, shared_app_paths_len, rp_array);
 728     if (mismatch) {
 729       return fail("[APP classpath mismatch, actual: -Djava.class.path=", appcp);
 730     }
 731   }
 732   return true;
 733 }
 734 
 735 void FileMapInfo::log_paths(const char* msg, int start_idx, int end_idx) {
 736   LogTarget(Info, class, path) lt;
 737   if (lt.is_enabled()) {
 738     LogStream ls(lt);
 739     ls.print("%s", msg);
 740     const char* prefix = "";
 741     for (int i = start_idx; i < end_idx; i++) {
 742       ls.print("%s%s", prefix, shared_path(i)->name());
 743       prefix = os::path_separator();
 744     }
 745     ls.cr();
 746   }
 747 }
 748 
 749 bool FileMapInfo::validate_shared_path_table() {
 750   assert(UseSharedSpaces, "runtime only");
 751 
 752   _validating_shared_path_table = true;
 753 
 754   // Load the shared path table info from the archive header
 755   _shared_path_table = _header->_shared_path_table;
 756   if (DynamicDumpSharedSpaces) {
 757     // Only support dynamic dumping with the usage of the default CDS archive
 758     // or a simple base archive.
 759     // If the base layer archive contains additional path component besides
 760     // the runtime image and the -cp, dynamic dumping is disabled.
 761     //
 762     // When dynamic archiving is enabled, the _shared_path_table is overwritten
 763     // to include the application path and stored in the top layer archive.
 764     assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
 765     if (_header->_app_class_paths_start_index > 1) {
 766       DynamicDumpSharedSpaces = false;
 767       warning(
 768         "Dynamic archiving is disabled because base layer archive has appended boot classpath");
 769     }
 770     if (_header->_num_module_paths > 0) {
 771       DynamicDumpSharedSpaces = false;
 772       warning(
 773         "Dynamic archiving is disabled because base layer archive has module path");
 774     }
 775   }
 776 
 777   log_paths("Expecting BOOT path=", 0, _header->_app_class_paths_start_index);
 778   log_paths("Expecting -Djava.class.path=", _header->_app_class_paths_start_index, _header->_app_module_paths_start_index);
 779 
 780   int module_paths_start_index = _header->_app_module_paths_start_index;
 781   int shared_app_paths_len = 0;
 782 
 783   // validate the path entries up to the _max_used_path_index
 784   for (int i=0; i < _header->_max_used_path_index + 1; i++) {
 785     if (i < module_paths_start_index) {
 786       if (shared_path(i)->validate()) {
 787         // Only count the app class paths not from the "Class-path" attribute of a jar manifest.
 788         if (!shared_path(i)->from_class_path_attr() && i >= _header->_app_class_paths_start_index) {
 789           shared_app_paths_len++;
 790         }
 791         log_info(class, path)("ok");
 792       } else {
 793         if (_dynamic_archive_info != NULL && _dynamic_archive_info->_is_static) {
 794           assert(!UseSharedSpaces, "UseSharedSpaces should be disabled");
 795         }
 796         return false;
 797       }
 798     } else if (i >= module_paths_start_index) {
 799       if (shared_path(i)->validate(false /* not a class path entry */)) {
 800         log_info(class, path)("ok");
 801       } else {
 802         if (_dynamic_archive_info != NULL && _dynamic_archive_info->_is_static) {
 803           assert(!UseSharedSpaces, "UseSharedSpaces should be disabled");
 804         }
 805         return false;
 806       }
 807     }
 808   }
 809 
 810   if (_header->_max_used_path_index == 0) {
 811     // default archive only contains the module image in the bootclasspath
 812     assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
 813   } else {
 814     if (!validate_boot_class_paths() || !validate_app_class_paths(shared_app_paths_len)) {
 815       fail_continue("shared class paths mismatch (hint: enable -Xlog:class+path=info to diagnose the failure)");
 816       return false;
 817     }
 818   }
 819 
 820   validate_non_existent_class_paths();
 821 
 822   _validating_shared_path_table = false;
 823 
 824 #if INCLUDE_JVMTI
 825   if (_classpath_entries_for_jvmti != NULL) {
 826     os::free(_classpath_entries_for_jvmti);
 827   }
 828   size_t sz = sizeof(ClassPathEntry*) * get_number_of_shared_paths();
 829   _classpath_entries_for_jvmti = (ClassPathEntry**)os::malloc(sz, mtClass);
 830   memset((void*)_classpath_entries_for_jvmti, 0, sz);
 831 #endif
 832 
 833   return true;
 834 }
 835 
 836 void FileMapInfo::validate_non_existent_class_paths() {
 837   // All of the recorded non-existent paths came from the Class-Path: attribute from the JAR
 838   // files on the app classpath. If any of these are found to exist during runtime,
 839   // it will change how classes are loading for the app loader. For safety, disable
 840   // loading of archived platform/app classes (currently there's no way to disable just the
 841   // app classes).
 842 
 843   assert(UseSharedSpaces, "runtime only");
 844   for (int i = _header->_app_module_paths_start_index + _header->_num_module_paths;
 845        i < get_number_of_shared_paths();
 846        i++) {
 847     SharedClassPathEntry* ent = shared_path(i);
 848     if (!ent->check_non_existent()) {
 849       warning("Archived non-system classes are disabled because the "
 850               "file %s exists", ent->name());
 851       _header->_has_platform_or_app_classes = false;
 852     }
 853   }
 854 }
 855 
 856 bool FileMapInfo::check_archive(const char* archive_name, bool is_static) {
 857   int fd = os::open(archive_name, O_RDONLY | O_BINARY, 0);
 858   if (fd < 0) {
 859     // do not vm_exit_during_initialization here because Arguments::init_shared_archive_paths()
 860     // requires a shared archive name. The open_for_read() function will log a message regarding
 861     // failure in opening a shared archive.
 862     return false;
 863   }
 864 
 865   size_t sz = is_static ? sizeof(FileMapHeader) : sizeof(DynamicArchiveHeader);
 866   void* header = os::malloc(sz, mtInternal);
 867   memset(header, 0, sz);
 868   size_t n = os::read(fd, header, (unsigned int)sz);
 869   if (n != sz) {
 870     os::free(header);
 871     os::close(fd);
 872     vm_exit_during_initialization("Unable to read header from shared archive", archive_name);
 873     return false;
 874   }
 875   if (is_static) {
 876     FileMapHeader* static_header = (FileMapHeader*)header;
 877     if (static_header->_magic != CDS_ARCHIVE_MAGIC) {
 878       os::free(header);
 879       os::close(fd);
 880       vm_exit_during_initialization("Not a base shared archive", archive_name);
 881       return false;
 882     }
 883   } else {
 884     DynamicArchiveHeader* dynamic_header = (DynamicArchiveHeader*)header;
 885     if (dynamic_header->_magic != CDS_DYNAMIC_ARCHIVE_MAGIC) {
 886       os::free(header);
 887       os::close(fd);
 888       vm_exit_during_initialization("Not a top shared archive", archive_name);
 889       return false;
 890     }
 891   }
 892   os::free(header);
 893   os::close(fd);
 894   return true;
 895 }
 896 
 897 bool FileMapInfo::get_base_archive_name_from_header(const char* archive_name,
 898                                                     int* size, char** base_archive_name) {
 899   int fd = os::open(archive_name, O_RDONLY | O_BINARY, 0);
 900   if (fd < 0) {
 901     *size = 0;
 902     return false;
 903   }
 904 
 905   // read the header as a dynamic archive header
 906   size_t sz = sizeof(DynamicArchiveHeader);
 907   DynamicArchiveHeader* dynamic_header = (DynamicArchiveHeader*)os::malloc(sz, mtInternal);
 908   size_t n = os::read(fd, dynamic_header, (unsigned int)sz);
 909   if (n != sz) {
 910     fail_continue("Unable to read the file header.");
 911     os::free(dynamic_header);
 912     os::close(fd);
 913     return false;
 914   }
 915   if (dynamic_header->_magic != CDS_DYNAMIC_ARCHIVE_MAGIC) {
 916     // Not a dynamic header, no need to proceed further.
 917     *size = 0;
 918     os::free(dynamic_header);
 919     os::close(fd);
 920     return false;
 921   }
 922   if (dynamic_header->_base_archive_is_default) {
 923     *base_archive_name = Arguments::get_default_shared_archive_path();
 924   } else {
 925     // read the base archive name
 926     size_t name_size = dynamic_header->_base_archive_name_size;
 927     if (name_size == 0) {
 928       os::free(dynamic_header);
 929       os::close(fd);
 930       return false;
 931     }
 932     *base_archive_name = NEW_C_HEAP_ARRAY(char, name_size, mtInternal);
 933     n = os::read(fd, *base_archive_name, (unsigned int)name_size);
 934     if (n != name_size) {
 935       fail_continue("Unable to read the base archive name from the header.");
 936       FREE_C_HEAP_ARRAY(char, *base_archive_name);
 937       *base_archive_name = NULL;
 938       os::free(dynamic_header);
 939       os::close(fd);
 940       return false;
 941     }
 942   }
 943 
 944   os::free(dynamic_header);
 945   os::close(fd);
 946   return true;
 947 }
 948 
 949 void FileMapInfo::restore_shared_path_table() {
 950   _shared_path_table = _current_info->_header->_shared_path_table;
 951 }
 952 
 953 // Read the FileMapInfo information from the file.
 954 
 955 bool FileMapInfo::init_from_file(int fd, bool is_static) {
 956   size_t sz = is_static ? sizeof(FileMapHeader) : sizeof(DynamicArchiveHeader);
 957   size_t n = os::read(fd, _header, (unsigned int)sz);
 958   if (n != sz) {
 959     fail_continue("Unable to read the file header.");
 960     return false;
 961   }
 962 
 963   if (!Arguments::has_jimage()) {
 964     FileMapInfo::fail_continue("The shared archive file cannot be used with an exploded module build.");
 965     return false;
 966   }
 967 
 968   unsigned int expected_magic = is_static ? CDS_ARCHIVE_MAGIC : CDS_DYNAMIC_ARCHIVE_MAGIC;
 969   if (_header->_magic != expected_magic) {
 970     log_info(cds)("_magic expected: 0x%08x", expected_magic);
 971     log_info(cds)("         actual: 0x%08x", _header->_magic);
 972     FileMapInfo::fail_continue("The shared archive file has a bad magic number.");
 973     return false;
 974   }
 975 
 976   if (_header->_version != CURRENT_CDS_ARCHIVE_VERSION) {
 977     log_info(cds)("_version expected: %d", CURRENT_CDS_ARCHIVE_VERSION);
 978     log_info(cds)("           actual: %d", _header->_version);
 979     fail_continue("The shared archive file has the wrong version.");
 980     return false;
 981   }
 982 
 983   if (_header->_header_size != sz) {
 984     log_info(cds)("_header_size expected: " SIZE_FORMAT, sz);
 985     log_info(cds)("               actual: " SIZE_FORMAT, _header->_header_size);
 986     FileMapInfo::fail_continue("The shared archive file has an incorrect header size.");
 987     return false;
 988   }
 989 
 990   if (_header->_jvm_ident[JVM_IDENT_MAX-1] != 0) {
 991     FileMapInfo::fail_continue("JVM version identifier is corrupted.");
 992     return false;
 993   }
 994 
 995   char header_version[JVM_IDENT_MAX];
 996   get_header_version(header_version);
 997   if (strncmp(_header->_jvm_ident, header_version, JVM_IDENT_MAX-1) != 0) {
 998     log_info(cds)("_jvm_ident expected: %s", header_version);
 999     log_info(cds)("             actual: %s", _header->_jvm_ident);
1000     FileMapInfo::fail_continue("The shared archive file was created by a different"
1001                   " version or build of HotSpot");
1002     return false;
1003   }
1004 
1005   if (VerifySharedSpaces) {
1006     int expected_crc = _header->compute_crc();
1007     if (expected_crc != _header->_crc) {
1008       log_info(cds)("_crc expected: %d", expected_crc);
1009       log_info(cds)("       actual: %d", _header->_crc);
1010       FileMapInfo::fail_continue("Header checksum verification failed.");
1011       return false;
1012     }
1013   }
1014 
1015   _file_offset = n + _header->_base_archive_name_size; // accounts for the size of _base_archive_name
1016 
1017   if (is_static) {
1018     // just checking the last region is sufficient since the archive is written
1019     // in sequential order
1020     size_t len = lseek(fd, 0, SEEK_END);
1021     CDSFileMapRegion* si = space_at(MetaspaceShared::last_valid_region);
1022     // The last space might be empty
1023     if (si->_file_offset > len || len - si->_file_offset < si->_used) {
1024       fail_continue("The shared archive file has been truncated.");
1025       return false;
1026     }
1027 
1028     SharedBaseAddress = _header->_shared_base_address;
1029   }
1030 
1031   return true;
1032 }
1033 
1034 
1035 // Read the FileMapInfo information from the file.
1036 bool FileMapInfo::open_for_read(const char* path) {
1037   if (_file_open) {
1038     return true;
1039   }
1040   if (path == NULL) {
1041     _full_path = Arguments::GetSharedArchivePath();
1042   } else {
1043     _full_path = path;
1044   }
1045   int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0);
1046   if (fd < 0) {
1047     if (errno == ENOENT) {
1048       // Not locating the shared archive is ok.
1049       fail_continue("Specified shared archive not found (%s).", _full_path);
1050     } else {
1051       fail_continue("Failed to open shared archive file (%s).",
1052                     os::strerror(errno));
1053     }
1054     return false;
1055   }
1056 
1057   _fd = fd;
1058   _file_open = true;
1059   return true;
1060 }
1061 
1062 // Write the FileMapInfo information to the file.
1063 
1064 void FileMapInfo::open_for_write(const char* path) {
1065   if (path == NULL) {
1066     _full_path = Arguments::GetSharedArchivePath();
1067   } else {
1068     _full_path = path;
1069   }
1070   LogMessage(cds) msg;
1071   if (msg.is_info()) {
1072     msg.info("Dumping shared data to file: ");
1073     msg.info("   %s", _full_path);
1074   }
1075 
1076 #ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
1077     chmod(_full_path, _S_IREAD | _S_IWRITE);
1078 #endif
1079 
1080   // Use remove() to delete the existing file because, on Unix, this will
1081   // allow processes that have it open continued access to the file.
1082   remove(_full_path);
1083   int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
1084   if (fd < 0) {
1085     fail_stop("Unable to create shared archive file %s: (%s).", _full_path,
1086               os::strerror(errno));
1087   }
1088   _fd = fd;
1089   _file_offset = 0;
1090   _file_open = true;
1091 }
1092 
1093 
1094 // Write the header to the file, seek to the next allocation boundary.
1095 
1096 void FileMapInfo::write_header() {
1097   char* base_archive_name = NULL;
1098   if (_header->_magic == CDS_DYNAMIC_ARCHIVE_MAGIC) {
1099     base_archive_name = (char*)Arguments::GetSharedArchivePath();
1100     _header->_base_archive_name_size = (int)strlen(base_archive_name) + 1;
1101     _header->_base_archive_is_default = FLAG_IS_DEFAULT(SharedArchiveFile);
1102   }
1103 
1104   assert(is_file_position_aligned(), "must be");
1105   write_bytes(_header, _header->_header_size);
1106   if (base_archive_name != NULL) {
1107     write_bytes(base_archive_name, (size_t)_header->_base_archive_name_size);
1108   }
1109   align_file_position();
1110 }
1111 
1112 // Dump region to file.
1113 // This is called twice for each region during archiving, once before
1114 // the archive file is open (_file_open is false) and once after.
1115 void FileMapInfo::write_region(int region, char* base, size_t size,
1116                                bool read_only, bool allow_exec) {
1117   assert(DumpSharedSpaces || DynamicDumpSharedSpaces, "Dump time only");
1118 
1119   CDSFileMapRegion* si = space_at(region);
1120   char* target_base = base;
1121   if (DynamicDumpSharedSpaces) {
1122     target_base = DynamicArchive::buffer_to_target(base);
1123   }
1124 
1125   if (_file_open) {
1126     guarantee(si->_file_offset == _file_offset, "file offset mismatch.");
1127     log_info(cds)("Shared file region %d: " SIZE_FORMAT_HEX_W(08)
1128                   " bytes, addr " INTPTR_FORMAT " file offset " SIZE_FORMAT_HEX_W(08),
1129                   region, size, p2i(target_base), _file_offset);
1130   } else {
1131     si->_file_offset = _file_offset;
1132   }
1133 
1134   if (HeapShared::is_heap_region(region)) {
1135     assert((target_base - (char*)CompressedKlassPointers::base()) % HeapWordSize == 0, "Sanity");
1136     if (target_base != NULL) {
1137       si->_addr._offset = (intx)CompressedOops::encode_not_null((oop)target_base);
1138     } else {
1139       si->_addr._offset = 0;
1140     }
1141   } else {
1142     si->_addr._base = target_base;
1143   }
1144   si->_used = size;
1145   si->_read_only = read_only;
1146   si->_allow_exec = allow_exec;
1147 
1148   // Use the current 'base' when computing the CRC value and writing out data
1149   si->_crc = ClassLoader::crc32(0, base, (jint)size);
1150   if (base != NULL) {
1151     write_bytes_aligned(base, size);
1152   }
1153 }
1154 
1155 // Write out the given archive heap memory regions.  GC code combines multiple
1156 // consecutive archive GC regions into one MemRegion whenever possible and
1157 // produces the 'heap_mem' array.
1158 //
1159 // If the archive heap memory size is smaller than a single dump time GC region
1160 // size, there is only one MemRegion in the array.
1161 //
1162 // If the archive heap memory size is bigger than one dump time GC region size,
1163 // the 'heap_mem' array may contain more than one consolidated MemRegions. When
1164 // the first/bottom archive GC region is a partial GC region (with the empty
1165 // portion at the higher address within the region), one MemRegion is used for
1166 // the bottom partial archive GC region. The rest of the consecutive archive
1167 // GC regions are combined into another MemRegion.
1168 //
1169 // Here's the mapping from (archive heap GC regions) -> (GrowableArray<MemRegion> *regions).
1170 //   + We have 1 or more archive heap regions: ah0, ah1, ah2 ..... ahn
1171 //   + We have 1 or 2 consolidated heap memory regions: r0 and r1
1172 //
1173 // If there's a single archive GC region (ah0), then r0 == ah0, and r1 is empty.
1174 // Otherwise:
1175 //
1176 // "X" represented space that's occupied by heap objects.
1177 // "_" represented unused spaced in the heap region.
1178 //
1179 //
1180 //    |ah0       | ah1 | ah2| ...... | ahn|
1181 //    |XXXXXX|__ |XXXXX|XXXX|XXXXXXXX|XXXX|
1182 //    |<-r0->|   |<- r1 ----------------->|
1183 //            ^^^
1184 //             |
1185 //             +-- gap
1186 size_t FileMapInfo::write_archive_heap_regions(GrowableArray<MemRegion> *heap_mem,
1187                                                GrowableArray<ArchiveHeapOopmapInfo> *oopmaps,
1188                                                int first_region_id, int max_num_regions,
1189                                                bool print_log) {
1190   assert(max_num_regions <= 2, "Only support maximum 2 memory regions");
1191 
1192   int arr_len = heap_mem == NULL ? 0 : heap_mem->length();
1193   if(arr_len > max_num_regions) {
1194     fail_stop("Unable to write archive heap memory regions: "
1195               "number of memory regions exceeds maximum due to fragmentation. "
1196               "Please increase java heap size "
1197               "(current MaxHeapSize is " SIZE_FORMAT ", InitialHeapSize is " SIZE_FORMAT ").",
1198               MaxHeapSize, InitialHeapSize);
1199   }
1200 
1201   size_t total_size = 0;
1202   for (int i = first_region_id, arr_idx = 0;
1203            i < first_region_id + max_num_regions;
1204            i++, arr_idx++) {
1205     char* start = NULL;
1206     size_t size = 0;
1207     if (arr_idx < arr_len) {
1208       start = (char*)heap_mem->at(arr_idx).start();
1209       size = heap_mem->at(arr_idx).byte_size();
1210       total_size += size;
1211     }
1212 
1213     if (print_log) {
1214       log_info(cds)("Archive heap region %d " INTPTR_FORMAT " - " INTPTR_FORMAT " = " SIZE_FORMAT_W(8) " bytes",
1215                     i, p2i(start), p2i(start + size), size);
1216     }
1217     write_region(i, start, size, false, false);
1218     if (size > 0) {
1219       space_at(i)->_oopmap = oopmaps->at(arr_idx)._oopmap;
1220       space_at(i)->_oopmap_size_in_bits = oopmaps->at(arr_idx)._oopmap_size_in_bits;
1221     }
1222   }
1223   return total_size;
1224 }
1225 
1226 // Dump bytes to file -- at the current file position.
1227 
1228 void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) {
1229   if (_file_open) {
1230     size_t n = os::write(_fd, buffer, (unsigned int)nbytes);
1231     if (n != nbytes) {
1232       // If the shared archive is corrupted, close it and remove it.
1233       close();
1234       remove(_full_path);
1235       fail_stop("Unable to write to shared archive file.");
1236     }
1237   }
1238   _file_offset += nbytes;
1239 }
1240 
1241 bool FileMapInfo::is_file_position_aligned() const {
1242   return _file_offset == align_up(_file_offset,
1243                                   os::vm_allocation_granularity());
1244 }
1245 
1246 // Align file position to an allocation unit boundary.
1247 
1248 void FileMapInfo::align_file_position() {
1249   size_t new_file_offset = align_up(_file_offset,
1250                                          os::vm_allocation_granularity());
1251   if (new_file_offset != _file_offset) {
1252     _file_offset = new_file_offset;
1253     if (_file_open) {
1254       // Seek one byte back from the target and write a byte to insure
1255       // that the written file is the correct length.
1256       _file_offset -= 1;
1257       if (lseek(_fd, (long)_file_offset, SEEK_SET) < 0) {
1258         fail_stop("Unable to seek.");
1259       }
1260       char zero = 0;
1261       write_bytes(&zero, 1);
1262     }
1263   }
1264 }
1265 
1266 
1267 // Dump bytes to file -- at the current file position.
1268 
1269 void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) {
1270   align_file_position();
1271   write_bytes(buffer, nbytes);
1272   align_file_position();
1273 }
1274 
1275 
1276 // Close the shared archive file.  This does NOT unmap mapped regions.
1277 
1278 void FileMapInfo::close() {
1279   if (_file_open) {
1280     if (::close(_fd) < 0) {
1281       fail_stop("Unable to close the shared archive file.");
1282     }
1283     _file_open = false;
1284     _fd = -1;
1285   }
1286 }
1287 
1288 
1289 // JVM/TI RedefineClasses() support:
1290 // Remap the shared readonly space to shared readwrite, private.
1291 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
1292   int idx = MetaspaceShared::ro;
1293   CDSFileMapRegion* si = space_at(idx);
1294   if (!si->_read_only) {
1295     // the space is already readwrite so we are done
1296     return true;
1297   }
1298   size_t used = si->_used;
1299   size_t size = align_up(used, os::vm_allocation_granularity());
1300   if (!open_for_read()) {
1301     return false;
1302   }
1303   char *addr = region_addr(idx);
1304   char *base = os::remap_memory(_fd, _full_path, si->_file_offset,
1305                                 addr, size, false /* !read_only */,
1306                                 si->_allow_exec);
1307   close();
1308   // These have to be errors because the shared region is now unmapped.
1309   if (base == NULL) {
1310     log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);
1311     vm_exit(1);
1312   }
1313   if (base != addr) {
1314     log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);
1315     vm_exit(1);
1316   }
1317   si->_read_only = false;
1318   return true;
1319 }
1320 
1321 // Map the whole region at once, assumed to be allocated contiguously.
1322 ReservedSpace FileMapInfo::reserve_shared_memory() {
1323   char* requested_addr = region_addr(0);
1324   size_t size = FileMapInfo::core_spaces_size();
1325 
1326   // Reserve the space first, then map otherwise map will go right over some
1327   // other reserved memory (like the code cache).
1328   ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr);
1329   if (!rs.is_reserved()) {
1330     fail_continue("Unable to reserve shared space at required address "
1331                   INTPTR_FORMAT, p2i(requested_addr));
1332     return rs;
1333   }
1334   // the reserved virtual memory is for mapping class data sharing archive
1335   MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared);
1336 
1337   return rs;
1338 }
1339 
1340 // Memory map a region in the address space.
1341 static const char* shared_region_name[] = { "MiscData", "ReadWrite", "ReadOnly", "MiscCode",
1342                                             "String1", "String2", "OpenArchive1", "OpenArchive2" };
1343 
1344 char* FileMapInfo::map_regions(int regions[], char* saved_base[], size_t len) {
1345   char* prev_top = NULL;
1346   char* curr_base;
1347   char* curr_top;
1348   int i = 0;
1349   for (i = 0; i < (int)len; i++) {
1350     curr_base = map_region(regions[i], &curr_top);
1351     if (curr_base == NULL) {
1352       return NULL;
1353     }
1354     if (i > 0) {
1355       // We require that mc->rw->ro->md to be laid out consecutively, with no
1356       // gaps between them. That way, we can ensure that the OS won't be able to
1357       // allocate any new memory spaces inside _shared_metaspace_{base,top}, which
1358       // would mess up the simple comparision in MetaspaceShared::is_in_shared_metaspace().
1359       assert(curr_base == prev_top, "must be");
1360     }
1361     log_info(cds)("Mapped region #%d at base %p top %p", regions[i], curr_base, curr_top);
1362     saved_base[i] = curr_base;
1363     prev_top = curr_top;
1364   }
1365   return curr_top;
1366 }
1367 
1368 char* FileMapInfo::map_region(int i, char** top_ret) {
1369   assert(!HeapShared::is_heap_region(i), "sanity");
1370   CDSFileMapRegion* si = space_at(i);
1371   size_t used = si->_used;
1372   size_t alignment = os::vm_allocation_granularity();
1373   size_t size = align_up(used, alignment);
1374   char *requested_addr = region_addr(i);
1375 
1376 #ifdef _WINDOWS
1377   // Windows cannot remap read-only shared memory to read-write when required for
1378   // RedefineClasses, which is also used by JFR.  Always map windows regions as RW.
1379   si->_read_only = false;
1380 #else
1381   // If a tool agent is in use (debugging enabled), or JFR, we must map the address space RW
1382   if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space() ||
1383       Arguments::has_jfr_option()) {
1384     si->_read_only = false;
1385   }
1386 #endif // _WINDOWS
1387 
1388   // map the contents of the CDS archive in this memory
1389   char *base = os::map_memory(_fd, _full_path, si->_file_offset,
1390                               requested_addr, size, si->_read_only,
1391                               si->_allow_exec);
1392   if (base == NULL || base != requested_addr) {
1393     fail_continue("Unable to map %s shared space at required address.", shared_region_name[i]);
1394     _memory_mapping_failed = true;
1395     return NULL;
1396   }
1397 #ifdef _WINDOWS
1398   // This call is Windows-only because the memory_type gets recorded for the other platforms
1399   // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows.
1400   MemTracker::record_virtual_memory_type((address)base, mtClassShared);
1401 #endif
1402 
1403   if (VerifySharedSpaces && !verify_region_checksum(i)) {
1404     return NULL;
1405   }
1406 
1407   *top_ret = base + size;
1408   return base;
1409 }
1410 
1411 size_t FileMapInfo::read_bytes(void* buffer, size_t count) {
1412   assert(_file_open, "Archive file is not open");
1413   size_t n = os::read(_fd, buffer, (unsigned int)count);
1414   if (n != count) {
1415     // Close the file if there's a problem reading it.
1416     close();
1417     return 0;
1418   }
1419   _file_offset += count;
1420   return count;
1421 }
1422 
1423 address FileMapInfo::decode_start_address(CDSFileMapRegion* spc, bool with_current_oop_encoding_mode) {
1424   if (with_current_oop_encoding_mode) {
1425     return (address)CompressedOops::decode_not_null(offset_of_space(spc));
1426   } else {
1427     return (address)HeapShared::decode_from_archive(offset_of_space(spc));
1428   }
1429 }
1430 
1431 static MemRegion *closed_archive_heap_ranges = NULL;
1432 static MemRegion *open_archive_heap_ranges = NULL;
1433 static int num_closed_archive_heap_ranges = 0;
1434 static int num_open_archive_heap_ranges = 0;
1435 
1436 #if INCLUDE_CDS_JAVA_HEAP
1437 bool FileMapInfo::has_heap_regions() {
1438   return (_header->_space[MetaspaceShared::first_closed_archive_heap_region]._used > 0);
1439 }
1440 
1441 // Returns the address range of the archived heap regions computed using the
1442 // current oop encoding mode. This range may be different than the one seen at
1443 // dump time due to encoding mode differences. The result is used in determining
1444 // if/how these regions should be relocated at run time.
1445 MemRegion FileMapInfo::get_heap_regions_range_with_current_oop_encoding_mode() {
1446   address start = (address) max_uintx;
1447   address end   = NULL;
1448 
1449   for (int i = MetaspaceShared::first_closed_archive_heap_region;
1450            i <= MetaspaceShared::last_valid_region;
1451            i++) {
1452     CDSFileMapRegion* si = space_at(i);
1453     size_t size = si->_used;
1454     if (size > 0) {
1455       address s = start_address_as_decoded_with_current_oop_encoding_mode(si);
1456       address e = s + size;
1457       if (start > s) {
1458         start = s;
1459       }
1460       if (end < e) {
1461         end = e;
1462       }
1463     }
1464   }
1465   assert(end != NULL, "must have at least one used heap region");
1466   return MemRegion((HeapWord*)start, (HeapWord*)end);
1467 }
1468 
1469 //
1470 // Map the closed and open archive heap objects to the runtime java heap.
1471 //
1472 // The shared objects are mapped at (or close to ) the java heap top in
1473 // closed archive regions. The mapped objects contain no out-going
1474 // references to any other java heap regions. GC does not write into the
1475 // mapped closed archive heap region.
1476 //
1477 // The open archive heap objects are mapped below the shared objects in
1478 // the runtime java heap. The mapped open archive heap data only contains
1479 // references to the shared objects and open archive objects initially.
1480 // During runtime execution, out-going references to any other java heap
1481 // regions may be added. GC may mark and update references in the mapped
1482 // open archive objects.
1483 void FileMapInfo::map_heap_regions_impl() {
1484   if (!HeapShared::is_heap_object_archiving_allowed()) {
1485     log_info(cds)("CDS heap data is being ignored. UseG1GC, "
1486                   "UseCompressedOops and UseCompressedClassPointers are required.");
1487     return;
1488   }
1489 
1490   if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
1491     ShouldNotReachHere(); // CDS should have been disabled.
1492     // The archived objects are mapped at JVM start-up, but we don't know if
1493     // j.l.String or j.l.Class might be replaced by the ClassFileLoadHook,
1494     // which would make the archived String or mirror objects invalid. Let's be safe and not
1495     // use the archived objects. These 2 classes are loaded during the JVMTI "early" stage.
1496     //
1497     // If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects
1498     // in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK
1499     // because we won't install an archived object subgraph if the klass of any of the
1500     // referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph().
1501   }
1502 
1503   MemRegion heap_reserved = Universe::heap()->reserved_region();
1504 
1505   log_info(cds)("CDS archive was created with max heap size = " SIZE_FORMAT "M, and the following configuration:",
1506                 max_heap_size()/M);
1507   log_info(cds)("    narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
1508                 p2i(narrow_klass_base()), narrow_klass_shift());
1509   log_info(cds)("    narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
1510                 narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift());
1511 
1512   log_info(cds)("The current max heap size = " SIZE_FORMAT "M, HeapRegion::GrainBytes = " SIZE_FORMAT,
1513                 heap_reserved.byte_size()/M, HeapRegion::GrainBytes);
1514   log_info(cds)("    narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
1515                 p2i(CompressedKlassPointers::base()), CompressedKlassPointers::shift());
1516   log_info(cds)("    narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
1517                 CompressedOops::mode(), p2i(CompressedOops::base()), CompressedOops::shift());
1518 
1519   if (narrow_klass_base() != CompressedKlassPointers::base() ||
1520       narrow_klass_shift() != CompressedKlassPointers::shift()) {
1521     log_info(cds)("CDS heap data cannot be used because the archive was created with an incompatible narrow klass encoding mode.");
1522     return;
1523   }
1524 
1525   if (narrow_oop_mode() != CompressedOops::mode() ||
1526       narrow_oop_base() != CompressedOops::base() ||
1527       narrow_oop_shift() != CompressedOops::shift()) {
1528     log_info(cds)("CDS heap data need to be relocated because the archive was created with an incompatible oop encoding mode.");
1529     _heap_pointers_need_patching = true;
1530   } else {
1531     MemRegion range = get_heap_regions_range_with_current_oop_encoding_mode();
1532     if (!heap_reserved.contains(range)) {
1533       log_info(cds)("CDS heap data need to be relocated because");
1534       log_info(cds)("the desired range " PTR_FORMAT " - "  PTR_FORMAT, p2i(range.start()), p2i(range.end()));
1535       log_info(cds)("is outside of the heap " PTR_FORMAT " - "  PTR_FORMAT, p2i(heap_reserved.start()), p2i(heap_reserved.end()));
1536       _heap_pointers_need_patching = true;
1537     }
1538   }
1539 
1540   ptrdiff_t delta = 0;
1541   if (_heap_pointers_need_patching) {
1542     //   dumptime heap end  ------------v
1543     //   [      |archived heap regions| ]         runtime heap end ------v
1544     //                                       [   |archived heap regions| ]
1545     //                                  |<-----delta-------------------->|
1546     //
1547     // At dump time, the archived heap regions were near the top of the heap.
1548     // At run time, they may not be inside the heap, so we move them so
1549     // that they are now near the top of the runtime time. This can be done by
1550     // the simple math of adding the delta as shown above.
1551     address dumptime_heap_end = (address)_header->_heap_reserved.end();
1552     address runtime_heap_end = (address)heap_reserved.end();
1553     delta = runtime_heap_end - dumptime_heap_end;
1554   }
1555 
1556   log_info(cds)("CDS heap data relocation delta = " INTX_FORMAT " bytes", delta);
1557   HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());
1558 
1559   CDSFileMapRegion* si = space_at(MetaspaceShared::first_closed_archive_heap_region);
1560   address relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si);
1561   if (!is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes)) {
1562     // Align the bottom of the closed archive heap regions at G1 region boundary.
1563     // This will avoid the situation where the highest open region and the lowest
1564     // closed region sharing the same G1 region. Otherwise we will fail to map the
1565     // open regions.
1566     size_t align = size_t(relocated_closed_heap_region_bottom) % HeapRegion::GrainBytes;
1567     delta -= align;
1568     log_info(cds)("CDS heap data need to be relocated lower by a further " SIZE_FORMAT
1569                   " bytes to " INTX_FORMAT " to be aligned with HeapRegion::GrainBytes",
1570                   align, delta);
1571     HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());
1572     _heap_pointers_need_patching = true;
1573     relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si);
1574   }
1575   assert(is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes),
1576          "must be");
1577 
1578   // Map the closed_archive_heap regions, GC does not write into the regions.
1579   if (map_heap_data(&closed_archive_heap_ranges,
1580                     MetaspaceShared::first_closed_archive_heap_region,
1581                     MetaspaceShared::max_closed_archive_heap_region,
1582                     &num_closed_archive_heap_ranges)) {
1583     HeapShared::set_closed_archive_heap_region_mapped();
1584 
1585     // Now, map open_archive heap regions, GC can write into the regions.
1586     if (map_heap_data(&open_archive_heap_ranges,
1587                       MetaspaceShared::first_open_archive_heap_region,
1588                       MetaspaceShared::max_open_archive_heap_region,
1589                       &num_open_archive_heap_ranges,
1590                       true /* open */)) {
1591       HeapShared::set_open_archive_heap_region_mapped();
1592     }
1593   }
1594 }
1595 
1596 void FileMapInfo::map_heap_regions() {
1597   if (has_heap_regions()) {
1598     map_heap_regions_impl();
1599   }
1600 
1601   if (!HeapShared::closed_archive_heap_region_mapped()) {
1602     assert(closed_archive_heap_ranges == NULL &&
1603            num_closed_archive_heap_ranges == 0, "sanity");
1604   }
1605 
1606   if (!HeapShared::open_archive_heap_region_mapped()) {
1607     assert(open_archive_heap_ranges == NULL && num_open_archive_heap_ranges == 0, "sanity");
1608   }
1609 }
1610 
1611 bool FileMapInfo::map_heap_data(MemRegion **heap_mem, int first,
1612                                 int max, int* num, bool is_open_archive) {
1613   MemRegion * regions = new MemRegion[max];
1614   CDSFileMapRegion* si;
1615   int region_num = 0;
1616 
1617   for (int i = first;
1618            i < first + max; i++) {
1619     si = space_at(i);
1620     size_t size = si->_used;
1621     if (size > 0) {
1622       HeapWord* start = (HeapWord*)start_address_as_decoded_from_archive(si);
1623       regions[region_num] = MemRegion(start, size / HeapWordSize);
1624       region_num ++;
1625       log_info(cds)("Trying to map heap data: region[%d] at " INTPTR_FORMAT ", size = " SIZE_FORMAT_W(8) " bytes",
1626                     i, p2i(start), size);
1627     }
1628   }
1629 
1630   if (region_num == 0) {
1631     return false; // no archived java heap data
1632   }
1633 
1634   // Check that ranges are within the java heap
1635   if (!G1CollectedHeap::heap()->check_archive_addresses(regions, region_num)) {
1636     log_info(cds)("UseSharedSpaces: Unable to allocate region, range is not within java heap.");
1637     return false;
1638   }
1639 
1640   // allocate from java heap
1641   if (!G1CollectedHeap::heap()->alloc_archive_regions(
1642              regions, region_num, is_open_archive)) {
1643     log_info(cds)("UseSharedSpaces: Unable to allocate region, java heap range is already in use.");
1644     return false;
1645   }
1646 
1647   // Map the archived heap data. No need to call MemTracker::record_virtual_memory_type()
1648   // for mapped regions as they are part of the reserved java heap, which is
1649   // already recorded.
1650   for (int i = 0; i < region_num; i++) {
1651     si = space_at(first + i);
1652     char* addr = (char*)regions[i].start();
1653     char* base = os::map_memory(_fd, _full_path, si->_file_offset,
1654                                 addr, regions[i].byte_size(), si->_read_only,
1655                                 si->_allow_exec);
1656     if (base == NULL || base != addr) {
1657       // dealloc the regions from java heap
1658       dealloc_archive_heap_regions(regions, region_num, is_open_archive);
1659       log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap. "
1660                     INTPTR_FORMAT ", size = " SIZE_FORMAT " bytes",
1661                     p2i(addr), regions[i].byte_size());
1662       return false;
1663     }
1664 
1665     if (VerifySharedSpaces && !region_crc_check(addr, regions[i].byte_size(), si->_crc)) {
1666       // dealloc the regions from java heap
1667       dealloc_archive_heap_regions(regions, region_num, is_open_archive);
1668       log_info(cds)("UseSharedSpaces: mapped heap regions are corrupt");
1669       return false;
1670     }
1671   }
1672 
1673   // the shared heap data is mapped successfully
1674   *heap_mem = regions;
1675   *num = region_num;
1676   return true;
1677 }
1678 
1679 void FileMapInfo::patch_archived_heap_embedded_pointers() {
1680   if (!_heap_pointers_need_patching) {
1681     return;
1682   }
1683 
1684   patch_archived_heap_embedded_pointers(closed_archive_heap_ranges,
1685                                         num_closed_archive_heap_ranges,
1686                                         MetaspaceShared::first_closed_archive_heap_region);
1687 
1688   patch_archived_heap_embedded_pointers(open_archive_heap_ranges,
1689                                         num_open_archive_heap_ranges,
1690                                         MetaspaceShared::first_open_archive_heap_region);
1691 }
1692 
1693 void FileMapInfo::patch_archived_heap_embedded_pointers(MemRegion* ranges, int num_ranges,
1694                                                         int first_region_idx) {
1695   for (int i=0; i<num_ranges; i++) {
1696     CDSFileMapRegion* si = space_at(i + first_region_idx);
1697     HeapShared::patch_archived_heap_embedded_pointers(ranges[i], (address)si->_oopmap,
1698                                                       si->_oopmap_size_in_bits);
1699   }
1700 }
1701 
1702 // This internally allocates objects using SystemDictionary::Object_klass(), so it
1703 // must be called after the well-known classes are resolved.
1704 void FileMapInfo::fixup_mapped_heap_regions() {
1705   // If any closed regions were found, call the fill routine to make them parseable.
1706   // Note that closed_archive_heap_ranges may be non-NULL even if no ranges were found.
1707   if (num_closed_archive_heap_ranges != 0) {
1708     assert(closed_archive_heap_ranges != NULL,
1709            "Null closed_archive_heap_ranges array with non-zero count");
1710     G1CollectedHeap::heap()->fill_archive_regions(closed_archive_heap_ranges,
1711                                                   num_closed_archive_heap_ranges);
1712   }
1713 
1714   // do the same for mapped open archive heap regions
1715   if (num_open_archive_heap_ranges != 0) {
1716     assert(open_archive_heap_ranges != NULL, "NULL open_archive_heap_ranges array with non-zero count");
1717     G1CollectedHeap::heap()->fill_archive_regions(open_archive_heap_ranges,
1718                                                   num_open_archive_heap_ranges);
1719   }
1720 }
1721 
1722 // dealloc the archive regions from java heap
1723 void FileMapInfo::dealloc_archive_heap_regions(MemRegion* regions, int num, bool is_open) {
1724   if (num > 0) {
1725     assert(regions != NULL, "Null archive ranges array with non-zero count");
1726     G1CollectedHeap::heap()->dealloc_archive_regions(regions, num, is_open);
1727   }
1728 }
1729 #endif // INCLUDE_CDS_JAVA_HEAP
1730 
1731 bool FileMapInfo::region_crc_check(char* buf, size_t size, int expected_crc) {
1732   int crc = ClassLoader::crc32(0, buf, (jint)size);
1733   if (crc != expected_crc) {
1734     fail_continue("Checksum verification failed.");
1735     return false;
1736   }
1737   return true;
1738 }
1739 
1740 bool FileMapInfo::verify_region_checksum(int i) {
1741   assert(VerifySharedSpaces, "sanity");
1742 
1743   size_t sz = space_at(i)->_used;
1744 
1745   if (sz == 0) {
1746     return true; // no data
1747   }
1748 
1749   return region_crc_check(region_addr(i), sz, space_at(i)->_crc);
1750 }
1751 
1752 void FileMapInfo::unmap_regions(int regions[], char* saved_base[], size_t len) {
1753   for (int i = 0; i < (int)len; i++) {
1754     if (saved_base[i] != NULL) {
1755       unmap_region(regions[i]);
1756     }
1757   }
1758 }
1759 
1760 // Unmap a memory region in the address space.
1761 
1762 void FileMapInfo::unmap_region(int i) {
1763   assert(!HeapShared::is_heap_region(i), "sanity");
1764   CDSFileMapRegion* si = space_at(i);
1765   size_t used = si->_used;
1766   size_t size = align_up(used, os::vm_allocation_granularity());
1767 
1768   if (used == 0) {
1769     return;
1770   }
1771 
1772   char* addr = region_addr(i);
1773   if (!os::unmap_memory(addr, size)) {
1774     fail_stop("Unable to unmap shared space.");
1775   }
1776 }
1777 
1778 void FileMapInfo::assert_mark(bool check) {
1779   if (!check) {
1780     fail_stop("Mark mismatch while restoring from shared file.");
1781   }
1782 }
1783 
1784 void FileMapInfo::metaspace_pointers_do(MetaspaceClosure* it) {
1785   _shared_path_table.metaspace_pointers_do(it);
1786 }
1787 
1788 FileMapInfo* FileMapInfo::_current_info = NULL;
1789 FileMapInfo* FileMapInfo::_dynamic_archive_info = NULL;
1790 bool FileMapInfo::_heap_pointers_need_patching = false;
1791 SharedPathTable FileMapInfo::_shared_path_table;
1792 bool FileMapInfo::_validating_shared_path_table = false;
1793 bool FileMapInfo::_memory_mapping_failed = false;
1794 GrowableArray<const char*>* FileMapInfo::_non_existent_class_paths = NULL;
1795 
1796 // Open the shared archive file, read and validate the header
1797 // information (version, boot classpath, etc.).  If initialization
1798 // fails, shared spaces are disabled and the file is closed. [See
1799 // fail_continue.]
1800 //
1801 // Validation of the archive is done in two steps:
1802 //
1803 // [1] validate_header() - done here.
1804 // [2] validate_shared_path_table - this is done later, because the table is in the RW
1805 //     region of the archive, which is not mapped yet.
1806 bool FileMapInfo::initialize(bool is_static) {
1807   assert(UseSharedSpaces, "UseSharedSpaces expected.");
1808 
1809   if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
1810     // CDS assumes that no classes resolved in SystemDictionary::resolve_well_known_classes
1811     // are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved
1812     // during the JVMTI "early" stage, so we can still use CDS if
1813     // JvmtiExport::has_early_class_hook_env() is false.
1814     FileMapInfo::fail_continue("CDS is disabled because early JVMTI ClassFileLoadHook is in use.");
1815     return false;
1816   }
1817 
1818   if (!open_for_read()) {
1819     return false;
1820   }
1821 
1822   init_from_file(_fd, is_static);
1823   // UseSharedSpaces could be disabled if the checking of some of the header fields in
1824   // init_from_file has failed.
1825   if (!UseSharedSpaces || !validate_header(is_static)) {
1826     return false;
1827   }
1828   return true;
1829 }
1830 
1831 char* FileMapInfo::region_addr(int idx) {
1832   CDSFileMapRegion* si = space_at(idx);
1833   if (HeapShared::is_heap_region(idx)) {
1834     assert(DumpSharedSpaces, "The following doesn't work at runtime");
1835     return si->_used > 0 ?
1836           (char*)start_address_as_decoded_with_current_oop_encoding_mode(si) : NULL;
1837   } else {
1838     return si->_addr._base;
1839   }
1840 }
1841 
1842 int FileMapHeader::compute_crc() {
1843   char* start = (char*)this;
1844   // start computing from the field after _crc
1845   char* buf = (char*)&_crc + sizeof(_crc);
1846   size_t sz = _header_size - (buf - start);
1847   int crc = ClassLoader::crc32(0, buf, (jint)sz);
1848   return crc;
1849 }
1850 
1851 // This function should only be called during run time with UseSharedSpaces enabled.
1852 bool FileMapHeader::validate() {
1853 
1854   if (_obj_alignment != ObjectAlignmentInBytes) {
1855     FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"
1856                   " does not equal the current ObjectAlignmentInBytes of " INTX_FORMAT ".",
1857                   _obj_alignment, ObjectAlignmentInBytes);
1858     return false;
1859   }
1860   if (_compact_strings != CompactStrings) {
1861     FileMapInfo::fail_continue("The shared archive file's CompactStrings setting (%s)"
1862                   " does not equal the current CompactStrings setting (%s).",
1863                   _compact_strings ? "enabled" : "disabled",
1864                   CompactStrings   ? "enabled" : "disabled");
1865     return false;
1866   }
1867 
1868   // This must be done after header validation because it might change the
1869   // header data
1870   const char* prop = Arguments::get_property("java.system.class.loader");
1871   if (prop != NULL) {
1872     warning("Archived non-system classes are disabled because the "
1873             "java.system.class.loader property is specified (value = \"%s\"). "
1874             "To use archived non-system classes, this property must not be set", prop);
1875     _has_platform_or_app_classes = false;
1876   }
1877 
1878   // For backwards compatibility, we don't check the verification setting
1879   // if the archive only contains system classes.
1880   if (_has_platform_or_app_classes &&
1881       ((!_verify_local && BytecodeVerificationLocal) ||
1882        (!_verify_remote && BytecodeVerificationRemote))) {
1883     FileMapInfo::fail_continue("The shared archive file was created with less restrictive "
1884                   "verification setting than the current setting.");
1885     return false;
1886   }
1887 
1888   // Java agents are allowed during run time. Therefore, the following condition is not
1889   // checked: (!_allow_archiving_with_java_agent && AllowArchivingWithJavaAgent)
1890   // Note: _allow_archiving_with_java_agent is set in the shared archive during dump time
1891   // while AllowArchivingWithJavaAgent is set during the current run.
1892   if (_allow_archiving_with_java_agent && !AllowArchivingWithJavaAgent) {
1893     FileMapInfo::fail_continue("The setting of the AllowArchivingWithJavaAgent is different "
1894                                "from the setting in the shared archive.");
1895     return false;
1896   }
1897 
1898   if (_allow_archiving_with_java_agent) {
1899     warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1900             "for testing purposes only and should not be used in a production environment");
1901   }
1902 
1903   return true;
1904 }
1905 
1906 bool FileMapInfo::validate_header(bool is_static) {
1907   return _header->validate();
1908 }
1909 
1910 // Check if a given address is within one of the shared regions
1911 bool FileMapInfo::is_in_shared_region(const void* p, int idx) {
1912   assert(idx == MetaspaceShared::ro ||
1913          idx == MetaspaceShared::rw ||
1914          idx == MetaspaceShared::mc ||
1915          idx == MetaspaceShared::md, "invalid region index");
1916   char* base = region_addr(idx);
1917   if (p >= base && p < base + space_at(idx)->_used) {
1918     return true;
1919   }
1920   return false;
1921 }
1922 
1923 // Unmap mapped regions of shared space.
1924 void FileMapInfo::stop_sharing_and_unmap(const char* msg) {
1925   MetaspaceShared::set_shared_metaspace_range(NULL, NULL);
1926 
1927   FileMapInfo *map_info = FileMapInfo::current_info();
1928   if (map_info) {
1929     map_info->fail_continue("%s", msg);
1930     for (int i = 0; i < MetaspaceShared::num_non_heap_spaces; i++) {
1931       if (!HeapShared::is_heap_region(i)) {
1932         char *addr = map_info->region_addr(i);
1933         if (addr != NULL) {
1934           map_info->unmap_region(i);
1935           map_info->space_at(i)->_addr._base = NULL;
1936         }
1937       }
1938     }
1939     // Dealloc the archive heap regions only without unmapping. The regions are part
1940     // of the java heap. Unmapping of the heap regions are managed by GC.
1941     map_info->dealloc_archive_heap_regions(open_archive_heap_ranges,
1942                                            num_open_archive_heap_ranges,
1943                                            true);
1944     map_info->dealloc_archive_heap_regions(closed_archive_heap_ranges,
1945                                            num_closed_archive_heap_ranges,
1946                                            false);
1947   } else if (DumpSharedSpaces) {
1948     fail_stop("%s", msg);
1949   }
1950 }
1951 
1952 #if INCLUDE_JVMTI
1953 ClassPathEntry** FileMapInfo::_classpath_entries_for_jvmti = NULL;
1954 
1955 ClassPathEntry* FileMapInfo::get_classpath_entry_for_jvmti(int i, TRAPS) {
1956   ClassPathEntry* ent = _classpath_entries_for_jvmti[i];
1957   if (ent == NULL) {
1958     if (i == 0) {
1959       ent = ClassLoader::get_jrt_entry();
1960       assert(ent != NULL, "must be");
1961     } else {
1962       SharedClassPathEntry* scpe = shared_path(i);
1963       assert(scpe->is_jar(), "must be"); // other types of scpe will not produce archived classes
1964 
1965       const char* path = scpe->name();
1966       struct stat st;
1967       if (os::stat(path, &st) != 0) {
1968         char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128); ;
1969         jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
1970         THROW_MSG_(vmSymbols::java_io_IOException(), msg, NULL);
1971       } else {
1972         ent = ClassLoader::create_class_path_entry(path, &st, /*throw_exception=*/true, false, false, CHECK_NULL);
1973       }
1974     }
1975 
1976     MutexLocker mu(CDSClassFileStream_lock, THREAD);
1977     if (_classpath_entries_for_jvmti[i] == NULL) {
1978       _classpath_entries_for_jvmti[i] = ent;
1979     } else {
1980       // Another thread has beat me to creating this entry
1981       delete ent;
1982       ent = _classpath_entries_for_jvmti[i];
1983     }
1984   }
1985 
1986   return ent;
1987 }
1988 
1989 ClassFileStream* FileMapInfo::open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS) {
1990   int path_index = ik->shared_classpath_index();
1991   assert(path_index >= 0, "should be called for shared built-in classes only");
1992   assert(path_index < (int)get_number_of_shared_paths(), "sanity");
1993 
1994   ClassPathEntry* cpe = get_classpath_entry_for_jvmti(path_index, CHECK_NULL);
1995   assert(cpe != NULL, "must be");
1996 
1997   Symbol* name = ik->name();
1998   const char* const class_name = name->as_C_string();
1999   const char* const file_name = ClassLoader::file_name_for_class_name(class_name,
2000                                                                       name->utf8_length());
2001   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
2002   ClassFileStream* cfs = cpe->open_stream_for_loader(file_name, loader_data, THREAD);
2003   assert(cfs != NULL, "must be able to read the classfile data of shared classes for built-in loaders.");
2004   log_debug(cds, jvmti)("classfile data for %s [%d: %s] = %d bytes", class_name, path_index,
2005                         cfs->source(), cfs->length());
2006   return cfs;
2007 }
2008 
2009 #endif