1 /*
   2  * Copyright (c) 2003, 2015, 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/sharedClassUtil.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/systemDictionaryShared.hpp"
  30 #include "classfile/altHashing.hpp"
  31 #if INCLUDE_ALL_GCS
  32 #include "gc/g1/g1CollectedHeap.hpp"
  33 #endif
  34 #include "memory/filemap.hpp"
  35 #include "memory/metadataFactory.hpp"
  36 #include "memory/oopFactory.hpp"
  37 #include "oops/objArrayOop.hpp"
  38 #include "prims/jvmtiExport.hpp"
  39 #include "runtime/arguments.hpp"
  40 #include "runtime/java.hpp"
  41 #include "runtime/os.hpp"
  42 #include "runtime/vm_version.hpp"
  43 #include "services/memTracker.hpp"
  44 #include "utilities/defaultStream.hpp"
  45 
  46 # include <sys/stat.h>
  47 # include <errno.h>
  48 
  49 #ifndef O_BINARY       // if defined (Win32) use binary files.
  50 #define O_BINARY 0     // otherwise do nothing.
  51 #endif
  52 
  53 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  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   _narrow_oop_mode = Universe::narrow_oop_mode();
 173   _narrow_oop_shift = Universe::narrow_oop_shift();
 174   _max_heap_size = MaxHeapSize;
 175   _narrow_klass_base = Universe::narrow_klass_base();
 176   _narrow_klass_shift = Universe::narrow_klass_shift();
 177   _classpath_entry_table_size = mapinfo->_classpath_entry_table_size;
 178   _classpath_entry_table = mapinfo->_classpath_entry_table;
 179   _classpath_entry_size = mapinfo->_classpath_entry_size;
 180 
 181   // The following fields are for sanity checks for whether this archive
 182   // will function correctly with this JVM and the bootclasspath it's
 183   // invoked with.
 184 
 185   // JVM version string ... changes on each build.
 186   get_header_version(_jvm_ident);
 187 }
 188 
 189 void FileMapInfo::allocate_classpath_entry_table() {
 190   int bytes = 0;
 191   int count = 0;
 192   char* strptr = NULL;
 193   char* strptr_max = NULL;
 194   Thread* THREAD = Thread::current();
 195 
 196   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 197   size_t entry_size = SharedClassUtil::shared_class_path_entry_size();
 198 
 199   for (int pass=0; pass<2; pass++) {
 200     ClassPathEntry *cpe = ClassLoader::classpath_entry(0);
 201 
 202     for (int cur_entry = 0 ; cpe != NULL; cpe = cpe->next(), cur_entry++) {
 203       const char *name = cpe->name();
 204       int name_bytes = (int)(strlen(name) + 1);
 205 
 206       if (pass == 0) {
 207         count ++;
 208         bytes += (int)entry_size;
 209         bytes += name_bytes;
 210         if (TraceClassPaths || (TraceClassLoading && Verbose)) {
 211           tty->print_cr("[Add main shared path (%s) %s]", (cpe->is_jar_file() ? "jar" : "dir"), name);
 212         }
 213       } else {
 214         SharedClassPathEntry* ent = shared_classpath(cur_entry);
 215         if (cpe->is_jar_file()) {
 216           struct stat st;
 217           if (os::stat(name, &st) != 0) {
 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 jar file %s.", name);
 224           }
 225 
 226           EXCEPTION_MARK; // The following call should never throw, but would exit VM on error.
 227           SharedClassUtil::update_shared_classpath(cpe, ent, st.st_mtime, st.st_size, THREAD);
 228         } else {
 229           struct stat st;
 230           if ((os::stat(name, &st) == 0) && ((st.st_mode & S_IFDIR) == S_IFDIR)) {
 231             if (!os::dir_is_empty(name)) {
 232               ClassLoader::exit_with_path_failure("Cannot have non-empty directory in archived classpaths", name);
 233             }
 234             ent->_filesize = -1;
 235           } else {
 236             ent->_filesize = -2;
 237           }
 238         }
 239         ent->_name = strptr;
 240         if (strptr + name_bytes <= strptr_max) {
 241           strncpy(strptr, name, (size_t)name_bytes); // name_bytes includes trailing 0.
 242           strptr += name_bytes;
 243         } else {
 244           assert(0, "miscalculated buffer size");
 245         }
 246       }
 247     }
 248 
 249     if (pass == 0) {
 250       EXCEPTION_MARK; // The following call should never throw, but would exit VM on error.
 251       Array<u8>* arr = MetadataFactory::new_array<u8>(loader_data, (bytes + 7)/8, THREAD);
 252       strptr = (char*)(arr->data());
 253       strptr_max = strptr + bytes;
 254       SharedClassPathEntry* table = (SharedClassPathEntry*)strptr;
 255       strptr += entry_size * count;
 256 
 257       _classpath_entry_table_size = count;
 258       _classpath_entry_table = table;
 259       _classpath_entry_size = entry_size;
 260     }
 261   }
 262 }
 263 
 264 bool FileMapInfo::validate_classpath_entry_table() {
 265   _validating_classpath_entry_table = true;
 266 
 267   int count = _header->_classpath_entry_table_size;
 268 
 269   _classpath_entry_table = _header->_classpath_entry_table;
 270   _classpath_entry_size = _header->_classpath_entry_size;
 271 
 272   for (int i=0; i<count; i++) {
 273     SharedClassPathEntry* ent = shared_classpath(i);
 274     struct stat st;
 275     const char* name = ent->_name;
 276     bool ok = true;
 277     if (TraceClassPaths || (TraceClassLoading && Verbose)) {
 278       tty->print_cr("[Checking shared classpath entry: %s]", name);
 279     }
 280     if (os::stat(name, &st) != 0) {
 281       fail_continue("Required classpath entry does not exist: %s", name);
 282       ok = false;
 283     } else if (ent->is_dir()) {
 284       if (!os::dir_is_empty(name)) {
 285         fail_continue("directory is not empty: %s", name);
 286         ok = false;
 287       }
 288     } else if (ent->is_jar()) {
 289       if (ent->_timestamp != st.st_mtime ||
 290           ent->_filesize != st.st_size) {
 291         ok = false;
 292         if (PrintSharedArchiveAndExit) {
 293           fail_continue(ent->_timestamp != st.st_mtime ?
 294                         "Timestamp mismatch" :
 295                         "File size mismatch");
 296         } else {
 297           fail_continue("A jar file is not the one used while building"
 298                         " the shared archive file: %s", name);
 299         }
 300       }
 301     }
 302     if (ok) {
 303       if (TraceClassPaths || (TraceClassLoading && Verbose)) {
 304         tty->print_cr("[ok]");
 305       }
 306     } else if (!PrintSharedArchiveAndExit) {
 307       _validating_classpath_entry_table = false;
 308       return false;
 309     }
 310   }
 311 
 312   _classpath_entry_table_size = _header->_classpath_entry_table_size;
 313   _validating_classpath_entry_table = false;
 314   return true;
 315 }
 316 
 317 
 318 // Read the FileMapInfo information from the file.
 319 
 320 bool FileMapInfo::init_from_file(int fd) {
 321   size_t sz = _header->data_size();
 322   char* addr = _header->data();
 323   size_t n = os::read(fd, addr, (unsigned int)sz);
 324   if (n != sz) {
 325     fail_continue("Unable to read the file header.");
 326     return false;
 327   }
 328   if (_header->_version != current_version()) {
 329     fail_continue("The shared archive file has the wrong version.");
 330     return false;
 331   }
 332   _file_offset = (long)n;
 333 
 334   size_t info_size = _header->_paths_misc_info_size;
 335   _paths_misc_info = NEW_C_HEAP_ARRAY_RETURN_NULL(char, info_size, mtClass);
 336   if (_paths_misc_info == NULL) {
 337     fail_continue("Unable to read the file header.");
 338     return false;
 339   }
 340   n = os::read(fd, _paths_misc_info, (unsigned int)info_size);
 341   if (n != info_size) {
 342     fail_continue("Unable to read the shared path info header.");
 343     FREE_C_HEAP_ARRAY(char, _paths_misc_info);
 344     _paths_misc_info = NULL;
 345     return false;
 346   }
 347 
 348   size_t len = lseek(fd, 0, SEEK_END);
 349   struct FileMapInfo::FileMapHeader::space_info* si =
 350     &_header->_space[MetaspaceShared::mc];
 351   if (si->_file_offset >= len || len - si->_file_offset < si->_used) {
 352     fail_continue("The shared archive file has been truncated.");
 353     return false;
 354   }
 355 
 356   _file_offset += (long)n;
 357   return true;
 358 }
 359 
 360 
 361 // Read the FileMapInfo information from the file.
 362 bool FileMapInfo::open_for_read() {
 363   _full_path = Arguments::GetSharedArchivePath();
 364   int fd = open(_full_path, O_RDONLY | O_BINARY, 0);
 365   if (fd < 0) {
 366     if (errno == ENOENT) {
 367       // Not locating the shared archive is ok.
 368       fail_continue("Specified shared archive not found.");
 369     } else {
 370       fail_continue("Failed to open shared archive file (%s).",
 371                     strerror(errno));
 372     }
 373     return false;
 374   }
 375 
 376   _fd = fd;
 377   _file_open = true;
 378   return true;
 379 }
 380 
 381 
 382 // Write the FileMapInfo information to the file.
 383 
 384 void FileMapInfo::open_for_write() {
 385  _full_path = Arguments::GetSharedArchivePath();
 386   if (PrintSharedSpaces) {
 387     tty->print_cr("Dumping shared data to file: ");
 388     tty->print_cr("   %s", _full_path);
 389   }
 390 
 391 #ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
 392   chmod(_full_path, _S_IREAD | _S_IWRITE);
 393 #endif
 394 
 395   // Use remove() to delete the existing file because, on Unix, this will
 396   // allow processes that have it open continued access to the file.
 397   remove(_full_path);
 398   int fd = open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
 399   if (fd < 0) {
 400     fail_stop("Unable to create shared archive file %s: (%s).", _full_path,
 401               strerror(errno));
 402   }
 403   _fd = fd;
 404   _file_offset = 0;
 405   _file_open = true;
 406 }
 407 
 408 
 409 // Write the header to the file, seek to the next allocation boundary.
 410 
 411 void FileMapInfo::write_header() {
 412   int info_size = ClassLoader::get_shared_paths_misc_info_size();
 413 
 414   _header->_paths_misc_info_size = info_size;
 415 
 416   align_file_position();
 417   size_t sz = _header->data_size();
 418   char* addr = _header->data();
 419   write_bytes(addr, (int)sz); // skip the C++ vtable
 420   write_bytes(ClassLoader::get_shared_paths_misc_info(), info_size);
 421   align_file_position();
 422 }
 423 
 424 
 425 // Dump shared spaces to file.
 426 
 427 void FileMapInfo::write_space(int i, Metaspace* space, bool read_only) {
 428   align_file_position();
 429   size_t used = space->used_bytes_slow(Metaspace::NonClassType);
 430   size_t capacity = space->capacity_bytes_slow(Metaspace::NonClassType);
 431   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 432   write_region(i, (char*)space->bottom(), used, capacity, read_only, false);
 433 }
 434 
 435 
 436 // Dump region to file.
 437 
 438 void FileMapInfo::write_region(int region, char* base, size_t size,
 439                                size_t capacity, bool read_only,
 440                                bool allow_exec) {
 441   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[region];
 442 
 443   if (_file_open) {
 444     guarantee(si->_file_offset == _file_offset, "file offset mismatch.");
 445     if (PrintSharedSpaces) {
 446       tty->print_cr("Shared file region %d: 0x%6x bytes, addr " INTPTR_FORMAT
 447                     " file offset 0x%6x", region, size, base, _file_offset);
 448     }
 449   } else {
 450     si->_file_offset = _file_offset;
 451   }
 452   if (MetaspaceShared::is_string_region(region)) {
 453     assert((base - (char*)Universe::narrow_oop_base()) % HeapWordSize == 0, "Sanity");
 454     if (base != NULL) {
 455       si->_addr._offset = (intx)oopDesc::encode_heap_oop_not_null((oop)base);
 456     } else {
 457       si->_addr._offset = 0;
 458     }
 459   } else {
 460     si->_addr._base = base;
 461   }
 462   si->_used = size;
 463   si->_capacity = capacity;
 464   si->_read_only = read_only;
 465   si->_allow_exec = allow_exec;
 466   si->_crc = ClassLoader::crc32(0, base, (jint)size);
 467   write_bytes_aligned(base, (int)size);
 468 }
 469 
 470 // Write the string space. The string space contains one or multiple GC(G1) regions.
 471 // When the total string space size is smaller than one GC region of the dump time,
 472 // only one string region is used for shared strings.
 473 //
 474 // If the total string space size is bigger than one GC region, there would be more
 475 // than one GC regions allocated for shared strings. The first/bottom GC region might
 476 // be a partial GC region with the empty portion at the higher address within that region.
 477 // The non-empty portion of the first region is written into the archive as one string
 478 // region. The rest are consecutive full GC regions if they exist, which can be written
 479 // out in one chunk as another string region.
 480 void FileMapInfo::write_string_regions(GrowableArray<MemRegion> *regions) {
 481   for (int i = MetaspaceShared::first_string;
 482            i < MetaspaceShared::first_string + MetaspaceShared::max_strings; i++) {
 483     char* start = NULL;
 484     size_t size = 0;
 485     if (regions->is_nonempty()) {
 486       if (i == MetaspaceShared::first_string) {
 487         MemRegion first = regions->first();
 488         start = (char*)first.start();
 489         size = first.byte_size();
 490       } else {
 491         int len = regions->length();
 492         if (len > 1) {
 493           start = (char*)regions->at(1).start();
 494           size = (char*)regions->at(len - 1).end() - start;
 495         }
 496       }
 497     }
 498     write_region(i, start, size, size, false, false);
 499   }
 500 }
 501 
 502 
 503 // Dump bytes to file -- at the current file position.
 504 
 505 void FileMapInfo::write_bytes(const void* buffer, int nbytes) {
 506   if (_file_open) {
 507     int n = ::write(_fd, buffer, nbytes);
 508     if (n != nbytes) {
 509       // It is dangerous to leave the corrupted shared archive file around,
 510       // close and remove the file. See bug 6372906.
 511       close();
 512       remove(_full_path);
 513       fail_stop("Unable to write to shared archive file.");
 514     }
 515   }
 516   _file_offset += nbytes;
 517 }
 518 
 519 
 520 // Align file position to an allocation unit boundary.
 521 
 522 void FileMapInfo::align_file_position() {
 523   size_t new_file_offset = align_size_up(_file_offset,
 524                                          os::vm_allocation_granularity());
 525   if (new_file_offset != _file_offset) {
 526     _file_offset = new_file_offset;
 527     if (_file_open) {
 528       // Seek one byte back from the target and write a byte to insure
 529       // that the written file is the correct length.
 530       _file_offset -= 1;
 531       if (lseek(_fd, (long)_file_offset, SEEK_SET) < 0) {
 532         fail_stop("Unable to seek.");
 533       }
 534       char zero = 0;
 535       write_bytes(&zero, 1);
 536     }
 537   }
 538 }
 539 
 540 
 541 // Dump bytes to file -- at the current file position.
 542 
 543 void FileMapInfo::write_bytes_aligned(const void* buffer, int nbytes) {
 544   align_file_position();
 545   write_bytes(buffer, nbytes);
 546   align_file_position();
 547 }
 548 
 549 
 550 // Close the shared archive file.  This does NOT unmap mapped regions.
 551 
 552 void FileMapInfo::close() {
 553   if (_file_open) {
 554     if (::close(_fd) < 0) {
 555       fail_stop("Unable to close the shared archive file.");
 556     }
 557     _file_open = false;
 558     _fd = -1;
 559   }
 560 }
 561 
 562 
 563 // JVM/TI RedefineClasses() support:
 564 // Remap the shared readonly space to shared readwrite, private.
 565 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
 566   int idx = 0;
 567   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[idx];
 568   if (!si->_read_only) {
 569     // the space is already readwrite so we are done
 570     return true;
 571   }
 572   size_t used = si->_used;
 573   size_t size = align_size_up(used, os::vm_allocation_granularity());
 574   if (!open_for_read()) {
 575     return false;
 576   }
 577   char *addr = _header->region_addr(idx);
 578   char *base = os::remap_memory(_fd, _full_path, si->_file_offset,
 579                                 addr, size, false /* !read_only */,
 580                                 si->_allow_exec);
 581   close();
 582   if (base == NULL) {
 583     fail_continue("Unable to remap shared readonly space (errno=%d).", errno);
 584     return false;
 585   }
 586   if (base != addr) {
 587     fail_continue("Unable to remap shared readonly space at required address.");
 588     return false;
 589   }
 590   si->_read_only = false;
 591   return true;
 592 }
 593 
 594 // Map the whole region at once, assumed to be allocated contiguously.
 595 ReservedSpace FileMapInfo::reserve_shared_memory() {
 596   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[0];
 597   char* requested_addr = _header->region_addr(0);
 598 
 599   size_t size = FileMapInfo::shared_spaces_size();
 600 
 601   // Reserve the space first, then map otherwise map will go right over some
 602   // other reserved memory (like the code cache).
 603   ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr);
 604   if (!rs.is_reserved()) {
 605     fail_continue("Unable to reserve shared space at required address " INTPTR_FORMAT, requested_addr);
 606     return rs;
 607   }
 608   // the reserved virtual memory is for mapping class data sharing archive
 609   MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared);
 610 
 611   return rs;
 612 }
 613 
 614 // Memory map a region in the address space.
 615 static const char* shared_region_name[] = { "ReadOnly", "ReadWrite", "MiscData", "MiscCode",
 616                                             "String1", "String2" };
 617 
 618 char* FileMapInfo::map_region(int i) {
 619   assert(!MetaspaceShared::is_string_region(i), "sanity");
 620   struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 621   size_t used = si->_used;
 622   size_t alignment = os::vm_allocation_granularity();
 623   size_t size = align_size_up(used, alignment);
 624   char *requested_addr = _header->region_addr(i);
 625 
 626   // If a tool agent is in use (debugging enabled), we must map the address space RW
 627   if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space()) {
 628     si->_read_only = false;
 629   }
 630 
 631   // map the contents of the CDS archive in this memory
 632   char *base = os::map_memory(_fd, _full_path, si->_file_offset,
 633                               requested_addr, size, si->_read_only,
 634                               si->_allow_exec);
 635   if (base == NULL || base != requested_addr) {
 636     fail_continue("Unable to map %s shared space at required address.", shared_region_name[i]);
 637     return NULL;
 638   }
 639 #ifdef _WINDOWS
 640   // This call is Windows-only because the memory_type gets recorded for the other platforms
 641   // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows.
 642   MemTracker::record_virtual_memory_type((address)base, mtClassShared);
 643 #endif
 644 
 645   return base;
 646 }
 647 
 648 static MemRegion *string_ranges = NULL;
 649 static int num_ranges = 0;
 650 bool FileMapInfo::map_string_regions() {
 651 #if INCLUDE_ALL_GCS
 652   if (UseG1GC && UseCompressedOops && UseCompressedClassPointers) {
 653     // Check that all the narrow oop and klass encodings match the archive
 654     if (narrow_oop_mode() != Universe::narrow_oop_mode() ||
 655         narrow_oop_shift() != Universe::narrow_oop_shift() ||
 656         narrow_klass_base() != Universe::narrow_klass_base() ||
 657         narrow_klass_shift() != Universe::narrow_klass_shift()) {
 658       if (PrintSharedSpaces && _header->_space[MetaspaceShared::first_string]._used > 0) {
 659         tty->print_cr("Shared string data from the CDS archive is being ignored. "
 660                      "The current CompressedOops/CompressedClassPointers encoding differs from "
 661                      "that archived due to heap size change. The archive was dumped using max heap "
 662                      "size %dM.", max_heap_size()/M);
 663       }
 664     } else {
 665       string_ranges = new MemRegion[MetaspaceShared::max_strings];
 666       struct FileMapInfo::FileMapHeader::space_info* si;
 667 
 668       for (int i = MetaspaceShared::first_string;
 669                i < MetaspaceShared::first_string + MetaspaceShared::max_strings; i++) {
 670         si = &_header->_space[i];
 671         size_t used = si->_used;
 672         if (used > 0) {
 673           size_t size = used;
 674           char* requested_addr = (char*)((void*)oopDesc::decode_heap_oop_not_null(
 675                                                  (narrowOop)si->_addr._offset));
 676           string_ranges[num_ranges] = MemRegion((HeapWord*)requested_addr, size / HeapWordSize);
 677           num_ranges ++;
 678         }
 679       }
 680 
 681       if (num_ranges == 0) {
 682         StringTable::ignore_shared_strings(true);
 683         return true; // no shared string data
 684       }
 685 
 686       // Check that ranges are within the java heap
 687       if (!G1CollectedHeap::heap()->check_archive_addresses(string_ranges, num_ranges)) {
 688         fail_continue("Unable to allocate shared string space: range is not "
 689                       "within java heap.");
 690         return false;
 691       }
 692 
 693       // allocate from java heap
 694       if (!G1CollectedHeap::heap()->alloc_archive_regions(string_ranges, num_ranges)) {
 695         fail_continue("Unable to allocate shared string space: range is "
 696                       "already in use.");
 697         return false;
 698       }
 699 
 700       // Map the string data. No need to call MemTracker::record_virtual_memory_type()
 701       // for mapped string regions as they are part of the reserved java heap, which
 702       // is already recorded.
 703       for (int i = 0; i < num_ranges; i++) {
 704         si = &_header->_space[MetaspaceShared::first_string + i];
 705         char* addr = (char*)string_ranges[i].start();
 706         char* base = os::map_memory(_fd, _full_path, si->_file_offset,
 707                                     addr, string_ranges[i].byte_size(), si->_read_only,
 708                                     si->_allow_exec);
 709         if (base == NULL || base != addr) {
 710           // free the archived region from java heap
 711           G1CollectedHeap::heap()->free_archive_regions(string_ranges, num_ranges); 
 712           fail_continue("Unable to map shared string space at required address.");
 713           return false;
 714         }
 715       }
 716 
 717       if (!verify_string_regions()) {
 718         fail_continue("Shared string regions are corrupt");
 719         return false;
 720       }
 721 
 722       // the shared string data is mapped successfully
 723       return true;
 724     }
 725   } else {
 726     if (PrintSharedSpaces && _header->_space[MetaspaceShared::first_string]._used > 0) {
 727       tty->print_cr("Shared string data from the CDS archive is being ignored. UseG1GC, "
 728                     "UseCompressedOops and UseCompressedClassPointers are required.");
 729     }
 730   }
 731 
 732   // if we get here, the shared string data is not mapped
 733   assert(string_ranges == NULL && num_ranges == 0, "sanity");
 734   StringTable::ignore_shared_strings(true);
 735 #endif
 736   return true;
 737 }
 738 
 739 bool FileMapInfo::verify_string_regions() {
 740   for (int i = MetaspaceShared::first_string;
 741            i < MetaspaceShared::first_string + MetaspaceShared::max_strings; i++) {
 742     if (!verify_region_checksum(i)) {
 743       return false;
 744     }
 745   }
 746   return true;
 747 }
 748 
 749 void FileMapInfo::fixup_string_regions() {
 750   // If any string regions were found, call the fill routine to make them parseable.
 751   // Note that string_ranges may be non-NULL even if no ranges were found.
 752   if (num_ranges != 0) {
 753     assert(string_ranges != NULL, "Null string_ranges array with non-zero count");
 754     G1CollectedHeap::heap()->fill_archive_regions(string_ranges, num_ranges);
 755   }
 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 void FileMapInfo::unmap_string_regions() {
 799   for (int i = MetaspaceShared::first_string;
 800            i < MetaspaceShared::first_string + MetaspaceShared::max_strings; i++) {
 801     struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 802     size_t used = si->_used;
 803     if (used > 0) {
 804       size_t size = align_size_up(used, os::vm_allocation_granularity());
 805       char* addr = (char*)((void*)oopDesc::decode_heap_oop_not_null(
 806                                              (narrowOop)si->_addr._offset));
 807       if (!os::unmap_memory(addr, size)) {
 808         fail_stop("Unable to unmap shared space.");
 809       }
 810     }
 811   }
 812 }
 813 
 814 void FileMapInfo::assert_mark(bool check) {
 815   if (!check) {
 816     fail_stop("Mark mismatch while restoring from shared file.");
 817   }
 818 }
 819 
 820 
 821 FileMapInfo* FileMapInfo::_current_info = NULL;
 822 SharedClassPathEntry* FileMapInfo::_classpath_entry_table = NULL;
 823 int FileMapInfo::_classpath_entry_table_size = 0;
 824 size_t FileMapInfo::_classpath_entry_size = 0x1234baad;
 825 bool FileMapInfo::_validating_classpath_entry_table = false;
 826 
 827 // Open the shared archive file, read and validate the header
 828 // information (version, boot classpath, etc.).  If initialization
 829 // fails, shared spaces are disabled and the file is closed. [See
 830 // fail_continue.]
 831 //
 832 // Validation of the archive is done in two steps:
 833 //
 834 // [1] validate_header() - done here. This checks the header, including _paths_misc_info.
 835 // [2] validate_classpath_entry_table - this is done later, because the table is in the RW
 836 //     region of the archive, which is not mapped yet.
 837 bool FileMapInfo::initialize() {
 838   assert(UseSharedSpaces, "UseSharedSpaces expected.");
 839 
 840   if (!open_for_read()) {
 841     return false;
 842   }
 843 
 844   init_from_file(_fd);
 845   if (!validate_header()) {
 846     return false;
 847   }
 848 
 849   SharedReadOnlySize =  _header->_space[0]._capacity;
 850   SharedReadWriteSize = _header->_space[1]._capacity;
 851   SharedMiscDataSize =  _header->_space[2]._capacity;
 852   SharedMiscCodeSize =  _header->_space[3]._capacity;
 853   return true;
 854 }
 855 
 856 char* FileMapInfo::FileMapHeader::region_addr(int idx) {
 857   if (MetaspaceShared::is_string_region(idx)) {
 858     return (char*)((void*)oopDesc::decode_heap_oop_not_null(
 859               (narrowOop)_space[idx]._addr._offset));
 860   } else {
 861     return _space[idx]._addr._base;
 862   }
 863 }
 864 
 865 int FileMapInfo::FileMapHeader::compute_crc() {
 866   char* header = data();
 867   // start computing from the field after _crc
 868   char* buf = (char*)&_crc + sizeof(int);
 869   size_t sz = data_size() - (buf - header);
 870   int crc = ClassLoader::crc32(0, buf, (jint)sz);
 871   return crc;
 872 }
 873 
 874 bool FileMapInfo::FileMapHeader::validate() {
 875   if (VerifySharedSpaces && compute_crc() != _crc) {
 876     fail_continue("Header checksum verification failed.");
 877     return false;
 878   }
 879 
 880   if (_version != current_version()) {
 881     FileMapInfo::fail_continue("The shared archive file is the wrong version.");
 882     return false;
 883   }
 884   if (_magic != (int)0xf00baba2) {
 885     FileMapInfo::fail_continue("The shared archive file has a bad magic number.");
 886     return false;
 887   }
 888   char header_version[JVM_IDENT_MAX];
 889   get_header_version(header_version);
 890   if (strncmp(_jvm_ident, header_version, JVM_IDENT_MAX-1) != 0) {
 891     if (TraceClassPaths) {
 892       tty->print_cr("Expected: %s", header_version);
 893       tty->print_cr("Actual:   %s", _jvm_ident);
 894     }
 895     FileMapInfo::fail_continue("The shared archive file was created by a different"
 896                   " version or build of HotSpot");
 897     return false;
 898   }
 899   if (_obj_alignment != ObjectAlignmentInBytes) {
 900     FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"
 901                   " does not equal the current ObjectAlignmentInBytes of %d.",
 902                   _obj_alignment, ObjectAlignmentInBytes);
 903     return false;
 904   }
 905 
 906   return true;
 907 }
 908 
 909 bool FileMapInfo::validate_header() {
 910   bool status = _header->validate();
 911 
 912   if (status) {
 913     if (!ClassLoader::check_shared_paths_misc_info(_paths_misc_info, _header->_paths_misc_info_size)) {
 914       if (!PrintSharedArchiveAndExit) {
 915         fail_continue("shared class paths mismatch (hint: enable -XX:+TraceClassPaths to diagnose the failure)");
 916         status = false;
 917       }
 918     }
 919   }
 920 
 921   if (_paths_misc_info != NULL) {
 922     FREE_C_HEAP_ARRAY(char, _paths_misc_info);
 923     _paths_misc_info = NULL;
 924   }
 925   return status;
 926 }
 927 
 928 // The following method is provided to see whether a given pointer
 929 // falls in the mapped shared space.
 930 // Param:
 931 // p, The given pointer
 932 // Return:
 933 // True if the p is within the mapped shared space, otherwise, false.
 934 bool FileMapInfo::is_in_shared_space(const void* p) {
 935   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
 936     char *base;
 937     if (MetaspaceShared::is_string_region(i) && _header->_space[i]._used == 0) {
 938       continue;
 939     }
 940     base = _header->region_addr(i);
 941     if (p >= base && p < base + _header->_space[i]._used) {
 942       return true;
 943     }
 944   }
 945 
 946   return false;
 947 }
 948 
 949 void FileMapInfo::print_shared_spaces() {
 950   gclog_or_tty->print_cr("Shared Spaces:");
 951   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
 952     struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
 953     char *base = _header->region_addr(i);
 954     gclog_or_tty->print("  %s " INTPTR_FORMAT "-" INTPTR_FORMAT,
 955                         shared_region_name[i],
 956                         base, base + si->_used);
 957   }
 958 }
 959 
 960 // Unmap mapped regions of shared space.
 961 void FileMapInfo::stop_sharing_and_unmap(const char* msg) {
 962   FileMapInfo *map_info = FileMapInfo::current_info();
 963   if (map_info) {
 964     map_info->fail_continue("%s", msg);
 965     for (int i = 0; i < MetaspaceShared::num_non_strings; i++) {
 966       char *addr = map_info->_header->region_addr(i);
 967       if (addr != NULL && !MetaspaceShared::is_string_region(i)) {
 968         map_info->unmap_region(i);
 969         map_info->_header->_space[i]._addr._base = NULL;
 970       }
 971     }
 972     map_info->unmap_string_regions();
 973   } else if (DumpSharedSpaces) {
 974     fail_stop("%s", msg);
 975   }
 976 }