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