filemap.cpp 23.7 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26
#include "precompiled.hpp"
#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
#include "memory/filemap.hpp"
32 33 34
#include "memory/metadataFactory.hpp"
#include "memory/oopFactory.hpp"
#include "oops/objArrayOop.hpp"
35 36 37
#include "runtime/arguments.hpp"
#include "runtime/java.hpp"
#include "runtime/os.hpp"
38
#include "services/memTracker.hpp"
39 40
#include "utilities/defaultStream.hpp"

D
duke 已提交
41 42 43 44 45 46 47
# include <sys/stat.h>
# include <errno.h>

#ifndef O_BINARY       // if defined (Win32) use binary files.
#define O_BINARY 0     // otherwise do nothing.
#endif

48
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
D
duke 已提交
49 50 51
extern address JVM_FunctionAtStart();
extern address JVM_FunctionAtEnd();

T
twisti 已提交
52
// Complain and stop. All error conditions occurring during the writing of
D
duke 已提交
53 54 55 56 57 58
// an archive file should stop the process.  Unrecoverable errors during
// the reading of the archive file should stop the process.

static void fail(const char *msg, va_list ap) {
  // This occurs very early during initialization: tty is not initialized.
  jio_fprintf(defaultStream::error_stream(),
T
twisti 已提交
59
              "An error has occurred while processing the"
D
duke 已提交
60 61 62
              " shared archive file.\n");
  jio_vfprintf(defaultStream::error_stream(), msg, ap);
  jio_fprintf(defaultStream::error_stream(), "\n");
63
  // Do not change the text of the below message because some tests check for it.
D
duke 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
  vm_exit_during_initialization("Unable to use shared archive.", NULL);
}


void FileMapInfo::fail_stop(const char *msg, ...) {
        va_list ap;
  va_start(ap, msg);
  fail(msg, ap);        // Never returns.
  va_end(ap);           // for completeness.
}


// Complain and continue.  Recoverable errors during the reading of the
// archive file may continue (with sharing disabled).
//
// If we continue, then disable shared spaces and close the file.

void FileMapInfo::fail_continue(const char *msg, ...) {
  va_list ap;
  va_start(ap, msg);
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
  MetaspaceShared::set_archive_loading_failed();
  if (PrintSharedArchiveAndExit && _validating_classpath_entry_table) {
    // If we are doing PrintSharedArchiveAndExit and some of the classpath entries
    // do not validate, we can still continue "limping" to validate the remaining
    // entries. No need to quit.
    tty->print("[");
    tty->vprint(msg, ap);
    tty->print_cr("]");
  } else {
    if (RequireSharedSpaces) {
      fail(msg, ap);
    } else {
      if (PrintSharedSpaces) {
        tty->print_cr("UseSharedSpaces: %s", msg);
      }
    }
D
duke 已提交
100 101 102
  }
  va_end(ap);
  UseSharedSpaces = false;
103 104
  assert(current_info() != NULL, "singleton must be registered");
  current_info()->close();
D
duke 已提交
105 106 107 108
}

// Fill in the fileMapInfo structure with data about this VM instance.

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
// This method copies the vm version info into header_version.  If the version is too
// long then a truncated version, which has a hash code appended to it, is copied.
//
// Using a template enables this method to verify that header_version is an array of
// length JVM_IDENT_MAX.  This ensures that the code that writes to the CDS file and
// the code that reads the CDS file will both use the same size buffer.  Hence, will
// use identical truncation.  This is necessary for matching of truncated versions.
template <int N> static void get_header_version(char (&header_version) [N]) {
  assert(N == JVM_IDENT_MAX, "Bad header_version size");

  const char *vm_version = VM_Version::internal_vm_info_string();
  const int version_len = (int)strlen(vm_version);

  if (version_len < (JVM_IDENT_MAX-1)) {
    strcpy(header_version, vm_version);

  } else {
    // Get the hash value.  Use a static seed because the hash needs to return the same
    // value over multiple jvm invocations.
    unsigned int hash = AltHashing::murmur3_32(8191, (const jbyte*)vm_version, version_len);

    // Truncate the ident, saving room for the 8 hex character hash value.
    strncpy(header_version, vm_version, JVM_IDENT_MAX-9);

    // Append the hash code as eight hex digits.
    sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash);
    header_version[JVM_IDENT_MAX-1] = 0;  // Null terminate.
  }
}

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
FileMapInfo::FileMapInfo() {
  assert(_current_info == NULL, "must be singleton"); // not thread safe
  _current_info = this;
  memset(this, 0, sizeof(FileMapInfo));
  _file_offset = 0;
  _file_open = false;
  _header = SharedClassUtil::allocate_file_map_header();
  _header->_version = _invalid_version;
}

