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->set_header_size(header_size);
 196   _header->set_version(INVALID_CDS_ARCHIVE_VERSION);
 197   _header->set_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_end = CompressedOops::end();
 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   Arguments::assert_is_dumping_archive();
 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   Arguments::assert_is_dumping_archive();
 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   Arguments::assert_is_dumping_archive();
 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         log_error(cds)("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   Arguments::assert_is_dumping_archive();
 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   Arguments::assert_is_dumping_archive();
 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()->set_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   const char* actual_ident = header()->jvm_ident();
 991 
 992   if (actual_ident[JVM_IDENT_MAX-1] != 0) {
 993     FileMapInfo::fail_continue("JVM version identifier is corrupted.");
 994     return false;
 995   }
 996 
 997   char expected_ident[JVM_IDENT_MAX];
 998   get_header_version(expected_ident);
 999   if (strncmp(actual_ident, expected_ident, JVM_IDENT_MAX-1) != 0) {
1000     log_info(cds)("_jvm_ident expected: %s", expected_ident);
1001     log_info(cds)("             actual: %s", actual_ident);
1002     FileMapInfo::fail_continue("The shared archive file was created by a different"
1003                   " version or build of HotSpot");
1004     return false;
1005   }
1006 
1007   if (VerifySharedSpaces) {
1008     int expected_crc = header()->compute_crc();
1009     if (expected_crc != header()->crc()) {
1010       log_info(cds)("_crc expected: %d", expected_crc);
1011       log_info(cds)("       actual: %d", header()->crc());
1012       FileMapInfo::fail_continue("Header checksum verification failed.");
1013       return false;
1014     }
1015   }
1016 
1017   _file_offset = n + header()->base_archive_name_size(); // accounts for the size of _base_archive_name
1018 
1019   if (is_static) {
1020     // just checking the last region is sufficient since the archive is written
1021     // in sequential order
1022     size_t len = lseek(fd, 0, SEEK_END);
1023     FileMapRegion* si = space_at(MetaspaceShared::last_valid_region);
1024     // The last space might be empty
1025     if (si->file_offset() > len || len - si->file_offset() < si->used()) {
1026       fail_continue("The shared archive file has been truncated.");
1027       return false;
1028     }
1029 
1030     SharedBaseAddress = header()->shared_base_address();
1031   }
1032 
1033   return true;
1034 }
1035 
1036 void FileMapInfo::seek_to_position(size_t pos) {
1037   if (lseek(_fd, (long)pos, SEEK_SET) < 0) {
1038     fail_stop("Unable to seek to position " SIZE_FORMAT, pos);
1039   }
1040 }
1041 
1042 // Read the FileMapInfo information from the file.
1043 bool FileMapInfo::open_for_read(const char* path) {
1044   if (_file_open) {
1045     return true;
1046   }
1047   if (path == NULL) {
1048     _full_path = Arguments::GetSharedArchivePath();
1049   } else {
1050     _full_path = path;
1051   }
1052   int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0);
1053   if (fd < 0) {
1054     if (errno == ENOENT) {
1055       // Not locating the shared archive is ok.
1056       fail_continue("Specified shared archive not found (%s).", _full_path);
1057     } else {
1058       fail_continue("Failed to open shared archive file (%s).",
1059                     os::strerror(errno));
1060     }
1061     return false;
1062   }
1063 
1064   _fd = fd;
1065   _file_open = true;
1066   return true;
1067 }
1068 
1069 // Write the FileMapInfo information to the file.
1070 
1071 void FileMapInfo::open_for_write(const char* path) {
1072   if (path == NULL) {
1073     _full_path = Arguments::GetSharedArchivePath();
1074   } else {
1075     _full_path = path;
1076   }
1077   LogMessage(cds) msg;
1078   if (msg.is_info()) {
1079     msg.info("Dumping shared data to file: ");
1080     msg.info("   %s", _full_path);
1081   }
1082 
1083 #ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
1084     chmod(_full_path, _S_IREAD | _S_IWRITE);
1085 #endif
1086 
1087   // Use remove() to delete the existing file because, on Unix, this will
1088   // allow processes that have it open continued access to the file.
1089   remove(_full_path);
1090   int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
1091   if (fd < 0) {
1092     fail_stop("Unable to create shared archive file %s: (%s).", _full_path,
1093               os::strerror(errno));
1094   }
1095   _fd = fd;
1096   _file_open = true;
1097 
1098   // Seek past the header. We will write the header after all regions are written
1099   // and their CRCs computed.
1100   size_t header_bytes = header()->header_size();
1101   if (header()->magic() == CDS_DYNAMIC_ARCHIVE_MAGIC) {
1102     header_bytes += strlen(Arguments::GetSharedArchivePath()) + 1;
1103   }
1104 
1105   header_bytes = align_up(header_bytes, os::vm_allocation_granularity());
1106   _file_offset = header_bytes;
1107   seek_to_position(_file_offset);
1108 }
1109 
1110 
1111 // Write the header to the file, seek to the next allocation boundary.
1112 
1113 void FileMapInfo::write_header() {
1114   _file_offset = 0;
1115   seek_to_position(_file_offset);
1116   char* base_archive_name = NULL;
1117   if (header()->magic() == CDS_DYNAMIC_ARCHIVE_MAGIC) {
1118     base_archive_name = (char*)Arguments::GetSharedArchivePath();
1119     header()->set_base_archive_name_size(strlen(base_archive_name) + 1);
1120     header()->set_base_archive_is_default(FLAG_IS_DEFAULT(SharedArchiveFile));
1121   }
1122 
1123   assert(is_file_position_aligned(), "must be");
1124   write_bytes(header(), header()->header_size());
1125   if (base_archive_name != NULL) {
1126     write_bytes(base_archive_name, header()->base_archive_name_size());
1127   }
1128 }
1129 
1130 void FileMapRegion::init(bool is_heap_region, char* base, size_t size, bool read_only,
1131                          bool allow_exec, int crc) {
1132   _is_heap_region = is_heap_region;
1133 
1134   if (is_heap_region) {
1135     assert(!DynamicDumpSharedSpaces, "must be");
1136     assert((base - (char*)CompressedKlassPointers::base()) % HeapWordSize == 0, "Sanity");
1137     if (base != NULL) {
1138       _addr._offset = (intx)CompressedOops::encode_not_null((oop)base);
1139     } else {
1140       _addr._offset = 0;
1141     }
1142   } else {
1143     _addr._base = base;
1144   }
1145   _used = size;
1146   _read_only = read_only;
1147   _allow_exec = allow_exec;
1148   _crc = crc;
1149 }
1150 
1151 void FileMapInfo::write_region(int region, char* base, size_t size,
1152                                bool read_only, bool allow_exec) {
1153   Arguments::assert_is_dumping_archive();
1154 
1155   FileMapRegion* si = space_at(region);
1156   char* target_base = base;
1157   if (DynamicDumpSharedSpaces) {
1158     assert(!HeapShared::is_heap_region(region), "dynamic archive doesn't support heap regions");
1159     target_base = DynamicArchive::buffer_to_target(base);
1160   }
1161 
1162   si->set_file_offset(_file_offset);
1163   log_info(cds)("Shared file region %d: " SIZE_FORMAT_HEX_W(08)
1164                 " bytes, addr " INTPTR_FORMAT " file offset " SIZE_FORMAT_HEX_W(08),
1165                 region, size, p2i(target_base), _file_offset);
1166 
1167   int crc = ClassLoader::crc32(0, base, (jint)size);
1168   si->init(HeapShared::is_heap_region(region), target_base, size, read_only, allow_exec, crc);
1169 
1170   if (base != NULL) {
1171     write_bytes_aligned(base, size);
1172   }
1173 }
1174 
1175 // Write out the given archive heap memory regions.  GC code combines multiple
1176 // consecutive archive GC regions into one MemRegion whenever possible and
1177 // produces the 'heap_mem' array.
1178 //
1179 // If the archive heap memory size is smaller than a single dump time GC region
1180 // size, there is only one MemRegion in the array.
1181 //
1182 // If the archive heap memory size is bigger than one dump time GC region size,
1183 // the 'heap_mem' array may contain more than one consolidated MemRegions. When
1184 // the first/bottom archive GC region is a partial GC region (with the empty
1185 // portion at the higher address within the region), one MemRegion is used for
1186 // the bottom partial archive GC region. The rest of the consecutive archive
1187 // GC regions are combined into another MemRegion.
1188 //
1189 // Here's the mapping from (archive heap GC regions) -> (GrowableArray<MemRegion> *regions).
1190 //   + We have 1 or more archive heap regions: ah0, ah1, ah2 ..... ahn
1191 //   + We have 1 or 2 consolidated heap memory regions: r0 and r1
1192 //
1193 // If there's a single archive GC region (ah0), then r0 == ah0, and r1 is empty.
1194 // Otherwise:
1195 //
1196 // "X" represented space that's occupied by heap objects.
1197 // "_" represented unused spaced in the heap region.
1198 //
1199 //
1200 //    |ah0       | ah1 | ah2| ...... | ahn|
1201 //    |XXXXXX|__ |XXXXX|XXXX|XXXXXXXX|XXXX|
1202 //    |<-r0->|   |<- r1 ----------------->|
1203 //            ^^^
1204 //             |
1205 //             +-- gap
1206 size_t FileMapInfo::write_archive_heap_regions(GrowableArray<MemRegion> *heap_mem,
1207                                                GrowableArray<ArchiveHeapOopmapInfo> *oopmaps,
1208                                                int first_region_id, int max_num_regions) {
1209   assert(max_num_regions <= 2, "Only support maximum 2 memory regions");
1210 
1211   int arr_len = heap_mem == NULL ? 0 : heap_mem->length();
1212   if(arr_len > max_num_regions) {
1213     fail_stop("Unable to write archive heap memory regions: "
1214               "number of memory regions exceeds maximum due to fragmentation. "
1215               "Please increase java heap size "
1216               "(current MaxHeapSize is " SIZE_FORMAT ", InitialHeapSize is " SIZE_FORMAT ").",
1217               MaxHeapSize, InitialHeapSize);
1218   }
1219 
1220   size_t total_size = 0;
1221   for (int i = first_region_id, arr_idx = 0;
1222            i < first_region_id + max_num_regions;
1223            i++, arr_idx++) {
1224     char* start = NULL;
1225     size_t size = 0;
1226     if (arr_idx < arr_len) {
1227       start = (char*)heap_mem->at(arr_idx).start();
1228       size = heap_mem->at(arr_idx).byte_size();
1229       total_size += size;
1230     }
1231 
1232     log_info(cds)("Archive heap region %d " INTPTR_FORMAT " - " INTPTR_FORMAT " = " SIZE_FORMAT_W(8) " bytes",
1233                   i, p2i(start), p2i(start + size), size);
1234     write_region(i, start, size, false, false);
1235     if (size > 0) {
1236       space_at(i)->init_oopmap(oopmaps->at(arr_idx)._oopmap,
1237                                oopmaps->at(arr_idx)._oopmap_size_in_bits);
1238     }
1239   }
1240   return total_size;
1241 }
1242 
1243 // Dump bytes to file -- at the current file position.
1244 
1245 void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) {
1246   assert(_file_open, "must be");
1247   size_t n = os::write(_fd, buffer, (unsigned int)nbytes);
1248   if (n != nbytes) {
1249     // If the shared archive is corrupted, close it and remove it.
1250     close();
1251     remove(_full_path);
1252     fail_stop("Unable to write to shared archive file.");
1253   }
1254   _file_offset += nbytes;
1255 }
1256 
1257 bool FileMapInfo::is_file_position_aligned() const {
1258   return _file_offset == align_up(_file_offset,
1259                                   os::vm_allocation_granularity());
1260 }
1261 
1262 // Align file position to an allocation unit boundary.
1263 
1264 void FileMapInfo::align_file_position() {
1265   assert(_file_open, "must be");
1266   size_t new_file_offset = align_up(_file_offset,
1267                                     os::vm_allocation_granularity());
1268   if (new_file_offset != _file_offset) {
1269     _file_offset = new_file_offset;
1270     // Seek one byte back from the target and write a byte to insure
1271     // that the written file is the correct length.
1272     _file_offset -= 1;
1273     seek_to_position(_file_offset);
1274     char zero = 0;
1275     write_bytes(&zero, 1);
1276   }
1277 }
1278 
1279 
1280 // Dump bytes to file -- at the current file position.
1281 
1282 void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) {
1283   align_file_position();
1284   write_bytes(buffer, nbytes);
1285   align_file_position();
1286 }
1287 
1288 
1289 // Close the shared archive file.  This does NOT unmap mapped regions.
1290 
1291 void FileMapInfo::close() {
1292   if (_file_open) {
1293     if (::close(_fd) < 0) {
1294       fail_stop("Unable to close the shared archive file.");
1295     }
1296     _file_open = false;
1297     _fd = -1;
1298   }
1299 }
1300 
1301 
1302 // JVM/TI RedefineClasses() support:
1303 // Remap the shared readonly space to shared readwrite, private.
1304 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
1305   int idx = MetaspaceShared::ro;
1306   FileMapRegion* si = space_at(idx);
1307   if (!si->read_only()) {
1308     // the space is already readwrite so we are done
1309     return true;
1310   }
1311   size_t used = si->used();
1312   size_t size = align_up(used, os::vm_allocation_granularity());
1313   if (!open_for_read()) {
1314     return false;
1315   }
1316   char *addr = region_addr(idx);
1317   char *base = os::remap_memory(_fd, _full_path, si->file_offset(),
1318                                 addr, size, false /* !read_only */,
1319                                 si->allow_exec());
1320   close();
1321   // These have to be errors because the shared region is now unmapped.
1322   if (base == NULL) {
1323     log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);
1324     vm_exit(1);
1325   }
1326   if (base != addr) {
1327     log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);
1328     vm_exit(1);
1329   }
1330   si->set_read_only(false);
1331   return true;
1332 }
1333 
1334 // Map the whole region at once, assumed to be allocated contiguously.
1335 ReservedSpace FileMapInfo::reserve_shared_memory() {
1336   char* requested_addr = region_addr(0);
1337   size_t size = FileMapInfo::core_spaces_size();
1338 
1339   // Reserve the space first, then map otherwise map will go right over some
1340   // other reserved memory (like the code cache).
1341   ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr);
1342   if (!rs.is_reserved()) {
1343     fail_continue("Unable to reserve shared space at required address "
1344                   INTPTR_FORMAT, p2i(requested_addr));
1345     return rs;
1346   }
1347   // the reserved virtual memory is for mapping class data sharing archive
1348   MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared);
1349 
1350   return rs;
1351 }
1352 
1353 // Memory map a region in the address space.
1354 static const char* shared_region_name[] = { "MiscData", "ReadWrite", "ReadOnly", "MiscCode",
1355                                             "String1", "String2", "OpenArchive1", "OpenArchive2" };
1356 
1357 char* FileMapInfo::map_regions(int regions[], char* saved_base[], size_t len) {
1358   char* prev_top = NULL;
1359   char* curr_base;
1360   char* curr_top;
1361   int i = 0;
1362   for (i = 0; i < (int)len; i++) {
1363     curr_base = map_region(regions[i], &curr_top);
1364     if (curr_base == NULL) {
1365       return NULL;
1366     }
1367     if (i > 0) {
1368       // We require that mc->rw->ro->md to be laid out consecutively, with no
1369       // gaps between them. That way, we can ensure that the OS won't be able to
1370       // allocate any new memory spaces inside _shared_metaspace_{base,top}, which
1371       // would mess up the simple comparision in MetaspaceShared::is_in_shared_metaspace().
1372       assert(curr_base == prev_top, "must be");
1373     }
1374     log_info(cds)("Mapped region #%d at base %p top %p", regions[i], curr_base, curr_top);
1375     saved_base[i] = curr_base;
1376     prev_top = curr_top;
1377   }
1378   return curr_top;
1379 }
1380 
1381 char* FileMapInfo::map_region(int i, char** top_ret) {
1382   assert(!HeapShared::is_heap_region(i), "sanity");
1383   FileMapRegion* si = space_at(i);
1384   size_t used = si->used();
1385   size_t alignment = os::vm_allocation_granularity();
1386   size_t size = align_up(used, alignment);
1387   char *requested_addr = region_addr(i);
1388 
1389 #ifdef _WINDOWS
1390   // Windows cannot remap read-only shared memory to read-write when required for
1391   // RedefineClasses, which is also used by JFR.  Always map windows regions as RW.
1392   si->set_read_only(false);
1393 #else
1394   // If a tool agent is in use (debugging enabled), or JFR, we must map the address space RW
1395   if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space() ||
1396       Arguments::has_jfr_option()) {
1397     si->set_read_only(false);
1398   }
1399 #endif // _WINDOWS
1400 
1401   // map the contents of the CDS archive in this memory
1402   char *base = os::map_memory(_fd, _full_path, si->file_offset(),
1403                               requested_addr, size, si->read_only(),
1404                               si->allow_exec());
1405   if (base == NULL || base != requested_addr) {
1406     fail_continue("Unable to map %s shared space at required address.", shared_region_name[i]);
1407     _memory_mapping_failed = true;
1408     return NULL;
1409   }
1410 #ifdef _WINDOWS
1411   // This call is Windows-only because the memory_type gets recorded for the other platforms
1412   // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows.
1413   MemTracker::record_virtual_memory_type((address)base, mtClassShared);
1414 #endif
1415 
1416   if (VerifySharedSpaces && !verify_region_checksum(i)) {
1417     return NULL;
1418   }
1419 
1420   *top_ret = base + size;
1421   return base;
1422 }
1423 
1424 size_t FileMapInfo::read_bytes(void* buffer, size_t count) {
1425   assert(_file_open, "Archive file is not open");
1426   size_t n = os::read(_fd, buffer, (unsigned int)count);
1427   if (n != count) {
1428     // Close the file if there's a problem reading it.
1429     close();
1430     return 0;
1431   }
1432   _file_offset += count;
1433   return count;
1434 }
1435 
1436 address FileMapInfo::decode_start_address(FileMapRegion* spc, bool with_current_oop_encoding_mode) {
1437   if (with_current_oop_encoding_mode) {
1438     return (address)CompressedOops::decode_not_null(spc->offset());
1439   } else {
1440     return (address)HeapShared::decode_from_archive(spc->offset());
1441   }
1442 }
1443 
1444 static MemRegion *closed_archive_heap_ranges = NULL;
1445 static MemRegion *open_archive_heap_ranges = NULL;
1446 static int num_closed_archive_heap_ranges = 0;
1447 static int num_open_archive_heap_ranges = 0;
1448 
1449 #if INCLUDE_CDS_JAVA_HEAP
1450 bool FileMapInfo::has_heap_regions() {
1451   return (space_at(MetaspaceShared::first_closed_archive_heap_region)->used() > 0);
1452 }
1453 
1454 // Returns the address range of the archived heap regions computed using the
1455 // current oop encoding mode. This range may be different than the one seen at
1456 // dump time due to encoding mode differences. The result is used in determining
1457 // if/how these regions should be relocated at run time.
1458 MemRegion FileMapInfo::get_heap_regions_range_with_current_oop_encoding_mode() {
1459   address start = (address) max_uintx;
1460   address end   = NULL;
1461 
1462   for (int i = MetaspaceShared::first_closed_archive_heap_region;
1463            i <= MetaspaceShared::last_valid_region;
1464            i++) {
1465     FileMapRegion* si = space_at(i);
1466     size_t size = si->used();
1467     if (size > 0) {
1468       address s = start_address_as_decoded_with_current_oop_encoding_mode(si);
1469       address e = s + size;
1470       if (start > s) {
1471         start = s;
1472       }
1473       if (end < e) {
1474         end = e;
1475       }
1476     }
1477   }
1478   assert(end != NULL, "must have at least one used heap region");
1479   return MemRegion((HeapWord*)start, (HeapWord*)end);
1480 }
1481 
1482 //
1483 // Map the closed and open archive heap objects to the runtime java heap.
1484 //
1485 // The shared objects are mapped at (or close to ) the java heap top in
1486 // closed archive regions. The mapped objects contain no out-going
1487 // references to any other java heap regions. GC does not write into the
1488 // mapped closed archive heap region.
1489 //
1490 // The open archive heap objects are mapped below the shared objects in
1491 // the runtime java heap. The mapped open archive heap data only contains
1492 // references to the shared objects and open archive objects initially.
1493 // During runtime execution, out-going references to any other java heap
1494 // regions may be added. GC may mark and update references in the mapped
1495 // open archive objects.
1496 void FileMapInfo::map_heap_regions_impl() {
1497   if (!HeapShared::is_heap_object_archiving_allowed()) {
1498     log_info(cds)("CDS heap data is being ignored. UseG1GC, "
1499                   "UseCompressedOops and UseCompressedClassPointers are required.");
1500     return;
1501   }
1502 
1503   if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
1504     ShouldNotReachHere(); // CDS should have been disabled.
1505     // The archived objects are mapped at JVM start-up, but we don't know if
1506     // j.l.String or j.l.Class might be replaced by the ClassFileLoadHook,
1507     // which would make the archived String or mirror objects invalid. Let's be safe and not
1508     // use the archived objects. These 2 classes are loaded during the JVMTI "early" stage.
1509     //
1510     // If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects
1511     // in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK
1512     // because we won't install an archived object subgraph if the klass of any of the
1513     // referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph().
1514   }
1515 
1516   log_info(cds)("CDS archive was created with max heap size = " SIZE_FORMAT "M, and the following configuration:",
1517                 max_heap_size()/M);
1518   log_info(cds)("    narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
1519                 p2i(narrow_klass_base()), narrow_klass_shift());
1520   log_info(cds)("    narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
1521                 narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift());
1522 
1523   log_info(cds)("The current max heap size = " SIZE_FORMAT "M, HeapRegion::GrainBytes = " SIZE_FORMAT,
1524                 MaxHeapSize/M, HeapRegion::GrainBytes);
1525   log_info(cds)("    narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
1526                 p2i(CompressedKlassPointers::base()), CompressedKlassPointers::shift());
1527   log_info(cds)("    narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
1528                 CompressedOops::mode(), p2i(CompressedOops::base()), CompressedOops::shift());
1529 
1530   if (narrow_klass_base() != CompressedKlassPointers::base() ||
1531       narrow_klass_shift() != CompressedKlassPointers::shift()) {
1532     log_info(cds)("CDS heap data cannot be used because the archive was created with an incompatible narrow klass encoding mode.");
1533     return;
1534   }
1535 
1536   if (narrow_oop_mode() != CompressedOops::mode() ||
1537       narrow_oop_base() != CompressedOops::base() ||
1538       narrow_oop_shift() != CompressedOops::shift()) {
1539     log_info(cds)("CDS heap data need to be relocated because the archive was created with an incompatible oop encoding mode.");
1540     _heap_pointers_need_patching = true;
1541   } else {
1542     MemRegion range = get_heap_regions_range_with_current_oop_encoding_mode();
1543     if (!CompressedOops::is_in(range)) {
1544       log_info(cds)("CDS heap data need to be relocated because");
1545       log_info(cds)("the desired range " PTR_FORMAT " - "  PTR_FORMAT, p2i(range.start()), p2i(range.end()));
1546       log_info(cds)("is outside of the heap " PTR_FORMAT " - "  PTR_FORMAT, p2i(CompressedOops::begin()), p2i(CompressedOops::end()));
1547       _heap_pointers_need_patching = true;
1548     }
1549   }
1550 
1551   ptrdiff_t delta = 0;
1552   if (_heap_pointers_need_patching) {
1553     //   dumptime heap end  ------------v
1554     //   [      |archived heap regions| ]         runtime heap end ------v
1555     //                                       [   |archived heap regions| ]
1556     //                                  |<-----delta-------------------->|
1557     //
1558     // At dump time, the archived heap regions were near the top of the heap.
1559     // At run time, they may not be inside the heap, so we move them so
1560     // that they are now near the top of the runtime time. This can be done by
1561     // the simple math of adding the delta as shown above.
1562     address dumptime_heap_end = header()->heap_end();
1563     address runtime_heap_end = (address)CompressedOops::end();
1564     delta = runtime_heap_end - dumptime_heap_end;
1565   }
1566 
1567   log_info(cds)("CDS heap data relocation delta = " INTX_FORMAT " bytes", delta);
1568   HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());
1569 
1570   FileMapRegion* si = space_at(MetaspaceShared::first_closed_archive_heap_region);
1571   address relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si);
1572   if (!is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes)) {
1573     // Align the bottom of the closed archive heap regions at G1 region boundary.
1574     // This will avoid the situation where the highest open region and the lowest
1575     // closed region sharing the same G1 region. Otherwise we will fail to map the
1576     // open regions.
1577     size_t align = size_t(relocated_closed_heap_region_bottom) % HeapRegion::GrainBytes;
1578     delta -= align;
1579     log_info(cds)("CDS heap data need to be relocated lower by a further " SIZE_FORMAT
1580                   " bytes to " INTX_FORMAT " to be aligned with HeapRegion::GrainBytes",
1581                   align, delta);
1582     HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());
1583     _heap_pointers_need_patching = true;
1584     relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si);
1585   }
1586   assert(is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes),
1587          "must be");
1588 
1589   // Map the closed_archive_heap regions, GC does not write into the regions.
1590   if (map_heap_data(&closed_archive_heap_ranges,
1591                     MetaspaceShared::first_closed_archive_heap_region,
1592                     MetaspaceShared::max_closed_archive_heap_region,
1593                     &num_closed_archive_heap_ranges)) {
1594     HeapShared::set_closed_archive_heap_region_mapped();
1595 
1596     // Now, map open_archive heap regions, GC can write into the regions.
1597     if (map_heap_data(&open_archive_heap_ranges,
1598                       MetaspaceShared::first_open_archive_heap_region,
1599                       MetaspaceShared::max_open_archive_heap_region,
1600                       &num_open_archive_heap_ranges,
1601                       true /* open */)) {
1602       HeapShared::set_open_archive_heap_region_mapped();
1603     }
1604   }
1605 }
1606 
1607 void FileMapInfo::map_heap_regions() {
1608   if (has_heap_regions()) {
1609     map_heap_regions_impl();
1610   }
1611 
1612   if (!HeapShared::closed_archive_heap_region_mapped()) {
1613     assert(closed_archive_heap_ranges == NULL &&
1614            num_closed_archive_heap_ranges == 0, "sanity");
1615   }
1616 
1617   if (!HeapShared::open_archive_heap_region_mapped()) {
1618     assert(open_archive_heap_ranges == NULL && num_open_archive_heap_ranges == 0, "sanity");
1619   }
1620 }
1621 
1622 bool FileMapInfo::map_heap_data(MemRegion **heap_mem, int first,
1623                                 int max, int* num, bool is_open_archive) {
1624   MemRegion * regions = new MemRegion[max];
1625   FileMapRegion* si;
1626   int region_num = 0;
1627 
1628   for (int i = first;
1629            i < first + max; i++) {
1630     si = space_at(i);
1631     size_t size = si->used();
1632     if (size > 0) {
1633       HeapWord* start = (HeapWord*)start_address_as_decoded_from_archive(si);
1634       regions[region_num] = MemRegion(start, size / HeapWordSize);
1635       region_num ++;
1636       log_info(cds)("Trying to map heap data: region[%d] at " INTPTR_FORMAT ", size = " SIZE_FORMAT_W(8) " bytes",
1637                     i, p2i(start), size);
1638     }
1639   }
1640 
1641   if (region_num == 0) {
1642     return false; // no archived java heap data
1643   }
1644 
1645   // Check that ranges are within the java heap
1646   if (!G1CollectedHeap::heap()->check_archive_addresses(regions, region_num)) {
1647     log_info(cds)("UseSharedSpaces: Unable to allocate region, range is not within java heap.");
1648     return false;
1649   }
1650 
1651   // allocate from java heap
1652   if (!G1CollectedHeap::heap()->alloc_archive_regions(
1653              regions, region_num, is_open_archive)) {
1654     log_info(cds)("UseSharedSpaces: Unable to allocate region, java heap range is already in use.");
1655     return false;
1656   }
1657 
1658   // Map the archived heap data. No need to call MemTracker::record_virtual_memory_type()
1659   // for mapped regions as they are part of the reserved java heap, which is
1660   // already recorded.
1661   for (int i = 0; i < region_num; i++) {
1662     si = space_at(first + i);
1663     char* addr = (char*)regions[i].start();
1664     char* base = os::map_memory(_fd, _full_path, si->file_offset(),
1665                                 addr, regions[i].byte_size(), si->read_only(),
1666                                 si->allow_exec());
1667     if (base == NULL || base != addr) {
1668       // dealloc the regions from java heap
1669       dealloc_archive_heap_regions(regions, region_num, is_open_archive);
1670       log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap. "
1671                     INTPTR_FORMAT ", size = " SIZE_FORMAT " bytes",
1672                     p2i(addr), regions[i].byte_size());
1673       return false;
1674     }
1675 
1676     if (VerifySharedSpaces && !region_crc_check(addr, regions[i].byte_size(), si->crc())) {
1677       // dealloc the regions from java heap
1678       dealloc_archive_heap_regions(regions, region_num, is_open_archive);
1679       log_info(cds)("UseSharedSpaces: mapped heap regions are corrupt");
1680       return false;
1681     }
1682   }
1683 
1684   // the shared heap data is mapped successfully
1685   *heap_mem = regions;
1686   *num = region_num;
1687   return true;
1688 }
1689 
1690 void FileMapInfo::patch_archived_heap_embedded_pointers() {
1691   if (!_heap_pointers_need_patching) {
1692     return;
1693   }
1694 
1695   patch_archived_heap_embedded_pointers(closed_archive_heap_ranges,
1696                                         num_closed_archive_heap_ranges,
1697                                         MetaspaceShared::first_closed_archive_heap_region);
1698 
1699   patch_archived_heap_embedded_pointers(open_archive_heap_ranges,
1700                                         num_open_archive_heap_ranges,
1701                                         MetaspaceShared::first_open_archive_heap_region);
1702 }
1703 
1704 void FileMapInfo::patch_archived_heap_embedded_pointers(MemRegion* ranges, int num_ranges,
1705                                                         int first_region_idx) {
1706   for (int i=0; i<num_ranges; i++) {
1707     FileMapRegion* si = space_at(i + first_region_idx);
1708     HeapShared::patch_archived_heap_embedded_pointers(ranges[i], (address)si->oopmap(),
1709                                                       si->oopmap_size_in_bits());
1710   }
1711 }
1712 
1713 // This internally allocates objects using SystemDictionary::Object_klass(), so it
1714 // must be called after the well-known classes are resolved.
1715 void FileMapInfo::fixup_mapped_heap_regions() {
1716   // If any closed regions were found, call the fill routine to make them parseable.
1717   // Note that closed_archive_heap_ranges may be non-NULL even if no ranges were found.
1718   if (num_closed_archive_heap_ranges != 0) {
1719     assert(closed_archive_heap_ranges != NULL,
1720            "Null closed_archive_heap_ranges array with non-zero count");
1721     G1CollectedHeap::heap()->fill_archive_regions(closed_archive_heap_ranges,
1722                                                   num_closed_archive_heap_ranges);
1723   }
1724 
1725   // do the same for mapped open archive heap regions
1726   if (num_open_archive_heap_ranges != 0) {
1727     assert(open_archive_heap_ranges != NULL, "NULL open_archive_heap_ranges array with non-zero count");
1728     G1CollectedHeap::heap()->fill_archive_regions(open_archive_heap_ranges,
1729                                                   num_open_archive_heap_ranges);
1730   }
1731 }
1732 
1733 // dealloc the archive regions from java heap
1734 void FileMapInfo::dealloc_archive_heap_regions(MemRegion* regions, int num, bool is_open) {
1735   if (num > 0) {
1736     assert(regions != NULL, "Null archive ranges array with non-zero count");
1737     G1CollectedHeap::heap()->dealloc_archive_regions(regions, num, is_open);
1738   }
1739 }
1740 #endif // INCLUDE_CDS_JAVA_HEAP
1741 
1742 bool FileMapInfo::region_crc_check(char* buf, size_t size, int expected_crc) {
1743   int crc = ClassLoader::crc32(0, buf, (jint)size);
1744   if (crc != expected_crc) {
1745     fail_continue("Checksum verification failed.");
1746     return false;
1747   }
1748   return true;
1749 }
1750 
1751 bool FileMapInfo::verify_region_checksum(int i) {
1752   assert(VerifySharedSpaces, "sanity");
1753   size_t sz = space_at(i)->used();
1754 
1755   if (sz == 0) {
1756     return true; // no data
1757   } else {
1758     return region_crc_check(region_addr(i), sz, space_at(i)->crc());
1759   }
1760 }
1761 
1762 void FileMapInfo::unmap_regions(int regions[], char* saved_base[], size_t len) {
1763   for (int i = 0; i < (int)len; i++) {
1764     if (saved_base[i] != NULL) {
1765       unmap_region(regions[i]);
1766     }
1767   }
1768 }
1769 
1770 // Unmap a memory region in the address space.
1771 
1772 void FileMapInfo::unmap_region(int i) {
1773   assert(!HeapShared::is_heap_region(i), "sanity");
1774   FileMapRegion* si = space_at(i);
1775   size_t used = si->used();
1776   size_t size = align_up(used, os::vm_allocation_granularity());
1777 
1778   if (used == 0) {
1779     return;
1780   }
1781 
1782   char* addr = region_addr(i);
1783   if (!os::unmap_memory(addr, size)) {
1784     fail_stop("Unable to unmap shared space.");
1785   }
1786 }
1787 
1788 void FileMapInfo::assert_mark(bool check) {
1789   if (!check) {
1790     fail_stop("Mark mismatch while restoring from shared file.");
1791   }
1792 }
1793 
1794 void FileMapInfo::metaspace_pointers_do(MetaspaceClosure* it) {
1795   _shared_path_table.metaspace_pointers_do(it);
1796 }
1797 
1798 FileMapInfo* FileMapInfo::_current_info = NULL;
1799 FileMapInfo* FileMapInfo::_dynamic_archive_info = NULL;
1800 bool FileMapInfo::_heap_pointers_need_patching = false;
1801 SharedPathTable FileMapInfo::_shared_path_table;
1802 bool FileMapInfo::_validating_shared_path_table = false;
1803 bool FileMapInfo::_memory_mapping_failed = false;
1804 GrowableArray<const char*>* FileMapInfo::_non_existent_class_paths = NULL;
1805 
1806 // Open the shared archive file, read and validate the header
1807 // information (version, boot classpath, etc.).  If initialization
1808 // fails, shared spaces are disabled and the file is closed. [See
1809 // fail_continue.]
1810 //
1811 // Validation of the archive is done in two steps:
1812 //
1813 // [1] validate_header() - done here.
1814 // [2] validate_shared_path_table - this is done later, because the table is in the RW
1815 //     region of the archive, which is not mapped yet.
1816 bool FileMapInfo::initialize(bool is_static) {
1817   assert(UseSharedSpaces, "UseSharedSpaces expected.");
1818 
1819   if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
1820     // CDS assumes that no classes resolved in SystemDictionary::resolve_well_known_classes
1821     // are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved
1822     // during the JVMTI "early" stage, so we can still use CDS if
1823     // JvmtiExport::has_early_class_hook_env() is false.
1824     FileMapInfo::fail_continue("CDS is disabled because early JVMTI ClassFileLoadHook is in use.");
1825     return false;
1826   }
1827 
1828   if (!open_for_read()) {
1829     return false;
1830   }
1831 
1832   init_from_file(_fd, is_static);
1833   // UseSharedSpaces could be disabled if the checking of some of the header fields in
1834   // init_from_file has failed.
1835   if (!UseSharedSpaces || !validate_header(is_static)) {
1836     return false;
1837   }
1838   return true;
1839 }
1840 
1841 char* FileMapInfo::region_addr(int idx) {
1842   FileMapRegion* si = space_at(idx);
1843   if (HeapShared::is_heap_region(idx)) {
1844     assert(DumpSharedSpaces, "The following doesn't work at runtime");
1845     return si->used() > 0 ?
1846           (char*)start_address_as_decoded_with_current_oop_encoding_mode(si) : NULL;
1847   } else {
1848     return si->base();
1849   }
1850 }
1851 
1852 int FileMapHeader::compute_crc() {
1853   char* start = (char*)this;
1854   // start computing from the field after _crc
1855   char* buf = (char*)&_crc + sizeof(_crc);
1856   size_t sz = _header_size - (buf - start);
1857   int crc = ClassLoader::crc32(0, buf, (jint)sz);
1858   return crc;
1859 }
1860 
1861 // This function should only be called during run time with UseSharedSpaces enabled.
1862 bool FileMapHeader::validate() {
1863 
1864   if (_obj_alignment != ObjectAlignmentInBytes) {
1865     FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"
1866                   " does not equal the current ObjectAlignmentInBytes of " INTX_FORMAT ".",
1867                   _obj_alignment, ObjectAlignmentInBytes);
1868     return false;
1869   }
1870   if (_compact_strings != CompactStrings) {
1871     FileMapInfo::fail_continue("The shared archive file's CompactStrings setting (%s)"
1872                   " does not equal the current CompactStrings setting (%s).",
1873                   _compact_strings ? "enabled" : "disabled",
1874                   CompactStrings   ? "enabled" : "disabled");
1875     return false;
1876   }
1877 
1878   // This must be done after header validation because it might change the
1879   // header data
1880   const char* prop = Arguments::get_property("java.system.class.loader");
1881   if (prop != NULL) {
1882     warning("Archived non-system classes are disabled because the "
1883             "java.system.class.loader property is specified (value = \"%s\"). "
1884             "To use archived non-system classes, this property must not be set", prop);
1885     _has_platform_or_app_classes = false;
1886   }
1887 
1888   // For backwards compatibility, we don't check the verification setting
1889   // if the archive only contains system classes.
1890   if (_has_platform_or_app_classes &&
1891       ((!_verify_local && BytecodeVerificationLocal) ||
1892        (!_verify_remote && BytecodeVerificationRemote))) {
1893     FileMapInfo::fail_continue("The shared archive file was created with less restrictive "
1894                   "verification setting than the current setting.");
1895     return false;
1896   }
1897 
1898   // Java agents are allowed during run time. Therefore, the following condition is not
1899   // checked: (!_allow_archiving_with_java_agent && AllowArchivingWithJavaAgent)
1900   // Note: _allow_archiving_with_java_agent is set in the shared archive during dump time
1901   // while AllowArchivingWithJavaAgent is set during the current run.
1902   if (_allow_archiving_with_java_agent && !AllowArchivingWithJavaAgent) {
1903     FileMapInfo::fail_continue("The setting of the AllowArchivingWithJavaAgent is different "
1904                                "from the setting in the shared archive.");
1905     return false;
1906   }
1907 
1908   if (_allow_archiving_with_java_agent) {
1909     warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1910             "for testing purposes only and should not be used in a production environment");
1911   }
1912 
1913   return true;
1914 }
1915 
1916 bool FileMapInfo::validate_header(bool is_static) {
1917   return header()->validate();
1918 }
1919 
1920 // Check if a given address is within one of the shared regions
1921 bool FileMapInfo::is_in_shared_region(const void* p, int idx) {
1922   assert(idx == MetaspaceShared::ro ||
1923          idx == MetaspaceShared::rw ||
1924          idx == MetaspaceShared::mc ||
1925          idx == MetaspaceShared::md, "invalid region index");
1926   char* base = region_addr(idx);
1927   if (p >= base && p < base + space_at(idx)->used()) {
1928     return true;
1929   }
1930   return false;
1931 }
1932 
1933 // Unmap mapped regions of shared space.
1934 void FileMapInfo::stop_sharing_and_unmap(const char* msg) {
1935   MetaspaceShared::set_shared_metaspace_range(NULL, NULL);
1936 
1937   FileMapInfo *map_info = FileMapInfo::current_info();
1938   if (map_info) {
1939     map_info->fail_continue("%s", msg);
1940     for (int i = 0; i < MetaspaceShared::num_non_heap_spaces; i++) {
1941       if (!HeapShared::is_heap_region(i)) {
1942         char *addr = map_info->region_addr(i);
1943         if (addr != NULL) {
1944           map_info->unmap_region(i);
1945           map_info->space_at(i)->mark_invalid();
1946         }
1947       }
1948     }
1949     // Dealloc the archive heap regions only without unmapping. The regions are part
1950     // of the java heap. Unmapping of the heap regions are managed by GC.
1951     map_info->dealloc_archive_heap_regions(open_archive_heap_ranges,
1952                                            num_open_archive_heap_ranges,
1953                                            true);
1954     map_info->dealloc_archive_heap_regions(closed_archive_heap_ranges,
1955                                            num_closed_archive_heap_ranges,
1956                                            false);
1957   } else if (DumpSharedSpaces) {
1958     fail_stop("%s", msg);
1959   }
1960 }
1961 
1962 #if INCLUDE_JVMTI
1963 ClassPathEntry** FileMapInfo::_classpath_entries_for_jvmti = NULL;
1964 
1965 ClassPathEntry* FileMapInfo::get_classpath_entry_for_jvmti(int i, TRAPS) {
1966   ClassPathEntry* ent = _classpath_entries_for_jvmti[i];
1967   if (ent == NULL) {
1968     if (i == 0) {
1969       ent = ClassLoader::get_jrt_entry();
1970       assert(ent != NULL, "must be");
1971     } else {
1972       SharedClassPathEntry* scpe = shared_path(i);
1973       assert(scpe->is_jar(), "must be"); // other types of scpe will not produce archived classes
1974 
1975       const char* path = scpe->name();
1976       struct stat st;
1977       if (os::stat(path, &st) != 0) {
1978         char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128); ;
1979         jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
1980         THROW_MSG_(vmSymbols::java_io_IOException(), msg, NULL);
1981       } else {
1982         ent = ClassLoader::create_class_path_entry(path, &st, /*throw_exception=*/true, false, false, CHECK_NULL);
1983       }
1984     }
1985 
1986     MutexLocker mu(CDSClassFileStream_lock, THREAD);
1987     if (_classpath_entries_for_jvmti[i] == NULL) {
1988       _classpath_entries_for_jvmti[i] = ent;
1989     } else {
1990       // Another thread has beat me to creating this entry
1991       delete ent;
1992       ent = _classpath_entries_for_jvmti[i];
1993     }
1994   }
1995 
1996   return ent;
1997 }
1998 
1999 ClassFileStream* FileMapInfo::open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS) {
2000   int path_index = ik->shared_classpath_index();
2001   assert(path_index >= 0, "should be called for shared built-in classes only");
2002   assert(path_index < (int)get_number_of_shared_paths(), "sanity");
2003 
2004   ClassPathEntry* cpe = get_classpath_entry_for_jvmti(path_index, CHECK_NULL);
2005   assert(cpe != NULL, "must be");
2006 
2007   Symbol* name = ik->name();
2008   const char* const class_name = name->as_C_string();
2009   const char* const file_name = ClassLoader::file_name_for_class_name(class_name,
2010                                                                       name->utf8_length());
2011   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
2012   ClassFileStream* cfs = cpe->open_stream_for_loader(file_name, loader_data, THREAD);
2013   assert(cfs != NULL, "must be able to read the classfile data of shared classes for built-in loaders.");
2014   log_debug(cds, jvmti)("classfile data for %s [%d: %s] = %d bytes", class_name, path_index,
2015                         cfs->source(), cfs->length());
2016   return cfs;
2017 }
2018 
2019 #endif