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