FileMapInfo::~FileMapInfo() {
  assert(_current_info == this, "must be singleton"); // not thread safe
  _current_info = NULL;
}

D
duke 已提交
154
void FileMapInfo::populate_header(size_t alignment) {
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
  _header->populate(this, alignment);
}

size_t FileMapInfo::FileMapHeader::data_size() {
  return SharedClassUtil::file_map_header_size() - sizeof(FileMapInfo::FileMapHeaderBase);
}

void FileMapInfo::FileMapHeader::populate(FileMapInfo* mapinfo, size_t alignment) {
  _magic = 0xf00baba2;
  _version = _current_version;
  _alignment = alignment;
  _obj_alignment = ObjectAlignmentInBytes;
  _classpath_entry_table_size = mapinfo->_classpath_entry_table_size;
  _classpath_entry_table = mapinfo->_classpath_entry_table;
  _classpath_entry_size = mapinfo->_classpath_entry_size;
D
duke 已提交
170 171 172 173 174 175

  // The following fields are for sanity checks for whether this archive
  // will function correctly with this JVM and the bootclasspath it's
  // invoked with.

  // JVM version string ... changes on each build.
176 177
  get_header_version(_jvm_ident);
}
D
duke 已提交
178

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
void FileMapInfo::allocate_classpath_entry_table() {
  int bytes = 0;
  int count = 0;
  char* strptr = NULL;
  char* strptr_max = NULL;
  Thread* THREAD = Thread::current();

  ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
  size_t entry_size = SharedClassUtil::shared_class_path_entry_size();

  for (int pass=0; pass<2; pass++) {
    ClassPathEntry *cpe = ClassLoader::classpath_entry(0);

    for (int cur_entry = 0 ; cpe != NULL; cpe = cpe->next(), cur_entry++) {
      const char *name = cpe->name();
      int name_bytes = (int)(strlen(name) + 1);

      if (pass == 0) {
        count ++;
        bytes += (int)entry_size;
        bytes += name_bytes;
        if (TraceClassPaths || (TraceClassLoading && Verbose)) {
          tty->print_cr("[Add main shared path (%s) %s]", (cpe->is_jar_file() ? "jar" : "dir"), name);
        }
      } else {
        SharedClassPathEntry* ent = shared_classpath(cur_entry);
        if (cpe->is_jar_file()) {
          struct stat st;
          if (os::stat(name, &st) != 0) {
            // The file/dir must exist, or it would not have been added
            // into ClassLoader::classpath_entry().
            //
            // If we can't access a jar file in the boot path, then we can't
            // make assumptions about where classes get loaded from.
            FileMapInfo::fail_stop("Unable to open jar file %s.", name);
          }

          EXCEPTION_MARK; // The following call should never throw, but would exit VM on error.
          SharedClassUtil::update_shared_classpath(cpe, ent, st.st_mtime, st.st_size, THREAD);
        } else {
          ent->_filesize  = -1;
          if (!os::dir_is_empty(name)) {
            ClassLoader::exit_with_path_failure("Cannot have non-empty directory in archived classpaths", name);
          }
        }
        ent->_name = strptr;
        if (strptr + name_bytes <= strptr_max) {
          strncpy(strptr, name, (size_t)name_bytes); // name_bytes includes trailing 0.
          strptr += name_bytes;
        } else {
          assert(0, "miscalculated buffer size");
        }
D
duke 已提交
231
      }
232
    }
D
duke 已提交
233

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    if (pass == 0) {
      EXCEPTION_MARK; // The following call should never throw, but would exit VM on error.
      Array<u8>* arr = MetadataFactory::new_array<u8>(loader_data, (bytes + 7)/8, THREAD);
      strptr = (char*)(arr->data());
      strptr_max = strptr + bytes;
      SharedClassPathEntry* table = (SharedClassPathEntry*)strptr;
      strptr += entry_size * count;

      _classpath_entry_table_size = count;
      _classpath_entry_table = table;
      _classpath_entry_size = entry_size;
    }
  }
}

