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