rev 58060 : [mq]: 8238999-iklam-review

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