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