bool FileMapInfo::validate_classpath_entry_table() {
  _validating_classpath_entry_table = true;
D
duke 已提交
251

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
  int count = _header->_classpath_entry_table_size;

  _classpath_entry_table = _header->_classpath_entry_table;
  _classpath_entry_size = _header->_classpath_entry_size;

  for (int i=0; i<count; i++) {
    SharedClassPathEntry* ent = shared_classpath(i);
    struct stat st;
    const char* name = ent->_name;
    bool ok = true;
    if (TraceClassPaths || (TraceClassLoading && Verbose)) {
      tty->print_cr("[Checking shared classpath entry: %s]", name);
    }
    if (os::stat(name, &st) != 0) {
      fail_continue("Required classpath entry does not exist: %s", name);
      ok = false;
    } else if (ent->is_dir()) {
D
duke 已提交
269
      if (!os::dir_is_empty(name)) {
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
        fail_continue("directory is not empty: %s", name);
        ok = false;
      }
    } else {
      if (ent->_timestamp != st.st_mtime ||
          ent->_filesize != st.st_size) {
        ok = false;
        if (PrintSharedArchiveAndExit) {
          fail_continue(ent->_timestamp != st.st_mtime ?
                        "Timestamp mismatch" :
                        "File size mismatch");
        } else {
          fail_continue("A jar file is not the one used while building"
                        " the shared archive file: %s", name);
        }
      }
    }
    if (ok) {
      if (TraceClassPaths || (TraceClassLoading && Verbose)) {
        tty->print_cr("[ok]");
D
duke 已提交
290
      }
291 292 293
    } else if (!PrintSharedArchiveAndExit) {
      _validating_classpath_entry_table = false;
      return false;
D
duke 已提交
294 295
    }
  }
296 297 298 299

  _classpath_entry_table_size = _header->_classpath_entry_table_size;
  _validating_classpath_entry_table = false;
  return true;
D
duke 已提交
300 301 302 303 304 305
}


// Read the FileMapInfo information from the file.

bool FileMapInfo::init_from_file(int fd) {
306 307 308 309
  size_t sz = _header->data_size();
  char* addr = _header->data();
  size_t n = os::read(fd, addr, (unsigned int)sz);
  if (n != sz) {
D
duke 已提交
310 311 312
    fail_continue("Unable to read the file header.");
    return false;
  }
313
  if (_header->_version != current_version()) {
D
duke 已提交
314 315 316 317
    fail_continue("The shared archive file has the wrong version.");
    return false;
  }
  _file_offset = (long)n;
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333

  size_t info_size = _header->_paths_misc_info_size;
  _paths_misc_info = NEW_C_HEAP_ARRAY_RETURN_NULL(char, info_size, mtClass);
  if (_paths_misc_info == NULL) {
    fail_continue("Unable to read the file header.");
    return false;
  }
  n = os::read(fd, _paths_misc_info, (unsigned int)info_size);
  if (n != info_size) {
    fail_continue("Unable to read the shared path info header.");
    FREE_C_HEAP_ARRAY(char, _paths_misc_info, mtClass);
    _paths_misc_info = NULL;
    return false;
  }

  _file_offset += (long)n;
D
duke 已提交
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
  return true;
}


// Read the FileMapInfo information from the file.
bool FileMapInfo::open_for_read() {
  _full_path = Arguments::GetSharedArchivePath();
  int fd = open(_full_path, O_RDONLY | O_BINARY, 0);
  if (fd < 0) {
    if (errno == ENOENT) {
      // Not locating the shared archive is ok.
      fail_continue("Specified shared archive not found.");
    } else {
      fail_continue("Failed to open shared archive file (%s).",
                    strerror(errno));
    }
    return false;
  }

  _fd = fd;
  _file_open = true;
  return true;
}


// Write the FileMapInfo information to the file.

