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