1 /*
   2  * Copyright (c) 2003, 2018, 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/classLoader.inline.hpp"
  28 #include "classfile/compactHashtable.inline.hpp"
  29 #include "classfile/sharedClassUtil.hpp"
  30 #include "classfile/stringTable.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/filemap.hpp"
  38 #include "memory/metadataFactory.hpp"
  39 #include "memory/metaspaceClosure.hpp"
  40 #include "memory/metaspaceShared.hpp"
  41 #include "memory/oopFactory.hpp"
  42 #include "oops/compressedOops.inline.hpp"
  43 #include "oops/objArrayOop.hpp"
  44 #include "prims/jvmtiExport.hpp"
  45 #include "runtime/arguments.hpp"
  46 #include "runtime/java.hpp"
  47 #include "runtime/os.hpp"
  48 #include "runtime/vm_version.hpp"
  49 #include "services/memTracker.hpp"
  50 #include "utilities/align.hpp"
  51 #include "utilities/defaultStream.hpp"
  52 #if INCLUDE_ALL_GCS
  53 #include "gc/g1/g1CollectedHeap.hpp"
  54 #endif
  55 
  56 # include <sys/stat.h>
  57 # include <errno.h>
  58 
  59 #ifndef O_BINARY       // if defined (Win32) use binary files.
  60 #define O_BINARY 0     // otherwise do nothing.
  61 #endif
  62 
  63 extern address JVM_FunctionAtStart();
  64 extern address JVM_FunctionAtEnd();
  65 
  66 // Complain and stop. All error conditions occurring during the writing of
  67 // an archive file should stop the process.  Unrecoverable errors during
  68 // the reading of the archive file should stop the process.
  69 
  70 static void fail(const char *msg, va_list ap) {
  71   // This occurs very early during initialization: tty is not initialized.
  72   jio_fprintf(defaultStream::error_stream(),
  73               "An error has occurred while processing the"
  74               " shared archive file.\n");
  75   jio_vfprintf(defaultStream::error_stream(), msg, ap);
  76   jio_fprintf(defaultStream::error_stream(), "\n");
  77   // Do not change the text of the below message because some tests check for it.
  78   vm_exit_during_initialization("Unable to use shared archive.", NULL);
  79 }
  80 
  81 
  82 void FileMapInfo::fail_stop(const char *msg, ...) {
  83         va_list ap;
  84   va_start(ap, msg);
  85   fail(msg, ap);        // Never returns.
  86   va_end(ap);           // for completeness.
  87 }
  88 
  89 
  90 // Complain and continue.  Recoverable errors during the reading of the
  91 // archive file may continue (with sharing disabled).
  92 //
  93 // If we continue, then disable shared spaces and close the file.
  94 
  95 void FileMapInfo::fail_continue(const char *msg, ...) {
  96   va_list ap;
  97   va_start(ap, msg);
  98   MetaspaceShared::set_archive_loading_failed();
  99   if (PrintSharedArchiveAndExit && _validating_shared_path_table) {
 100     // If we are doing PrintSharedArchiveAndExit and some of the classpath entries
 101     // do not validate, we can still continue "limping" to validate the remaining
 102     // entries. No need to quit.
 103     tty->print("[");
 104     tty->vprint(msg, ap);
 105     tty->print_cr("]");
 106   } else {
 107     if (RequireSharedSpaces) {
 108       fail(msg, ap);
 109     } else {
 110       if (log_is_enabled(Info, cds)) {
 111         ResourceMark rm;
 112         LogStream ls(Log(cds)::info());
 113         ls.print("UseSharedSpaces: ");
 114         ls.vprint_cr(msg, ap);
 115       }
 116     }
 117     UseSharedSpaces = false;
 118     assert(current_info() != NULL, "singleton must be registered");
 119     current_info()->close();
 120   }
 121   va_end(ap);
 122 }
 123 
 124 // Fill in the fileMapInfo structure with data about this VM instance.
 125 
 126 // This method copies the vm version info into header_version.  If the version is too
 127 // long then a truncated version, which has a hash code appended to it, is copied.
 128 //
 129 // Using a template enables this method to verify that header_version is an array of
 130 // length JVM_IDENT_MAX.  This ensures that the code that writes to the CDS file and
 131 // the code that reads the CDS file will both use the same size buffer.  Hence, will
 132 // use identical truncation.  This is necessary for matching of truncated versions.
 133 template <int N> static void get_header_version(char (&header_version) [N]) {
 134   assert(N == JVM_IDENT_MAX, "Bad header_version size");
 135 
 136   const char *vm_version = VM_Version::internal_vm_info_string();
 137   const int version_len = (int)strlen(vm_version);
 138 
 139   if (version_len < (JVM_IDENT_MAX-1)) {
 140     strcpy(header_version, vm_version);
 141 
 142   } else {
 143     // Get the hash value.  Use a static seed because the hash needs to return the same
 144     // value over multiple jvm invocations.
 145     unsigned int hash = AltHashing::murmur3_32(8191, (const jbyte*)vm_version, version_len);
 146 
 147     // Truncate the ident, saving room for the 8 hex character hash value.
 148     strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
 149 
 150     // Append the hash code as eight hex digits.
 151     sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash);
 152     header_version[JVM_IDENT_MAX-1] = 0;  // Null terminate.
 153   }
 154 }
 155 
 156 FileMapInfo::FileMapInfo() {
 157   assert(_current_info == NULL, "must be singleton"); // not thread safe
 158   _current_info = this;
 159   memset((void*)this, 0, sizeof(FileMapInfo));
 160   _file_offset = 0;
 161   _file_open = false;
 162   _header = SharedClassUtil::allocate_file_map_header();
 163   _header->_version = _invalid_version;
 164 }
 165 
 166 FileMapInfo::~FileMapInfo() {
 167   assert(_current_info == this, "must be singleton"); // not thread safe
 168   _current_info = NULL;
 169 }
 170 
 171 void FileMapInfo::populate_header(size_t alignment) {
 172   _header->populate(this, alignment);
 173 }
 174 
 175 size_t FileMapInfo::FileMapHeader::data_size() {
 176   return SharedClassUtil::file_map_header_size() - sizeof(FileMapInfo::FileMapHeaderBase);
 177 }
 178 
 179 void FileMapInfo::FileMapHeader::populate(FileMapInfo* mapinfo, size_t alignment) {
 180   _magic = 0xf00baba2;
 181   _version = _current_version;
 182   _alignment = alignment;
 183   _obj_alignment = ObjectAlignmentInBytes;
 184   _compact_strings = CompactStrings;
 185   _narrow_oop_mode = Universe::narrow_oop_mode();
 186   _narrow_oop_base = Universe::narrow_oop_base();
 187   _narrow_oop_shift = Universe::narrow_oop_shift();
 188   _max_heap_size = MaxHeapSize;
 189   _narrow_klass_base = Universe::narrow_klass_base();
 190   _narrow_klass_shift = Universe::narrow_klass_shift();
 191   _shared_path_table_size = mapinfo->_shared_path_table_size;
 192   _shared_path_table = mapinfo->_shared_path_table;
 193   _shared_path_entry_size = mapinfo->_shared_path_entry_size;
 194 
 195   // The following fields are for sanity checks for whether this archive
 196   // will function correctly with this JVM and the bootclasspath it's
 197   // invoked with.
 198 
 199   // JVM version string ... changes on each build.
 200   get_header_version(_jvm_ident);
 201 }
 202 
 203 void SharedClassPathEntry::init(const char* name, TRAPS) {
 204   _timestamp = 0;
 205   _filesize  = 0;
 206 
 207   struct stat st;
 208   if (os::stat(name, &st) == 0) {
 209     if ((st.st_mode & S_IFMT) == S_IFDIR) {
 210       _is_dir = true;
 211     } else {
 212       _is_dir = false;
 213       _timestamp = st.st_mtime;
 214       _filesize = st.st_size;
 215     }
 216   } else {
 217     // The file/dir must exist, or it would not have been added
 218     // into ClassLoader::classpath_entry().
 219     //
 220     // If we can't access a jar file in the boot path, then we can't
 221     // make assumptions about where classes get loaded from.
 222     FileMapInfo::fail_stop("Unable to open file %s.", name);
 223   }
 224 
 225   size_t len = strlen(name) + 1;
 226   _name = MetadataFactory::new_array<char>(ClassLoaderData::the_null_class_loader_data(), (int)len, THREAD);
 227   strcpy(_name->data(), name);
 228 }
 229 
 230 bool SharedClassPathEntry::validate(bool is_class_path) {
 231   assert(UseSharedSpaces, "runtime only");
 232 
 233   struct stat st;
 234   const char* name = this->name();
 235   bool ok = true;
 236   log_info(class, path)("checking shared classpath entry: %s", name);
 237   if (os::stat(name, &st) != 0 && is_class_path) {
 238     // If the archived module path entry does not exist at runtime, it is not fatal
 239     // (no need to invalid the shared archive) because the shared runtime visibility check
 240     // filters out any archived module classes that do not have a matching runtime
 241     // module path location.
 242     FileMapInfo::fail_continue("Required classpath entry does not exist: %s", name);
 243     ok = false;
 244   } else if (is_dir()) {
 245     if (!os::dir_is_empty(name)) {
 246       FileMapInfo::fail_continue("directory is not empty: %s", name);
 247       ok = false;
 248     }
 249   } else if (is_jar_or_bootimage()) {
 250     if (_timestamp != st.st_mtime ||
 251         _filesize != st.st_size) {
 252       ok = false;
 253       if (PrintSharedArchiveAndExit) {
 254         FileMapInfo::fail_continue(_timestamp != st.st_mtime ?
 255                                    "Timestamp mismatch" :
 256                                    "File size mismatch");
 257       } else {
 258         FileMapInfo::fail_continue("A jar/jimage file is not the one used while building"
 259                                    " the shared archive file: %s", name);
 260       }
 261     }
 262   }
 263   return ok;
 264 }
 265 
 266 void SharedClassPathEntry::metaspace_pointers_do(MetaspaceClosure* it) {
 267   it->push(&_name);
 268   it->push(&_manifest);
 269 }
 270 
 271 void FileMapInfo::allocate_shared_path_table() {
 272   assert(DumpSharedSpaces, "Sanity");
 273 
 274   Thread* THREAD = Thread::current();
 275   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 276   ClassPathEntry* jrt = ClassLoader::get_jrt_entry();
 277 
 278   assert(jrt != NULL,
 279          "No modular java runtime image present when allocating the CDS classpath entry table");
 280 
 281   size_t entry_size = SharedClassUtil::shared_class_path_entry_size(); // assert ( should be 8 byte aligned??)
 282   int num_boot_classpath_entries = ClassLoader::num_boot_classpath_entries();
 283   int num_app_classpath_entries = ClassLoader::num_app_classpath_entries();
 284   int num_module_path_entries = ClassLoader::num_module_path_entries();
 285   int num_entries = num_boot_classpath_entries + num_app_classpath_entries + num_module_path_entries;
 286   size_t bytes = entry_size * num_entries;
 287 
 288   _shared_path_table = MetadataFactory::new_array<u8>(loader_data, (int)(bytes + 7 / 8), THREAD);
 289   _shared_path_table_size = num_entries;
 290   _shared_path_entry_size = entry_size;
 291 
 292   // 1. boot class path
 293   int i = 0;
 294   ClassPathEntry* cpe = jrt;
 295   while (cpe != NULL) {
 296     const char* type = ((cpe == jrt) ? "jrt" : (cpe->is_jar_file() ? "jar" : "dir"));
 297     log_info(class, path)("add main shared path (%s) %s", type, cpe->name());
 298     SharedClassPathEntry* ent = shared_path(i);
 299     ent->init(cpe->name(), THREAD);
 300     if (cpe != jrt) { // No need to do jimage.
 301       EXCEPTION_MARK; // The following call should never throw, but would exit VM on error.
 302       SharedClassUtil::update_shared_classpath(cpe, ent, THREAD);
 303     }
 304     cpe = ClassLoader::get_next_boot_classpath_entry(cpe);
 305     i++;
 306   }
 307   assert(i == num_boot_classpath_entries,
 308          "number of boot class path entry mismatch");
 309 
 310   // 2. app class path
 311   ClassPathEntry *acpe = ClassLoader::app_classpath_entries();
 312   while (acpe != NULL) {
 313     log_info(class, path)("add app shared path %s", acpe->name());
 314     SharedClassPathEntry* ent = shared_path(i);
 315     ent->init(acpe->name(), THREAD);
 316     EXCEPTION_MARK;
 317     SharedClassUtil::update_shared_classpath(acpe, ent, THREAD);
 318     acpe = acpe->next();
 319     i++;
 320   }
 321 
 322   // 3. module path
 323   ClassPathEntry *mpe = ClassLoader::module_path_entries();
 324   while (mpe != NULL) {
 325     log_info(class, path)("add module path %s",mpe->name());
 326     SharedClassPathEntry* ent = shared_path(i);
 327     ent->init(mpe->name(), THREAD);
 328     EXCEPTION_MARK;
 329     SharedClassUtil::update_shared_classpath(mpe, ent, THREAD);
 330     mpe = mpe->next();
 331     i++;
 332   }
 333   assert(i == num_entries, "number of shared path entry mismatch");
 334 }
 335 
 336 void FileMapInfo::check_nonempty_dir_in_shared_path_table() {
 337   assert(DumpSharedSpaces, "dump time only");
 338   int end = _shared_path_table_size;
 339   if (!ClassLoaderExt::has_platform_or_app_classes()) {
 340     // only check the boot path if no app class is loaded
 341     end = ClassLoaderExt::app_class_paths_start_index();
 342   }
 343   for (int i = 0; i < end; i++) {
 344     SharedClassPathEntry *e = shared_path(i);
 345     if (e->is_dir()) {
 346       const char* path = e->name();
 347       if (!os::dir_is_empty(path)) {
 348         tty->print_cr("Error: non-empty directory '%s'", path);
 349         ClassLoader::exit_with_path_failure("Cannot have non-empty directory in paths", NULL);
 350       }
 351     }
 352   }
 353 }
 354 
 355 bool FileMapInfo::validate_shared_path_table() {
 356   assert(UseSharedSpaces, "runtime only");
 357 
 358   _validating_shared_path_table = true;
 359   _shared_path_table = _header->_shared_path_table;
 360   _shared_path_entry_size = _header->_shared_path_entry_size;
 361   _shared_path_table_size = _header->_shared_path_table_size;
 362 
 363   FileMapHeaderExt* header = (FileMapHeaderExt*)FileMapInfo::current_info()->header();
 364   int module_paths_start_index = header->_app_module_paths_start_index;
 365 
 366   // If the shared archive contain app or platform classes, validate all entries
 367   // in the shared path table. Otherwise, only validate the boot path entries (with
 368   // entry index < _app_class_paths_start_index).
 369   int count = header->has_platform_or_app_classes() ?
 370               _shared_path_table_size : header->_app_class_paths_start_index;
 371 
 372   for (int i=0; i<count; i++) {
 373     if (i < module_paths_start_index) {
 374       if (shared_path(i)->validate()) {
 375         log_info(class, path)("ok");
 376       }
 377     } else if (i >= module_paths_start_index) {
 378       if (shared_path(i)->validate(false /* not a class path entry */)) {
 379         log_info(class, path)("ok");
 380       }
 381     } else if (!PrintSharedArchiveAndExit) {
 382       _validating_shared_path_table = false;
 383       _shared_path_table = NULL;
 384       _shared_path_table_size = 0;
 385       return false;
 386     }
 387   }
 388 
 389   _validating_shared_path_table = false;
 390   return true;
 391 }
 392 
 393 // Read the FileMapInfo information from the file.
 394 
 395 bool FileMapInfo::init_from_file(int fd) {
 396   size_t sz = _header->data_size();
 397   char* addr = _header->data();
 398   size_t n = os::read(fd, addr, (unsigned int)sz);
 399   if (n != sz) {
 400     fail_continue("Unable to read the file header.");
 401     return false;
 402   }
 403   if (_header->_version != current_version()) {
 404     fail_continue("The shared archive file has the wrong version.");
 405     return false;
 406   }
 407   _file_offset = (long)n;
 408 
 409   size_t info_size = _header->_paths_misc_info_size;
 410   _paths_misc_info = NEW_C_HEAP_ARRAY_RETURN_NULL(char, info_size, mtClass);
 411   if (_paths_misc_info == NULL) {
 412     fail_continue("Unable to read the file header.");
 413     return false;
 414   }
 415   n = os::read(fd, _paths_misc_info, (unsigned int)info_size);
 416   if (n != info_size) {
 417     fail_continue("Unable to read the shared path info header.");
 418     FREE_C_HEAP_ARRAY(char, _paths_misc_info);
 419     _paths_misc_info = NULL;
 420     return false;
 421   }
 422 
 423   size_t len = lseek(fd, 0, SEEK_END);
 424   struct FileMapInfo::FileMapHeader::space_info* si =
 425     &_header->_space[MetaspaceShared::last_valid_region];
 426   // The last space might be empty
 427   if (si->_file_offset > len || len - si->_file_offset < si->_used) {
 428     fail_continue("The shared archive file has been truncated.");
 429     return false;
 430   }
 431 
 432   _file_offset += (long)n;
 433   return true;
 434 }
 435 
 436 
 437 // Read the FileMapInfo information from the file.
 438 bool FileMapInfo::open_for_read() {
 439   _full_path = Arguments::GetSharedArchivePath();
 440   int fd = open(_full_path, O_RDONLY | O_BINARY, 0);
 441   if (fd < 0) {
 442     if (errno == ENOENT) {
 443       // Not locating the shared archive is ok.
 444       fail_continue("Specified shared archive not found.");
 445     } else {
 446       fail_continue("Failed to open shared archive file (%s).",
 447                     os::strerror(errno));
 448     }
 449     return false;
 450   }
 451 
 452   _fd = fd;
 453   _file_open = true;
 454   return true;
 455 }
 456 
 457 
 458 // Write the FileMapInfo information to the file.
 459 
 460 void FileMapInfo::open_for_write() {
 461   _full_path = Arguments::GetSharedArchivePath();
 462   LogMessage(cds) msg;
 463   if (msg.is_info()) {
 464     msg.info("Dumping shared data to file: ");
 465     msg.info("   %s", _full_path);
 466   }
 467 
 468 #ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
 469   chmod(_full_path, _S_IREAD | _S_IWRITE);
 470 #endif
 471 
 472   // Use remove() to delete the existing file because, on Unix, this will
 473   // allow processes that have it open continued access to the file.
 474   remove(_full_path);
 475   int fd = open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
 476   if (fd < 0) {
 477     fail_stop("Unable to create shared archive file %s: (%s).", _full_path,
 478               os::strerror(errno));
 479   }
 480   _fd = fd;
 481   _file_offset = 0;
 482   _file_open = true;
 483 }
 484 
 485 
 486 // Write the header to the file, seek to the next allocation boundary.
 487 
 488 void FileMapInfo::write_header() {
 489   int info_size = ClassLoader::get_shared_paths_misc_info_size();
 490 
 491   _header->_paths_misc_info_size = info_size;
 492 
 493   align_file_position();
 494   size_t sz = _header->data_size();
 495   char* addr = _header->data();
 496   write_bytes(addr, (int)sz); // skip the C++ vtable
 497   write_bytes(ClassLoader::get_shared_paths_misc_info(), info_size);
 498   align_file_position();
 499 }
 500 
 501 
 502 // Dump region to file.
 503 
 504 void FileMapInfo::write_region(int region, char* base, size_t size,
 505                                bool read_only, bool allow_exec) {
 506   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[region];
 507 
 508   if (_file_open) {
 509     guarantee(si->_file_offset == _file_offset, "file offset mismatch.");
 510     log_info(cds)("Shared file region %d: " SIZE_FORMAT_HEX_W(08)
 511                   " bytes, addr " INTPTR_FORMAT " file offset " SIZE_FORMAT_HEX_W(08),
 512                   region, size, p2i(base), _file_offset);
 513   } else {
 514     si->_file_offset = _file_offset;
 515   }
 516   if (MetaspaceShared::is_heap_region(region)) {
 517     assert((base - (char*)Universe::narrow_oop_base()) % HeapWordSize == 0, "Sanity");
 518     if (base != NULL) {
 519       si->_addr._offset = (intx)CompressedOops::encode_not_null((oop)base);
 520     } else {
 521       si->_addr._offset = 0;
 522     }
 523   } else {
 524     si->_addr._base = base;
 525   }
 526   si->_used = size;
 527   si->_read_only = read_only;
 528   si->_allow_exec = allow_exec;
 529   si->_crc = ClassLoader::crc32(0, base, (jint)size);
 530   write_bytes_aligned(base, (int)size);
 531 }
 532 
 533 // Write out the given archive heap memory regions.  GC code combines multiple
 534 // consecutive archive GC regions into one MemRegion whenever possible and
 535 // produces the 'heap_mem' array.
 536 //
 537 // If the archive heap memory size is smaller than a single dump time GC region
 538 // size, there is only one MemRegion in the array.
 539 //
 540 // If the archive heap memory size is bigger than one dump time GC region size,
 541 // the 'heap_mem' array may contain more than one consolidated MemRegions. When
 542 // the first/bottom archive GC region is a partial GC region (with the empty
 543 // portion at the higher address within the region), one MemRegion is used for
 544 // the bottom partial archive GC region. The rest of the consecutive archive
 545 // GC regions are combined into another MemRegion.
 546 //
 547 // Here's the mapping from (archive heap GC regions) -> (GrowableArray<MemRegion> *regions).
 548 //   + We have 1 or more archive heap regions: ah0, ah1, ah2 ..... ahn
 549 //   + We have 1 or 2 consolidated heap memory regions: r0 and r1
 550 //
 551 // If there's a single archive GC region (ah0), then r0 == ah0, and r1 is empty.
 552 // Otherwise:
 553 //
 554 // "X" represented space that's occupied by heap objects.
 555 // "_" represented unused spaced in the heap region.
 556 //
 557 //
 558 //    |ah0       | ah1 | ah2| ...... | ahn |
 559 //    |XXXXXX|__ |XXXXX|XXXX|XXXXXXXX|XXXX|
 560 //    |<-r0->|   |<- r1 ----------------->|
 561 //            ^^^
 562 //             |
 563 //             +-- gap
 564 size_t FileMapInfo::write_archive_heap_regions(GrowableArray<MemRegion> *heap_mem,
 565                                                int first_region_id, int max_num_regions) {
 566   assert(max_num_regions <= 2, "Only support maximum 2 memory regions");
 567 
 568   int arr_len = heap_mem == NULL ? 0 : heap_mem->length();
 569   if(arr_len > max_num_regions) {
 570     fail_stop("Unable to write archive heap memory regions: "
 571               "number of memory regions exceeds maximum due to fragmentation");
 572   }
 573 
 574   size_t total_size = 0;
 575   for (int i = first_region_id, arr_idx = 0;
 576            i < first_region_id + max_num_regions;
 577            i++, arr_idx++) {
 578     char* start = NULL;
 579     size_t size = 0;
 580     if (arr_idx < arr_len) {
 581       start = (char*)heap_mem->at(arr_idx).start();
 582       size = heap_mem->at(arr_idx).byte_size();
 583       total_size += size;
 584     }
 585 
 586     log_info(cds)("Archive heap region %d " INTPTR_FORMAT " - " INTPTR_FORMAT " = " SIZE_FORMAT_W(8) " bytes",
 587                   i, p2i(start), p2i(start + size), size);
 588     write_region(i, start, size, false, false);
 589   }
 590   return total_size;
 591 }
 592 
 593 // Dump bytes to file -- at the current file position.
 594 
 595 void FileMapInfo::write_bytes(const void* buffer, int nbytes) {
 596   if (_file_open) {
 597     int n = ::write(_fd, buffer, nbytes);
 598     if (n != nbytes) {
 599       // It is dangerous to leave the corrupted shared archive file around,
 600       // close and remove the file. See bug 6372906.
 601       close();
 602       remove(_full_path);
 603       fail_stop("Unable to write to shared archive file.");
 604     }
 605   }
 606   _file_offset += nbytes;
 607 }
 608 
 609 
 610 // Align file position to an allocation unit boundary.
 611 
 612 void FileMapInfo::align_file_position() {
 613   size_t new_file_offset = align_up(_file_offset,
 614                                          os::vm_allocation_granularity());
 615   if (new_file_offset != _file_offset) {
 616     _file_offset = new_file_offset;
 617     if (_file_open) {
 618       // Seek one byte back from the target and write a byte to insure
 619       // that the written file is the correct length.
 620       _file_offset -= 1;
 621       if (lseek(_fd, (long)_file_offset, SEEK_SET) < 0) {
 622         fail_stop("Unable to seek.");
 623       }
 624       char zero = 0;
 625       write_bytes(&zero, 1);
 626     }
 627   }
 628 }
 629 
 630 
 631 // Dump bytes to file -- at the current file position.
 632 
 633 void FileMapInfo::write_bytes_aligned(const void* buffer, int nbytes) {
 634   align_file_position();
 635   write_bytes(buffer, nbytes);
 636   align_file_position();
 637 }
 638 
 639 
 640 // Close the shared archive file.  This does NOT unmap mapped regions.
 641 
 642 void FileMapInfo::close() {
 643   if (_file_open) {
 644     if (::close(_fd) < 0) {
 645       fail_stop("Unable to close the shared archive file.");
 646     }
 647     _file_open = false;
 648     _fd = -1;
 649   }
 650 }
 651 
 652 
 653 // JVM/TI RedefineClasses() support:
 654 // Remap the shared readonly space to shared readwrite, private.
 655 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
 656   int idx = MetaspaceShared::ro;
 657   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[idx];
 658   if (!si->_read_only) {
 659     // the space is already readwrite so we are done
 660     return true;
 661   }
 662   size_t used = si->_used;
 663   size_t size = align_up(used, os::vm_allocation_granularity());
 664   if (!open_for_read()) {
 665     return false;
 666   }
 667   char *addr = _header->region_addr(idx);
 668   char *base = os::remap_memory(_fd, _full_path, si->_file_offset,
 669                                 addr, size, false /* !read_only */,
 670                                 si->_allow_exec);
 671   close();
 672   if (base == NULL) {
 673     fail_continue("Unable to remap shared readonly space (errno=%d).", errno);
 674     return false;
 675   }
 676   if (base != addr) {
 677     fail_continue("Unable to remap shared readonly space at required address.");
 678     return false;
 679   }
 680   si->_read_only = false;
 681   return true;
 682 }
 683 
 684 // Map the whole region at once, assumed to be allocated contiguously.
 685 ReservedSpace FileMapInfo::reserve_shared_memory() {
 686   char* requested_addr = _header->region_addr(0);
 687   size_t size = FileMapInfo::core_spaces_size();
 688 
 689   // Reserve the space first, then map otherwise map will go right over some
 690   // other reserved memory (like the code cache).
 691   ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr);
 692   if (!rs.is_reserved()) {
 693     fail_continue("Unable to reserve shared space at required address "
 694                   INTPTR_FORMAT, p2i(requested_addr));
 695     return rs;
 696   }
 697   // the reserved virtual memory is for mapping class data sharing archive
 698   MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared);
 699 
 700   return rs;
 701 }
 702 
 703 // Memory map a region in the address space.
 704 static const char* shared_region_name[] = { "MiscData", "ReadWrite", "ReadOnly", "MiscCode", "OptionalData",
 705                                             "String1", "String2", "OpenArchive1", "OpenArchive2" };
 706 
 707 char* FileMapInfo::map_region(int i, char** top_ret) {
 708   assert(!MetaspaceShared::is_heap_region(i), "sanity");
 709   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 710   size_t used = si->_used;
 711   size_t alignment = os::vm_allocation_granularity();
 712   size_t size = align_up(used, alignment);
 713   char *requested_addr = _header->region_addr(i);
 714 
 715   // If a tool agent is in use (debugging enabled), we must map the address space RW
 716   if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space()) {
 717     si->_read_only = false;
 718   }
 719 
 720   // map the contents of the CDS archive in this memory
 721   char *base = os::map_memory(_fd, _full_path, si->_file_offset,
 722                               requested_addr, size, si->_read_only,
 723                               si->_allow_exec);
 724   if (base == NULL || base != requested_addr) {
 725     fail_continue("Unable to map %s shared space at required address.", shared_region_name[i]);
 726     return NULL;
 727   }
 728 #ifdef _WINDOWS
 729   // This call is Windows-only because the memory_type gets recorded for the other platforms
 730   // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows.
 731   MemTracker::record_virtual_memory_type((address)base, mtClassShared);
 732 #endif
 733 
 734 
 735   if (!verify_region_checksum(i)) {
 736     return NULL;
 737   }
 738 
 739   *top_ret = base + size;
 740   return base;
 741 }
 742 
 743 static MemRegion *string_ranges = NULL;
 744 static MemRegion *open_archive_heap_ranges = NULL;
 745 static int num_string_ranges = 0;
 746 static int num_open_archive_heap_ranges = 0;
 747 
 748 #if INCLUDE_CDS_JAVA_HEAP
 749 //
 750 // Map the shared string objects and open archive heap objects to the runtime
 751 // java heap.
 752 //
 753 // The shared strings are mapped near the runtime java heap top. The
 754 // mapped strings contain no out-going references to any other java heap
 755 // regions. GC does not write into the mapped shared strings.
 756 //
 757 // The open archive heap objects are mapped below the shared strings in
 758 // the runtime java heap. The mapped open archive heap data only contain
 759 // references to the shared strings and open archive objects initially.
 760 // During runtime execution, out-going references to any other java heap
 761 // regions may be added. GC may mark and update references in the mapped
 762 // open archive objects.
 763 void FileMapInfo::map_heap_regions() {
 764   if (MetaspaceShared::is_heap_object_archiving_allowed()) {
 765       log_info(cds)("Archived narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
 766                     narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift());
 767       log_info(cds)("Archived narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
 768                     p2i(narrow_klass_base()), narrow_klass_shift());
 769 
 770     // Check that all the narrow oop and klass encodings match the archive
 771     if (narrow_oop_mode() != Universe::narrow_oop_mode() ||
 772         narrow_oop_base() != Universe::narrow_oop_base() ||
 773         narrow_oop_shift() != Universe::narrow_oop_shift() ||
 774         narrow_klass_base() != Universe::narrow_klass_base() ||
 775         narrow_klass_shift() != Universe::narrow_klass_shift()) {
 776       if (log_is_enabled(Info, cds) && _header->_space[MetaspaceShared::first_string]._used > 0) {
 777         log_info(cds)("Cached heap data from the CDS archive is being ignored. "
 778                       "The current CompressedOops/CompressedClassPointers encoding differs from "
 779                       "that archived due to heap size change. The archive was dumped using max heap "
 780                       "size " UINTX_FORMAT "M.", max_heap_size()/M);
 781         log_info(cds)("Current narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
 782                       Universe::narrow_oop_mode(), p2i(Universe::narrow_oop_base()),
 783                       Universe::narrow_oop_shift());
 784         log_info(cds)("Current narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
 785                       p2i(Universe::narrow_klass_base()), Universe::narrow_klass_shift());
 786       }
 787     } else {
 788       // First, map string regions as closed archive heap regions.
 789       // GC does not write into the regions.
 790       if (map_heap_data(&string_ranges,
 791                          MetaspaceShared::first_string,
 792                          MetaspaceShared::max_strings,
 793                          &num_string_ranges)) {
 794         StringTable::set_shared_string_mapped();
 795 
 796         // Now, map open_archive heap regions, GC can write into the regions.
 797         if (map_heap_data(&open_archive_heap_ranges,
 798                           MetaspaceShared::first_open_archive_heap_region,
 799                           MetaspaceShared::max_open_archive_heap_region,
 800                           &num_open_archive_heap_ranges,
 801                           true /* open */)) {
 802           MetaspaceShared::set_open_archive_heap_region_mapped();
 803         }
 804       }
 805     }
 806   } else {
 807     if (log_is_enabled(Info, cds) && _header->_space[MetaspaceShared::first_string]._used > 0) {
 808       log_info(cds)("Cached heap data from the CDS archive is being ignored. UseG1GC, "
 809                     "UseCompressedOops and UseCompressedClassPointers are required.");
 810     }
 811   }
 812 
 813   if (!StringTable::shared_string_mapped()) {
 814     assert(string_ranges == NULL && num_string_ranges == 0, "sanity");
 815   }
 816 
 817   if (!MetaspaceShared::open_archive_heap_region_mapped()) {
 818     assert(open_archive_heap_ranges == NULL && num_open_archive_heap_ranges == 0, "sanity");
 819   }
 820 }
 821 
 822 bool FileMapInfo::map_heap_data(MemRegion **heap_mem, int first,
 823                                 int max, int* num, bool is_open_archive) {
 824   MemRegion * regions = new MemRegion[max];
 825   struct FileMapInfo::FileMapHeader::space_info* si;
 826   int region_num = 0;
 827 
 828   for (int i = first;
 829            i < first + max; i++) {
 830     si = &_header->_space[i];
 831     size_t used = si->_used;
 832     if (used > 0) {
 833       size_t size = used;
 834       char* requested_addr = (char*)((void*)CompressedOops::decode_not_null(
 835                                             (narrowOop)si->_addr._offset));
 836       regions[region_num] = MemRegion((HeapWord*)requested_addr, size / HeapWordSize);
 837       region_num ++;
 838     }
 839   }
 840 
 841   if (region_num == 0) {
 842     return false; // no archived java heap data
 843   }
 844 
 845   // Check that ranges are within the java heap
 846   if (!G1CollectedHeap::heap()->check_archive_addresses(regions, region_num)) {
 847     log_info(cds)("UseSharedSpaces: Unable to allocate region, "
 848                   "range is not within java heap.");
 849     return false;
 850   }
 851 
 852   // allocate from java heap
 853   if (!G1CollectedHeap::heap()->alloc_archive_regions(
 854              regions, region_num, is_open_archive)) {
 855     log_info(cds)("UseSharedSpaces: Unable to allocate region, "
 856                   "java heap range is already in use.");
 857     return false;
 858   }
 859 
 860   // Map the archived heap data. No need to call MemTracker::record_virtual_memory_type()
 861   // for mapped regions as they are part of the reserved java heap, which is
 862   // already recorded.
 863   for (int i = 0; i < region_num; i++) {
 864     si = &_header->_space[first + i];
 865     char* addr = (char*)regions[i].start();
 866     char* base = os::map_memory(_fd, _full_path, si->_file_offset,
 867                                 addr, regions[i].byte_size(), si->_read_only,
 868                                 si->_allow_exec);
 869     if (base == NULL || base != addr) {
 870       // dealloc the regions from java heap
 871       dealloc_archive_heap_regions(regions, region_num);
 872       log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap.");
 873       return false;
 874     }
 875   }
 876 
 877   if (!verify_mapped_heap_regions(first, region_num)) {
 878     // dealloc the regions from java heap
 879     dealloc_archive_heap_regions(regions, region_num);
 880     log_info(cds)("UseSharedSpaces: mapped heap regions are corrupt");
 881     return false;
 882   }
 883 
 884   // the shared heap data is mapped successfully
 885   *heap_mem = regions;
 886   *num = region_num;
 887   return true;
 888 }
 889 
 890 bool FileMapInfo::verify_mapped_heap_regions(int first, int num) {
 891   for (int i = first;
 892            i <= first + num; i++) {
 893     if (!verify_region_checksum(i)) {
 894       return false;
 895     }
 896   }
 897   return true;
 898 }
 899 
 900 void FileMapInfo::fixup_mapped_heap_regions() {
 901   // If any string regions were found, call the fill routine to make them parseable.
 902   // Note that string_ranges may be non-NULL even if no ranges were found.
 903   if (num_string_ranges != 0) {
 904     assert(string_ranges != NULL, "Null string_ranges array with non-zero count");
 905     G1CollectedHeap::heap()->fill_archive_regions(string_ranges, num_string_ranges);
 906   }
 907 
 908   // do the same for mapped open archive heap regions
 909   if (num_open_archive_heap_ranges != 0) {
 910     assert(open_archive_heap_ranges != NULL, "NULL open_archive_heap_ranges array with non-zero count");
 911     G1CollectedHeap::heap()->fill_archive_regions(open_archive_heap_ranges,
 912                                                   num_open_archive_heap_ranges);
 913   }
 914 }
 915 
 916 // dealloc the archive regions from java heap
 917 void FileMapInfo::dealloc_archive_heap_regions(MemRegion* regions, int num) {
 918   if (num > 0) {
 919     assert(regions != NULL, "Null archive ranges array with non-zero count");
 920     G1CollectedHeap::heap()->dealloc_archive_regions(regions, num);
 921   }
 922 }
 923 #endif // INCLUDE_CDS_JAVA_HEAP
 924 
 925 bool FileMapInfo::verify_region_checksum(int i) {
 926   if (!VerifySharedSpaces) {
 927     return true;
 928   }
 929 
 930   size_t sz = _header->_space[i]._used;
 931 
 932   if (sz == 0) {
 933     return true; // no data
 934   }
 935   if ((MetaspaceShared::is_string_region(i) &&
 936        !StringTable::shared_string_mapped()) ||
 937       (MetaspaceShared::is_open_archive_heap_region(i) &&
 938        !MetaspaceShared::open_archive_heap_region_mapped())) {
 939     return true; // archived heap data is not mapped
 940   }
 941   const char* buf = _header->region_addr(i);
 942   int crc = ClassLoader::crc32(0, buf, (jint)sz);
 943   if (crc != _header->_space[i]._crc) {
 944     fail_continue("Checksum verification failed.");
 945     return false;
 946   }
 947   return true;
 948 }
 949 
 950 // Unmap a memory region in the address space.
 951 
 952 void FileMapInfo::unmap_region(int i) {
 953   assert(!MetaspaceShared::is_heap_region(i), "sanity");
 954   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 955   size_t used = si->_used;
 956   size_t size = align_up(used, os::vm_allocation_granularity());
 957 
 958   if (used == 0) {
 959     return;
 960   }
 961 
 962   char* addr = _header->region_addr(i);
 963   if (!os::unmap_memory(addr, size)) {
 964     fail_stop("Unable to unmap shared space.");
 965   }
 966 }
 967 
 968 void FileMapInfo::assert_mark(bool check) {
 969   if (!check) {
 970     fail_stop("Mark mismatch while restoring from shared file.");
 971   }
 972 }
 973 
 974 void FileMapInfo::metaspace_pointers_do(MetaspaceClosure* it) {
 975   it->push(&_shared_path_table);
 976   for (int i=0; i<_shared_path_table_size; i++) {
 977     shared_path(i)->metaspace_pointers_do(it);
 978   }
 979 }
 980 
 981 
 982 FileMapInfo* FileMapInfo::_current_info = NULL;
 983 Array<u8>* FileMapInfo::_shared_path_table = NULL;
 984 int FileMapInfo::_shared_path_table_size = 0;
 985 size_t FileMapInfo::_shared_path_entry_size = 0x1234baad;
 986 bool FileMapInfo::_validating_shared_path_table = false;
 987 
 988 // Open the shared archive file, read and validate the header
 989 // information (version, boot classpath, etc.).  If initialization
 990 // fails, shared spaces are disabled and the file is closed. [See
 991 // fail_continue.]
 992 //
 993 // Validation of the archive is done in two steps:
 994 //
 995 // [1] validate_header() - done here. This checks the header, including _paths_misc_info.
 996 // [2] validate_shared_path_table - this is done later, because the table is in the RW
 997 //     region of the archive, which is not mapped yet.
 998 bool FileMapInfo::initialize() {
 999   assert(UseSharedSpaces, "UseSharedSpaces expected.");
1000 
1001   if (!open_for_read()) {
1002     return false;
1003   }
1004 
1005   init_from_file(_fd);
1006   if (!validate_header()) {
1007     return false;
1008   }
1009   return true;
1010 }
1011 
1012 char* FileMapInfo::FileMapHeader::region_addr(int idx) {
1013   if (MetaspaceShared::is_heap_region(idx)) {
1014     return _space[idx]._used > 0 ?
1015              (char*)((void*)CompressedOops::decode_not_null((narrowOop)_space[idx]._addr._offset)) : NULL;
1016   } else {
1017     return _space[idx]._addr._base;
1018   }
1019 }
1020 
1021 int FileMapInfo::FileMapHeader::compute_crc() {
1022   char* header = data();
1023   // start computing from the field after _crc
1024   char* buf = (char*)&_crc + sizeof(int);
1025   size_t sz = data_size() - (buf - header);
1026   int crc = ClassLoader::crc32(0, buf, (jint)sz);
1027   return crc;
1028 }
1029 
1030 // This function should only be called during run time with UseSharedSpaces enabled.
1031 bool FileMapInfo::FileMapHeader::validate() {
1032   if (VerifySharedSpaces && compute_crc() != _crc) {
1033     fail_continue("Header checksum verification failed.");
1034     return false;
1035   }
1036 
1037   if (!Arguments::has_jimage()) {
1038     FileMapInfo::fail_continue("The shared archive file cannot be used with an exploded module build.");
1039     return false;
1040   }
1041 
1042   if (_version != current_version()) {
1043     FileMapInfo::fail_continue("The shared archive file is the wrong version.");
1044     return false;
1045   }
1046   if (_magic != (int)0xf00baba2) {
1047     FileMapInfo::fail_continue("The shared archive file has a bad magic number.");
1048     return false;
1049   }
1050   char header_version[JVM_IDENT_MAX];
1051   get_header_version(header_version);
1052   if (strncmp(_jvm_ident, header_version, JVM_IDENT_MAX-1) != 0) {
1053     log_info(class, path)("expected: %s", header_version);
1054     log_info(class, path)("actual:   %s", _jvm_ident);
1055     FileMapInfo::fail_continue("The shared archive file was created by a different"
1056                   " version or build of HotSpot");
1057     return false;
1058   }
1059   if (_obj_alignment != ObjectAlignmentInBytes) {
1060     FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"
1061                   " does not equal the current ObjectAlignmentInBytes of " INTX_FORMAT ".",
1062                   _obj_alignment, ObjectAlignmentInBytes);
1063     return false;
1064   }
1065   if (_compact_strings != CompactStrings) {
1066     FileMapInfo::fail_continue("The shared archive file's CompactStrings setting (%s)"
1067                   " does not equal the current CompactStrings setting (%s).",
1068                   _compact_strings ? "enabled" : "disabled",
1069                   CompactStrings   ? "enabled" : "disabled");
1070     return false;
1071   }
1072 
1073   return true;
1074 }
1075 
1076 bool FileMapInfo::validate_header() {
1077   bool status = _header->validate();
1078 
1079   if (status) {
1080     if (!ClassLoader::check_shared_paths_misc_info(_paths_misc_info, _header->_paths_misc_info_size)) {
1081       if (!PrintSharedArchiveAndExit) {
1082         fail_continue("shared class paths mismatch (hint: enable -Xlog:class+path=info to diagnose the failure)");
1083         status = false;
1084       }
1085     }
1086   }
1087 
1088   if (_paths_misc_info != NULL) {
1089     FREE_C_HEAP_ARRAY(char, _paths_misc_info);
1090     _paths_misc_info = NULL;
1091   }
1092   return status;
1093 }
1094 
1095 // Check if a given address is within one of the shared regions
1096 bool FileMapInfo::is_in_shared_region(const void* p, int idx) {
1097   assert(idx == MetaspaceShared::ro ||
1098          idx == MetaspaceShared::rw ||
1099          idx == MetaspaceShared::mc ||
1100          idx == MetaspaceShared::md, "invalid region index");
1101   char* base = _header->region_addr(idx);
1102   if (p >= base && p < base + _header->_space[idx]._used) {
1103     return true;
1104   }
1105   return false;
1106 }
1107 
1108 void FileMapInfo::print_shared_spaces() {
1109   tty->print_cr("Shared Spaces:");
1110   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
1111     struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
1112     char *base = _header->region_addr(i);
1113     tty->print("  %s " INTPTR_FORMAT "-" INTPTR_FORMAT,
1114                         shared_region_name[i],
1115                         p2i(base), p2i(base + si->_used));
1116   }
1117 }
1118 
1119 // Unmap mapped regions of shared space.
1120 void FileMapInfo::stop_sharing_and_unmap(const char* msg) {
1121   FileMapInfo *map_info = FileMapInfo::current_info();
1122   if (map_info) {
1123     map_info->fail_continue("%s", msg);
1124     for (int i = 0; i < MetaspaceShared::num_non_heap_spaces; i++) {
1125       char *addr = map_info->_header->region_addr(i);
1126       if (addr != NULL && !MetaspaceShared::is_heap_region(i)) {
1127         map_info->unmap_region(i);
1128         map_info->_header->_space[i]._addr._base = NULL;
1129       }
1130     }
1131     // Dealloc the archive heap regions only without unmapping. The regions are part
1132     // of the java heap. Unmapping of the heap regions are managed by GC.
1133     map_info->dealloc_archive_heap_regions(open_archive_heap_ranges,
1134                                            num_open_archive_heap_ranges);
1135     map_info->dealloc_archive_heap_regions(string_ranges, num_string_ranges);
1136   } else if (DumpSharedSpaces) {
1137     fail_stop("%s", msg);
1138   }
1139 }