void FileMapInfo::open_for_write() {
 _full_path = Arguments::GetSharedArchivePath();
  if (PrintSharedSpaces) {
    tty->print_cr("Dumping shared data to file: ");
    tty->print_cr("   %s", _full_path);
  }

368 369 370 371 372 373
#ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
  chmod(_full_path, _S_IREAD | _S_IWRITE);
#endif

  // Use remove() to delete the existing file because, on Unix, this will
  // allow processes that have it open continued access to the file.
D
duke 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386 387
  remove(_full_path);
  int fd = open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
  if (fd < 0) {
    fail_stop("Unable to create shared archive file %s.", _full_path);
  }
  _fd = fd;
  _file_offset = 0;
  _file_open = true;
}


// Write the header to the file, seek to the next allocation boundary.

void FileMapInfo::write_header() {
388 389 390 391 392 393 394 395 396 397
  int info_size = ClassLoader::get_shared_paths_misc_info_size();

  _header->_paths_misc_info_size = info_size;

  align_file_position();
  size_t sz = _header->data_size();
  char* addr = _header->data();
  write_bytes(addr, (int)sz); // skip the C++ vtable
  write_bytes(ClassLoader::get_shared_paths_misc_info(), info_size);
  align_file_position();
D
duke 已提交
398 399 400 401 402
}


// Dump shared spaces to file.

403
void FileMapInfo::write_space(int i, Metaspace* space, bool read_only) {
D
duke 已提交
404
  align_file_position();
405 406
  size_t used = space->used_bytes_slow(Metaspace::NonClassType);
  size_t capacity = space->capacity_bytes_slow(Metaspace::NonClassType);
407
  struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
408
  write_region(i, (char*)space->bottom(), used, capacity, read_only, false);
D
duke 已提交
409 410 411 412 413 414 415 416
}


// Dump region to file.

void FileMapInfo::write_region(int region, char* base, size_t size,
                               size_t capacity, bool read_only,
                               bool allow_exec) {
417
  struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[region];
D
duke 已提交
418 419 420 421

  if (_file_open) {
    guarantee(si->_file_offset == _file_offset, "file offset mismatch.");
    if (PrintSharedSpaces) {
422 423
      tty->print_cr("Shared file region %d: 0x%6x bytes, addr " INTPTR_FORMAT
                    " file offset 0x%6x", region, size, base, _file_offset);
D
duke 已提交
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
    }
  } else {
    si->_file_offset = _file_offset;
  }
  si->_base = base;
  si->_used = size;
  si->_capacity = capacity;
  si->_read_only = read_only;
  si->_allow_exec = allow_exec;
  write_bytes_aligned(base, (int)size);
}


// Dump bytes to file -- at the current file position.

void FileMapInfo::write_bytes(const void* buffer, int nbytes) {
  if (_file_open) {
    int n = ::write(_fd, buffer, nbytes);
    if (n != nbytes) {
      // It is dangerous to leave the corrupted shared archive file around,
      // close and remove the file. See bug 6372906.
      close();
      remove(_full_path);
      fail_stop("Unable to write to shared archive file.", NULL);
    }
  }
  _file_offset += nbytes;
}


// Align file position to an allocation unit boundary.

void FileMapInfo::align_file_position() {
  long new_file_offset = align_size_up(_file_offset, os::vm_allocation_granularity());
  if (new_file_offset != _file_offset) {
    _file_offset = new_file_offset;
    if (_file_open) {
      // Seek one byte back from the target and write a byte to insure
      // that the written file is the correct length.
      _file_offset -= 1;
      if (lseek(_fd, _file_offset, SEEK_SET) < 0) {
        fail_stop("Unable to seek.", NULL);
      }
      char zero = 0;
      write_bytes(&zero, 1);
    }
  }
}


// Dump bytes to file -- at the current file position.

void FileMapInfo::write_bytes_aligned(const void* buffer, int nbytes) {
  align_file_position();
  write_bytes(buffer, nbytes);
  align_file_position();
}


// Close the shared archive file.  This does NOT unmap mapped regions.

void FileMapInfo::close() {
  if (_file_open) {
    if (::close(_fd) < 0) {
      fail_stop("Unable to close the shared archive file.");
    }
    _file_open = false;
    _fd = -1;
  }
}


