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