Path: blob/master/src/hotspot/share/cds/filemap.cpp
41145 views
/*1* Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "jvm.h"26#include "cds/archiveBuilder.hpp"27#include "cds/archiveUtils.inline.hpp"28#include "cds/dynamicArchive.hpp"29#include "cds/filemap.hpp"30#include "cds/heapShared.inline.hpp"31#include "cds/metaspaceShared.hpp"32#include "classfile/altHashing.hpp"33#include "classfile/classFileStream.hpp"34#include "classfile/classLoader.inline.hpp"35#include "classfile/classLoaderData.inline.hpp"36#include "classfile/classLoaderExt.hpp"37#include "classfile/symbolTable.hpp"38#include "classfile/systemDictionaryShared.hpp"39#include "classfile/vmClasses.hpp"40#include "classfile/vmSymbols.hpp"41#include "logging/log.hpp"42#include "logging/logStream.hpp"43#include "logging/logMessage.hpp"44#include "memory/iterator.inline.hpp"45#include "memory/metadataFactory.hpp"46#include "memory/metaspaceClosure.hpp"47#include "memory/oopFactory.hpp"48#include "memory/universe.hpp"49#include "oops/compressedOops.hpp"50#include "oops/compressedOops.inline.hpp"51#include "oops/objArrayOop.hpp"52#include "oops/oop.inline.hpp"53#include "prims/jvmtiExport.hpp"54#include "runtime/arguments.hpp"55#include "runtime/java.hpp"56#include "runtime/mutexLocker.hpp"57#include "runtime/os.hpp"58#include "runtime/vm_version.hpp"59#include "services/memTracker.hpp"60#include "utilities/align.hpp"61#include "utilities/bitMap.inline.hpp"62#include "utilities/classpathStream.hpp"63#include "utilities/defaultStream.hpp"64#include "utilities/ostream.hpp"65#if INCLUDE_G1GC66#include "gc/g1/g1CollectedHeap.hpp"67#include "gc/g1/heapRegion.hpp"68#endif6970# include <sys/stat.h>71# include <errno.h>7273#ifndef O_BINARY // if defined (Win32) use binary files.74#define O_BINARY 0 // otherwise do nothing.75#endif7677// Complain and stop. All error conditions occurring during the writing of78// an archive file should stop the process. Unrecoverable errors during79// the reading of the archive file should stop the process.8081static void fail_exit(const char *msg, va_list ap) {82// This occurs very early during initialization: tty is not initialized.83jio_fprintf(defaultStream::error_stream(),84"An error has occurred while processing the"85" shared archive file.\n");86jio_vfprintf(defaultStream::error_stream(), msg, ap);87jio_fprintf(defaultStream::error_stream(), "\n");88// Do not change the text of the below message because some tests check for it.89vm_exit_during_initialization("Unable to use shared archive.", NULL);90}919293void FileMapInfo::fail_stop(const char *msg, ...) {94va_list ap;95va_start(ap, msg);96fail_exit(msg, ap); // Never returns.97va_end(ap); // for completeness.98}99100101// Complain and continue. Recoverable errors during the reading of the102// archive file may continue (with sharing disabled).103//104// If we continue, then disable shared spaces and close the file.105106void FileMapInfo::fail_continue(const char *msg, ...) {107va_list ap;108va_start(ap, msg);109if (PrintSharedArchiveAndExit && _validating_shared_path_table) {110// If we are doing PrintSharedArchiveAndExit and some of the classpath entries111// do not validate, we can still continue "limping" to validate the remaining112// entries. No need to quit.113tty->print("[");114tty->vprint(msg, ap);115tty->print_cr("]");116} else {117if (RequireSharedSpaces) {118fail_exit(msg, ap);119} else {120if (log_is_enabled(Info, cds)) {121ResourceMark rm;122LogStream ls(Log(cds)::info());123ls.print("UseSharedSpaces: ");124ls.vprint_cr(msg, ap);125}126}127}128va_end(ap);129}130131// Fill in the fileMapInfo structure with data about this VM instance.132133// This method copies the vm version info into header_version. If the version is too134// long then a truncated version, which has a hash code appended to it, is copied.135//136// Using a template enables this method to verify that header_version is an array of137// length JVM_IDENT_MAX. This ensures that the code that writes to the CDS file and138// the code that reads the CDS file will both use the same size buffer. Hence, will139// use identical truncation. This is necessary for matching of truncated versions.140template <int N> static void get_header_version(char (&header_version) [N]) {141assert(N == JVM_IDENT_MAX, "Bad header_version size");142143const char *vm_version = VM_Version::internal_vm_info_string();144const int version_len = (int)strlen(vm_version);145146memset(header_version, 0, JVM_IDENT_MAX);147148if (version_len < (JVM_IDENT_MAX-1)) {149strcpy(header_version, vm_version);150151} else {152// Get the hash value. Use a static seed because the hash needs to return the same153// value over multiple jvm invocations.154uint32_t hash = AltHashing::halfsiphash_32(8191, (const uint8_t*)vm_version, version_len);155156// Truncate the ident, saving room for the 8 hex character hash value.157strncpy(header_version, vm_version, JVM_IDENT_MAX-9);158159// Append the hash code as eight hex digits.160sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash);161header_version[JVM_IDENT_MAX-1] = 0; // Null terminate.162}163164assert(header_version[JVM_IDENT_MAX-1] == 0, "must be");165}166167FileMapInfo::FileMapInfo(bool is_static) {168memset((void*)this, 0, sizeof(FileMapInfo));169_is_static = is_static;170size_t header_size;171if (is_static) {172assert(_current_info == NULL, "must be singleton"); // not thread safe173_current_info = this;174header_size = sizeof(FileMapHeader);175} else {176assert(_dynamic_archive_info == NULL, "must be singleton"); // not thread safe177_dynamic_archive_info = this;178header_size = sizeof(DynamicArchiveHeader);179}180_header = (FileMapHeader*)os::malloc(header_size, mtInternal);181memset((void*)_header, 0, header_size);182_header->set_header_size(header_size);183_header->set_version(INVALID_CDS_ARCHIVE_VERSION);184_header->set_has_platform_or_app_classes(true);185_file_offset = 0;186_file_open = false;187}188189FileMapInfo::~FileMapInfo() {190if (_is_static) {191assert(_current_info == this, "must be singleton"); // not thread safe192_current_info = NULL;193} else {194assert(_dynamic_archive_info == this, "must be singleton"); // not thread safe195_dynamic_archive_info = NULL;196}197}198199void FileMapInfo::populate_header(size_t core_region_alignment) {200header()->populate(this, core_region_alignment);201}202203void FileMapHeader::populate(FileMapInfo* mapinfo, size_t core_region_alignment) {204if (DynamicDumpSharedSpaces) {205_magic = CDS_DYNAMIC_ARCHIVE_MAGIC;206} else {207_magic = CDS_ARCHIVE_MAGIC;208}209_version = CURRENT_CDS_ARCHIVE_VERSION;210_core_region_alignment = core_region_alignment;211_obj_alignment = ObjectAlignmentInBytes;212_compact_strings = CompactStrings;213if (HeapShared::is_heap_object_archiving_allowed()) {214_narrow_oop_mode = CompressedOops::mode();215_narrow_oop_base = CompressedOops::base();216_narrow_oop_shift = CompressedOops::shift();217_heap_begin = CompressedOops::begin();218_heap_end = CompressedOops::end();219}220_compressed_oops = UseCompressedOops;221_compressed_class_ptrs = UseCompressedClassPointers;222_max_heap_size = MaxHeapSize;223_narrow_klass_shift = CompressedKlassPointers::shift();224_use_optimized_module_handling = MetaspaceShared::use_optimized_module_handling();225_use_full_module_graph = MetaspaceShared::use_full_module_graph();226227// The following fields are for sanity checks for whether this archive228// will function correctly with this JVM and the bootclasspath it's229// invoked with.230231// JVM version string ... changes on each build.232get_header_version(_jvm_ident);233234_app_class_paths_start_index = ClassLoaderExt::app_class_paths_start_index();235_app_module_paths_start_index = ClassLoaderExt::app_module_paths_start_index();236_num_module_paths = ClassLoader::num_module_path_entries();237_max_used_path_index = ClassLoaderExt::max_used_path_index();238239_verify_local = BytecodeVerificationLocal;240_verify_remote = BytecodeVerificationRemote;241_has_platform_or_app_classes = ClassLoaderExt::has_platform_or_app_classes();242_requested_base_address = (char*)SharedBaseAddress;243_mapped_base_address = (char*)SharedBaseAddress;244_allow_archiving_with_java_agent = AllowArchivingWithJavaAgent;245// the following 2 fields will be set in write_header for dynamic archive header246_base_archive_name_size = 0;247_base_archive_is_default = false;248249if (!DynamicDumpSharedSpaces) {250set_shared_path_table(mapinfo->_shared_path_table);251CDS_JAVA_HEAP_ONLY(_heap_obj_roots = CompressedOops::encode(HeapShared::roots());)252}253}254255void FileMapHeader::print(outputStream* st) {256ResourceMark rm;257258st->print_cr("- magic: 0x%08x", _magic);259st->print_cr("- crc: 0x%08x", _crc);260st->print_cr("- version: %d", _version);261262for (int i = 0; i < NUM_CDS_REGIONS; i++) {263FileMapRegion* si = space_at(i);264si->print(st, i);265}266st->print_cr("============ end regions ======== ");267268st->print_cr("- header_size: " SIZE_FORMAT, _header_size);269st->print_cr("- core_region_alignment: " SIZE_FORMAT, _core_region_alignment);270st->print_cr("- obj_alignment: %d", _obj_alignment);271st->print_cr("- narrow_oop_base: " INTPTR_FORMAT, p2i(_narrow_oop_base));272st->print_cr("- narrow_oop_base: " INTPTR_FORMAT, p2i(_narrow_oop_base));273st->print_cr("- narrow_oop_shift %d", _narrow_oop_shift);274st->print_cr("- compact_strings: %d", _compact_strings);275st->print_cr("- max_heap_size: " UINTX_FORMAT, _max_heap_size);276st->print_cr("- narrow_oop_mode: %d", _narrow_oop_mode);277st->print_cr("- narrow_klass_shift: %d", _narrow_klass_shift);278st->print_cr("- compressed_oops: %d", _compressed_oops);279st->print_cr("- compressed_class_ptrs: %d", _compressed_class_ptrs);280st->print_cr("- cloned_vtables_offset: " SIZE_FORMAT_HEX, _cloned_vtables_offset);281st->print_cr("- serialized_data_offset: " SIZE_FORMAT_HEX, _serialized_data_offset);282st->print_cr("- heap_end: " INTPTR_FORMAT, p2i(_heap_end));283st->print_cr("- base_archive_is_default: %d", _base_archive_is_default);284st->print_cr("- jvm_ident: %s", _jvm_ident);285st->print_cr("- base_archive_name_size: " SIZE_FORMAT, _base_archive_name_size);286st->print_cr("- shared_path_table_offset: " SIZE_FORMAT_HEX, _shared_path_table_offset);287st->print_cr("- shared_path_table_size: %d", _shared_path_table_size);288st->print_cr("- app_class_paths_start_index: %d", _app_class_paths_start_index);289st->print_cr("- app_module_paths_start_index: %d", _app_module_paths_start_index);290st->print_cr("- num_module_paths: %d", _num_module_paths);291st->print_cr("- max_used_path_index: %d", _max_used_path_index);292st->print_cr("- verify_local: %d", _verify_local);293st->print_cr("- verify_remote: %d", _verify_remote);294st->print_cr("- has_platform_or_app_classes: %d", _has_platform_or_app_classes);295st->print_cr("- requested_base_address: " INTPTR_FORMAT, p2i(_requested_base_address));296st->print_cr("- mapped_base_address: " INTPTR_FORMAT, p2i(_mapped_base_address));297st->print_cr("- allow_archiving_with_java_agent:%d", _allow_archiving_with_java_agent);298st->print_cr("- use_optimized_module_handling: %d", _use_optimized_module_handling);299st->print_cr("- use_full_module_graph %d", _use_full_module_graph);300st->print_cr("- ptrmap_size_in_bits: " SIZE_FORMAT, _ptrmap_size_in_bits);301}302303void SharedClassPathEntry::init_as_non_existent(const char* path, TRAPS) {304_type = non_existent_entry;305set_name(path, CHECK);306}307308void SharedClassPathEntry::init(bool is_modules_image,309bool is_module_path,310ClassPathEntry* cpe, TRAPS) {311Arguments::assert_is_dumping_archive();312_timestamp = 0;313_filesize = 0;314_from_class_path_attr = false;315316struct stat st;317if (os::stat(cpe->name(), &st) == 0) {318if ((st.st_mode & S_IFMT) == S_IFDIR) {319_type = dir_entry;320} else {321// The timestamp of the modules_image is not checked at runtime.322if (is_modules_image) {323_type = modules_image_entry;324} else {325_type = jar_entry;326_timestamp = st.st_mtime;327_from_class_path_attr = cpe->from_class_path_attr();328}329_filesize = st.st_size;330_is_module_path = is_module_path;331}332} else {333// The file/dir must exist, or it would not have been added334// into ClassLoader::classpath_entry().335//336// If we can't access a jar file in the boot path, then we can't337// make assumptions about where classes get loaded from.338FileMapInfo::fail_stop("Unable to open file %s.", cpe->name());339}340341// No need to save the name of the module file, as it will be computed at run time342// to allow relocation of the JDK directory.343const char* name = is_modules_image ? "" : cpe->name();344set_name(name, CHECK);345}346347void SharedClassPathEntry::set_name(const char* name, TRAPS) {348size_t len = strlen(name) + 1;349_name = MetadataFactory::new_array<char>(ClassLoaderData::the_null_class_loader_data(), (int)len, CHECK);350strcpy(_name->data(), name);351}352353void SharedClassPathEntry::copy_from(SharedClassPathEntry* ent, ClassLoaderData* loader_data, TRAPS) {354_type = ent->_type;355_is_module_path = ent->_is_module_path;356_timestamp = ent->_timestamp;357_filesize = ent->_filesize;358_from_class_path_attr = ent->_from_class_path_attr;359set_name(ent->name(), CHECK);360361if (ent->is_jar() && !ent->is_signed() && ent->manifest() != NULL) {362Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,363ent->manifest_size(),364CHECK);365char* p = (char*)(buf->data());366memcpy(p, ent->manifest(), ent->manifest_size());367set_manifest(buf);368}369}370371const char* SharedClassPathEntry::name() const {372if (UseSharedSpaces && is_modules_image()) {373// In order to validate the runtime modules image file size against the archived374// size information, we need to obtain the runtime modules image path. The recorded375// dump time modules image path in the archive may be different from the runtime path376// if the JDK image has beed moved after generating the archive.377return ClassLoader::get_jrt_entry()->name();378} else {379return _name->data();380}381}382383bool SharedClassPathEntry::validate(bool is_class_path) const {384assert(UseSharedSpaces, "runtime only");385386struct stat st;387const char* name = this->name();388389bool ok = true;390log_info(class, path)("checking shared classpath entry: %s", name);391if (os::stat(name, &st) != 0 && is_class_path) {392// If the archived module path entry does not exist at runtime, it is not fatal393// (no need to invalid the shared archive) because the shared runtime visibility check394// filters out any archived module classes that do not have a matching runtime395// module path location.396FileMapInfo::fail_continue("Required classpath entry does not exist: %s", name);397ok = false;398} else if (is_dir()) {399if (!os::dir_is_empty(name)) {400FileMapInfo::fail_continue("directory is not empty: %s", name);401ok = false;402}403} else if ((has_timestamp() && _timestamp != st.st_mtime) ||404_filesize != st.st_size) {405ok = false;406if (PrintSharedArchiveAndExit) {407FileMapInfo::fail_continue(_timestamp != st.st_mtime ?408"Timestamp mismatch" :409"File size mismatch");410} else {411FileMapInfo::fail_continue("A jar file is not the one used while building"412" the shared archive file: %s", name);413}414}415416if (PrintSharedArchiveAndExit && !ok) {417// If PrintSharedArchiveAndExit is enabled, don't report failure to the418// caller. Please see above comments for more details.419ok = true;420MetaspaceShared::set_archive_loading_failed();421}422return ok;423}424425bool SharedClassPathEntry::check_non_existent() const {426assert(_type == non_existent_entry, "must be");427log_info(class, path)("should be non-existent: %s", name());428struct stat st;429if (os::stat(name(), &st) != 0) {430log_info(class, path)("ok");431return true; // file doesn't exist432} else {433return false;434}435}436437438void SharedClassPathEntry::metaspace_pointers_do(MetaspaceClosure* it) {439it->push(&_name);440it->push(&_manifest);441}442443void SharedPathTable::metaspace_pointers_do(MetaspaceClosure* it) {444it->push(&_table);445for (int i=0; i<_size; i++) {446path_at(i)->metaspace_pointers_do(it);447}448}449450void SharedPathTable::dumptime_init(ClassLoaderData* loader_data, TRAPS) {451size_t entry_size = sizeof(SharedClassPathEntry);452int num_entries = 0;453num_entries += ClassLoader::num_boot_classpath_entries();454num_entries += ClassLoader::num_app_classpath_entries();455num_entries += ClassLoader::num_module_path_entries();456num_entries += FileMapInfo::num_non_existent_class_paths();457size_t bytes = entry_size * num_entries;458459_table = MetadataFactory::new_array<u8>(loader_data, (int)bytes, CHECK);460_size = num_entries;461}462463// Make a copy of the _shared_path_table for use during dynamic CDS dump.464// It is needed because some Java code continues to execute after dynamic dump has finished.465// However, during dynamic dump, we have modified FileMapInfo::_shared_path_table so466// FileMapInfo::shared_path(i) returns incorrect information in ClassLoader::record_result().467void FileMapInfo::copy_shared_path_table(ClassLoaderData* loader_data, TRAPS) {468size_t entry_size = sizeof(SharedClassPathEntry);469size_t bytes = entry_size * _shared_path_table.size();470471Array<u8>* array = MetadataFactory::new_array<u8>(loader_data, (int)bytes, CHECK);472_saved_shared_path_table = SharedPathTable(array, _shared_path_table.size());473474for (int i = 0; i < _shared_path_table.size(); i++) {475_saved_shared_path_table.path_at(i)->copy_from(shared_path(i), loader_data, CHECK);476}477}478479void FileMapInfo::allocate_shared_path_table(TRAPS) {480Arguments::assert_is_dumping_archive();481482ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();483ClassPathEntry* jrt = ClassLoader::get_jrt_entry();484485assert(jrt != NULL,486"No modular java runtime image present when allocating the CDS classpath entry table");487488_shared_path_table.dumptime_init(loader_data, CHECK);489490// 1. boot class path491int i = 0;492i = add_shared_classpaths(i, "boot", jrt, CHECK);493i = add_shared_classpaths(i, "app", ClassLoader::app_classpath_entries(), CHECK);494i = add_shared_classpaths(i, "module", ClassLoader::module_path_entries(), CHECK);495496for (int x = 0; x < num_non_existent_class_paths(); x++, i++) {497const char* path = _non_existent_class_paths->at(x);498shared_path(i)->init_as_non_existent(path, CHECK);499}500501assert(i == _shared_path_table.size(), "number of shared path entry mismatch");502503copy_shared_path_table(loader_data, CHECK);504}505506int FileMapInfo::add_shared_classpaths(int i, const char* which, ClassPathEntry *cpe, TRAPS) {507while (cpe != NULL) {508bool is_jrt = (cpe == ClassLoader::get_jrt_entry());509bool is_module_path = i >= ClassLoaderExt::app_module_paths_start_index();510const char* type = (is_jrt ? "jrt" : (cpe->is_jar_file() ? "jar" : "dir"));511log_info(class, path)("add %s shared path (%s) %s", which, type, cpe->name());512SharedClassPathEntry* ent = shared_path(i);513ent->init(is_jrt, is_module_path, cpe, CHECK_0);514if (cpe->is_jar_file()) {515update_jar_manifest(cpe, ent, CHECK_0);516}517if (is_jrt) {518cpe = ClassLoader::get_next_boot_classpath_entry(cpe);519} else {520cpe = cpe->next();521}522i++;523}524525return i;526}527528void FileMapInfo::check_nonempty_dir_in_shared_path_table() {529Arguments::assert_is_dumping_archive();530531bool has_nonempty_dir = false;532533int last = _shared_path_table.size() - 1;534if (last > ClassLoaderExt::max_used_path_index()) {535// no need to check any path beyond max_used_path_index536last = ClassLoaderExt::max_used_path_index();537}538539for (int i = 0; i <= last; i++) {540SharedClassPathEntry *e = shared_path(i);541if (e->is_dir()) {542const char* path = e->name();543if (!os::dir_is_empty(path)) {544log_error(cds)("Error: non-empty directory '%s'", path);545has_nonempty_dir = true;546}547}548}549550if (has_nonempty_dir) {551ClassLoader::exit_with_path_failure("Cannot have non-empty directory in paths", NULL);552}553}554555void FileMapInfo::record_non_existent_class_path_entry(const char* path) {556Arguments::assert_is_dumping_archive();557log_info(class, path)("non-existent Class-Path entry %s", path);558if (_non_existent_class_paths == NULL) {559_non_existent_class_paths = new (ResourceObj::C_HEAP, mtClass)GrowableArray<const char*>(10, mtClass);560}561_non_existent_class_paths->append(os::strdup(path));562}563564int FileMapInfo::num_non_existent_class_paths() {565Arguments::assert_is_dumping_archive();566if (_non_existent_class_paths != NULL) {567return _non_existent_class_paths->length();568} else {569return 0;570}571}572573int FileMapInfo::get_module_shared_path_index(Symbol* location) {574if (location->starts_with("jrt:", 4) && get_number_of_shared_paths() > 0) {575assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");576return 0;577}578579if (ClassLoaderExt::app_module_paths_start_index() >= get_number_of_shared_paths()) {580// The archive(s) were created without --module-path option581return -1;582}583584if (!location->starts_with("file:", 5)) {585return -1;586}587588// skip_uri_protocol was also called during dump time -- see ClassLoaderExt::process_module_table()589ResourceMark rm;590const char* file = ClassLoader::skip_uri_protocol(location->as_C_string());591for (int i = ClassLoaderExt::app_module_paths_start_index(); i < get_number_of_shared_paths(); i++) {592SharedClassPathEntry* ent = shared_path(i);593assert(ent->in_named_module(), "must be");594bool cond = strcmp(file, ent->name()) == 0;595log_debug(class, path)("get_module_shared_path_index (%d) %s : %s = %s", i,596location->as_C_string(), ent->name(), cond ? "same" : "different");597if (cond) {598return i;599}600}601602return -1;603}604605class ManifestStream: public ResourceObj {606private:607u1* _buffer_start; // Buffer bottom608u1* _buffer_end; // Buffer top (one past last element)609u1* _current; // Current buffer position610611public:612// Constructor613ManifestStream(u1* buffer, int length) : _buffer_start(buffer),614_current(buffer) {615_buffer_end = buffer + length;616}617618static bool is_attr(u1* attr, const char* name) {619return strncmp((const char*)attr, name, strlen(name)) == 0;620}621622static char* copy_attr(u1* value, size_t len) {623char* buf = NEW_RESOURCE_ARRAY(char, len + 1);624strncpy(buf, (char*)value, len);625buf[len] = 0;626return buf;627}628629// The return value indicates if the JAR is signed or not630bool check_is_signed() {631u1* attr = _current;632bool isSigned = false;633while (_current < _buffer_end) {634if (*_current == '\n') {635*_current = '\0';636u1* value = (u1*)strchr((char*)attr, ':');637if (value != NULL) {638assert(*(value+1) == ' ', "Unrecognized format" );639if (strstr((char*)attr, "-Digest") != NULL) {640isSigned = true;641break;642}643}644*_current = '\n'; // restore645attr = _current + 1;646}647_current ++;648}649return isSigned;650}651};652653void FileMapInfo::update_jar_manifest(ClassPathEntry *cpe, SharedClassPathEntry* ent, TRAPS) {654ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();655ResourceMark rm(THREAD);656jint manifest_size;657658assert(cpe->is_jar_file() && ent->is_jar(), "the shared class path entry is not a JAR file");659char* manifest = ClassLoaderExt::read_manifest(THREAD, cpe, &manifest_size);660if (manifest != NULL) {661ManifestStream* stream = new ManifestStream((u1*)manifest,662manifest_size);663if (stream->check_is_signed()) {664ent->set_is_signed();665} else {666// Copy the manifest into the shared archive667manifest = ClassLoaderExt::read_raw_manifest(THREAD, cpe, &manifest_size);668Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,669manifest_size,670CHECK);671char* p = (char*)(buf->data());672memcpy(p, manifest, manifest_size);673ent->set_manifest(buf);674}675}676}677678char* FileMapInfo::skip_first_path_entry(const char* path) {679size_t path_sep_len = strlen(os::path_separator());680char* p = strstr((char*)path, os::path_separator());681if (p != NULL) {682debug_only( {683size_t image_name_len = strlen(MODULES_IMAGE_NAME);684assert(strncmp(p - image_name_len, MODULES_IMAGE_NAME, image_name_len) == 0,685"first entry must be the modules image");686} );687p += path_sep_len;688} else {689debug_only( {690assert(ClassLoader::string_ends_with(path, MODULES_IMAGE_NAME),691"first entry must be the modules image");692} );693}694return p;695}696697int FileMapInfo::num_paths(const char* path) {698if (path == NULL) {699return 0;700}701int npaths = 1;702char* p = (char*)path;703while (p != NULL) {704char* prev = p;705p = strstr((char*)p, os::path_separator());706if (p != NULL) {707p++;708// don't count empty path709if ((p - prev) > 1) {710npaths++;711}712}713}714return npaths;715}716717GrowableArray<const char*>* FileMapInfo::create_path_array(const char* paths) {718GrowableArray<const char*>* path_array = new GrowableArray<const char*>(10);719720ClasspathStream cp_stream(paths);721while (cp_stream.has_next()) {722const char* path = cp_stream.get_next();723struct stat st;724if (os::stat(path, &st) == 0) {725path_array->append(path);726}727}728return path_array;729}730731bool FileMapInfo::classpath_failure(const char* msg, const char* name) {732ClassLoader::trace_class_path(msg, name);733if (PrintSharedArchiveAndExit) {734MetaspaceShared::set_archive_loading_failed();735}736return false;737}738739bool FileMapInfo::check_paths(int shared_path_start_idx, int num_paths, GrowableArray<const char*>* rp_array) {740int i = 0;741int j = shared_path_start_idx;742bool mismatch = false;743while (i < num_paths && !mismatch) {744while (shared_path(j)->from_class_path_attr()) {745// shared_path(j) was expanded from the JAR file attribute "Class-Path:"746// during dump time. It's not included in the -classpath VM argument.747j++;748}749if (!os::same_files(shared_path(j)->name(), rp_array->at(i))) {750mismatch = true;751}752i++;753j++;754}755return mismatch;756}757758bool FileMapInfo::validate_boot_class_paths() {759//760// - Archive contains boot classes only - relaxed boot path check:761// Extra path elements appended to the boot path at runtime are allowed.762//763// - Archive contains application or platform classes - strict boot path check:764// Validate the entire runtime boot path, which must be compatible765// with the dump time boot path. Appending boot path at runtime is not766// allowed.767//768769// The first entry in boot path is the modules_image (guaranteed by770// ClassLoader::setup_boot_search_path()). Skip the first entry. The771// path of the runtime modules_image may be different from the dump772// time path (e.g. the JDK image is copied to a different location773// after generating the shared archive), which is acceptable. For most774// common cases, the dump time boot path might contain modules_image only.775char* runtime_boot_path = Arguments::get_sysclasspath();776char* rp = skip_first_path_entry(runtime_boot_path);777assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");778int dp_len = header()->app_class_paths_start_index() - 1; // ignore the first path to the module image779bool mismatch = false;780781bool relaxed_check = !header()->has_platform_or_app_classes();782if (dp_len == 0 && rp == NULL) {783return true; // ok, both runtime and dump time boot paths have modules_images only784} else if (dp_len == 0 && rp != NULL) {785if (relaxed_check) {786return true; // ok, relaxed check, runtime has extra boot append path entries787} else {788mismatch = true;789}790} else if (dp_len > 0 && rp != NULL) {791int num;792ResourceMark rm;793GrowableArray<const char*>* rp_array = create_path_array(rp);794int rp_len = rp_array->length();795if (rp_len >= dp_len) {796if (relaxed_check) {797// only check the leading entries in the runtime boot path, up to798// the length of the dump time boot path799num = dp_len;800} else {801// check the full runtime boot path, must match with dump time802num = rp_len;803}804mismatch = check_paths(1, num, rp_array);805} else {806// create_path_array() ignores non-existing paths. Although the dump time and runtime boot classpath lengths807// are the same initially, after the call to create_path_array(), the runtime boot classpath length could become808// shorter. We consider boot classpath mismatch in this case.809mismatch = true;810}811}812813if (mismatch) {814// The paths are different815return classpath_failure("[BOOT classpath mismatch, actual =", runtime_boot_path);816}817return true;818}819820bool FileMapInfo::validate_app_class_paths(int shared_app_paths_len) {821const char *appcp = Arguments::get_appclasspath();822assert(appcp != NULL, "NULL app classpath");823int rp_len = num_paths(appcp);824bool mismatch = false;825if (rp_len < shared_app_paths_len) {826return classpath_failure("Run time APP classpath is shorter than the one at dump time: ", appcp);827}828if (shared_app_paths_len != 0 && rp_len != 0) {829// Prefix is OK: E.g., dump with -cp foo.jar, but run with -cp foo.jar:bar.jar.830ResourceMark rm;831GrowableArray<const char*>* rp_array = create_path_array(appcp);832if (rp_array->length() == 0) {833// None of the jar file specified in the runtime -cp exists.834return classpath_failure("None of the jar file specified in the runtime -cp exists: -Djava.class.path=", appcp);835}836if (rp_array->length() < shared_app_paths_len) {837// create_path_array() ignores non-existing paths. Although the dump time and runtime app classpath lengths838// are the same initially, after the call to create_path_array(), the runtime app classpath length could become839// shorter. We consider app classpath mismatch in this case.840return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp);841}842843// Handling of non-existent entries in the classpath: we eliminate all the non-existent844// entries from both the dump time classpath (ClassLoader::update_class_path_entry_list)845// and the runtime classpath (FileMapInfo::create_path_array), and check the remaining846// entries. E.g.:847//848// dump : -cp a.jar:NE1:NE2:b.jar -> a.jar:b.jar -> recorded in archive.849// run 1: -cp NE3:a.jar:NE4:b.jar -> a.jar:b.jar -> matched850// run 2: -cp x.jar:NE4:b.jar -> x.jar:b.jar -> mismatched851852int j = header()->app_class_paths_start_index();853mismatch = check_paths(j, shared_app_paths_len, rp_array);854if (mismatch) {855return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp);856}857}858return true;859}860861void FileMapInfo::log_paths(const char* msg, int start_idx, int end_idx) {862LogTarget(Info, class, path) lt;863if (lt.is_enabled()) {864LogStream ls(lt);865ls.print("%s", msg);866const char* prefix = "";867for (int i = start_idx; i < end_idx; i++) {868ls.print("%s%s", prefix, shared_path(i)->name());869prefix = os::path_separator();870}871ls.cr();872}873}874875bool FileMapInfo::validate_shared_path_table() {876assert(UseSharedSpaces, "runtime only");877878_validating_shared_path_table = true;879880// Load the shared path table info from the archive header881_shared_path_table = header()->shared_path_table();882if (DynamicDumpSharedSpaces) {883// Only support dynamic dumping with the usage of the default CDS archive884// or a simple base archive.885// If the base layer archive contains additional path component besides886// the runtime image and the -cp, dynamic dumping is disabled.887//888// When dynamic archiving is enabled, the _shared_path_table is overwritten889// to include the application path and stored in the top layer archive.890assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");891if (header()->app_class_paths_start_index() > 1) {892DynamicDumpSharedSpaces = false;893warning(894"Dynamic archiving is disabled because base layer archive has appended boot classpath");895}896if (header()->num_module_paths() > 0) {897DynamicDumpSharedSpaces = false;898warning(899"Dynamic archiving is disabled because base layer archive has module path");900}901}902903log_paths("Expecting BOOT path=", 0, header()->app_class_paths_start_index());904log_paths("Expecting -Djava.class.path=", header()->app_class_paths_start_index(), header()->app_module_paths_start_index());905906int module_paths_start_index = header()->app_module_paths_start_index();907int shared_app_paths_len = 0;908909// validate the path entries up to the _max_used_path_index910for (int i=0; i < header()->max_used_path_index() + 1; i++) {911if (i < module_paths_start_index) {912if (shared_path(i)->validate()) {913// Only count the app class paths not from the "Class-path" attribute of a jar manifest.914if (!shared_path(i)->from_class_path_attr() && i >= header()->app_class_paths_start_index()) {915shared_app_paths_len++;916}917log_info(class, path)("ok");918} else {919if (_dynamic_archive_info != NULL && _dynamic_archive_info->_is_static) {920assert(!UseSharedSpaces, "UseSharedSpaces should be disabled");921}922return false;923}924} else if (i >= module_paths_start_index) {925if (shared_path(i)->validate(false /* not a class path entry */)) {926log_info(class, path)("ok");927} else {928if (_dynamic_archive_info != NULL && _dynamic_archive_info->_is_static) {929assert(!UseSharedSpaces, "UseSharedSpaces should be disabled");930}931return false;932}933}934}935936if (header()->max_used_path_index() == 0) {937// default archive only contains the module image in the bootclasspath938assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");939} else {940if (!validate_boot_class_paths() || !validate_app_class_paths(shared_app_paths_len)) {941fail_continue("shared class paths mismatch (hint: enable -Xlog:class+path=info to diagnose the failure)");942return false;943}944}945946validate_non_existent_class_paths();947948_validating_shared_path_table = false;949950#if INCLUDE_JVMTI951if (_classpath_entries_for_jvmti != NULL) {952os::free(_classpath_entries_for_jvmti);953}954size_t sz = sizeof(ClassPathEntry*) * get_number_of_shared_paths();955_classpath_entries_for_jvmti = (ClassPathEntry**)os::malloc(sz, mtClass);956memset((void*)_classpath_entries_for_jvmti, 0, sz);957#endif958959return true;960}961962void FileMapInfo::validate_non_existent_class_paths() {963// All of the recorded non-existent paths came from the Class-Path: attribute from the JAR964// files on the app classpath. If any of these are found to exist during runtime,965// it will change how classes are loading for the app loader. For safety, disable966// loading of archived platform/app classes (currently there's no way to disable just the967// app classes).968969assert(UseSharedSpaces, "runtime only");970for (int i = header()->app_module_paths_start_index() + header()->num_module_paths();971i < get_number_of_shared_paths();972i++) {973SharedClassPathEntry* ent = shared_path(i);974if (!ent->check_non_existent()) {975warning("Archived non-system classes are disabled because the "976"file %s exists", ent->name());977header()->set_has_platform_or_app_classes(false);978}979}980}981982bool FileMapInfo::check_archive(const char* archive_name, bool is_static) {983int fd = os::open(archive_name, O_RDONLY | O_BINARY, 0);984if (fd < 0) {985// do not vm_exit_during_initialization here because Arguments::init_shared_archive_paths()986// requires a shared archive name. The open_for_read() function will log a message regarding987// failure in opening a shared archive.988return false;989}990991size_t sz = is_static ? sizeof(FileMapHeader) : sizeof(DynamicArchiveHeader);992void* header = os::malloc(sz, mtInternal);993memset(header, 0, sz);994size_t n = os::read(fd, header, (unsigned int)sz);995if (n != sz) {996os::free(header);997os::close(fd);998vm_exit_during_initialization("Unable to read header from shared archive", archive_name);999return false;1000}1001if (is_static) {1002FileMapHeader* static_header = (FileMapHeader*)header;1003if (static_header->magic() != CDS_ARCHIVE_MAGIC) {1004os::free(header);1005os::close(fd);1006vm_exit_during_initialization("Not a base shared archive", archive_name);1007return false;1008}1009} else {1010DynamicArchiveHeader* dynamic_header = (DynamicArchiveHeader*)header;1011if (dynamic_header->magic() != CDS_DYNAMIC_ARCHIVE_MAGIC) {1012os::free(header);1013os::close(fd);1014vm_exit_during_initialization("Not a top shared archive", archive_name);1015return false;1016}1017}1018os::free(header);1019os::close(fd);1020return true;1021}10221023bool FileMapInfo::get_base_archive_name_from_header(const char* archive_name,1024int* size, char** base_archive_name) {1025int fd = os::open(archive_name, O_RDONLY | O_BINARY, 0);1026if (fd < 0) {1027*size = 0;1028return false;1029}10301031// read the header as a dynamic archive header1032size_t sz = sizeof(DynamicArchiveHeader);1033DynamicArchiveHeader* dynamic_header = (DynamicArchiveHeader*)os::malloc(sz, mtInternal);1034size_t n = os::read(fd, dynamic_header, (unsigned int)sz);1035if (n != sz) {1036fail_continue("Unable to read the file header.");1037os::free(dynamic_header);1038os::close(fd);1039return false;1040}1041if (dynamic_header->magic() != CDS_DYNAMIC_ARCHIVE_MAGIC) {1042// Not a dynamic header, no need to proceed further.1043*size = 0;1044os::free(dynamic_header);1045os::close(fd);1046return false;1047}1048if (dynamic_header->base_archive_is_default()) {1049*base_archive_name = Arguments::get_default_shared_archive_path();1050} else {1051// read the base archive name1052size_t name_size = dynamic_header->base_archive_name_size();1053if (name_size == 0) {1054os::free(dynamic_header);1055os::close(fd);1056return false;1057}1058*base_archive_name = NEW_C_HEAP_ARRAY(char, name_size, mtInternal);1059n = os::read(fd, *base_archive_name, (unsigned int)name_size);1060if (n != name_size) {1061fail_continue("Unable to read the base archive name from the header.");1062FREE_C_HEAP_ARRAY(char, *base_archive_name);1063*base_archive_name = NULL;1064os::free(dynamic_header);1065os::close(fd);1066return false;1067}1068}10691070os::free(dynamic_header);1071os::close(fd);1072return true;1073}10741075// Read the FileMapInfo information from the file.10761077bool FileMapInfo::init_from_file(int fd) {1078size_t sz = is_static() ? sizeof(FileMapHeader) : sizeof(DynamicArchiveHeader);1079size_t n = os::read(fd, header(), (unsigned int)sz);1080if (n != sz) {1081fail_continue("Unable to read the file header.");1082return false;1083}10841085if (!Arguments::has_jimage()) {1086FileMapInfo::fail_continue("The shared archive file cannot be used with an exploded module build.");1087return false;1088}10891090unsigned int expected_magic = is_static() ? CDS_ARCHIVE_MAGIC : CDS_DYNAMIC_ARCHIVE_MAGIC;1091if (header()->magic() != expected_magic) {1092log_info(cds)("_magic expected: 0x%08x", expected_magic);1093log_info(cds)(" actual: 0x%08x", header()->magic());1094FileMapInfo::fail_continue("The shared archive file has a bad magic number.");1095return false;1096}10971098if (header()->version() != CURRENT_CDS_ARCHIVE_VERSION) {1099log_info(cds)("_version expected: %d", CURRENT_CDS_ARCHIVE_VERSION);1100log_info(cds)(" actual: %d", header()->version());1101fail_continue("The shared archive file has the wrong version.");1102return false;1103}11041105if (header()->header_size() != sz) {1106log_info(cds)("_header_size expected: " SIZE_FORMAT, sz);1107log_info(cds)(" actual: " SIZE_FORMAT, header()->header_size());1108FileMapInfo::fail_continue("The shared archive file has an incorrect header size.");1109return false;1110}11111112const char* actual_ident = header()->jvm_ident();11131114if (actual_ident[JVM_IDENT_MAX-1] != 0) {1115FileMapInfo::fail_continue("JVM version identifier is corrupted.");1116return false;1117}11181119char expected_ident[JVM_IDENT_MAX];1120get_header_version(expected_ident);1121if (strncmp(actual_ident, expected_ident, JVM_IDENT_MAX-1) != 0) {1122log_info(cds)("_jvm_ident expected: %s", expected_ident);1123log_info(cds)(" actual: %s", actual_ident);1124FileMapInfo::fail_continue("The shared archive file was created by a different"1125" version or build of HotSpot");1126return false;1127}11281129if (VerifySharedSpaces) {1130int expected_crc = header()->compute_crc();1131if (expected_crc != header()->crc()) {1132log_info(cds)("_crc expected: %d", expected_crc);1133log_info(cds)(" actual: %d", header()->crc());1134FileMapInfo::fail_continue("Header checksum verification failed.");1135return false;1136}1137}11381139_file_offset = n + header()->base_archive_name_size(); // accounts for the size of _base_archive_name11401141if (is_static()) {1142// just checking the last region is sufficient since the archive is written1143// in sequential order1144size_t len = lseek(fd, 0, SEEK_END);1145FileMapRegion* si = space_at(MetaspaceShared::last_valid_region);1146// The last space might be empty1147if (si->file_offset() > len || len - si->file_offset() < si->used()) {1148fail_continue("The shared archive file has been truncated.");1149return false;1150}1151}11521153return true;1154}11551156void FileMapInfo::seek_to_position(size_t pos) {1157if (lseek(_fd, (long)pos, SEEK_SET) < 0) {1158fail_stop("Unable to seek to position " SIZE_FORMAT, pos);1159}1160}11611162// Read the FileMapInfo information from the file.1163bool FileMapInfo::open_for_read() {1164if (_file_open) {1165return true;1166}1167if (is_static()) {1168_full_path = Arguments::GetSharedArchivePath();1169} else {1170_full_path = Arguments::GetSharedDynamicArchivePath();1171}1172log_info(cds)("trying to map %s", _full_path);1173int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0);1174if (fd < 0) {1175if (errno == ENOENT) {1176fail_continue("Specified shared archive not found (%s).", _full_path);1177} else {1178fail_continue("Failed to open shared archive file (%s).",1179os::strerror(errno));1180}1181return false;1182} else {1183log_info(cds)("Opened archive %s.", _full_path);1184}11851186_fd = fd;1187_file_open = true;1188return true;1189}11901191// Write the FileMapInfo information to the file.11921193void FileMapInfo::open_for_write(const char* path) {1194if (path == NULL) {1195_full_path = Arguments::GetSharedArchivePath();1196} else {1197_full_path = path;1198}1199LogMessage(cds) msg;1200if (msg.is_info()) {1201msg.info("Dumping shared data to file: ");1202msg.info(" %s", _full_path);1203}12041205#ifdef _WINDOWS // On Windows, need WRITE permission to remove the file.1206chmod(_full_path, _S_IREAD | _S_IWRITE);1207#endif12081209// Use remove() to delete the existing file because, on Unix, this will1210// allow processes that have it open continued access to the file.1211remove(_full_path);1212int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);1213if (fd < 0) {1214fail_stop("Unable to create shared archive file %s: (%s).", _full_path,1215os::strerror(errno));1216}1217_fd = fd;1218_file_open = true;12191220// Seek past the header. We will write the header after all regions are written1221// and their CRCs computed.1222size_t header_bytes = header()->header_size();1223if (header()->magic() == CDS_DYNAMIC_ARCHIVE_MAGIC) {1224header_bytes += strlen(Arguments::GetSharedArchivePath()) + 1;1225}12261227header_bytes = align_up(header_bytes, MetaspaceShared::core_region_alignment());1228_file_offset = header_bytes;1229seek_to_position(_file_offset);1230}123112321233// Write the header to the file, seek to the next allocation boundary.12341235void FileMapInfo::write_header() {1236_file_offset = 0;1237seek_to_position(_file_offset);1238assert(is_file_position_aligned(), "must be");1239write_bytes(header(), header()->header_size());12401241if (header()->magic() == CDS_DYNAMIC_ARCHIVE_MAGIC) {1242char* base_archive_name = (char*)Arguments::GetSharedArchivePath();1243if (base_archive_name != NULL) {1244write_bytes(base_archive_name, header()->base_archive_name_size());1245}1246}1247}12481249size_t FileMapRegion::used_aligned() const {1250return align_up(used(), MetaspaceShared::core_region_alignment());1251}12521253void FileMapRegion::init(int region_index, size_t mapping_offset, size_t size, bool read_only,1254bool allow_exec, int crc) {1255_is_heap_region = HeapShared::is_heap_region(region_index);1256_is_bitmap_region = (region_index == MetaspaceShared::bm);1257_mapping_offset = mapping_offset;1258_used = size;1259_read_only = read_only;1260_allow_exec = allow_exec;1261_crc = crc;1262_mapped_from_file = false;1263_mapped_base = NULL;1264}126512661267static const char* region_name(int region_index) {1268static const char* names[] = {1269"rw", "ro", "bm", "ca0", "ca1", "oa0", "oa1"1270};1271const int num_regions = sizeof(names)/sizeof(names[0]);1272assert(0 <= region_index && region_index < num_regions, "sanity");12731274return names[region_index];1275}12761277void FileMapRegion::print(outputStream* st, int region_index) {1278st->print_cr("============ region ============= %d \"%s\"", region_index, region_name(region_index));1279st->print_cr("- crc: 0x%08x", _crc);1280st->print_cr("- read_only: %d", _read_only);1281st->print_cr("- allow_exec: %d", _allow_exec);1282st->print_cr("- is_heap_region: %d", _is_heap_region);1283st->print_cr("- is_bitmap_region: %d", _is_bitmap_region);1284st->print_cr("- mapped_from_file: %d", _mapped_from_file);1285st->print_cr("- file_offset: " SIZE_FORMAT_HEX, _file_offset);1286st->print_cr("- mapping_offset: " SIZE_FORMAT_HEX, _mapping_offset);1287st->print_cr("- used: " SIZE_FORMAT, _used);1288st->print_cr("- oopmap_offset: " SIZE_FORMAT_HEX, _oopmap_offset);1289st->print_cr("- oopmap_size_in_bits: " SIZE_FORMAT, _oopmap_size_in_bits);1290st->print_cr("- mapped_base: " INTPTR_FORMAT, p2i(_mapped_base));1291}12921293void FileMapInfo::write_region(int region, char* base, size_t size,1294bool read_only, bool allow_exec) {1295Arguments::assert_is_dumping_archive();12961297FileMapRegion* si = space_at(region);1298char* requested_base;1299size_t mapping_offset = 0;13001301if (region == MetaspaceShared::bm) {1302requested_base = NULL; // always NULL for bm region1303} else if (size == 0) {1304// This is an unused region (e.g., a heap region when !INCLUDE_CDS_JAVA_HEAP)1305requested_base = NULL;1306} else if (HeapShared::is_heap_region(region)) {1307assert(!DynamicDumpSharedSpaces, "must be");1308requested_base = base;1309mapping_offset = (size_t)CompressedOops::encode_not_null(cast_to_oop(base));1310assert(mapping_offset == (size_t)(uint32_t)mapping_offset, "must be 32-bit only");1311} else {1312char* requested_SharedBaseAddress = (char*)MetaspaceShared::requested_base_address();1313requested_base = ArchiveBuilder::current()->to_requested(base);1314assert(requested_base >= requested_SharedBaseAddress, "must be");1315mapping_offset = requested_base - requested_SharedBaseAddress;1316}13171318si->set_file_offset(_file_offset);1319int crc = ClassLoader::crc32(0, base, (jint)size);1320if (size > 0) {1321log_info(cds)("Shared file region (%-3s) %d: " SIZE_FORMAT_W(8)1322" bytes, addr " INTPTR_FORMAT " file offset " SIZE_FORMAT_HEX_W(08)1323" crc 0x%08x",1324region_name(region), region, size, p2i(requested_base), _file_offset, crc);1325}1326si->init(region, mapping_offset, size, read_only, allow_exec, crc);13271328if (base != NULL) {1329write_bytes_aligned(base, size);1330}1331}13321333size_t FileMapInfo::set_oopmaps_offset(GrowableArray<ArchiveHeapOopmapInfo>* oopmaps, size_t curr_size) {1334for (int i = 0; i < oopmaps->length(); i++) {1335oopmaps->at(i)._offset = curr_size;1336curr_size += oopmaps->at(i)._oopmap_size_in_bytes;1337}1338return curr_size;1339}13401341size_t FileMapInfo::write_oopmaps(GrowableArray<ArchiveHeapOopmapInfo>* oopmaps, size_t curr_offset, char* buffer) {1342for (int i = 0; i < oopmaps->length(); i++) {1343memcpy(buffer + curr_offset, oopmaps->at(i)._oopmap, oopmaps->at(i)._oopmap_size_in_bytes);1344curr_offset += oopmaps->at(i)._oopmap_size_in_bytes;1345}1346return curr_offset;1347}13481349char* FileMapInfo::write_bitmap_region(const CHeapBitMap* ptrmap,1350GrowableArray<ArchiveHeapOopmapInfo>* closed_oopmaps,1351GrowableArray<ArchiveHeapOopmapInfo>* open_oopmaps,1352size_t &size_in_bytes) {1353size_t size_in_bits = ptrmap->size();1354size_in_bytes = ptrmap->size_in_bytes();13551356if (closed_oopmaps != NULL && open_oopmaps != NULL) {1357size_in_bytes = set_oopmaps_offset(closed_oopmaps, size_in_bytes);1358size_in_bytes = set_oopmaps_offset(open_oopmaps, size_in_bytes);1359}13601361char* buffer = NEW_C_HEAP_ARRAY(char, size_in_bytes, mtClassShared);1362ptrmap->write_to((BitMap::bm_word_t*)buffer, ptrmap->size_in_bytes());1363header()->set_ptrmap_size_in_bits(size_in_bits);13641365if (closed_oopmaps != NULL && open_oopmaps != NULL) {1366size_t curr_offset = write_oopmaps(closed_oopmaps, ptrmap->size_in_bytes(), buffer);1367write_oopmaps(open_oopmaps, curr_offset, buffer);1368}13691370write_region(MetaspaceShared::bm, (char*)buffer, size_in_bytes, /*read_only=*/true, /*allow_exec=*/false);1371return buffer;1372}13731374// Write out the given archive heap memory regions. GC code combines multiple1375// consecutive archive GC regions into one MemRegion whenever possible and1376// produces the 'heap_mem' array.1377//1378// If the archive heap memory size is smaller than a single dump time GC region1379// size, there is only one MemRegion in the array.1380//1381// If the archive heap memory size is bigger than one dump time GC region size,1382// the 'heap_mem' array may contain more than one consolidated MemRegions. When1383// the first/bottom archive GC region is a partial GC region (with the empty1384// portion at the higher address within the region), one MemRegion is used for1385// the bottom partial archive GC region. The rest of the consecutive archive1386// GC regions are combined into another MemRegion.1387//1388// Here's the mapping from (archive heap GC regions) -> (GrowableArray<MemRegion> *regions).1389// + We have 1 or more archive heap regions: ah0, ah1, ah2 ..... ahn1390// + We have 1 or 2 consolidated heap memory regions: r0 and r11391//1392// If there's a single archive GC region (ah0), then r0 == ah0, and r1 is empty.1393// Otherwise:1394//1395// "X" represented space that's occupied by heap objects.1396// "_" represented unused spaced in the heap region.1397//1398//1399// |ah0 | ah1 | ah2| ...... | ahn|1400// |XXXXXX|__ |XXXXX|XXXX|XXXXXXXX|XXXX|1401// |<-r0->| |<- r1 ----------------->|1402// ^^^1403// |1404// +-- gap1405size_t FileMapInfo::write_archive_heap_regions(GrowableArray<MemRegion> *heap_mem,1406GrowableArray<ArchiveHeapOopmapInfo> *oopmaps,1407int first_region_id, int max_num_regions) {1408assert(max_num_regions <= 2, "Only support maximum 2 memory regions");14091410int arr_len = heap_mem == NULL ? 0 : heap_mem->length();1411if(arr_len > max_num_regions) {1412fail_stop("Unable to write archive heap memory regions: "1413"number of memory regions exceeds maximum due to fragmentation. "1414"Please increase java heap size "1415"(current MaxHeapSize is " SIZE_FORMAT ", InitialHeapSize is " SIZE_FORMAT ").",1416MaxHeapSize, InitialHeapSize);1417}14181419size_t total_size = 0;1420for (int i = 0; i < max_num_regions; i++) {1421char* start = NULL;1422size_t size = 0;1423if (i < arr_len) {1424start = (char*)heap_mem->at(i).start();1425size = heap_mem->at(i).byte_size();1426total_size += size;1427}14281429int region_idx = i + first_region_id;1430write_region(region_idx, start, size, false, false);1431if (size > 0) {1432space_at(region_idx)->init_oopmap(oopmaps->at(i)._offset,1433oopmaps->at(i)._oopmap_size_in_bits);1434}1435}1436return total_size;1437}14381439// Dump bytes to file -- at the current file position.14401441void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) {1442assert(_file_open, "must be");1443size_t n = os::write(_fd, buffer, (unsigned int)nbytes);1444if (n != nbytes) {1445// If the shared archive is corrupted, close it and remove it.1446close();1447remove(_full_path);1448fail_stop("Unable to write to shared archive file.");1449}1450_file_offset += nbytes;1451}14521453bool FileMapInfo::is_file_position_aligned() const {1454return _file_offset == align_up(_file_offset,1455MetaspaceShared::core_region_alignment());1456}14571458// Align file position to an allocation unit boundary.14591460void FileMapInfo::align_file_position() {1461assert(_file_open, "must be");1462size_t new_file_offset = align_up(_file_offset,1463MetaspaceShared::core_region_alignment());1464if (new_file_offset != _file_offset) {1465_file_offset = new_file_offset;1466// Seek one byte back from the target and write a byte to insure1467// that the written file is the correct length.1468_file_offset -= 1;1469seek_to_position(_file_offset);1470char zero = 0;1471write_bytes(&zero, 1);1472}1473}147414751476// Dump bytes to file -- at the current file position.14771478void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) {1479align_file_position();1480write_bytes(buffer, nbytes);1481align_file_position();1482}14831484// Close the shared archive file. This does NOT unmap mapped regions.14851486void FileMapInfo::close() {1487if (_file_open) {1488if (::close(_fd) < 0) {1489fail_stop("Unable to close the shared archive file.");1490}1491_file_open = false;1492_fd = -1;1493}1494}149514961497// JVM/TI RedefineClasses() support:1498// Remap the shared readonly space to shared readwrite, private.1499bool FileMapInfo::remap_shared_readonly_as_readwrite() {1500int idx = MetaspaceShared::ro;1501FileMapRegion* si = space_at(idx);1502if (!si->read_only()) {1503// the space is already readwrite so we are done1504return true;1505}1506size_t size = si->used_aligned();1507if (!open_for_read()) {1508return false;1509}1510char *addr = region_addr(idx);1511char *base = os::remap_memory(_fd, _full_path, si->file_offset(),1512addr, size, false /* !read_only */,1513si->allow_exec());1514close();1515// These have to be errors because the shared region is now unmapped.1516if (base == NULL) {1517log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);1518vm_exit(1);1519}1520if (base != addr) {1521log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);1522vm_exit(1);1523}1524si->set_read_only(false);1525return true;1526}15271528// Memory map a region in the address space.1529static const char* shared_region_name[] = { "ReadWrite", "ReadOnly", "Bitmap",1530"String1", "String2", "OpenArchive1", "OpenArchive2" };15311532MapArchiveResult FileMapInfo::map_regions(int regions[], int num_regions, char* mapped_base_address, ReservedSpace rs) {1533DEBUG_ONLY(FileMapRegion* last_region = NULL);1534intx addr_delta = mapped_base_address - header()->requested_base_address();15351536// Make sure we don't attempt to use header()->mapped_base_address() unless1537// it's been successfully mapped.1538DEBUG_ONLY(header()->set_mapped_base_address((char*)(uintptr_t)0xdeadbeef);)15391540for (int r = 0; r < num_regions; r++) {1541int idx = regions[r];1542MapArchiveResult result = map_region(idx, addr_delta, mapped_base_address, rs);1543if (result != MAP_ARCHIVE_SUCCESS) {1544return result;1545}1546FileMapRegion* si = space_at(idx);1547DEBUG_ONLY(if (last_region != NULL) {1548// Ensure that the OS won't be able to allocate new memory spaces between any mapped1549// regions, or else it would mess up the simple comparision in MetaspaceObj::is_shared().1550assert(si->mapped_base() == last_region->mapped_end(), "must have no gaps");1551}1552last_region = si;)1553log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)", is_static() ? "static " : "dynamic",1554idx, p2i(si->mapped_base()), p2i(si->mapped_end()),1555shared_region_name[idx]);15561557}15581559header()->set_mapped_base_address(header()->requested_base_address() + addr_delta);1560if (addr_delta != 0 && !relocate_pointers_in_core_regions(addr_delta)) {1561return MAP_ARCHIVE_OTHER_FAILURE;1562}15631564return MAP_ARCHIVE_SUCCESS;1565}15661567bool FileMapInfo::read_region(int i, char* base, size_t size) {1568assert(MetaspaceShared::use_windows_memory_mapping(), "used by windows only");1569FileMapRegion* si = space_at(i);1570log_info(cds)("Commit %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)%s",1571is_static() ? "static " : "dynamic", i, p2i(base), p2i(base + size),1572shared_region_name[i], si->allow_exec() ? " exec" : "");1573if (!os::commit_memory(base, size, si->allow_exec())) {1574log_error(cds)("Failed to commit %s region #%d (%s)", is_static() ? "static " : "dynamic",1575i, shared_region_name[i]);1576return false;1577}1578if (lseek(_fd, (long)si->file_offset(), SEEK_SET) != (int)si->file_offset() ||1579read_bytes(base, size) != size) {1580return false;1581}1582return true;1583}15841585MapArchiveResult FileMapInfo::map_region(int i, intx addr_delta, char* mapped_base_address, ReservedSpace rs) {1586assert(!HeapShared::is_heap_region(i), "sanity");1587FileMapRegion* si = space_at(i);1588size_t size = si->used_aligned();1589char *requested_addr = mapped_base_address + si->mapping_offset();1590assert(si->mapped_base() == NULL, "must be not mapped yet");1591assert(requested_addr != NULL, "must be specified");15921593si->set_mapped_from_file(false);15941595if (MetaspaceShared::use_windows_memory_mapping()) {1596// Windows cannot remap read-only shared memory to read-write when required for1597// RedefineClasses, which is also used by JFR. Always map windows regions as RW.1598si->set_read_only(false);1599} else if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space() ||1600Arguments::has_jfr_option()) {1601// If a tool agent is in use (debugging enabled), or JFR, we must map the address space RW1602si->set_read_only(false);1603} else if (addr_delta != 0) {1604si->set_read_only(false); // Need to patch the pointers1605}16061607if (MetaspaceShared::use_windows_memory_mapping() && rs.is_reserved()) {1608// This is the second time we try to map the archive(s). We have already created a ReservedSpace1609// that covers all the FileMapRegions to ensure all regions can be mapped. However, Windows1610// can't mmap into a ReservedSpace, so we just os::read() the data. We're going to patch all the1611// regions anyway, so there's no benefit for mmap anyway.1612if (!read_region(i, requested_addr, size)) {1613log_info(cds)("Failed to read %s shared space into reserved space at " INTPTR_FORMAT,1614shared_region_name[i], p2i(requested_addr));1615return MAP_ARCHIVE_OTHER_FAILURE; // oom or I/O error.1616}1617} else {1618// Note that this may either be a "fresh" mapping into unreserved address1619// space (Windows, first mapping attempt), or a mapping into pre-reserved1620// space (Posix). See also comment in MetaspaceShared::map_archives().1621char* base = os::map_memory(_fd, _full_path, si->file_offset(),1622requested_addr, size, si->read_only(),1623si->allow_exec(), mtClassShared);1624if (base != requested_addr) {1625log_info(cds)("Unable to map %s shared space at " INTPTR_FORMAT,1626shared_region_name[i], p2i(requested_addr));1627_memory_mapping_failed = true;1628return MAP_ARCHIVE_MMAP_FAILURE;1629}1630si->set_mapped_from_file(true);1631}1632si->set_mapped_base(requested_addr);16331634if (VerifySharedSpaces && !verify_region_checksum(i)) {1635return MAP_ARCHIVE_OTHER_FAILURE;1636}16371638return MAP_ARCHIVE_SUCCESS;1639}16401641// The return value is the location of the archive relocation bitmap.1642char* FileMapInfo::map_bitmap_region() {1643FileMapRegion* si = space_at(MetaspaceShared::bm);1644if (si->mapped_base() != NULL) {1645return si->mapped_base();1646}1647bool read_only = true, allow_exec = false;1648char* requested_addr = NULL; // allow OS to pick any location1649char* bitmap_base = os::map_memory(_fd, _full_path, si->file_offset(),1650requested_addr, si->used_aligned(), read_only, allow_exec, mtClassShared);1651if (bitmap_base == NULL) {1652log_info(cds)("failed to map relocation bitmap");1653return NULL;1654}16551656if (VerifySharedSpaces && !region_crc_check(bitmap_base, si->used(), si->crc())) {1657log_error(cds)("relocation bitmap CRC error");1658if (!os::unmap_memory(bitmap_base, si->used_aligned())) {1659fatal("os::unmap_memory of relocation bitmap failed");1660}1661return NULL;1662}16631664si->set_mapped_base(bitmap_base);1665si->set_mapped_from_file(true);1666log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)",1667is_static() ? "static " : "dynamic",1668MetaspaceShared::bm, p2i(si->mapped_base()), p2i(si->mapped_end()),1669shared_region_name[MetaspaceShared::bm]);1670return bitmap_base;1671}16721673// This is called when we cannot map the archive at the requested[ base address (usually 0x800000000).1674// We relocate all pointers in the 2 core regions (ro, rw).1675bool FileMapInfo::relocate_pointers_in_core_regions(intx addr_delta) {1676log_debug(cds, reloc)("runtime archive relocation start");1677char* bitmap_base = map_bitmap_region();16781679if (bitmap_base == NULL) {1680return false; // OOM, or CRC check failure1681} else {1682size_t ptrmap_size_in_bits = header()->ptrmap_size_in_bits();1683log_debug(cds, reloc)("mapped relocation bitmap @ " INTPTR_FORMAT " (" SIZE_FORMAT " bits)",1684p2i(bitmap_base), ptrmap_size_in_bits);16851686BitMapView ptrmap((BitMap::bm_word_t*)bitmap_base, ptrmap_size_in_bits);16871688// Patch all pointers in the the mapped region that are marked by ptrmap.1689address patch_base = (address)mapped_base();1690address patch_end = (address)mapped_end();16911692// the current value of the pointers to be patched must be within this1693// range (i.e., must be between the requesed base address, and the of the current archive).1694// Note: top archive may point to objects in the base archive, but not the other way around.1695address valid_old_base = (address)header()->requested_base_address();1696address valid_old_end = valid_old_base + mapping_end_offset();16971698// after patching, the pointers must point inside this range1699// (the requested location of the archive, as mapped at runtime).1700address valid_new_base = (address)header()->mapped_base_address();1701address valid_new_end = (address)mapped_end();17021703SharedDataRelocator patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end,1704valid_new_base, valid_new_end, addr_delta);1705ptrmap.iterate(&patcher);17061707// The MetaspaceShared::bm region will be unmapped in MetaspaceShared::initialize_shared_spaces().17081709log_debug(cds, reloc)("runtime archive relocation done");1710return true;1711}1712}17131714size_t FileMapInfo::read_bytes(void* buffer, size_t count) {1715assert(_file_open, "Archive file is not open");1716size_t n = os::read(_fd, buffer, (unsigned int)count);1717if (n != count) {1718// Close the file if there's a problem reading it.1719close();1720return 0;1721}1722_file_offset += count;1723return count;1724}17251726address FileMapInfo::decode_start_address(FileMapRegion* spc, bool with_current_oop_encoding_mode) {1727size_t offset = spc->mapping_offset();1728narrowOop n = CompressedOops::narrow_oop_cast(offset);1729if (with_current_oop_encoding_mode) {1730return cast_from_oop<address>(CompressedOops::decode_raw_not_null(n));1731} else {1732return cast_from_oop<address>(HeapShared::decode_from_archive(n));1733}1734}17351736static MemRegion *closed_archive_heap_ranges = NULL;1737static MemRegion *open_archive_heap_ranges = NULL;1738static int num_closed_archive_heap_ranges = 0;1739static int num_open_archive_heap_ranges = 0;17401741#if INCLUDE_CDS_JAVA_HEAP1742bool FileMapInfo::has_heap_regions() {1743return (space_at(MetaspaceShared::first_closed_archive_heap_region)->used() > 0);1744}17451746// Returns the address range of the archived heap regions computed using the1747// current oop encoding mode. This range may be different than the one seen at1748// dump time due to encoding mode differences. The result is used in determining1749// if/how these regions should be relocated at run time.1750MemRegion FileMapInfo::get_heap_regions_range_with_current_oop_encoding_mode() {1751address start = (address) max_uintx;1752address end = NULL;17531754for (int i = MetaspaceShared::first_closed_archive_heap_region;1755i <= MetaspaceShared::last_valid_region;1756i++) {1757FileMapRegion* si = space_at(i);1758size_t size = si->used();1759if (size > 0) {1760address s = start_address_as_decoded_with_current_oop_encoding_mode(si);1761address e = s + size;1762if (start > s) {1763start = s;1764}1765if (end < e) {1766end = e;1767}1768}1769}1770assert(end != NULL, "must have at least one used heap region");1771return MemRegion((HeapWord*)start, (HeapWord*)end);1772}17731774//1775// Map the closed and open archive heap objects to the runtime java heap.1776//1777// The shared objects are mapped at (or close to ) the java heap top in1778// closed archive regions. The mapped objects contain no out-going1779// references to any other java heap regions. GC does not write into the1780// mapped closed archive heap region.1781//1782// The open archive heap objects are mapped below the shared objects in1783// the runtime java heap. The mapped open archive heap data only contains1784// references to the shared objects and open archive objects initially.1785// During runtime execution, out-going references to any other java heap1786// regions may be added. GC may mark and update references in the mapped1787// open archive objects.1788void FileMapInfo::map_heap_regions_impl() {1789if (!HeapShared::is_heap_object_archiving_allowed()) {1790log_info(cds)("CDS heap data is being ignored. UseG1GC, "1791"UseCompressedOops and UseCompressedClassPointers are required.");1792return;1793}17941795if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {1796ShouldNotReachHere(); // CDS should have been disabled.1797// The archived objects are mapped at JVM start-up, but we don't know if1798// j.l.String or j.l.Class might be replaced by the ClassFileLoadHook,1799// which would make the archived String or mirror objects invalid. Let's be safe and not1800// use the archived objects. These 2 classes are loaded during the JVMTI "early" stage.1801//1802// If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects1803// in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK1804// because we won't install an archived object subgraph if the klass of any of the1805// referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph().1806}18071808log_info(cds)("CDS archive was created with max heap size = " SIZE_FORMAT "M, and the following configuration:",1809max_heap_size()/M);1810log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",1811p2i(narrow_klass_base()), narrow_klass_shift());1812log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",1813narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift());1814log_info(cds)(" heap range = [" PTR_FORMAT " - " PTR_FORMAT "]",1815p2i(header()->heap_begin()), p2i(header()->heap_end()));18161817log_info(cds)("The current max heap size = " SIZE_FORMAT "M, HeapRegion::GrainBytes = " SIZE_FORMAT,1818MaxHeapSize/M, HeapRegion::GrainBytes);1819log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",1820p2i(CompressedKlassPointers::base()), CompressedKlassPointers::shift());1821log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",1822CompressedOops::mode(), p2i(CompressedOops::base()), CompressedOops::shift());1823log_info(cds)(" heap range = [" PTR_FORMAT " - " PTR_FORMAT "]",1824p2i(CompressedOops::begin()), p2i(CompressedOops::end()));18251826if (narrow_klass_base() != CompressedKlassPointers::base() ||1827narrow_klass_shift() != CompressedKlassPointers::shift()) {1828log_info(cds)("CDS heap data cannot be used because the archive was created with an incompatible narrow klass encoding mode.");1829return;1830}18311832if (narrow_oop_mode() != CompressedOops::mode() ||1833narrow_oop_base() != CompressedOops::base() ||1834narrow_oop_shift() != CompressedOops::shift()) {1835log_info(cds)("CDS heap data needs to be relocated because the archive was created with an incompatible oop encoding mode.");1836_heap_pointers_need_patching = true;1837} else {1838MemRegion range = get_heap_regions_range_with_current_oop_encoding_mode();1839if (!CompressedOops::is_in(range)) {1840log_info(cds)("CDS heap data needs to be relocated because");1841log_info(cds)("the desired range " PTR_FORMAT " - " PTR_FORMAT, p2i(range.start()), p2i(range.end()));1842log_info(cds)("is outside of the heap " PTR_FORMAT " - " PTR_FORMAT, p2i(CompressedOops::begin()), p2i(CompressedOops::end()));1843_heap_pointers_need_patching = true;1844} else if (header()->heap_end() != CompressedOops::end()) {1845log_info(cds)("CDS heap data needs to be relocated to the end of the runtime heap to reduce fragmentation");1846_heap_pointers_need_patching = true;1847}1848}18491850ptrdiff_t delta = 0;1851if (_heap_pointers_need_patching) {1852// dumptime heap end ------------v1853// [ |archived heap regions| ] runtime heap end ------v1854// [ |archived heap regions| ]1855// |<-----delta-------------------->|1856//1857// At dump time, the archived heap regions were near the top of the heap.1858// At run time, they may not be inside the heap, so we move them so1859// that they are now near the top of the runtime time. This can be done by1860// the simple math of adding the delta as shown above.1861address dumptime_heap_end = header()->heap_end();1862address runtime_heap_end = CompressedOops::end();1863delta = runtime_heap_end - dumptime_heap_end;1864}18651866log_info(cds)("CDS heap data relocation delta = " INTX_FORMAT " bytes", delta);1867HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());18681869FileMapRegion* si = space_at(MetaspaceShared::first_closed_archive_heap_region);1870address relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si);1871if (!is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes)) {1872// Align the bottom of the closed archive heap regions at G1 region boundary.1873// This will avoid the situation where the highest open region and the lowest1874// closed region sharing the same G1 region. Otherwise we will fail to map the1875// open regions.1876size_t align = size_t(relocated_closed_heap_region_bottom) % HeapRegion::GrainBytes;1877delta -= align;1878log_info(cds)("CDS heap data needs to be relocated lower by a further " SIZE_FORMAT1879" bytes to " INTX_FORMAT " to be aligned with HeapRegion::GrainBytes",1880align, delta);1881HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());1882_heap_pointers_need_patching = true;1883relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si);1884}1885assert(is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes),1886"must be");18871888// Map the closed_archive_heap regions, GC does not write into the regions.1889if (map_heap_data(&closed_archive_heap_ranges,1890MetaspaceShared::first_closed_archive_heap_region,1891MetaspaceShared::max_closed_archive_heap_region,1892&num_closed_archive_heap_ranges)) {1893HeapShared::set_closed_archive_heap_region_mapped();18941895// Now, map open_archive heap regions, GC can write into the regions.1896if (map_heap_data(&open_archive_heap_ranges,1897MetaspaceShared::first_open_archive_heap_region,1898MetaspaceShared::max_open_archive_heap_region,1899&num_open_archive_heap_ranges,1900true /* open */)) {1901HeapShared::set_open_archive_heap_region_mapped();1902HeapShared::set_roots(header()->heap_obj_roots());1903}1904}1905}19061907void FileMapInfo::map_heap_regions() {1908if (has_heap_regions()) {1909map_heap_regions_impl();1910}19111912if (!HeapShared::closed_archive_heap_region_mapped()) {1913assert(closed_archive_heap_ranges == NULL &&1914num_closed_archive_heap_ranges == 0, "sanity");1915}19161917if (!HeapShared::open_archive_heap_region_mapped()) {1918assert(open_archive_heap_ranges == NULL && num_open_archive_heap_ranges == 0, "sanity");1919MetaspaceShared::disable_full_module_graph();1920}1921}19221923bool FileMapInfo::map_heap_data(MemRegion **heap_mem, int first,1924int max, int* num, bool is_open_archive) {1925MemRegion* regions = MemRegion::create_array(max, mtInternal);19261927struct Cleanup {1928MemRegion* _regions;1929uint _length;1930bool _aborted;1931Cleanup(MemRegion* regions, uint length) : _regions(regions), _length(length), _aborted(true) { }1932~Cleanup() { if (_aborted) { MemRegion::destroy_array(_regions, _length); } }1933} cleanup(regions, max);19341935FileMapRegion* si;1936int region_num = 0;19371938for (int i = first;1939i < first + max; i++) {1940si = space_at(i);1941size_t size = si->used();1942if (size > 0) {1943HeapWord* start = (HeapWord*)start_address_as_decoded_from_archive(si);1944regions[region_num] = MemRegion(start, size / HeapWordSize);1945region_num ++;1946log_info(cds)("Trying to map heap data: region[%d] at " INTPTR_FORMAT ", size = " SIZE_FORMAT_W(8) " bytes",1947i, p2i(start), size);1948}1949}19501951if (region_num == 0) {1952return false; // no archived java heap data1953}19541955// Check that ranges are within the java heap1956if (!G1CollectedHeap::heap()->check_archive_addresses(regions, region_num)) {1957log_info(cds)("UseSharedSpaces: Unable to allocate region, range is not within java heap.");1958return false;1959}19601961// allocate from java heap1962if (!G1CollectedHeap::heap()->alloc_archive_regions(1963regions, region_num, is_open_archive)) {1964log_info(cds)("UseSharedSpaces: Unable to allocate region, java heap range is already in use.");1965return false;1966}19671968// Map the archived heap data. No need to call MemTracker::record_virtual_memory_type()1969// for mapped regions as they are part of the reserved java heap, which is1970// already recorded.1971for (int i = 0; i < region_num; i++) {1972si = space_at(first + i);1973char* addr = (char*)regions[i].start();1974char* base = os::map_memory(_fd, _full_path, si->file_offset(),1975addr, regions[i].byte_size(), si->read_only(),1976si->allow_exec());1977if (base == NULL || base != addr) {1978// dealloc the regions from java heap1979dealloc_archive_heap_regions(regions, region_num);1980log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap. "1981INTPTR_FORMAT ", size = " SIZE_FORMAT " bytes",1982p2i(addr), regions[i].byte_size());1983return false;1984}19851986if (VerifySharedSpaces && !region_crc_check(addr, regions[i].byte_size(), si->crc())) {1987// dealloc the regions from java heap1988dealloc_archive_heap_regions(regions, region_num);1989log_info(cds)("UseSharedSpaces: mapped heap regions are corrupt");1990return false;1991}1992}19931994cleanup._aborted = false;1995// the shared heap data is mapped successfully1996*heap_mem = regions;1997*num = region_num;1998return true;1999}20002001void FileMapInfo::patch_archived_heap_embedded_pointers() {2002if (!_heap_pointers_need_patching) {2003return;2004}20052006log_info(cds)("patching heap embedded pointers");2007patch_archived_heap_embedded_pointers(closed_archive_heap_ranges,2008num_closed_archive_heap_ranges,2009MetaspaceShared::first_closed_archive_heap_region);20102011patch_archived_heap_embedded_pointers(open_archive_heap_ranges,2012num_open_archive_heap_ranges,2013MetaspaceShared::first_open_archive_heap_region);2014}20152016void FileMapInfo::patch_archived_heap_embedded_pointers(MemRegion* ranges, int num_ranges,2017int first_region_idx) {2018char* bitmap_base = map_bitmap_region();2019if (bitmap_base == NULL) {2020return;2021}2022for (int i=0; i<num_ranges; i++) {2023FileMapRegion* si = space_at(i + first_region_idx);2024HeapShared::patch_archived_heap_embedded_pointers(2025ranges[i],2026(address)(space_at(MetaspaceShared::bm)->mapped_base()) + si->oopmap_offset(),2027si->oopmap_size_in_bits());2028}2029}20302031// This internally allocates objects using vmClasses::Object_klass(), so it2032// must be called after the Object_klass is loaded2033void FileMapInfo::fixup_mapped_heap_regions() {2034assert(vmClasses::Object_klass_loaded(), "must be");2035// If any closed regions were found, call the fill routine to make them parseable.2036// Note that closed_archive_heap_ranges may be non-NULL even if no ranges were found.2037if (num_closed_archive_heap_ranges != 0) {2038assert(closed_archive_heap_ranges != NULL,2039"Null closed_archive_heap_ranges array with non-zero count");2040G1CollectedHeap::heap()->fill_archive_regions(closed_archive_heap_ranges,2041num_closed_archive_heap_ranges);2042}20432044// do the same for mapped open archive heap regions2045if (num_open_archive_heap_ranges != 0) {2046assert(open_archive_heap_ranges != NULL, "NULL open_archive_heap_ranges array with non-zero count");2047G1CollectedHeap::heap()->fill_archive_regions(open_archive_heap_ranges,2048num_open_archive_heap_ranges);20492050// Populate the open archive regions' G1BlockOffsetTableParts. That ensures2051// fast G1BlockOffsetTablePart::block_start operations for any given address2052// within the open archive regions when trying to find start of an object2053// (e.g. during card table scanning).2054//2055// This is only needed for open archive regions but not the closed archive2056// regions, because objects in closed archive regions never reference objects2057// outside the closed archive regions and they are immutable. So we never2058// need their BOT during garbage collection.2059G1CollectedHeap::heap()->populate_archive_regions_bot_part(open_archive_heap_ranges,2060num_open_archive_heap_ranges);2061}2062}20632064// dealloc the archive regions from java heap2065void FileMapInfo::dealloc_archive_heap_regions(MemRegion* regions, int num) {2066if (num > 0) {2067assert(regions != NULL, "Null archive ranges array with non-zero count");2068G1CollectedHeap::heap()->dealloc_archive_regions(regions, num);2069}2070}2071#endif // INCLUDE_CDS_JAVA_HEAP20722073bool FileMapInfo::region_crc_check(char* buf, size_t size, int expected_crc) {2074int crc = ClassLoader::crc32(0, buf, (jint)size);2075if (crc != expected_crc) {2076fail_continue("Checksum verification failed.");2077return false;2078}2079return true;2080}20812082bool FileMapInfo::verify_region_checksum(int i) {2083assert(VerifySharedSpaces, "sanity");2084size_t sz = space_at(i)->used();20852086if (sz == 0) {2087return true; // no data2088} else {2089return region_crc_check(region_addr(i), sz, space_at(i)->crc());2090}2091}20922093void FileMapInfo::unmap_regions(int regions[], int num_regions) {2094for (int r = 0; r < num_regions; r++) {2095int idx = regions[r];2096unmap_region(idx);2097}2098}20992100// Unmap a memory region in the address space.21012102void FileMapInfo::unmap_region(int i) {2103assert(!HeapShared::is_heap_region(i), "sanity");2104FileMapRegion* si = space_at(i);2105char* mapped_base = si->mapped_base();2106size_t size = si->used_aligned();21072108if (mapped_base != NULL) {2109if (size > 0 && si->mapped_from_file()) {2110log_info(cds)("Unmapping region #%d at base " INTPTR_FORMAT " (%s)", i, p2i(mapped_base),2111shared_region_name[i]);2112if (!os::unmap_memory(mapped_base, size)) {2113fatal("os::unmap_memory failed");2114}2115}2116si->set_mapped_base(NULL);2117}2118}21192120void FileMapInfo::assert_mark(bool check) {2121if (!check) {2122fail_stop("Mark mismatch while restoring from shared file.");2123}2124}21252126void FileMapInfo::metaspace_pointers_do(MetaspaceClosure* it, bool use_copy) {2127if (use_copy) {2128_saved_shared_path_table.metaspace_pointers_do(it);2129} else {2130_shared_path_table.metaspace_pointers_do(it);2131}2132}21332134FileMapInfo* FileMapInfo::_current_info = NULL;2135FileMapInfo* FileMapInfo::_dynamic_archive_info = NULL;2136bool FileMapInfo::_heap_pointers_need_patching = false;2137SharedPathTable FileMapInfo::_shared_path_table;2138SharedPathTable FileMapInfo::_saved_shared_path_table;2139bool FileMapInfo::_validating_shared_path_table = false;2140bool FileMapInfo::_memory_mapping_failed = false;2141GrowableArray<const char*>* FileMapInfo::_non_existent_class_paths = NULL;21422143// Open the shared archive file, read and validate the header2144// information (version, boot classpath, etc.). If initialization2145// fails, shared spaces are disabled and the file is closed. [See2146// fail_continue.]2147//2148// Validation of the archive is done in two steps:2149//2150// [1] validate_header() - done here.2151// [2] validate_shared_path_table - this is done later, because the table is in the RW2152// region of the archive, which is not mapped yet.2153bool FileMapInfo::initialize() {2154assert(UseSharedSpaces, "UseSharedSpaces expected.");21552156if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {2157// CDS assumes that no classes resolved in vmClasses::resolve_all()2158// are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved2159// during the JVMTI "early" stage, so we can still use CDS if2160// JvmtiExport::has_early_class_hook_env() is false.2161FileMapInfo::fail_continue("CDS is disabled because early JVMTI ClassFileLoadHook is in use.");2162return false;2163}21642165if (!open_for_read()) {2166return false;2167}2168if (!init_from_file(_fd)) {2169return false;2170}2171if (!validate_header()) {2172return false;2173}2174return true;2175}21762177char* FileMapInfo::region_addr(int idx) {2178FileMapRegion* si = space_at(idx);2179if (HeapShared::is_heap_region(idx)) {2180assert(DumpSharedSpaces, "The following doesn't work at runtime");2181return si->used() > 0 ?2182(char*)start_address_as_decoded_with_current_oop_encoding_mode(si) : NULL;2183} else {2184return si->mapped_base();2185}2186}21872188// The 2 core spaces are RW->RO2189FileMapRegion* FileMapInfo::first_core_space() const {2190return space_at(MetaspaceShared::rw);2191}21922193FileMapRegion* FileMapInfo::last_core_space() const {2194return space_at(MetaspaceShared::ro);2195}21962197void FileMapHeader::set_as_offset(char* p, size_t *offset) {2198*offset = ArchiveBuilder::current()->any_to_offset((address)p);2199}22002201int FileMapHeader::compute_crc() {2202char* start = (char*)this;2203// start computing from the field after _crc2204char* buf = (char*)&_crc + sizeof(_crc);2205size_t sz = _header_size - (buf - start);2206int crc = ClassLoader::crc32(0, buf, (jint)sz);2207return crc;2208}22092210// This function should only be called during run time with UseSharedSpaces enabled.2211bool FileMapHeader::validate() {2212if (_obj_alignment != ObjectAlignmentInBytes) {2213FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"2214" does not equal the current ObjectAlignmentInBytes of " INTX_FORMAT ".",2215_obj_alignment, ObjectAlignmentInBytes);2216return false;2217}2218if (_compact_strings != CompactStrings) {2219FileMapInfo::fail_continue("The shared archive file's CompactStrings setting (%s)"2220" does not equal the current CompactStrings setting (%s).",2221_compact_strings ? "enabled" : "disabled",2222CompactStrings ? "enabled" : "disabled");2223return false;2224}22252226// This must be done after header validation because it might change the2227// header data2228const char* prop = Arguments::get_property("java.system.class.loader");2229if (prop != NULL) {2230warning("Archived non-system classes are disabled because the "2231"java.system.class.loader property is specified (value = \"%s\"). "2232"To use archived non-system classes, this property must not be set", prop);2233_has_platform_or_app_classes = false;2234}223522362237if (!_verify_local && BytecodeVerificationLocal) {2238// we cannot load boot classes, so there's no point of using the CDS archive2239FileMapInfo::fail_continue("The shared archive file's BytecodeVerificationLocal setting (%s)"2240" does not equal the current BytecodeVerificationLocal setting (%s).",2241_verify_local ? "enabled" : "disabled",2242BytecodeVerificationLocal ? "enabled" : "disabled");2243return false;2244}22452246// For backwards compatibility, we don't check the BytecodeVerificationRemote setting2247// if the archive only contains system classes.2248if (_has_platform_or_app_classes2249&& !_verify_remote // we didn't verify the archived platform/app classes2250&& BytecodeVerificationRemote) { // but we want to verify all loaded platform/app classes2251FileMapInfo::fail_continue("The shared archive file was created with less restrictive "2252"verification setting than the current setting.");2253// Pretend that we didn't have any archived platform/app classes, so they won't be loaded2254// by SystemDictionaryShared.2255_has_platform_or_app_classes = false;2256}22572258// Java agents are allowed during run time. Therefore, the following condition is not2259// checked: (!_allow_archiving_with_java_agent && AllowArchivingWithJavaAgent)2260// Note: _allow_archiving_with_java_agent is set in the shared archive during dump time2261// while AllowArchivingWithJavaAgent is set during the current run.2262if (_allow_archiving_with_java_agent && !AllowArchivingWithJavaAgent) {2263FileMapInfo::fail_continue("The setting of the AllowArchivingWithJavaAgent is different "2264"from the setting in the shared archive.");2265return false;2266}22672268if (_allow_archiving_with_java_agent) {2269warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "2270"for testing purposes only and should not be used in a production environment");2271}22722273log_info(cds)("Archive was created with UseCompressedOops = %d, UseCompressedClassPointers = %d",2274compressed_oops(), compressed_class_pointers());2275if (compressed_oops() != UseCompressedOops || compressed_class_pointers() != UseCompressedClassPointers) {2276FileMapInfo::fail_continue("Unable to use shared archive.\nThe saved state of UseCompressedOops and UseCompressedClassPointers is "2277"different from runtime, CDS will be disabled.");2278return false;2279}22802281if (!_use_optimized_module_handling) {2282MetaspaceShared::disable_optimized_module_handling();2283log_info(cds)("optimized module handling: disabled because archive was created without optimized module handling");2284}22852286if (!_use_full_module_graph) {2287MetaspaceShared::disable_full_module_graph();2288log_info(cds)("full module graph: disabled because archive was created without full module graph");2289}22902291return true;2292}22932294bool FileMapInfo::validate_header() {2295if (!header()->validate()) {2296return false;2297}2298if (_is_static) {2299return true;2300} else {2301return DynamicArchive::validate(this);2302}2303}23042305// Check if a given address is within one of the shared regions2306bool FileMapInfo::is_in_shared_region(const void* p, int idx) {2307assert(idx == MetaspaceShared::ro ||2308idx == MetaspaceShared::rw, "invalid region index");2309char* base = region_addr(idx);2310if (p >= base && p < base + space_at(idx)->used()) {2311return true;2312}2313return false;2314}23152316// Unmap mapped regions of shared space.2317void FileMapInfo::stop_sharing_and_unmap(const char* msg) {2318MetaspaceShared::set_shared_metaspace_range(NULL, NULL, NULL);23192320FileMapInfo *map_info = FileMapInfo::current_info();2321if (map_info) {2322map_info->fail_continue("%s", msg);2323for (int i = 0; i < MetaspaceShared::num_non_heap_spaces; i++) {2324if (!HeapShared::is_heap_region(i)) {2325map_info->unmap_region(i);2326}2327}2328// Dealloc the archive heap regions only without unmapping. The regions are part2329// of the java heap. Unmapping of the heap regions are managed by GC.2330map_info->dealloc_archive_heap_regions(open_archive_heap_ranges,2331num_open_archive_heap_ranges);2332map_info->dealloc_archive_heap_regions(closed_archive_heap_ranges,2333num_closed_archive_heap_ranges);2334} else if (DumpSharedSpaces) {2335fail_stop("%s", msg);2336}2337}23382339#if INCLUDE_JVMTI2340ClassPathEntry** FileMapInfo::_classpath_entries_for_jvmti = NULL;23412342ClassPathEntry* FileMapInfo::get_classpath_entry_for_jvmti(int i, TRAPS) {2343ClassPathEntry* ent = _classpath_entries_for_jvmti[i];2344if (ent == NULL) {2345if (i == 0) {2346ent = ClassLoader::get_jrt_entry();2347assert(ent != NULL, "must be");2348} else {2349SharedClassPathEntry* scpe = shared_path(i);2350assert(scpe->is_jar(), "must be"); // other types of scpe will not produce archived classes23512352const char* path = scpe->name();2353struct stat st;2354if (os::stat(path, &st) != 0) {2355char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);2356jio_snprintf(msg, strlen(path) + 127, "error in finding JAR file %s", path);2357THROW_MSG_(vmSymbols::java_io_IOException(), msg, NULL);2358} else {2359ent = ClassLoader::create_class_path_entry(THREAD, path, &st, false, false);2360if (ent == NULL) {2361char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);2362jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);2363THROW_MSG_(vmSymbols::java_io_IOException(), msg, NULL);2364}2365}2366}23672368MutexLocker mu(THREAD, CDSClassFileStream_lock);2369if (_classpath_entries_for_jvmti[i] == NULL) {2370_classpath_entries_for_jvmti[i] = ent;2371} else {2372// Another thread has beat me to creating this entry2373delete ent;2374ent = _classpath_entries_for_jvmti[i];2375}2376}23772378return ent;2379}23802381ClassFileStream* FileMapInfo::open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS) {2382int path_index = ik->shared_classpath_index();2383assert(path_index >= 0, "should be called for shared built-in classes only");2384assert(path_index < (int)get_number_of_shared_paths(), "sanity");23852386ClassPathEntry* cpe = get_classpath_entry_for_jvmti(path_index, CHECK_NULL);2387assert(cpe != NULL, "must be");23882389Symbol* name = ik->name();2390const char* const class_name = name->as_C_string();2391const char* const file_name = ClassLoader::file_name_for_class_name(class_name,2392name->utf8_length());2393ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());2394ClassFileStream* cfs = cpe->open_stream_for_loader(THREAD, file_name, loader_data);2395assert(cfs != NULL, "must be able to read the classfile data of shared classes for built-in loaders.");2396log_debug(cds, jvmti)("classfile data for %s [%d: %s] = %d bytes", class_name, path_index,2397cfs->source(), cfs->length());2398return cfs;2399}24002401#endif240224032404