// JVM/TI RedefineClasses() support:
// Remap the shared readonly space to shared readwrite, private.
bool FileMapInfo::remap_shared_readonly_as_readwrite() {
499
  struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[0];
D
duke 已提交
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
  if (!si->_read_only) {
    // the space is already readwrite so we are done
    return true;
  }
  size_t used = si->_used;
  size_t size = align_size_up(used, os::vm_allocation_granularity());
  if (!open_for_read()) {
    return false;
  }
  char *base = os::remap_memory(_fd, _full_path, si->_file_offset,
                                si->_base, size, false /* !read_only */,
                                si->_allow_exec);
  close();
  if (base == NULL) {
    fail_continue("Unable to remap shared readonly space (errno=%d).", errno);
    return false;
  }
  if (base != si->_base) {
    fail_continue("Unable to remap shared readonly space at required address.");
    return false;
  }
  si->_read_only = false;
  return true;
}

525 526
// Map the whole region at once, assumed to be allocated contiguously.
ReservedSpace FileMapInfo::reserve_shared_memory() {
527
  struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[0];
528 529
  char* requested_addr = si->_base;

530
  size_t size = FileMapInfo::shared_spaces_size();
531 532 533

  // Reserve the space first, then map otherwise map will go right over some
  // other reserved memory (like the code cache).
534
  ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr);
535
  if (!rs.is_reserved()) {
536
    fail_continue(err_msg("Unable to reserve shared space at required address " INTPTR_FORMAT, requested_addr));
537 538
    return rs;
  }
539
  // the reserved virtual memory is for mapping class data sharing archive
540 541
  MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared);

542 543
  return rs;
}
D
duke 已提交
544 545

// Memory map a region in the address space.
546
static const char* shared_region_name[] = { "ReadOnly", "ReadWrite", "MiscData", "MiscCode"};
D
duke 已提交
547

548
char* FileMapInfo::map_region(int i) {
549
  struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
D
duke 已提交
550
  size_t used = si->_used;
551 552 553 554 555
  size_t alignment = os::vm_allocation_granularity();
  size_t size = align_size_up(used, alignment);
  char *requested_addr = si->_base;

  // map the contents of the CDS archive in this memory
D
duke 已提交
556 557 558
  char *base = os::map_memory(_fd, _full_path, si->_file_offset,
                              requested_addr, size, si->_read_only,
                              si->_allow_exec);
559 560
  if (base == NULL || base != si->_base) {
    fail_continue(err_msg("Unable to map %s shared space at required address.", shared_region_name[i]));
D
duke 已提交
561 562
    return NULL;
  }
563 564 565 566 567
#ifdef _WINDOWS
  // This call is Windows-only because the memory_type gets recorded for the other platforms
  // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows.
  MemTracker::record_virtual_memory_type((address)base, mtClassShared);
#endif
D
duke 已提交
568 569 570 571 572 573 574
  return base;
}


// Unmap a memory region in the address space.

void FileMapInfo::unmap_region(int i) {
575
  struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
D
duke 已提交
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
  size_t used = si->_used;
  size_t size = align_size_up(used, os::vm_allocation_granularity());
  if (!os::unmap_memory(si->_base, size)) {
    fail_stop("Unable to unmap shared space.");
  }
}


void FileMapInfo::assert_mark(bool check) {
  if (!check) {
    fail_stop("Mark mismatch while restoring from shared file.", NULL);
  }
}


FileMapInfo* FileMapInfo::_current_info = NULL;
592 593 594 595
SharedClassPathEntry* FileMapInfo::_classpath_entry_table = NULL;
int FileMapInfo::_classpath_entry_table_size = 0;
size_t FileMapInfo::_classpath_entry_size = 0x1234baad;
bool FileMapInfo::_validating_classpath_entry_table = false;
D
duke 已提交
596 597 598 599 600

// Open the shared archive file, read and validate the header
// information (version, boot classpath, etc.).  If initialization
// fails, shared spaces are disabled and the file is closed. [See
// fail_continue.]
601 602 603 604 605 606
//
// Validation of the archive is done in two steps:
//
// [1] validate_header() - done here. This checks the header, including _paths_misc_info.
// [2] validate_classpath_entry_table - this is done later, because the table is in the RW
//     region of the archive, which is not mapped yet.
D
duke 已提交
607 608 609 610 611 612 613 614 615 616 617 618 619
bool FileMapInfo::initialize() {
  assert(UseSharedSpaces, "UseSharedSpaces expected.");

  if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space()) {
    fail_continue("Tool agent requires sharing to be disabled.");
    return false;
  }

  if (!open_for_read()) {
    return false;
  }

  init_from_file(_fd);
