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