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