620
  if (!validate_header()) {
D
duke 已提交
621 622 623
    return false;
  }

624 625 626 627
  SharedReadOnlySize =  _header->_space[0]._capacity;
  SharedReadWriteSize = _header->_space[1]._capacity;
  SharedMiscDataSize =  _header->_space[2]._capacity;
  SharedMiscCodeSize =  _header->_space[3]._capacity;
D
duke 已提交
628 629 630
  return true;
}

631 632 633
bool FileMapInfo::FileMapHeader::validate() {
  if (_version != current_version()) {
    FileMapInfo::fail_continue("The shared archive file is the wrong version.");
D
duke 已提交
634 635
    return false;
  }
636 637
  if (_magic != (int)0xf00baba2) {
    FileMapInfo::fail_continue("The shared archive file has a bad magic number.");
D
duke 已提交
638 639
    return false;
  }
640 641
  char header_version[JVM_IDENT_MAX];
  get_header_version(header_version);
642 643 644 645 646 647 648
  if (strncmp(_jvm_ident, header_version, JVM_IDENT_MAX-1) != 0) {
    if (TraceClassPaths) {
      tty->print_cr("Expected: %s", header_version);
      tty->print_cr("Actual:   %s", _jvm_ident);
    }
    FileMapInfo::fail_continue("The shared archive file was created by a different"
                  " version or build of HotSpot");
D
duke 已提交
649 650
    return false;
  }
651 652
  if (_obj_alignment != ObjectAlignmentInBytes) {
    FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"
653
                  " does not equal the current ObjectAlignmentInBytes of %d.",
654
                  _obj_alignment, ObjectAlignmentInBytes);
D
duke 已提交
655 656 657
    return false;
  }

658 659
  return true;
}
D
duke 已提交
660

661 662
bool FileMapInfo::validate_header() {
  bool status = _header->validate();
D
duke 已提交
663

664 665 666 667 668
  if (status) {
    if (!ClassLoader::check_shared_paths_misc_info(_paths_misc_info, _header->_paths_misc_info_size)) {
      if (!PrintSharedArchiveAndExit) {
        fail_continue("shared class paths mismatch (hint: enable -XX:+TraceClassPaths to diagnose the failure)");
        status = false;
D
duke 已提交
669 670 671 672
      }
    }
  }

673 674 675 676 677
  if (_paths_misc_info != NULL) {
    FREE_C_HEAP_ARRAY(char, _paths_misc_info, mtClass);
    _paths_misc_info = NULL;
  }
  return status;
D
duke 已提交
678 679 680 681 682 683 684 685 686
}

// The following method is provided to see whether a given pointer
// falls in the mapped shared space.
// Param:
// p, The given pointer
// Return:
// True if the p is within the mapped shared space, otherwise, false.
bool FileMapInfo::is_in_shared_space(const void* p) {
687
  for (int i = 0; i < MetaspaceShared::n_regions; i++) {
688 689
    if (p >= _header->_space[i]._base &&
        p < _header->_space[i]._base + _header->_space[i]._used) {
D
duke 已提交
690 691 692 693 694 695
      return true;
    }
  }

  return false;
}
696 697 698 699

void FileMapInfo::print_shared_spaces() {
  gclog_or_tty->print_cr("Shared Spaces:");
  for (int i = 0; i < MetaspaceShared::n_regions; i++) {
700
    struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
701 702 703 704 705
    gclog_or_tty->print("  %s " INTPTR_FORMAT "-" INTPTR_FORMAT,
                        shared_region_name[i],
                        si->_base, si->_base + si->_used);
  }
}
706 707 708 709 710 711 712

// Unmap mapped regions of shared space.
void FileMapInfo::stop_sharing_and_unmap(const char* msg) {
  FileMapInfo *map_info = FileMapInfo::current_info();
  if (map_info) {
    map_info->fail_continue(msg);
    for (int i = 0; i < MetaspaceShared::n_regions; i++) {
713
      if (map_info->_header->_space[i]._base != NULL) {
714
        map_info->unmap_region(i);
715
        map_info->_header->_space[i]._base = NULL;
716 717 718 719 720 721
      }
    }
  } else if (DumpSharedSpaces) {
    fail_stop(msg, NULL);
  }
}