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