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