1 /*
   2  * Copyright (c) 2003, 2016, 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 "memory/filemap.hpp"
  36 #include "memory/metadataFactory.hpp"
  37 #include "memory/oopFactory.hpp"
  38 #include "oops/objArrayOop.hpp"
  39 #include "prims/jvmtiExport.hpp"
  40 #include "runtime/arguments.hpp"
  41 #include "runtime/java.hpp"
  42 #include "runtime/os.hpp"
  43 #include "runtime/vm_version.hpp"
  44 #include "services/memTracker.hpp"
  45 #include "utilities/defaultStream.hpp"
  46 
  47 # include <sys/stat.h>
  48 # include <errno.h>
  49 
  50 #ifndef O_BINARY       // if defined (Win32) use binary files.
  51 #define O_BINARY 0     // otherwise do nothing.
  52 #endif
  53 
  54 extern address JVM_FunctionAtStart();
  55 extern address JVM_FunctionAtEnd();
  56 
  57 // Complain and stop. All error conditions occurring during the writing of
  58 // an archive file should stop the process.  Unrecoverable errors during
  59 // the reading of the archive file should stop the process.
  60 
  61 static void fail(const char *msg, va_list ap) {
  62   // This occurs very early during initialization: tty is not initialized.
  63   jio_fprintf(defaultStream::error_stream(),
  64               "An error has occurred while processing the"
  65               " shared archive file.\n");
  66   jio_vfprintf(defaultStream::error_stream(), msg, ap);
  67   jio_fprintf(defaultStream::error_stream(), "\n");
  68   // Do not change the text of the below message because some tests check for it.
  69   vm_exit_during_initialization("Unable to use shared archive.", NULL);
  70 }
  71 
  72 
  73 void FileMapInfo::fail_stop(const char *msg, ...) {
  74         va_list ap;
  75   va_start(ap, msg);
  76   fail(msg, ap);        // Never returns.
  77   va_end(ap);           // for completeness.
  78 }
  79 
  80 
  81 // Complain and continue.  Recoverable errors during the reading of the
  82 // archive file may continue (with sharing disabled).
  83 //
  84 // If we continue, then disable shared spaces and close the file.
  85 
  86 void FileMapInfo::fail_continue(const char *msg, ...) {
  87   va_list ap;
  88   va_start(ap, msg);
  89   MetaspaceShared::set_archive_loading_failed();
  90   if (PrintSharedArchiveAndExit && _validating_classpath_entry_table) {
  91     // If we are doing PrintSharedArchiveAndExit and some of the classpath entries
  92     // do not validate, we can still continue "limping" to validate the remaining
  93     // entries. No need to quit.
  94     tty->print("[");
  95     tty->vprint(msg, ap);
  96     tty->print_cr("]");
  97   } else {
  98     if (RequireSharedSpaces) {
  99       fail(msg, ap);
 100     } else {
 101       if (PrintSharedSpaces) {
 102         tty->print_cr("UseSharedSpaces: %s", msg);
 103       }
 104     }
 105     UseSharedSpaces = false;
 106     assert(current_info() != NULL, "singleton must be registered");
 107     current_info()->close();
 108   }
 109   va_end(ap);
 110 }
 111 
 112 // Fill in the fileMapInfo structure with data about this VM instance.
 113 
 114 // This method copies the vm version info into header_version.  If the version is too
 115 // long then a truncated version, which has a hash code appended to it, is copied.
 116 //
 117 // Using a template enables this method to verify that header_version is an array of
 118 // length JVM_IDENT_MAX.  This ensures that the code that writes to the CDS file and
 119 // the code that reads the CDS file will both use the same size buffer.  Hence, will
 120 // use identical truncation.  This is necessary for matching of truncated versions.
 121 template <int N> static void get_header_version(char (&header_version) [N]) {
 122   assert(N == JVM_IDENT_MAX, "Bad header_version size");
 123 
 124   const char *vm_version = VM_Version::internal_vm_info_string();
 125   const int version_len = (int)strlen(vm_version);
 126 
 127   if (version_len < (JVM_IDENT_MAX-1)) {
 128     strcpy(header_version, vm_version);
 129 
 130   } else {
 131     // Get the hash value.  Use a static seed because the hash needs to return the same
 132     // value over multiple jvm invocations.
 133     unsigned int hash = AltHashing::murmur3_32(8191, (const jbyte*)vm_version, version_len);
 134 
 135     // Truncate the ident, saving room for the 8 hex character hash value.
 136     strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
 137 
 138     // Append the hash code as eight hex digits.
 139     sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash);
 140     header_version[JVM_IDENT_MAX-1] = 0;  // Null terminate.
 141   }
 142 }
 143 
 144 FileMapInfo::FileMapInfo() {
 145   assert(_current_info == NULL, "must be singleton"); // not thread safe
 146   _current_info = this;
 147   memset(this, 0, sizeof(FileMapInfo));
 148   _file_offset = 0;
 149   _file_open = false;
 150   _header = SharedClassUtil::allocate_file_map_header();
 151   _header->_version = _invalid_version;
 152 }
 153 
 154 FileMapInfo::~FileMapInfo() {
 155   assert(_current_info == this, "must be singleton"); // not thread safe
 156   _current_info = NULL;
 157 }
 158 
 159 void FileMapInfo::populate_header(size_t alignment) {
 160   _header->populate(this, alignment);
 161 }
 162 
 163 size_t FileMapInfo::FileMapHeader::data_size() {
 164   return SharedClassUtil::file_map_header_size() - sizeof(FileMapInfo::FileMapHeaderBase);
 165 }
 166 
 167 void FileMapInfo::FileMapHeader::populate(FileMapInfo* mapinfo, size_t alignment) {
 168   _magic = 0xf00baba2;
 169   _version = _current_version;
 170   _alignment = alignment;
 171   _obj_alignment = ObjectAlignmentInBytes;
 172   _compact_strings = CompactStrings;
 173   _narrow_oop_mode = Universe::narrow_oop_mode();
 174   _narrow_oop_shift = Universe::narrow_oop_shift();
 175   _max_heap_size = MaxHeapSize;
 176   _narrow_klass_base = Universe::narrow_klass_base();
 177   _narrow_klass_shift = Universe::narrow_klass_shift();
 178   _classpath_entry_table_size = mapinfo->_classpath_entry_table_size;
 179   _classpath_entry_table = mapinfo->_classpath_entry_table;
 180   _classpath_entry_size = mapinfo->_classpath_entry_size;
 181 
 182   // The following fields are for sanity checks for whether this archive
 183   // will function correctly with this JVM and the bootclasspath it's
 184   // invoked with.
 185 
 186   // JVM version string ... changes on each build.
 187   get_header_version(_jvm_ident);
 188 }
 189 
 190 void FileMapInfo::allocate_classpath_entry_table() {
 191   int bytes = 0;
 192   int count = 0;
 193   char* strptr = NULL;
 194   char* strptr_max = NULL;
 195   Thread* THREAD = Thread::current();
 196 
 197   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 198   size_t entry_size = SharedClassUtil::shared_class_path_entry_size();
 199 
 200   for (int pass=0; pass<2; pass++) {
 201     ClassPathEntry *cpe = ClassLoader::classpath_entry(0);
 202 
 203     for (int cur_entry = 0 ; cpe != NULL; cpe = cpe->next(), cur_entry++) {
 204       const char *name = cpe->name();
 205       int name_bytes = (int)(strlen(name) + 1);
 206 
 207       if (pass == 0) {
 208         count ++;
 209         bytes += (int)entry_size;
 210         bytes += name_bytes;
 211         log_info(classpath)("add main shared path (%s) %s", (cpe->is_jar_file() ? "jar" : "dir"), name);


 212       } else {
 213         SharedClassPathEntry* ent = shared_classpath(cur_entry);
 214         if (cpe->is_jar_file()) {
 215           struct stat st;
 216           if (os::stat(name, &st) != 0) {
 217             // The file/dir must exist, or it would not have been added
 218             // into ClassLoader::classpath_entry().
 219             //
 220             // If we can't access a jar file in the boot path, then we can't
 221             // make assumptions about where classes get loaded from.
 222             FileMapInfo::fail_stop("Unable to open jar file %s.", name);
 223           }
 224 
 225           EXCEPTION_MARK; // The following call should never throw, but would exit VM on error.
 226           SharedClassUtil::update_shared_classpath(cpe, ent, st.st_mtime, st.st_size, THREAD);
 227         } else {
 228           struct stat st;
 229           if ((os::stat(name, &st) == 0) && ((st.st_mode & S_IFDIR) == S_IFDIR)) {
 230             if (!os::dir_is_empty(name)) {
 231               ClassLoader::exit_with_path_failure("Cannot have non-empty directory in archived classpaths", name);
 232             }
 233             ent->_filesize = -1;
 234           } else {
 235             ent->_filesize = -2;
 236           }
 237         }
 238         ent->_name = strptr;
 239         if (strptr + name_bytes <= strptr_max) {
 240           strncpy(strptr, name, (size_t)name_bytes); // name_bytes includes trailing 0.
 241           strptr += name_bytes;
 242         } else {
 243           assert(0, "miscalculated buffer size");
 244         }
 245       }
 246     }
 247 
 248     if (pass == 0) {
 249       EXCEPTION_MARK; // The following call should never throw, but would exit VM on error.
 250       Array<u8>* arr = MetadataFactory::new_array<u8>(loader_data, (bytes + 7)/8, THREAD);
 251       strptr = (char*)(arr->data());
 252       strptr_max = strptr + bytes;
 253       SharedClassPathEntry* table = (SharedClassPathEntry*)strptr;
 254       strptr += entry_size * count;
 255 
 256       _classpath_entry_table_size = count;
 257       _classpath_entry_table = table;
 258       _classpath_entry_size = entry_size;
 259     }
 260   }
 261 }
 262 
 263 bool FileMapInfo::validate_classpath_entry_table() {
 264   _validating_classpath_entry_table = true;
 265 
 266   int count = _header->_classpath_entry_table_size;
 267 
 268   _classpath_entry_table = _header->_classpath_entry_table;
 269   _classpath_entry_size = _header->_classpath_entry_size;
 270 
 271   for (int i=0; i<count; i++) {
 272     SharedClassPathEntry* ent = shared_classpath(i);
 273     struct stat st;
 274     const char* name = ent->_name;
 275     bool ok = true;
 276     log_info(classpath)("checking shared classpath entry: %s", name);


 277     if (os::stat(name, &st) != 0) {
 278       fail_continue("Required classpath entry does not exist: %s", name);
 279       ok = false;
 280     } else if (ent->is_dir()) {
 281       if (!os::dir_is_empty(name)) {
 282         fail_continue("directory is not empty: %s", name);
 283         ok = false;
 284       }
 285     } else if (ent->is_jar()) {
 286       if (ent->_timestamp != st.st_mtime ||
 287           ent->_filesize != st.st_size) {
 288         ok = false;
 289         if (PrintSharedArchiveAndExit) {
 290           fail_continue(ent->_timestamp != st.st_mtime ?
 291                         "Timestamp mismatch" :
 292                         "File size mismatch");
 293         } else {
 294           fail_continue("A jar file is not the one used while building"
 295                         " the shared archive file: %s", name);
 296         }
 297       }
 298     }
 299     if (ok) {
 300       log_info(classpath)("ok");


 301     } else if (!PrintSharedArchiveAndExit) {
 302       _validating_classpath_entry_table = false;
 303       return false;
 304     }
 305   }
 306 
 307   _classpath_entry_table_size = _header->_classpath_entry_table_size;
 308   _validating_classpath_entry_table = false;
 309   return true;
 310 }
 311 
 312 
 313 // Read the FileMapInfo information from the file.
 314 
 315 bool FileMapInfo::init_from_file(int fd) {
 316   size_t sz = _header->data_size();
 317   char* addr = _header->data();
 318   size_t n = os::read(fd, addr, (unsigned int)sz);
 319   if (n != sz) {
 320     fail_continue("Unable to read the file header.");
 321     return false;
 322   }
 323   if (_header->_version != current_version()) {
 324     fail_continue("The shared archive file has the wrong version.");
 325     return false;
 326   }
 327   _file_offset = (long)n;
 328 
 329   size_t info_size = _header->_paths_misc_info_size;
 330   _paths_misc_info = NEW_C_HEAP_ARRAY_RETURN_NULL(char, info_size, mtClass);
 331   if (_paths_misc_info == NULL) {
 332     fail_continue("Unable to read the file header.");
 333     return false;
 334   }
 335   n = os::read(fd, _paths_misc_info, (unsigned int)info_size);
 336   if (n != info_size) {
 337     fail_continue("Unable to read the shared path info header.");
 338     FREE_C_HEAP_ARRAY(char, _paths_misc_info);
 339     _paths_misc_info = NULL;
 340     return false;
 341   }
 342 
 343   size_t len = lseek(fd, 0, SEEK_END);
 344   struct FileMapInfo::FileMapHeader::space_info* si =
 345     &_header->_space[MetaspaceShared::mc];
 346   if (si->_file_offset >= len || len - si->_file_offset < si->_used) {
 347     fail_continue("The shared archive file has been truncated.");
 348     return false;
 349   }
 350 
 351   _file_offset += (long)n;
 352   return true;
 353 }
 354 
 355 
 356 // Read the FileMapInfo information from the file.
 357 bool FileMapInfo::open_for_read() {
 358   _full_path = Arguments::GetSharedArchivePath();
 359   int fd = open(_full_path, O_RDONLY | O_BINARY, 0);
 360   if (fd < 0) {
 361     if (errno == ENOENT) {
 362       // Not locating the shared archive is ok.
 363       fail_continue("Specified shared archive not found.");
 364     } else {
 365       fail_continue("Failed to open shared archive file (%s).",
 366                     strerror(errno));
 367     }
 368     return false;
 369   }
 370 
 371   _fd = fd;
 372   _file_open = true;
 373   return true;
 374 }
 375 
 376 
 377 // Write the FileMapInfo information to the file.
 378 
 379 void FileMapInfo::open_for_write() {
 380  _full_path = Arguments::GetSharedArchivePath();
 381   if (PrintSharedSpaces) {
 382     tty->print_cr("Dumping shared data to file: ");
 383     tty->print_cr("   %s", _full_path);
 384   }
 385 
 386 #ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
 387   chmod(_full_path, _S_IREAD | _S_IWRITE);
 388 #endif
 389 
 390   // Use remove() to delete the existing file because, on Unix, this will
 391   // allow processes that have it open continued access to the file.
 392   remove(_full_path);
 393   int fd = open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
 394   if (fd < 0) {
 395     fail_stop("Unable to create shared archive file %s: (%s).", _full_path,
 396               strerror(errno));
 397   }
 398   _fd = fd;
 399   _file_offset = 0;
 400   _file_open = true;
 401 }
 402 
 403 
 404 // Write the header to the file, seek to the next allocation boundary.
 405 
 406 void FileMapInfo::write_header() {
 407   int info_size = ClassLoader::get_shared_paths_misc_info_size();
 408 
 409   _header->_paths_misc_info_size = info_size;
 410 
 411   align_file_position();
 412   size_t sz = _header->data_size();
 413   char* addr = _header->data();
 414   write_bytes(addr, (int)sz); // skip the C++ vtable
 415   write_bytes(ClassLoader::get_shared_paths_misc_info(), info_size);
 416   align_file_position();
 417 }
 418 
 419 
 420 // Dump shared spaces to file.
 421 
 422 void FileMapInfo::write_space(int i, Metaspace* space, bool read_only) {
 423   align_file_position();
 424   size_t used = space->used_bytes_slow(Metaspace::NonClassType);
 425   size_t capacity = space->capacity_bytes_slow(Metaspace::NonClassType);
 426   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 427   write_region(i, (char*)space->bottom(), used, capacity, read_only, false);
 428 }
 429 
 430 
 431 // Dump region to file.
 432 
 433 void FileMapInfo::write_region(int region, char* base, size_t size,
 434                                size_t capacity, bool read_only,
 435                                bool allow_exec) {
 436   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[region];
 437 
 438   if (_file_open) {
 439     guarantee(si->_file_offset == _file_offset, "file offset mismatch.");
 440     if (PrintSharedSpaces) {
 441       tty->print_cr("Shared file region %d: " SIZE_FORMAT_HEX_W(6) " bytes, addr " INTPTR_FORMAT
 442                     " file offset " SIZE_FORMAT_HEX_W(6), region, size, p2i(base), _file_offset);
 443     }
 444   } else {
 445     si->_file_offset = _file_offset;
 446   }
 447   if (MetaspaceShared::is_string_region(region)) {
 448     assert((base - (char*)Universe::narrow_oop_base()) % HeapWordSize == 0, "Sanity");
 449     if (base != NULL) {
 450       si->_addr._offset = (intx)oopDesc::encode_heap_oop_not_null((oop)base);
 451     } else {
 452       si->_addr._offset = 0;
 453     }
 454   } else {
 455     si->_addr._base = base;
 456   }
 457   si->_used = size;
 458   si->_capacity = capacity;
 459   si->_read_only = read_only;
 460   si->_allow_exec = allow_exec;
 461   si->_crc = ClassLoader::crc32(0, base, (jint)size);
 462   write_bytes_aligned(base, (int)size);
 463 }
 464 
 465 // Write the string space. The string space contains one or multiple GC(G1) regions.
 466 // When the total string space size is smaller than one GC region of the dump time,
 467 // only one string region is used for shared strings.
 468 //
 469 // If the total string space size is bigger than one GC region, there would be more
 470 // than one GC regions allocated for shared strings. The first/bottom GC region might
 471 // be a partial GC region with the empty portion at the higher address within that region.
 472 // The non-empty portion of the first region is written into the archive as one string
 473 // region. The rest are consecutive full GC regions if they exist, which can be written
 474 // out in one chunk as another string region.
 475 void FileMapInfo::write_string_regions(GrowableArray<MemRegion> *regions) {
 476   for (int i = MetaspaceShared::first_string;
 477            i < MetaspaceShared::first_string + MetaspaceShared::max_strings; i++) {
 478     char* start = NULL;
 479     size_t size = 0;
 480     if (regions->is_nonempty()) {
 481       if (i == MetaspaceShared::first_string) {
 482         MemRegion first = regions->first();
 483         start = (char*)first.start();
 484         size = first.byte_size();
 485       } else {
 486         int len = regions->length();
 487         if (len > 1) {
 488           start = (char*)regions->at(1).start();
 489           size = (char*)regions->at(len - 1).end() - start;
 490         }
 491       }
 492     }
 493     write_region(i, start, size, size, false, false);
 494   }
 495 }
 496 
 497 
 498 // Dump bytes to file -- at the current file position.
 499 
 500 void FileMapInfo::write_bytes(const void* buffer, int nbytes) {
 501   if (_file_open) {
 502     int n = ::write(_fd, buffer, nbytes);
 503     if (n != nbytes) {
 504       // It is dangerous to leave the corrupted shared archive file around,
 505       // close and remove the file. See bug 6372906.
 506       close();
 507       remove(_full_path);
 508       fail_stop("Unable to write to shared archive file.");
 509     }
 510   }
 511   _file_offset += nbytes;
 512 }
 513 
 514 
 515 // Align file position to an allocation unit boundary.
 516 
 517 void FileMapInfo::align_file_position() {
 518   size_t new_file_offset = align_size_up(_file_offset,
 519                                          os::vm_allocation_granularity());
 520   if (new_file_offset != _file_offset) {
 521     _file_offset = new_file_offset;
 522     if (_file_open) {
 523       // Seek one byte back from the target and write a byte to insure
 524       // that the written file is the correct length.
 525       _file_offset -= 1;
 526       if (lseek(_fd, (long)_file_offset, SEEK_SET) < 0) {
 527         fail_stop("Unable to seek.");
 528       }
 529       char zero = 0;
 530       write_bytes(&zero, 1);
 531     }
 532   }
 533 }
 534 
 535 
 536 // Dump bytes to file -- at the current file position.
 537 
 538 void FileMapInfo::write_bytes_aligned(const void* buffer, int nbytes) {
 539   align_file_position();
 540   write_bytes(buffer, nbytes);
 541   align_file_position();
 542 }
 543 
 544 
 545 // Close the shared archive file.  This does NOT unmap mapped regions.
 546 
 547 void FileMapInfo::close() {
 548   if (_file_open) {
 549     if (::close(_fd) < 0) {
 550       fail_stop("Unable to close the shared archive file.");
 551     }
 552     _file_open = false;
 553     _fd = -1;
 554   }
 555 }
 556 
 557 
 558 // JVM/TI RedefineClasses() support:
 559 // Remap the shared readonly space to shared readwrite, private.
 560 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
 561   int idx = 0;
 562   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[idx];
 563   if (!si->_read_only) {
 564     // the space is already readwrite so we are done
 565     return true;
 566   }
 567   size_t used = si->_used;
 568   size_t size = align_size_up(used, os::vm_allocation_granularity());
 569   if (!open_for_read()) {
 570     return false;
 571   }
 572   char *addr = _header->region_addr(idx);
 573   char *base = os::remap_memory(_fd, _full_path, si->_file_offset,
 574                                 addr, size, false /* !read_only */,
 575                                 si->_allow_exec);
 576   close();
 577   if (base == NULL) {
 578     fail_continue("Unable to remap shared readonly space (errno=%d).", errno);
 579     return false;
 580   }
 581   if (base != addr) {
 582     fail_continue("Unable to remap shared readonly space at required address.");
 583     return false;
 584   }
 585   si->_read_only = false;
 586   return true;
 587 }
 588 
 589 // Map the whole region at once, assumed to be allocated contiguously.
 590 ReservedSpace FileMapInfo::reserve_shared_memory() {
 591   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[0];
 592   char* requested_addr = _header->region_addr(0);
 593 
 594   size_t size = FileMapInfo::shared_spaces_size();
 595 
 596   // Reserve the space first, then map otherwise map will go right over some
 597   // other reserved memory (like the code cache).
 598   ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr);
 599   if (!rs.is_reserved()) {
 600     fail_continue("Unable to reserve shared space at required address "
 601                   INTPTR_FORMAT, p2i(requested_addr));
 602     return rs;
 603   }
 604   // the reserved virtual memory is for mapping class data sharing archive
 605   MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared);
 606 
 607   return rs;
 608 }
 609 
 610 // Memory map a region in the address space.
 611 static const char* shared_region_name[] = { "ReadOnly", "ReadWrite", "MiscData", "MiscCode",
 612                                             "String1", "String2" };
 613 
 614 char* FileMapInfo::map_region(int i) {
 615   assert(!MetaspaceShared::is_string_region(i), "sanity");
 616   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 617   size_t used = si->_used;
 618   size_t alignment = os::vm_allocation_granularity();
 619   size_t size = align_size_up(used, alignment);
 620   char *requested_addr = _header->region_addr(i);
 621 
 622   // If a tool agent is in use (debugging enabled), we must map the address space RW
 623   if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space()) {
 624     si->_read_only = false;
 625   }
 626 
 627   // map the contents of the CDS archive in this memory
 628   char *base = os::map_memory(_fd, _full_path, si->_file_offset,
 629                               requested_addr, size, si->_read_only,
 630                               si->_allow_exec);
 631   if (base == NULL || base != requested_addr) {
 632     fail_continue("Unable to map %s shared space at required address.", shared_region_name[i]);
 633     return NULL;
 634   }
 635 #ifdef _WINDOWS
 636   // This call is Windows-only because the memory_type gets recorded for the other platforms
 637   // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows.
 638   MemTracker::record_virtual_memory_type((address)base, mtClassShared);
 639 #endif
 640 
 641   return base;
 642 }
 643 
 644 static MemRegion *string_ranges = NULL;
 645 static int num_ranges = 0;
 646 bool FileMapInfo::map_string_regions() {
 647 #if INCLUDE_ALL_GCS
 648   if (UseG1GC && UseCompressedOops && UseCompressedClassPointers) {
 649     // Check that all the narrow oop and klass encodings match the archive
 650     if (narrow_oop_mode() != Universe::narrow_oop_mode() ||
 651         narrow_oop_shift() != Universe::narrow_oop_shift() ||
 652         narrow_klass_base() != Universe::narrow_klass_base() ||
 653         narrow_klass_shift() != Universe::narrow_klass_shift()) {
 654       if (PrintSharedSpaces && _header->_space[MetaspaceShared::first_string]._used > 0) {
 655         tty->print_cr("Shared string data from the CDS archive is being ignored. "
 656                      "The current CompressedOops/CompressedClassPointers encoding differs from "
 657                      "that archived due to heap size change. The archive was dumped using max heap "
 658                      "size " UINTX_FORMAT "M.", max_heap_size()/M);
 659       }
 660     } else {
 661       string_ranges = new MemRegion[MetaspaceShared::max_strings];
 662       struct FileMapInfo::FileMapHeader::space_info* si;
 663 
 664       for (int i = MetaspaceShared::first_string;
 665                i < MetaspaceShared::first_string + MetaspaceShared::max_strings; i++) {
 666         si = &_header->_space[i];
 667         size_t used = si->_used;
 668         if (used > 0) {
 669           size_t size = used;
 670           char* requested_addr = (char*)((void*)oopDesc::decode_heap_oop_not_null(
 671                                                  (narrowOop)si->_addr._offset));
 672           string_ranges[num_ranges] = MemRegion((HeapWord*)requested_addr, size / HeapWordSize);
 673           num_ranges ++;
 674         }
 675       }
 676 
 677       if (num_ranges == 0) {
 678         StringTable::ignore_shared_strings(true);
 679         return true; // no shared string data
 680       }
 681 
 682       // Check that ranges are within the java heap
 683       if (!G1CollectedHeap::heap()->check_archive_addresses(string_ranges, num_ranges)) {
 684         fail_continue("Unable to allocate shared string space: range is not "
 685                       "within java heap.");
 686         return false;
 687       }
 688 
 689       // allocate from java heap
 690       if (!G1CollectedHeap::heap()->alloc_archive_regions(string_ranges, num_ranges)) {
 691         fail_continue("Unable to allocate shared string space: range is "
 692                       "already in use.");
 693         return false;
 694       }
 695 
 696       // Map the string data. No need to call MemTracker::record_virtual_memory_type()
 697       // for mapped string regions as they are part of the reserved java heap, which
 698       // is already recorded.
 699       for (int i = 0; i < num_ranges; i++) {
 700         si = &_header->_space[MetaspaceShared::first_string + i];
 701         char* addr = (char*)string_ranges[i].start();
 702         char* base = os::map_memory(_fd, _full_path, si->_file_offset,
 703                                     addr, string_ranges[i].byte_size(), si->_read_only,
 704                                     si->_allow_exec);
 705         if (base == NULL || base != addr) {
 706           // dealloc the string regions from java heap
 707           dealloc_string_regions();
 708           fail_continue("Unable to map shared string space at required address.");
 709           return false;
 710         }
 711       }
 712 
 713       if (!verify_string_regions()) {
 714         // dealloc the string regions from java heap
 715         dealloc_string_regions();
 716         fail_continue("Shared string regions are corrupt");
 717         return false;
 718       }
 719 
 720       // the shared string data is mapped successfully
 721       return true;
 722     }
 723   } else {
 724     if (PrintSharedSpaces && _header->_space[MetaspaceShared::first_string]._used > 0) {
 725       tty->print_cr("Shared string data from the CDS archive is being ignored. UseG1GC, "
 726                     "UseCompressedOops and UseCompressedClassPointers are required.");
 727     }
 728   }
 729 
 730   // if we get here, the shared string data is not mapped
 731   assert(string_ranges == NULL && num_ranges == 0, "sanity");
 732   StringTable::ignore_shared_strings(true);
 733 #endif
 734   return true;
 735 }
 736 
 737 bool FileMapInfo::verify_string_regions() {
 738   for (int i = MetaspaceShared::first_string;
 739            i < MetaspaceShared::first_string + MetaspaceShared::max_strings; i++) {
 740     if (!verify_region_checksum(i)) {
 741       return false;
 742     }
 743   }
 744   return true;
 745 }
 746 
 747 void FileMapInfo::fixup_string_regions() {
 748 #if INCLUDE_ALL_GCS
 749   // If any string regions were found, call the fill routine to make them parseable.
 750   // Note that string_ranges may be non-NULL even if no ranges were found.
 751   if (num_ranges != 0) {
 752     assert(string_ranges != NULL, "Null string_ranges array with non-zero count");
 753     G1CollectedHeap::heap()->fill_archive_regions(string_ranges, num_ranges);
 754   }
 755 #endif
 756 }
 757 
 758 bool FileMapInfo::verify_region_checksum(int i) {
 759   if (!VerifySharedSpaces) {
 760     return true;
 761   }
 762 
 763   size_t sz = _header->_space[i]._used;
 764 
 765   if (sz == 0) {
 766     return true; // no data
 767   }
 768   if (MetaspaceShared::is_string_region(i) && StringTable::shared_string_ignored()) {
 769     return true; // shared string data are not mapped
 770   }
 771   const char* buf = _header->region_addr(i);
 772   int crc = ClassLoader::crc32(0, buf, (jint)sz);
 773   if (crc != _header->_space[i]._crc) {
 774     fail_continue("Checksum verification failed.");
 775     return false;
 776   }
 777   return true;
 778 }
 779 
 780 // Unmap a memory region in the address space.
 781 
 782 void FileMapInfo::unmap_region(int i) {
 783   assert(!MetaspaceShared::is_string_region(i), "sanity");
 784   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 785   size_t used = si->_used;
 786   size_t size = align_size_up(used, os::vm_allocation_granularity());
 787 
 788   if (used == 0) {
 789     return;
 790   }
 791 
 792   char* addr = _header->region_addr(i);
 793   if (!os::unmap_memory(addr, size)) {
 794     fail_stop("Unable to unmap shared space.");
 795   }
 796 }
 797 
 798 // dealloc the archived string region from java heap
 799 void FileMapInfo::dealloc_string_regions() {
 800 #if INCLUDE_ALL_GCS
 801   if (num_ranges > 0) {
 802     assert(string_ranges != NULL, "Null string_ranges array with non-zero count");
 803     G1CollectedHeap::heap()->dealloc_archive_regions(string_ranges, num_ranges);
 804   }
 805 #endif
 806 }
 807 
 808 void FileMapInfo::assert_mark(bool check) {
 809   if (!check) {
 810     fail_stop("Mark mismatch while restoring from shared file.");
 811   }
 812 }
 813 
 814 
 815 FileMapInfo* FileMapInfo::_current_info = NULL;
 816 SharedClassPathEntry* FileMapInfo::_classpath_entry_table = NULL;
 817 int FileMapInfo::_classpath_entry_table_size = 0;
 818 size_t FileMapInfo::_classpath_entry_size = 0x1234baad;
 819 bool FileMapInfo::_validating_classpath_entry_table = false;
 820 
 821 // Open the shared archive file, read and validate the header
 822 // information (version, boot classpath, etc.).  If initialization
 823 // fails, shared spaces are disabled and the file is closed. [See
 824 // fail_continue.]
 825 //
 826 // Validation of the archive is done in two steps:
 827 //
 828 // [1] validate_header() - done here. This checks the header, including _paths_misc_info.
 829 // [2] validate_classpath_entry_table - this is done later, because the table is in the RW
 830 //     region of the archive, which is not mapped yet.
 831 bool FileMapInfo::initialize() {
 832   assert(UseSharedSpaces, "UseSharedSpaces expected.");
 833 
 834   if (!open_for_read()) {
 835     return false;
 836   }
 837 
 838   init_from_file(_fd);
 839   if (!validate_header()) {
 840     return false;
 841   }
 842 
 843   SharedReadOnlySize =  _header->_space[0]._capacity;
 844   SharedReadWriteSize = _header->_space[1]._capacity;
 845   SharedMiscDataSize =  _header->_space[2]._capacity;
 846   SharedMiscCodeSize =  _header->_space[3]._capacity;
 847   return true;
 848 }
 849 
 850 char* FileMapInfo::FileMapHeader::region_addr(int idx) {
 851   if (MetaspaceShared::is_string_region(idx)) {
 852     return (char*)((void*)oopDesc::decode_heap_oop_not_null(
 853               (narrowOop)_space[idx]._addr._offset));
 854   } else {
 855     return _space[idx]._addr._base;
 856   }
 857 }
 858 
 859 int FileMapInfo::FileMapHeader::compute_crc() {
 860   char* header = data();
 861   // start computing from the field after _crc
 862   char* buf = (char*)&_crc + sizeof(int);
 863   size_t sz = data_size() - (buf - header);
 864   int crc = ClassLoader::crc32(0, buf, (jint)sz);
 865   return crc;
 866 }
 867 
 868 bool FileMapInfo::FileMapHeader::validate() {
 869   if (VerifySharedSpaces && compute_crc() != _crc) {
 870     fail_continue("Header checksum verification failed.");
 871     return false;
 872   }
 873 
 874   if (_version != current_version()) {
 875     FileMapInfo::fail_continue("The shared archive file is the wrong version.");
 876     return false;
 877   }
 878   if (_magic != (int)0xf00baba2) {
 879     FileMapInfo::fail_continue("The shared archive file has a bad magic number.");
 880     return false;
 881   }
 882   char header_version[JVM_IDENT_MAX];
 883   get_header_version(header_version);
 884   if (strncmp(_jvm_ident, header_version, JVM_IDENT_MAX-1) != 0) {
 885     log_info(classpath)("expected: %s", header_version);
 886     log_info(classpath)("actual:   %s", _jvm_ident);


 887     FileMapInfo::fail_continue("The shared archive file was created by a different"
 888                   " version or build of HotSpot");
 889     return false;
 890   }
 891   if (_obj_alignment != ObjectAlignmentInBytes) {
 892     FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"
 893                   " does not equal the current ObjectAlignmentInBytes of " INTX_FORMAT ".",
 894                   _obj_alignment, ObjectAlignmentInBytes);
 895     return false;
 896   }
 897   if (_compact_strings != CompactStrings) {
 898     FileMapInfo::fail_continue("The shared archive file's CompactStrings setting (%s)"
 899                   " does not equal the current CompactStrings setting (%s).",
 900                   _compact_strings ? "enabled" : "disabled",
 901                   CompactStrings   ? "enabled" : "disabled");
 902     return false;
 903   }
 904 
 905   return true;
 906 }
 907 
 908 bool FileMapInfo::validate_header() {
 909   bool status = _header->validate();
 910 
 911   if (status) {
 912     if (!ClassLoader::check_shared_paths_misc_info(_paths_misc_info, _header->_paths_misc_info_size)) {
 913       if (!PrintSharedArchiveAndExit) {
 914         fail_continue("shared class paths mismatch (hint: enable -Xlog:classpath=info to diagnose the failure)");
 915         status = false;
 916       }
 917     }
 918   }
 919 
 920   if (_paths_misc_info != NULL) {
 921     FREE_C_HEAP_ARRAY(char, _paths_misc_info);
 922     _paths_misc_info = NULL;
 923   }
 924   return status;
 925 }
 926 
 927 // The following method is provided to see whether a given pointer
 928 // falls in the mapped shared space.
 929 // Param:
 930 // p, The given pointer
 931 // Return:
 932 // True if the p is within the mapped shared space, otherwise, false.
 933 bool FileMapInfo::is_in_shared_space(const void* p) {
 934   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
 935     char *base;
 936     if (MetaspaceShared::is_string_region(i) && _header->_space[i]._used == 0) {
 937       continue;
 938     }
 939     base = _header->region_addr(i);
 940     if (p >= base && p < base + _header->_space[i]._used) {
 941       return true;
 942     }
 943   }
 944 
 945   return false;
 946 }
 947 
 948 void FileMapInfo::print_shared_spaces() {
 949   tty->print_cr("Shared Spaces:");
 950   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
 951     struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 952     char *base = _header->region_addr(i);
 953     tty->print("  %s " INTPTR_FORMAT "-" INTPTR_FORMAT,
 954                         shared_region_name[i],
 955                         p2i(base), p2i(base + si->_used));
 956   }
 957 }
 958 
 959 // Unmap mapped regions of shared space.
 960 void FileMapInfo::stop_sharing_and_unmap(const char* msg) {
 961   FileMapInfo *map_info = FileMapInfo::current_info();
 962   if (map_info) {
 963     map_info->fail_continue("%s", msg);
 964     for (int i = 0; i < MetaspaceShared::num_non_strings; i++) {
 965       char *addr = map_info->_header->region_addr(i);
 966       if (addr != NULL && !MetaspaceShared::is_string_region(i)) {
 967         map_info->unmap_region(i);
 968         map_info->_header->_space[i]._addr._base = NULL;
 969       }
 970     }
 971     // Dealloc the string regions only without unmapping. The string regions are part
 972     // of the java heap. Unmapping of the heap regions are managed by GC.
 973     map_info->dealloc_string_regions();
 974   } else if (DumpSharedSpaces) {
 975     fail_stop("%s", msg);
 976   }
 977 }
--- EOF ---