Path: blob/master/src/hotspot/share/cds/filemap.cpp
64440 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) :168_is_static(is_static), _file_open(false), _is_mapped(false), _fd(-1), _file_offset(0),169_full_path(nullptr), _base_archive_name(nullptr), _header(nullptr) {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}186187FileMapInfo::~FileMapInfo() {188if (_is_static) {189assert(_current_info == this, "must be singleton"); // not thread safe190_current_info = NULL;191} else {192assert(_dynamic_archive_info == this, "must be singleton"); // not thread safe193_dynamic_archive_info = NULL;194}195196if (_header != nullptr) {197os::free(_header);198}199200if (_file_open) {201::close(_fd);202}203}204205void FileMapInfo::populate_header(size_t core_region_alignment) {206header()->populate(this, core_region_alignment);207}208209void FileMapHeader::populate(FileMapInfo* mapinfo, size_t core_region_alignment) {210if (DynamicDumpSharedSpaces) {211_magic = CDS_DYNAMIC_ARCHIVE_MAGIC;212} else {213_magic = CDS_ARCHIVE_MAGIC;214}215_version = CURRENT_CDS_ARCHIVE_VERSION;216_core_region_alignment = core_region_alignment;217_obj_alignment = ObjectAlignmentInBytes;218_compact_strings = CompactStrings;219if (HeapShared::is_heap_object_archiving_allowed()) {220_narrow_oop_mode = CompressedOops::mode();221_narrow_oop_base = CompressedOops::base();222_narrow_oop_shift = CompressedOops::shift();223_heap_begin = CompressedOops::begin();224_heap_end = CompressedOops::end();225}226_compressed_oops = UseCompressedOops;227_compressed_class_ptrs = UseCompressedClassPointers;228_max_heap_size = MaxHeapSize;229_narrow_klass_shift = CompressedKlassPointers::shift();230_use_optimized_module_handling = MetaspaceShared::use_optimized_module_handling();231_use_full_module_graph = MetaspaceShared::use_full_module_graph();232233// The following fields are for sanity checks for whether this archive234// will function correctly with this JVM and the bootclasspath it's235// invoked with.236237// JVM version string ... changes on each build.238get_header_version(_jvm_ident);239240_app_class_paths_start_index = ClassLoaderExt::app_class_paths_start_index();241_app_module_paths_start_index = ClassLoaderExt::app_module_paths_start_index();242_num_module_paths = ClassLoader::num_module_path_entries();243_max_used_path_index = ClassLoaderExt::max_used_path_index();244245_verify_local = BytecodeVerificationLocal;246_verify_remote = BytecodeVerificationRemote;247_has_platform_or_app_classes = ClassLoaderExt::has_platform_or_app_classes();248_requested_base_address = (char*)SharedBaseAddress;249_mapped_base_address = (char*)SharedBaseAddress;250_allow_archiving_with_java_agent = AllowArchivingWithJavaAgent;251// the following 2 fields will be set in write_header for dynamic archive header252_base_archive_name_size = 0;253_base_archive_is_default = false;254255if (!DynamicDumpSharedSpaces) {256set_shared_path_table(mapinfo->_shared_path_table);257CDS_JAVA_HEAP_ONLY(_heap_obj_roots = CompressedOops::encode(HeapShared::roots());)258}259}260261void FileMapHeader::print(outputStream* st) {262ResourceMark rm;263264st->print_cr("- magic: 0x%08x", _magic);265st->print_cr("- crc: 0x%08x", _crc);266st->print_cr("- version: %d", _version);267268for (int i = 0; i < NUM_CDS_REGIONS; i++) {269FileMapRegion* si = space_at(i);270si->print(st, i);271}272st->print_cr("============ end regions ======== ");273274st->print_cr("- header_size: " SIZE_FORMAT, _header_size);275st->print_cr("- core_region_alignment: " SIZE_FORMAT, _core_region_alignment);276st->print_cr("- obj_alignment: %d", _obj_alignment);277st->print_cr("- narrow_oop_base: " INTPTR_FORMAT, p2i(_narrow_oop_base));278st->print_cr("- narrow_oop_base: " INTPTR_FORMAT, p2i(_narrow_oop_base));279st->print_cr("- narrow_oop_shift %d", _narrow_oop_shift);280st->print_cr("- compact_strings: %d", _compact_strings);281st->print_cr("- max_heap_size: " UINTX_FORMAT, _max_heap_size);282st->print_cr("- narrow_oop_mode: %d", _narrow_oop_mode);283st->print_cr("- narrow_klass_shift: %d", _narrow_klass_shift);284st->print_cr("- compressed_oops: %d", _compressed_oops);285st->print_cr("- compressed_class_ptrs: %d", _compressed_class_ptrs);286st->print_cr("- cloned_vtables_offset: " SIZE_FORMAT_HEX, _cloned_vtables_offset);287st->print_cr("- serialized_data_offset: " SIZE_FORMAT_HEX, _serialized_data_offset);288st->print_cr("- heap_end: " INTPTR_FORMAT, p2i(_heap_end));289st->print_cr("- base_archive_is_default: %d", _base_archive_is_default);290st->print_cr("- jvm_ident: %s", _jvm_ident);291st->print_cr("- base_archive_name_size: " SIZE_FORMAT, _base_archive_name_size);292st->print_cr("- shared_path_table_offset: " SIZE_FORMAT_HEX, _shared_path_table_offset);293st->print_cr("- shared_path_table_size: %d", _shared_path_table_size);294st->print_cr("- app_class_paths_start_index: %d", _app_class_paths_start_index);295st->print_cr("- app_module_paths_start_index: %d", _app_module_paths_start_index);296st->print_cr("- num_module_paths: %d", _num_module_paths);297st->print_cr("- max_used_path_index: %d", _max_used_path_index);298st->print_cr("- verify_local: %d", _verify_local);299st->print_cr("- verify_remote: %d", _verify_remote);300st->print_cr("- has_platform_or_app_classes: %d", _has_platform_or_app_classes);301st->print_cr("- requested_base_address: " INTPTR_FORMAT, p2i(_requested_base_address));302st->print_cr("- mapped_base_address: " INTPTR_FORMAT, p2i(_mapped_base_address));303st->print_cr("- allow_archiving_with_java_agent:%d", _allow_archiving_with_java_agent);304st->print_cr("- use_optimized_module_handling: %d", _use_optimized_module_handling);305st->print_cr("- use_full_module_graph %d", _use_full_module_graph);306st->print_cr("- ptrmap_size_in_bits: " SIZE_FORMAT, _ptrmap_size_in_bits);307}308309void SharedClassPathEntry::init_as_non_existent(const char* path, TRAPS) {310_type = non_existent_entry;311set_name(path, CHECK);312}313314void SharedClassPathEntry::init(bool is_modules_image,315bool is_module_path,316ClassPathEntry* cpe, TRAPS) {317Arguments::assert_is_dumping_archive();318_timestamp = 0;319_filesize = 0;320_from_class_path_attr = false;321322struct stat st;323if (os::stat(cpe->name(), &st) == 0) {324if ((st.st_mode & S_IFMT) == S_IFDIR) {325_type = dir_entry;326} else {327// The timestamp of the modules_image is not checked at runtime.328if (is_modules_image) {329_type = modules_image_entry;330} else {331_type = jar_entry;332_timestamp = st.st_mtime;333_from_class_path_attr = cpe->from_class_path_attr();334}335_filesize = st.st_size;336_is_module_path = is_module_path;337}338} else {339// The file/dir must exist, or it would not have been added340// into ClassLoader::classpath_entry().341//342// If we can't access a jar file in the boot path, then we can't343// make assumptions about where classes get loaded from.344FileMapInfo::fail_stop("Unable to open file %s.", cpe->name());345}346347// No need to save the name of the module file, as it will be computed at run time348// to allow relocation of the JDK directory.349const char* name = is_modules_image ? "" : cpe->name();350set_name(name, CHECK);351}352353void SharedClassPathEntry::set_name(const char* name, TRAPS) {354size_t len = strlen(name) + 1;355_name = MetadataFactory::new_array<char>(ClassLoaderData::the_null_class_loader_data(), (int)len, CHECK);356strcpy(_name->data(), name);357}358359void SharedClassPathEntry::copy_from(SharedClassPathEntry* ent, ClassLoaderData* loader_data, TRAPS) {360_type = ent->_type;361_is_module_path = ent->_is_module_path;362_timestamp = ent->_timestamp;363_filesize = ent->_filesize;364_from_class_path_attr = ent->_from_class_path_attr;365set_name(ent->name(), CHECK);366367if (ent->is_jar() && !ent->is_signed() && ent->manifest() != NULL) {368Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,369ent->manifest_size(),370CHECK);371char* p = (char*)(buf->data());372memcpy(p, ent->manifest(), ent->manifest_size());373set_manifest(buf);374}375}376377const char* SharedClassPathEntry::name() const {378if (UseSharedSpaces && is_modules_image()) {379// In order to validate the runtime modules image file size against the archived380// size information, we need to obtain the runtime modules image path. The recorded381// dump time modules image path in the archive may be different from the runtime path382// if the JDK image has beed moved after generating the archive.383return ClassLoader::get_jrt_entry()->name();384} else {385return _name->data();386}387}388389bool SharedClassPathEntry::validate(bool is_class_path) const {390assert(UseSharedSpaces, "runtime only");391392struct stat st;393const char* name = this->name();394395bool ok = true;396log_info(class, path)("checking shared classpath entry: %s", name);397if (os::stat(name, &st) != 0 && is_class_path) {398// If the archived module path entry does not exist at runtime, it is not fatal399// (no need to invalid the shared archive) because the shared runtime visibility check400// filters out any archived module classes that do not have a matching runtime401// module path location.402FileMapInfo::fail_continue("Required classpath entry does not exist: %s", name);403ok = false;404} else if (is_dir()) {405if (!os::dir_is_empty(name)) {406FileMapInfo::fail_continue("directory is not empty: %s", name);407ok = false;408}409} else if ((has_timestamp() && _timestamp != st.st_mtime) ||410_filesize != st.st_size) {411ok = false;412if (PrintSharedArchiveAndExit) {413FileMapInfo::fail_continue(_timestamp != st.st_mtime ?414"Timestamp mismatch" :415"File size mismatch");416} else {417FileMapInfo::fail_continue("A jar file is not the one used while building"418" the shared archive file: %s", name);419}420}421422if (PrintSharedArchiveAndExit && !ok) {423// If PrintSharedArchiveAndExit is enabled, don't report failure to the424// caller. Please see above comments for more details.425ok = true;426MetaspaceShared::set_archive_loading_failed();427}428return ok;429}430431bool SharedClassPathEntry::check_non_existent() const {432assert(_type == non_existent_entry, "must be");433log_info(class, path)("should be non-existent: %s", name());434struct stat st;435if (os::stat(name(), &st) != 0) {436log_info(class, path)("ok");437return true; // file doesn't exist438} else {439return false;440}441}442443444void SharedClassPathEntry::metaspace_pointers_do(MetaspaceClosure* it) {445it->push(&_name);446it->push(&_manifest);447}448449void SharedPathTable::metaspace_pointers_do(MetaspaceClosure* it) {450it->push(&_table);451for (int i=0; i<_size; i++) {452path_at(i)->metaspace_pointers_do(it);453}454}455456void SharedPathTable::dumptime_init(ClassLoaderData* loader_data, TRAPS) {457size_t entry_size = sizeof(SharedClassPathEntry);458int num_entries = 0;459num_entries += ClassLoader::num_boot_classpath_entries();460num_entries += ClassLoader::num_app_classpath_entries();461num_entries += ClassLoader::num_module_path_entries();462num_entries += FileMapInfo::num_non_existent_class_paths();463size_t bytes = entry_size * num_entries;464465_table = MetadataFactory::new_array<u8>(loader_data, (int)bytes, CHECK);466_size = num_entries;467}468469// Make a copy of the _shared_path_table for use during dynamic CDS dump.470// It is needed because some Java code continues to execute after dynamic dump has finished.471// However, during dynamic dump, we have modified FileMapInfo::_shared_path_table so472// FileMapInfo::shared_path(i) returns incorrect information in ClassLoader::record_result().473void FileMapInfo::copy_shared_path_table(ClassLoaderData* loader_data, TRAPS) {474size_t entry_size = sizeof(SharedClassPathEntry);475size_t bytes = entry_size * _shared_path_table.size();476477Array<u8>* array = MetadataFactory::new_array<u8>(loader_data, (int)bytes, CHECK);478_saved_shared_path_table = SharedPathTable(array, _shared_path_table.size());479480for (int i = 0; i < _shared_path_table.size(); i++) {481_saved_shared_path_table.path_at(i)->copy_from(shared_path(i), loader_data, CHECK);482}483}484485void FileMapInfo::allocate_shared_path_table(TRAPS) {486Arguments::assert_is_dumping_archive();487488ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();489ClassPathEntry* jrt = ClassLoader::get_jrt_entry();490491assert(jrt != NULL,492"No modular java runtime image present when allocating the CDS classpath entry table");493494_shared_path_table.dumptime_init(loader_data, CHECK);495496// 1. boot class path497int i = 0;498i = add_shared_classpaths(i, "boot", jrt, CHECK);499i = add_shared_classpaths(i, "app", ClassLoader::app_classpath_entries(), CHECK);500i = add_shared_classpaths(i, "module", ClassLoader::module_path_entries(), CHECK);501502for (int x = 0; x < num_non_existent_class_paths(); x++, i++) {503const char* path = _non_existent_class_paths->at(x);504shared_path(i)->init_as_non_existent(path, CHECK);505}506507assert(i == _shared_path_table.size(), "number of shared path entry mismatch");508509copy_shared_path_table(loader_data, CHECK);510}511512int FileMapInfo::add_shared_classpaths(int i, const char* which, ClassPathEntry *cpe, TRAPS) {513while (cpe != NULL) {514bool is_jrt = (cpe == ClassLoader::get_jrt_entry());515bool is_module_path = i >= ClassLoaderExt::app_module_paths_start_index();516const char* type = (is_jrt ? "jrt" : (cpe->is_jar_file() ? "jar" : "dir"));517log_info(class, path)("add %s shared path (%s) %s", which, type, cpe->name());518SharedClassPathEntry* ent = shared_path(i);519ent->init(is_jrt, is_module_path, cpe, CHECK_0);520if (cpe->is_jar_file()) {521update_jar_manifest(cpe, ent, CHECK_0);522}523if (is_jrt) {524cpe = ClassLoader::get_next_boot_classpath_entry(cpe);525} else {526cpe = cpe->next();527}528i++;529}530531return i;532}533534void FileMapInfo::check_nonempty_dir_in_shared_path_table() {535Arguments::assert_is_dumping_archive();536537bool has_nonempty_dir = false;538539int last = _shared_path_table.size() - 1;540if (last > ClassLoaderExt::max_used_path_index()) {541// no need to check any path beyond max_used_path_index542last = ClassLoaderExt::max_used_path_index();543}544545for (int i = 0; i <= last; i++) {546SharedClassPathEntry *e = shared_path(i);547if (e->is_dir()) {548const char* path = e->name();549if (!os::dir_is_empty(path)) {550log_error(cds)("Error: non-empty directory '%s'", path);551has_nonempty_dir = true;552}553}554}555556if (has_nonempty_dir) {557ClassLoader::exit_with_path_failure("Cannot have non-empty directory in paths", NULL);558}559}560561void FileMapInfo::record_non_existent_class_path_entry(const char* path) {562Arguments::assert_is_dumping_archive();563log_info(class, path)("non-existent Class-Path entry %s", path);564if (_non_existent_class_paths == NULL) {565_non_existent_class_paths = new (ResourceObj::C_HEAP, mtClass)GrowableArray<const char*>(10, mtClass);566}567_non_existent_class_paths->append(os::strdup(path));568}569570int FileMapInfo::num_non_existent_class_paths() {571Arguments::assert_is_dumping_archive();572if (_non_existent_class_paths != NULL) {573return _non_existent_class_paths->length();574} else {575return 0;576}577}578579int FileMapInfo::get_module_shared_path_index(Symbol* location) {580if (location->starts_with("jrt:", 4) && get_number_of_shared_paths() > 0) {581assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");582return 0;583}584585if (ClassLoaderExt::app_module_paths_start_index() >= get_number_of_shared_paths()) {586// The archive(s) were created without --module-path option587return -1;588}589590if (!location->starts_with("file:", 5)) {591return -1;592}593594// skip_uri_protocol was also called during dump time -- see ClassLoaderExt::process_module_table()595ResourceMark rm;596const char* file = ClassLoader::skip_uri_protocol(location->as_C_string());597for (int i = ClassLoaderExt::app_module_paths_start_index(); i < get_number_of_shared_paths(); i++) {598SharedClassPathEntry* ent = shared_path(i);599assert(ent->in_named_module(), "must be");600bool cond = strcmp(file, ent->name()) == 0;601log_debug(class, path)("get_module_shared_path_index (%d) %s : %s = %s", i,602location->as_C_string(), ent->name(), cond ? "same" : "different");603if (cond) {604return i;605}606}607608return -1;609}610611class ManifestStream: public ResourceObj {612private:613u1* _buffer_start; // Buffer bottom614u1* _buffer_end; // Buffer top (one past last element)615u1* _current; // Current buffer position616617public:618// Constructor619ManifestStream(u1* buffer, int length) : _buffer_start(buffer),620_current(buffer) {621_buffer_end = buffer + length;622}623624static bool is_attr(u1* attr, const char* name) {625return strncmp((const char*)attr, name, strlen(name)) == 0;626}627628static char* copy_attr(u1* value, size_t len) {629char* buf = NEW_RESOURCE_ARRAY(char, len + 1);630strncpy(buf, (char*)value, len);631buf[len] = 0;632return buf;633}634635// The return value indicates if the JAR is signed or not636bool check_is_signed() {637u1* attr = _current;638bool isSigned = false;639while (_current < _buffer_end) {640if (*_current == '\n') {641*_current = '\0';642u1* value = (u1*)strchr((char*)attr, ':');643if (value != NULL) {644assert(*(value+1) == ' ', "Unrecognized format" );645if (strstr((char*)attr, "-Digest") != NULL) {646isSigned = true;647break;648}649}650*_current = '\n'; // restore651attr = _current + 1;652}653_current ++;654}655return isSigned;656}657};658659void FileMapInfo::update_jar_manifest(ClassPathEntry *cpe, SharedClassPathEntry* ent, TRAPS) {660ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();661ResourceMark rm(THREAD);662jint manifest_size;663664assert(cpe->is_jar_file() && ent->is_jar(), "the shared class path entry is not a JAR file");665char* manifest = ClassLoaderExt::read_manifest(THREAD, cpe, &manifest_size);666if (manifest != NULL) {667ManifestStream* stream = new ManifestStream((u1*)manifest,668manifest_size);669if (stream->check_is_signed()) {670ent->set_is_signed();671} else {672// Copy the manifest into the shared archive673manifest = ClassLoaderExt::read_raw_manifest(THREAD, cpe, &manifest_size);674Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,675manifest_size,676CHECK);677char* p = (char*)(buf->data());678memcpy(p, manifest, manifest_size);679ent->set_manifest(buf);680}681}682}683684char* FileMapInfo::skip_first_path_entry(const char* path) {685size_t path_sep_len = strlen(os::path_separator());686char* p = strstr((char*)path, os::path_separator());687if (p != NULL) {688debug_only( {689size_t image_name_len = strlen(MODULES_IMAGE_NAME);690assert(strncmp(p - image_name_len, MODULES_IMAGE_NAME, image_name_len) == 0,691"first entry must be the modules image");692} );693p += path_sep_len;694} else {695debug_only( {696assert(ClassLoader::string_ends_with(path, MODULES_IMAGE_NAME),697"first entry must be the modules image");698} );699}700return p;701}702703int FileMapInfo::num_paths(const char* path) {704if (path == NULL) {705return 0;706}707int npaths = 1;708char* p = (char*)path;709while (p != NULL) {710char* prev = p;711p = strstr((char*)p, os::path_separator());712if (p != NULL) {713p++;714// don't count empty path715if ((p - prev) > 1) {716npaths++;717}718}719}720return npaths;721}722723GrowableArray<const char*>* FileMapInfo::create_path_array(const char* paths) {724GrowableArray<const char*>* path_array = new GrowableArray<const char*>(10);725726ClasspathStream cp_stream(paths);727while (cp_stream.has_next()) {728const char* path = cp_stream.get_next();729struct stat st;730if (os::stat(path, &st) == 0) {731path_array->append(path);732}733}734return path_array;735}736737bool FileMapInfo::classpath_failure(const char* msg, const char* name) {738ClassLoader::trace_class_path(msg, name);739if (PrintSharedArchiveAndExit) {740MetaspaceShared::set_archive_loading_failed();741}742return false;743}744745bool FileMapInfo::check_paths(int shared_path_start_idx, int num_paths, GrowableArray<const char*>* rp_array) {746int i = 0;747int j = shared_path_start_idx;748bool mismatch = false;749while (i < num_paths && !mismatch) {750while (shared_path(j)->from_class_path_attr()) {751// shared_path(j) was expanded from the JAR file attribute "Class-Path:"752// during dump time. It's not included in the -classpath VM argument.753j++;754}755if (!os::same_files(shared_path(j)->name(), rp_array->at(i))) {756mismatch = true;757}758i++;759j++;760}761return mismatch;762}763764bool FileMapInfo::validate_boot_class_paths() {765//766// - Archive contains boot classes only - relaxed boot path check:767// Extra path elements appended to the boot path at runtime are allowed.768//769// - Archive contains application or platform classes - strict boot path check:770// Validate the entire runtime boot path, which must be compatible771// with the dump time boot path. Appending boot path at runtime is not772// allowed.773//774775// The first entry in boot path is the modules_image (guaranteed by776// ClassLoader::setup_boot_search_path()). Skip the first entry. The777// path of the runtime modules_image may be different from the dump778// time path (e.g. the JDK image is copied to a different location779// after generating the shared archive), which is acceptable. For most780// common cases, the dump time boot path might contain modules_image only.781char* runtime_boot_path = Arguments::get_sysclasspath();782char* rp = skip_first_path_entry(runtime_boot_path);783assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");784int dp_len = header()->app_class_paths_start_index() - 1; // ignore the first path to the module image785bool mismatch = false;786787bool relaxed_check = !header()->has_platform_or_app_classes();788if (dp_len == 0 && rp == NULL) {789return true; // ok, both runtime and dump time boot paths have modules_images only790} else if (dp_len == 0 && rp != NULL) {791if (relaxed_check) {792return true; // ok, relaxed check, runtime has extra boot append path entries793} else {794mismatch = true;795}796} else if (dp_len > 0 && rp != NULL) {797int num;798ResourceMark rm;799GrowableArray<const char*>* rp_array = create_path_array(rp);800int rp_len = rp_array->length();801if (rp_len >= dp_len) {802if (relaxed_check) {803// only check the leading entries in the runtime boot path, up to804// the length of the dump time boot path805num = dp_len;806} else {807// check the full runtime boot path, must match with dump time808num = rp_len;809}810mismatch = check_paths(1, num, rp_array);811} else {812// create_path_array() ignores non-existing paths. Although the dump time and runtime boot classpath lengths813// are the same initially, after the call to create_path_array(), the runtime boot classpath length could become814// shorter. We consider boot classpath mismatch in this case.815mismatch = true;816}817}818819if (mismatch) {820// The paths are different821return classpath_failure("[BOOT classpath mismatch, actual =", runtime_boot_path);822}823return true;824}825826bool FileMapInfo::validate_app_class_paths(int shared_app_paths_len) {827const char *appcp = Arguments::get_appclasspath();828assert(appcp != NULL, "NULL app classpath");829int rp_len = num_paths(appcp);830bool mismatch = false;831if (rp_len < shared_app_paths_len) {832return classpath_failure("Run time APP classpath is shorter than the one at dump time: ", appcp);833}834if (shared_app_paths_len != 0 && rp_len != 0) {835// Prefix is OK: E.g., dump with -cp foo.jar, but run with -cp foo.jar:bar.jar.836ResourceMark rm;837GrowableArray<const char*>* rp_array = create_path_array(appcp);838if (rp_array->length() == 0) {839// None of the jar file specified in the runtime -cp exists.840return classpath_failure("None of the jar file specified in the runtime -cp exists: -Djava.class.path=", appcp);841}842if (rp_array->length() < shared_app_paths_len) {843// create_path_array() ignores non-existing paths. Although the dump time and runtime app classpath lengths844// are the same initially, after the call to create_path_array(), the runtime app classpath length could become845// shorter. We consider app classpath mismatch in this case.846return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp);847}848849// Handling of non-existent entries in the classpath: we eliminate all the non-existent850// entries from both the dump time classpath (ClassLoader::update_class_path_entry_list)851// and the runtime classpath (FileMapInfo::create_path_array), and check the remaining852// entries. E.g.:853//854// dump : -cp a.jar:NE1:NE2:b.jar -> a.jar:b.jar -> recorded in archive.855// run 1: -cp NE3:a.jar:NE4:b.jar -> a.jar:b.jar -> matched856// run 2: -cp x.jar:NE4:b.jar -> x.jar:b.jar -> mismatched857858int j = header()->app_class_paths_start_index();859mismatch = check_paths(j, shared_app_paths_len, rp_array);860if (mismatch) {861return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp);862}863}864return true;865}866867void FileMapInfo::log_paths(const char* msg, int start_idx, int end_idx) {868LogTarget(Info, class, path) lt;869if (lt.is_enabled()) {870LogStream ls(lt);871ls.print("%s", msg);872const char* prefix = "";873for (int i = start_idx; i < end_idx; i++) {874ls.print("%s%s", prefix, shared_path(i)->name());875prefix = os::path_separator();876}877ls.cr();878}879}880881bool FileMapInfo::validate_shared_path_table() {882assert(UseSharedSpaces, "runtime only");883884_validating_shared_path_table = true;885886// Load the shared path table info from the archive header887_shared_path_table = header()->shared_path_table();888if (DynamicDumpSharedSpaces) {889// Only support dynamic dumping with the usage of the default CDS archive890// or a simple base archive.891// If the base layer archive contains additional path component besides892// the runtime image and the -cp, dynamic dumping is disabled.893//894// When dynamic archiving is enabled, the _shared_path_table is overwritten895// to include the application path and stored in the top layer archive.896assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");897if (header()->app_class_paths_start_index() > 1) {898DynamicDumpSharedSpaces = false;899warning(900"Dynamic archiving is disabled because base layer archive has appended boot classpath");901}902if (header()->num_module_paths() > 0) {903DynamicDumpSharedSpaces = false;904warning(905"Dynamic archiving is disabled because base layer archive has module path");906}907}908909log_paths("Expecting BOOT path=", 0, header()->app_class_paths_start_index());910log_paths("Expecting -Djava.class.path=", header()->app_class_paths_start_index(), header()->app_module_paths_start_index());911912int module_paths_start_index = header()->app_module_paths_start_index();913int shared_app_paths_len = 0;914915// validate the path entries up to the _max_used_path_index916for (int i=0; i < header()->max_used_path_index() + 1; i++) {917if (i < module_paths_start_index) {918if (shared_path(i)->validate()) {919// Only count the app class paths not from the "Class-path" attribute of a jar manifest.920if (!shared_path(i)->from_class_path_attr() && i >= header()->app_class_paths_start_index()) {921shared_app_paths_len++;922}923log_info(class, path)("ok");924} else {925if (_dynamic_archive_info != NULL && _dynamic_archive_info->_is_static) {926assert(!UseSharedSpaces, "UseSharedSpaces should be disabled");927}928return false;929}930} else if (i >= module_paths_start_index) {931if (shared_path(i)->validate(false /* not a class path entry */)) {932log_info(class, path)("ok");933} else {934if (_dynamic_archive_info != NULL && _dynamic_archive_info->_is_static) {935assert(!UseSharedSpaces, "UseSharedSpaces should be disabled");936}937return false;938}939}940}941942if (header()->max_used_path_index() == 0) {943// default archive only contains the module image in the bootclasspath944assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");945} else {946if (!validate_boot_class_paths() || !validate_app_class_paths(shared_app_paths_len)) {947fail_continue("shared class paths mismatch (hint: enable -Xlog:class+path=info to diagnose the failure)");948return false;949}950}951952validate_non_existent_class_paths();953954_validating_shared_path_table = false;955956#if INCLUDE_JVMTI957if (_classpath_entries_for_jvmti != NULL) {958os::free(_classpath_entries_for_jvmti);959}960size_t sz = sizeof(ClassPathEntry*) * get_number_of_shared_paths();961_classpath_entries_for_jvmti = (ClassPathEntry**)os::malloc(sz, mtClass);962memset((void*)_classpath_entries_for_jvmti, 0, sz);963#endif964965return true;966}967968void FileMapInfo::validate_non_existent_class_paths() {969// All of the recorded non-existent paths came from the Class-Path: attribute from the JAR970// files on the app classpath. If any of these are found to exist during runtime,971// it will change how classes are loading for the app loader. For safety, disable972// loading of archived platform/app classes (currently there's no way to disable just the973// app classes).974975assert(UseSharedSpaces, "runtime only");976for (int i = header()->app_module_paths_start_index() + header()->num_module_paths();977i < get_number_of_shared_paths();978i++) {979SharedClassPathEntry* ent = shared_path(i);980if (!ent->check_non_existent()) {981warning("Archived non-system classes are disabled because the "982"file %s exists", ent->name());983header()->set_has_platform_or_app_classes(false);984}985}986}987988bool FileMapInfo::check_archive(const char* archive_name, bool is_static) {989int fd = os::open(archive_name, O_RDONLY | O_BINARY, 0);990if (fd < 0) {991// do not vm_exit_during_initialization here because Arguments::init_shared_archive_paths()992// requires a shared archive name. The open_for_read() function will log a message regarding993// failure in opening a shared archive.994return false;995}996997size_t sz = is_static ? sizeof(FileMapHeader) : sizeof(DynamicArchiveHeader);998void* header = os::malloc(sz, mtInternal);999memset(header, 0, sz);1000size_t n = os::read(fd, header, (unsigned int)sz);1001if (n != sz) {1002os::free(header);1003os::close(fd);1004vm_exit_during_initialization("Unable to read header from shared archive", archive_name);1005return false;1006}1007if (is_static) {1008FileMapHeader* static_header = (FileMapHeader*)header;1009if (static_header->magic() != CDS_ARCHIVE_MAGIC) {1010os::free(header);1011os::close(fd);1012vm_exit_during_initialization("Not a base shared archive", archive_name);1013return false;1014}1015} else {1016DynamicArchiveHeader* dynamic_header = (DynamicArchiveHeader*)header;1017if (dynamic_header->magic() != CDS_DYNAMIC_ARCHIVE_MAGIC) {1018os::free(header);1019os::close(fd);1020vm_exit_during_initialization("Not a top shared archive", archive_name);1021return false;1022}1023}1024os::free(header);1025os::close(fd);1026return true;1027}10281029bool FileMapInfo::get_base_archive_name_from_header(const char* archive_name,1030int* size, char** base_archive_name) {1031int fd = os::open(archive_name, O_RDONLY | O_BINARY, 0);1032if (fd < 0) {1033*size = 0;1034return false;1035}10361037// read the header as a dynamic archive header1038size_t sz = sizeof(DynamicArchiveHeader);1039DynamicArchiveHeader* dynamic_header = (DynamicArchiveHeader*)os::malloc(sz, mtInternal);1040size_t n = os::read(fd, dynamic_header, (unsigned int)sz);1041if (n != sz) {1042fail_continue("Unable to read the file header.");1043os::free(dynamic_header);1044os::close(fd);1045return false;1046}1047if (dynamic_header->magic() != CDS_DYNAMIC_ARCHIVE_MAGIC) {1048// Not a dynamic header, no need to proceed further.1049*size = 0;1050os::free(dynamic_header);1051os::close(fd);1052return false;1053}1054if (dynamic_header->base_archive_is_default()) {1055*base_archive_name = Arguments::get_default_shared_archive_path();1056} else {1057// read the base archive name1058size_t name_size = dynamic_header->base_archive_name_size();1059if (name_size == 0) {1060os::free(dynamic_header);1061os::close(fd);1062return false;1063}1064*base_archive_name = NEW_C_HEAP_ARRAY(char, name_size, mtInternal);1065n = os::read(fd, *base_archive_name, (unsigned int)name_size);1066if (n != name_size) {1067fail_continue("Unable to read the base archive name from the header.");1068FREE_C_HEAP_ARRAY(char, *base_archive_name);1069*base_archive_name = NULL;1070os::free(dynamic_header);1071os::close(fd);1072return false;1073}1074}10751076os::free(dynamic_header);1077os::close(fd);1078return true;1079}10801081// Read the FileMapInfo information from the file.10821083bool FileMapInfo::init_from_file(int fd) {1084size_t sz = is_static() ? sizeof(FileMapHeader) : sizeof(DynamicArchiveHeader);1085size_t n = os::read(fd, header(), (unsigned int)sz);1086if (n != sz) {1087fail_continue("Unable to read the file header.");1088return false;1089}10901091if (!Arguments::has_jimage()) {1092FileMapInfo::fail_continue("The shared archive file cannot be used with an exploded module build.");1093return false;1094}10951096unsigned int expected_magic = is_static() ? CDS_ARCHIVE_MAGIC : CDS_DYNAMIC_ARCHIVE_MAGIC;1097if (header()->magic() != expected_magic) {1098log_info(cds)("_magic expected: 0x%08x", expected_magic);1099log_info(cds)(" actual: 0x%08x", header()->magic());1100FileMapInfo::fail_continue("The shared archive file has a bad magic number.");1101return false;1102}11031104if (header()->version() != CURRENT_CDS_ARCHIVE_VERSION) {1105log_info(cds)("_version expected: %d", CURRENT_CDS_ARCHIVE_VERSION);1106log_info(cds)(" actual: %d", header()->version());1107fail_continue("The shared archive file has the wrong version.");1108return false;1109}11101111if (header()->header_size() != sz) {1112log_info(cds)("_header_size expected: " SIZE_FORMAT, sz);1113log_info(cds)(" actual: " SIZE_FORMAT, header()->header_size());1114FileMapInfo::fail_continue("The shared archive file has an incorrect header size.");1115return false;1116}11171118const char* actual_ident = header()->jvm_ident();11191120if (actual_ident[JVM_IDENT_MAX-1] != 0) {1121FileMapInfo::fail_continue("JVM version identifier is corrupted.");1122return false;1123}11241125char expected_ident[JVM_IDENT_MAX];1126get_header_version(expected_ident);1127if (strncmp(actual_ident, expected_ident, JVM_IDENT_MAX-1) != 0) {1128log_info(cds)("_jvm_ident expected: %s", expected_ident);1129log_info(cds)(" actual: %s", actual_ident);1130FileMapInfo::fail_continue("The shared archive file was created by a different"1131" version or build of HotSpot");1132return false;1133}11341135if (VerifySharedSpaces) {1136int expected_crc = header()->compute_crc();1137if (expected_crc != header()->crc()) {1138log_info(cds)("_crc expected: %d", expected_crc);1139log_info(cds)(" actual: %d", header()->crc());1140FileMapInfo::fail_continue("Header checksum verification failed.");1141return false;1142}1143}11441145_file_offset = n + header()->base_archive_name_size(); // accounts for the size of _base_archive_name11461147if (is_static()) {1148// just checking the last region is sufficient since the archive is written1149// in sequential order1150size_t len = lseek(fd, 0, SEEK_END);1151FileMapRegion* si = space_at(MetaspaceShared::last_valid_region);1152// The last space might be empty1153if (si->file_offset() > len || len - si->file_offset() < si->used()) {1154fail_continue("The shared archive file has been truncated.");1155return false;1156}1157}11581159return true;1160}11611162void FileMapInfo::seek_to_position(size_t pos) {1163if (lseek(_fd, (long)pos, SEEK_SET) < 0) {1164fail_stop("Unable to seek to position " SIZE_FORMAT, pos);1165}1166}11671168// Read the FileMapInfo information from the file.1169bool FileMapInfo::open_for_read() {1170if (_file_open) {1171return true;1172}1173if (is_static()) {1174_full_path = Arguments::GetSharedArchivePath();1175} else {1176_full_path = Arguments::GetSharedDynamicArchivePath();1177}1178log_info(cds)("trying to map %s", _full_path);1179int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0);1180if (fd < 0) {1181if (errno == ENOENT) {1182fail_continue("Specified shared archive not found (%s).", _full_path);1183} else {1184fail_continue("Failed to open shared archive file (%s).",1185os::strerror(errno));1186}1187return false;1188} else {1189log_info(cds)("Opened archive %s.", _full_path);1190}11911192_fd = fd;1193_file_open = true;1194return true;1195}11961197// Write the FileMapInfo information to the file.11981199void FileMapInfo::open_for_write(const char* path) {1200if (path == NULL) {1201_full_path = Arguments::GetSharedArchivePath();1202} else {1203_full_path = path;1204}1205LogMessage(cds) msg;1206if (msg.is_info()) {1207msg.info("Dumping shared data to file: ");1208msg.info(" %s", _full_path);1209}12101211#ifdef _WINDOWS // On Windows, need WRITE permission to remove the file.1212chmod(_full_path, _S_IREAD | _S_IWRITE);1213#endif12141215// Use remove() to delete the existing file because, on Unix, this will1216// allow processes that have it open continued access to the file.1217remove(_full_path);1218int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);1219if (fd < 0) {1220fail_stop("Unable to create shared archive file %s: (%s).", _full_path,1221os::strerror(errno));1222}1223_fd = fd;1224_file_open = true;12251226// Seek past the header. We will write the header after all regions are written1227// and their CRCs computed.1228size_t header_bytes = header()->header_size();1229if (header()->magic() == CDS_DYNAMIC_ARCHIVE_MAGIC) {1230header_bytes += strlen(Arguments::GetSharedArchivePath()) + 1;1231}12321233header_bytes = align_up(header_bytes, MetaspaceShared::core_region_alignment());1234_file_offset = header_bytes;1235seek_to_position(_file_offset);1236}123712381239// Write the header to the file, seek to the next allocation boundary.12401241void FileMapInfo::write_header() {1242_file_offset = 0;1243seek_to_position(_file_offset);1244assert(is_file_position_aligned(), "must be");1245write_bytes(header(), header()->header_size());12461247if (header()->magic() == CDS_DYNAMIC_ARCHIVE_MAGIC) {1248char* base_archive_name = (char*)Arguments::GetSharedArchivePath();1249if (base_archive_name != NULL) {1250write_bytes(base_archive_name, header()->base_archive_name_size());1251}1252}1253}12541255size_t FileMapRegion::used_aligned() const {1256return align_up(used(), MetaspaceShared::core_region_alignment());1257}12581259void FileMapRegion::init(int region_index, size_t mapping_offset, size_t size, bool read_only,1260bool allow_exec, int crc) {1261_is_heap_region = HeapShared::is_heap_region(region_index);1262_is_bitmap_region = (region_index == MetaspaceShared::bm);1263_mapping_offset = mapping_offset;1264_used = size;1265_read_only = read_only;1266_allow_exec = allow_exec;1267_crc = crc;1268_mapped_from_file = false;1269_mapped_base = NULL;1270}127112721273static const char* region_name(int region_index) {1274static const char* names[] = {1275"rw", "ro", "bm", "ca0", "ca1", "oa0", "oa1"1276};1277const int num_regions = sizeof(names)/sizeof(names[0]);1278assert(0 <= region_index && region_index < num_regions, "sanity");12791280return names[region_index];1281}12821283void FileMapRegion::print(outputStream* st, int region_index) {1284st->print_cr("============ region ============= %d \"%s\"", region_index, region_name(region_index));1285st->print_cr("- crc: 0x%08x", _crc);1286st->print_cr("- read_only: %d", _read_only);1287st->print_cr("- allow_exec: %d", _allow_exec);1288st->print_cr("- is_heap_region: %d", _is_heap_region);1289st->print_cr("- is_bitmap_region: %d", _is_bitmap_region);1290st->print_cr("- mapped_from_file: %d", _mapped_from_file);1291st->print_cr("- file_offset: " SIZE_FORMAT_HEX, _file_offset);1292st->print_cr("- mapping_offset: " SIZE_FORMAT_HEX, _mapping_offset);1293st->print_cr("- used: " SIZE_FORMAT, _used);1294st->print_cr("- oopmap_offset: " SIZE_FORMAT_HEX, _oopmap_offset);1295st->print_cr("- oopmap_size_in_bits: " SIZE_FORMAT, _oopmap_size_in_bits);1296st->print_cr("- mapped_base: " INTPTR_FORMAT, p2i(_mapped_base));1297}12981299void FileMapInfo::write_region(int region, char* base, size_t size,1300bool read_only, bool allow_exec) {1301Arguments::assert_is_dumping_archive();13021303FileMapRegion* si = space_at(region);1304char* requested_base;1305size_t mapping_offset = 0;13061307if (region == MetaspaceShared::bm) {1308requested_base = NULL; // always NULL for bm region1309} else if (size == 0) {1310// This is an unused region (e.g., a heap region when !INCLUDE_CDS_JAVA_HEAP)1311requested_base = NULL;1312} else if (HeapShared::is_heap_region(region)) {1313assert(!DynamicDumpSharedSpaces, "must be");1314requested_base = base;1315mapping_offset = (size_t)CompressedOops::encode_not_null(cast_to_oop(base));1316assert(mapping_offset == (size_t)(uint32_t)mapping_offset, "must be 32-bit only");1317} else {1318char* requested_SharedBaseAddress = (char*)MetaspaceShared::requested_base_address();1319requested_base = ArchiveBuilder::current()->to_requested(base);1320assert(requested_base >= requested_SharedBaseAddress, "must be");1321mapping_offset = requested_base - requested_SharedBaseAddress;1322}13231324si->set_file_offset(_file_offset);1325int crc = ClassLoader::crc32(0, base, (jint)size);1326if (size > 0) {1327log_info(cds)("Shared file region (%-3s) %d: " SIZE_FORMAT_W(8)1328" bytes, addr " INTPTR_FORMAT " file offset " SIZE_FORMAT_HEX_W(08)1329" crc 0x%08x",1330region_name(region), region, size, p2i(requested_base), _file_offset, crc);1331}1332si->init(region, mapping_offset, size, read_only, allow_exec, crc);13331334if (base != NULL) {1335write_bytes_aligned(base, size);1336}1337}13381339size_t FileMapInfo::set_oopmaps_offset(GrowableArray<ArchiveHeapOopmapInfo>* oopmaps, size_t curr_size) {1340for (int i = 0; i < oopmaps->length(); i++) {1341oopmaps->at(i)._offset = curr_size;1342curr_size += oopmaps->at(i)._oopmap_size_in_bytes;1343}1344return curr_size;1345}13461347size_t FileMapInfo::write_oopmaps(GrowableArray<ArchiveHeapOopmapInfo>* oopmaps, size_t curr_offset, char* buffer) {1348for (int i = 0; i < oopmaps->length(); i++) {1349memcpy(buffer + curr_offset, oopmaps->at(i)._oopmap, oopmaps->at(i)._oopmap_size_in_bytes);1350curr_offset += oopmaps->at(i)._oopmap_size_in_bytes;1351}1352return curr_offset;1353}13541355char* FileMapInfo::write_bitmap_region(const CHeapBitMap* ptrmap,1356GrowableArray<ArchiveHeapOopmapInfo>* closed_oopmaps,1357GrowableArray<ArchiveHeapOopmapInfo>* open_oopmaps,1358size_t &size_in_bytes) {1359size_t size_in_bits = ptrmap->size();1360size_in_bytes = ptrmap->size_in_bytes();13611362if (closed_oopmaps != NULL && open_oopmaps != NULL) {1363size_in_bytes = set_oopmaps_offset(closed_oopmaps, size_in_bytes);1364size_in_bytes = set_oopmaps_offset(open_oopmaps, size_in_bytes);1365}13661367char* buffer = NEW_C_HEAP_ARRAY(char, size_in_bytes, mtClassShared);1368ptrmap->write_to((BitMap::bm_word_t*)buffer, ptrmap->size_in_bytes());1369header()->set_ptrmap_size_in_bits(size_in_bits);13701371if (closed_oopmaps != NULL && open_oopmaps != NULL) {1372size_t curr_offset = write_oopmaps(closed_oopmaps, ptrmap->size_in_bytes(), buffer);1373write_oopmaps(open_oopmaps, curr_offset, buffer);1374}13751376write_region(MetaspaceShared::bm, (char*)buffer, size_in_bytes, /*read_only=*/true, /*allow_exec=*/false);1377return buffer;1378}13791380// Write out the given archive heap memory regions. GC code combines multiple1381// consecutive archive GC regions into one MemRegion whenever possible and1382// produces the 'heap_mem' array.1383//1384// If the archive heap memory size is smaller than a single dump time GC region1385// size, there is only one MemRegion in the array.1386//1387// If the archive heap memory size is bigger than one dump time GC region size,1388// the 'heap_mem' array may contain more than one consolidated MemRegions. When1389// the first/bottom archive GC region is a partial GC region (with the empty1390// portion at the higher address within the region), one MemRegion is used for1391// the bottom partial archive GC region. The rest of the consecutive archive1392// GC regions are combined into another MemRegion.1393//1394// Here's the mapping from (archive heap GC regions) -> (GrowableArray<MemRegion> *regions).1395// + We have 1 or more archive heap regions: ah0, ah1, ah2 ..... ahn1396// + We have 1 or 2 consolidated heap memory regions: r0 and r11397//1398// If there's a single archive GC region (ah0), then r0 == ah0, and r1 is empty.1399// Otherwise:1400//1401// "X" represented space that's occupied by heap objects.1402// "_" represented unused spaced in the heap region.1403//1404//1405// |ah0 | ah1 | ah2| ...... | ahn|1406// |XXXXXX|__ |XXXXX|XXXX|XXXXXXXX|XXXX|1407// |<-r0->| |<- r1 ----------------->|1408// ^^^1409// |1410// +-- gap1411size_t FileMapInfo::write_archive_heap_regions(GrowableArray<MemRegion> *heap_mem,1412GrowableArray<ArchiveHeapOopmapInfo> *oopmaps,1413int first_region_id, int max_num_regions) {1414assert(max_num_regions <= 2, "Only support maximum 2 memory regions");14151416int arr_len = heap_mem == NULL ? 0 : heap_mem->length();1417if(arr_len > max_num_regions) {1418fail_stop("Unable to write archive heap memory regions: "1419"number of memory regions exceeds maximum due to fragmentation. "1420"Please increase java heap size "1421"(current MaxHeapSize is " SIZE_FORMAT ", InitialHeapSize is " SIZE_FORMAT ").",1422MaxHeapSize, InitialHeapSize);1423}14241425size_t total_size = 0;1426for (int i = 0; i < max_num_regions; i++) {1427char* start = NULL;1428size_t size = 0;1429if (i < arr_len) {1430start = (char*)heap_mem->at(i).start();1431size = heap_mem->at(i).byte_size();1432total_size += size;1433}14341435int region_idx = i + first_region_id;1436write_region(region_idx, start, size, false, false);1437if (size > 0) {1438space_at(region_idx)->init_oopmap(oopmaps->at(i)._offset,1439oopmaps->at(i)._oopmap_size_in_bits);1440}1441}1442return total_size;1443}14441445// Dump bytes to file -- at the current file position.14461447void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) {1448assert(_file_open, "must be");1449size_t n = os::write(_fd, buffer, (unsigned int)nbytes);1450if (n != nbytes) {1451// If the shared archive is corrupted, close it and remove it.1452close();1453remove(_full_path);1454fail_stop("Unable to write to shared archive file.");1455}1456_file_offset += nbytes;1457}14581459bool FileMapInfo::is_file_position_aligned() const {1460return _file_offset == align_up(_file_offset,1461MetaspaceShared::core_region_alignment());1462}14631464// Align file position to an allocation unit boundary.14651466void FileMapInfo::align_file_position() {1467assert(_file_open, "must be");1468size_t new_file_offset = align_up(_file_offset,1469MetaspaceShared::core_region_alignment());1470if (new_file_offset != _file_offset) {1471_file_offset = new_file_offset;1472// Seek one byte back from the target and write a byte to insure1473// that the written file is the correct length.1474_file_offset -= 1;1475seek_to_position(_file_offset);1476char zero = 0;1477write_bytes(&zero, 1);1478}1479}148014811482// Dump bytes to file -- at the current file position.14831484void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) {1485align_file_position();1486write_bytes(buffer, nbytes);1487align_file_position();1488}14891490// Close the shared archive file. This does NOT unmap mapped regions.14911492void FileMapInfo::close() {1493if (_file_open) {1494if (::close(_fd) < 0) {1495fail_stop("Unable to close the shared archive file.");1496}1497_file_open = false;1498_fd = -1;1499}1500}150115021503// JVM/TI RedefineClasses() support:1504// Remap the shared readonly space to shared readwrite, private.1505bool FileMapInfo::remap_shared_readonly_as_readwrite() {1506int idx = MetaspaceShared::ro;1507FileMapRegion* si = space_at(idx);1508if (!si->read_only()) {1509// the space is already readwrite so we are done1510return true;1511}1512size_t size = si->used_aligned();1513if (!open_for_read()) {1514return false;1515}1516char *addr = region_addr(idx);1517char *base = os::remap_memory(_fd, _full_path, si->file_offset(),1518addr, size, false /* !read_only */,1519si->allow_exec());1520close();1521// These have to be errors because the shared region is now unmapped.1522if (base == NULL) {1523log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);1524vm_exit(1);1525}1526if (base != addr) {1527log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);1528vm_exit(1);1529}1530si->set_read_only(false);1531return true;1532}15331534// Memory map a region in the address space.1535static const char* shared_region_name[] = { "ReadWrite", "ReadOnly", "Bitmap",1536"String1", "String2", "OpenArchive1", "OpenArchive2" };15371538MapArchiveResult FileMapInfo::map_regions(int regions[], int num_regions, char* mapped_base_address, ReservedSpace rs) {1539DEBUG_ONLY(FileMapRegion* last_region = NULL);1540intx addr_delta = mapped_base_address - header()->requested_base_address();15411542// Make sure we don't attempt to use header()->mapped_base_address() unless1543// it's been successfully mapped.1544DEBUG_ONLY(header()->set_mapped_base_address((char*)(uintptr_t)0xdeadbeef);)15451546for (int r = 0; r < num_regions; r++) {1547int idx = regions[r];1548MapArchiveResult result = map_region(idx, addr_delta, mapped_base_address, rs);1549if (result != MAP_ARCHIVE_SUCCESS) {1550return result;1551}1552FileMapRegion* si = space_at(idx);1553DEBUG_ONLY(if (last_region != NULL) {1554// Ensure that the OS won't be able to allocate new memory spaces between any mapped1555// regions, or else it would mess up the simple comparision in MetaspaceObj::is_shared().1556assert(si->mapped_base() == last_region->mapped_end(), "must have no gaps");1557}1558last_region = si;)1559log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)", is_static() ? "static " : "dynamic",1560idx, p2i(si->mapped_base()), p2i(si->mapped_end()),1561shared_region_name[idx]);15621563}15641565header()->set_mapped_base_address(header()->requested_base_address() + addr_delta);1566if (addr_delta != 0 && !relocate_pointers_in_core_regions(addr_delta)) {1567return MAP_ARCHIVE_OTHER_FAILURE;1568}15691570return MAP_ARCHIVE_SUCCESS;1571}15721573bool FileMapInfo::read_region(int i, char* base, size_t size) {1574assert(MetaspaceShared::use_windows_memory_mapping(), "used by windows only");1575FileMapRegion* si = space_at(i);1576log_info(cds)("Commit %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)%s",1577is_static() ? "static " : "dynamic", i, p2i(base), p2i(base + size),1578shared_region_name[i], si->allow_exec() ? " exec" : "");1579if (!os::commit_memory(base, size, si->allow_exec())) {1580log_error(cds)("Failed to commit %s region #%d (%s)", is_static() ? "static " : "dynamic",1581i, shared_region_name[i]);1582return false;1583}1584if (lseek(_fd, (long)si->file_offset(), SEEK_SET) != (int)si->file_offset() ||1585read_bytes(base, size) != size) {1586return false;1587}1588return true;1589}15901591MapArchiveResult FileMapInfo::map_region(int i, intx addr_delta, char* mapped_base_address, ReservedSpace rs) {1592assert(!HeapShared::is_heap_region(i), "sanity");1593FileMapRegion* si = space_at(i);1594size_t size = si->used_aligned();1595char *requested_addr = mapped_base_address + si->mapping_offset();1596assert(si->mapped_base() == NULL, "must be not mapped yet");1597assert(requested_addr != NULL, "must be specified");15981599si->set_mapped_from_file(false);16001601if (MetaspaceShared::use_windows_memory_mapping()) {1602// Windows cannot remap read-only shared memory to read-write when required for1603// RedefineClasses, which is also used by JFR. Always map windows regions as RW.1604si->set_read_only(false);1605} else if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space() ||1606Arguments::has_jfr_option()) {1607// If a tool agent is in use (debugging enabled), or JFR, we must map the address space RW1608si->set_read_only(false);1609} else if (addr_delta != 0) {1610si->set_read_only(false); // Need to patch the pointers1611}16121613if (MetaspaceShared::use_windows_memory_mapping() && rs.is_reserved()) {1614// This is the second time we try to map the archive(s). We have already created a ReservedSpace1615// that covers all the FileMapRegions to ensure all regions can be mapped. However, Windows1616// can't mmap into a ReservedSpace, so we just os::read() the data. We're going to patch all the1617// regions anyway, so there's no benefit for mmap anyway.1618if (!read_region(i, requested_addr, size)) {1619log_info(cds)("Failed to read %s shared space into reserved space at " INTPTR_FORMAT,1620shared_region_name[i], p2i(requested_addr));1621return MAP_ARCHIVE_OTHER_FAILURE; // oom or I/O error.1622}1623} else {1624// Note that this may either be a "fresh" mapping into unreserved address1625// space (Windows, first mapping attempt), or a mapping into pre-reserved1626// space (Posix). See also comment in MetaspaceShared::map_archives().1627char* base = os::map_memory(_fd, _full_path, si->file_offset(),1628requested_addr, size, si->read_only(),1629si->allow_exec(), mtClassShared);1630if (base != requested_addr) {1631log_info(cds)("Unable to map %s shared space at " INTPTR_FORMAT,1632shared_region_name[i], p2i(requested_addr));1633_memory_mapping_failed = true;1634return MAP_ARCHIVE_MMAP_FAILURE;1635}1636si->set_mapped_from_file(true);1637}1638si->set_mapped_base(requested_addr);16391640if (VerifySharedSpaces && !verify_region_checksum(i)) {1641return MAP_ARCHIVE_OTHER_FAILURE;1642}16431644return MAP_ARCHIVE_SUCCESS;1645}16461647// The return value is the location of the archive relocation bitmap.1648char* FileMapInfo::map_bitmap_region() {1649FileMapRegion* si = space_at(MetaspaceShared::bm);1650if (si->mapped_base() != NULL) {1651return si->mapped_base();1652}1653bool read_only = true, allow_exec = false;1654char* requested_addr = NULL; // allow OS to pick any location1655char* bitmap_base = os::map_memory(_fd, _full_path, si->file_offset(),1656requested_addr, si->used_aligned(), read_only, allow_exec, mtClassShared);1657if (bitmap_base == NULL) {1658log_info(cds)("failed to map relocation bitmap");1659return NULL;1660}16611662if (VerifySharedSpaces && !region_crc_check(bitmap_base, si->used(), si->crc())) {1663log_error(cds)("relocation bitmap CRC error");1664if (!os::unmap_memory(bitmap_base, si->used_aligned())) {1665fatal("os::unmap_memory of relocation bitmap failed");1666}1667return NULL;1668}16691670si->set_mapped_base(bitmap_base);1671si->set_mapped_from_file(true);1672log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)",1673is_static() ? "static " : "dynamic",1674MetaspaceShared::bm, p2i(si->mapped_base()), p2i(si->mapped_end()),1675shared_region_name[MetaspaceShared::bm]);1676return bitmap_base;1677}16781679// This is called when we cannot map the archive at the requested[ base address (usually 0x800000000).1680// We relocate all pointers in the 2 core regions (ro, rw).1681bool FileMapInfo::relocate_pointers_in_core_regions(intx addr_delta) {1682log_debug(cds, reloc)("runtime archive relocation start");1683char* bitmap_base = map_bitmap_region();16841685if (bitmap_base == NULL) {1686return false; // OOM, or CRC check failure1687} else {1688size_t ptrmap_size_in_bits = header()->ptrmap_size_in_bits();1689log_debug(cds, reloc)("mapped relocation bitmap @ " INTPTR_FORMAT " (" SIZE_FORMAT " bits)",1690p2i(bitmap_base), ptrmap_size_in_bits);16911692BitMapView ptrmap((BitMap::bm_word_t*)bitmap_base, ptrmap_size_in_bits);16931694// Patch all pointers in the the mapped region that are marked by ptrmap.1695address patch_base = (address)mapped_base();1696address patch_end = (address)mapped_end();16971698// the current value of the pointers to be patched must be within this1699// range (i.e., must be between the requesed base address, and the of the current archive).1700// Note: top archive may point to objects in the base archive, but not the other way around.1701address valid_old_base = (address)header()->requested_base_address();1702address valid_old_end = valid_old_base + mapping_end_offset();17031704// after patching, the pointers must point inside this range1705// (the requested location of the archive, as mapped at runtime).1706address valid_new_base = (address)header()->mapped_base_address();1707address valid_new_end = (address)mapped_end();17081709SharedDataRelocator patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end,1710valid_new_base, valid_new_end, addr_delta);1711ptrmap.iterate(&patcher);17121713// The MetaspaceShared::bm region will be unmapped in MetaspaceShared::initialize_shared_spaces().17141715log_debug(cds, reloc)("runtime archive relocation done");1716return true;1717}1718}17191720size_t FileMapInfo::read_bytes(void* buffer, size_t count) {1721assert(_file_open, "Archive file is not open");1722size_t n = os::read(_fd, buffer, (unsigned int)count);1723if (n != count) {1724// Close the file if there's a problem reading it.1725close();1726return 0;1727}1728_file_offset += count;1729return count;1730}17311732address FileMapInfo::decode_start_address(FileMapRegion* spc, bool with_current_oop_encoding_mode) {1733size_t offset = spc->mapping_offset();1734narrowOop n = CompressedOops::narrow_oop_cast(offset);1735if (with_current_oop_encoding_mode) {1736return cast_from_oop<address>(CompressedOops::decode_raw_not_null(n));1737} else {1738return cast_from_oop<address>(HeapShared::decode_from_archive(n));1739}1740}17411742static MemRegion *closed_archive_heap_ranges = NULL;1743static MemRegion *open_archive_heap_ranges = NULL;1744static int num_closed_archive_heap_ranges = 0;1745static int num_open_archive_heap_ranges = 0;17461747#if INCLUDE_CDS_JAVA_HEAP1748bool FileMapInfo::has_heap_regions() {1749return (space_at(MetaspaceShared::first_closed_archive_heap_region)->used() > 0);1750}17511752// Returns the address range of the archived heap regions computed using the1753// current oop encoding mode. This range may be different than the one seen at1754// dump time due to encoding mode differences. The result is used in determining1755// if/how these regions should be relocated at run time.1756MemRegion FileMapInfo::get_heap_regions_range_with_current_oop_encoding_mode() {1757address start = (address) max_uintx;1758address end = NULL;17591760for (int i = MetaspaceShared::first_closed_archive_heap_region;1761i <= MetaspaceShared::last_valid_region;1762i++) {1763FileMapRegion* si = space_at(i);1764size_t size = si->used();1765if (size > 0) {1766address s = start_address_as_decoded_with_current_oop_encoding_mode(si);1767address e = s + size;1768if (start > s) {1769start = s;1770}1771if (end < e) {1772end = e;1773}1774}1775}1776assert(end != NULL, "must have at least one used heap region");1777return MemRegion((HeapWord*)start, (HeapWord*)end);1778}17791780//1781// Map the closed and open archive heap objects to the runtime java heap.1782//1783// The shared objects are mapped at (or close to ) the java heap top in1784// closed archive regions. The mapped objects contain no out-going1785// references to any other java heap regions. GC does not write into the1786// mapped closed archive heap region.1787//1788// The open archive heap objects are mapped below the shared objects in1789// the runtime java heap. The mapped open archive heap data only contains1790// references to the shared objects and open archive objects initially.1791// During runtime execution, out-going references to any other java heap1792// regions may be added. GC may mark and update references in the mapped1793// open archive objects.1794void FileMapInfo::map_heap_regions_impl() {1795if (!HeapShared::is_heap_object_archiving_allowed()) {1796log_info(cds)("CDS heap data is being ignored. UseG1GC, "1797"UseCompressedOops and UseCompressedClassPointers are required.");1798return;1799}18001801if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {1802ShouldNotReachHere(); // CDS should have been disabled.1803// The archived objects are mapped at JVM start-up, but we don't know if1804// j.l.String or j.l.Class might be replaced by the ClassFileLoadHook,1805// which would make the archived String or mirror objects invalid. Let's be safe and not1806// use the archived objects. These 2 classes are loaded during the JVMTI "early" stage.1807//1808// If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects1809// in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK1810// because we won't install an archived object subgraph if the klass of any of the1811// referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph().1812}18131814log_info(cds)("CDS archive was created with max heap size = " SIZE_FORMAT "M, and the following configuration:",1815max_heap_size()/M);1816log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",1817p2i(narrow_klass_base()), narrow_klass_shift());1818log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",1819narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift());1820log_info(cds)(" heap range = [" PTR_FORMAT " - " PTR_FORMAT "]",1821p2i(header()->heap_begin()), p2i(header()->heap_end()));18221823log_info(cds)("The current max heap size = " SIZE_FORMAT "M, HeapRegion::GrainBytes = " SIZE_FORMAT,1824MaxHeapSize/M, HeapRegion::GrainBytes);1825log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",1826p2i(CompressedKlassPointers::base()), CompressedKlassPointers::shift());1827log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",1828CompressedOops::mode(), p2i(CompressedOops::base()), CompressedOops::shift());1829log_info(cds)(" heap range = [" PTR_FORMAT " - " PTR_FORMAT "]",1830p2i(CompressedOops::begin()), p2i(CompressedOops::end()));18311832if (narrow_klass_base() != CompressedKlassPointers::base() ||1833narrow_klass_shift() != CompressedKlassPointers::shift()) {1834log_info(cds)("CDS heap data cannot be used because the archive was created with an incompatible narrow klass encoding mode.");1835return;1836}18371838if (narrow_oop_mode() != CompressedOops::mode() ||1839narrow_oop_base() != CompressedOops::base() ||1840narrow_oop_shift() != CompressedOops::shift()) {1841log_info(cds)("CDS heap data needs to be relocated because the archive was created with an incompatible oop encoding mode.");1842_heap_pointers_need_patching = true;1843} else {1844MemRegion range = get_heap_regions_range_with_current_oop_encoding_mode();1845if (!CompressedOops::is_in(range)) {1846log_info(cds)("CDS heap data needs to be relocated because");1847log_info(cds)("the desired range " PTR_FORMAT " - " PTR_FORMAT, p2i(range.start()), p2i(range.end()));1848log_info(cds)("is outside of the heap " PTR_FORMAT " - " PTR_FORMAT, p2i(CompressedOops::begin()), p2i(CompressedOops::end()));1849_heap_pointers_need_patching = true;1850} else if (header()->heap_end() != CompressedOops::end()) {1851log_info(cds)("CDS heap data needs to be relocated to the end of the runtime heap to reduce fragmentation");1852_heap_pointers_need_patching = true;1853}1854}18551856ptrdiff_t delta = 0;1857if (_heap_pointers_need_patching) {1858// dumptime heap end ------------v1859// [ |archived heap regions| ] runtime heap end ------v1860// [ |archived heap regions| ]1861// |<-----delta-------------------->|1862//1863// At dump time, the archived heap regions were near the top of the heap.1864// At run time, they may not be inside the heap, so we move them so1865// that they are now near the top of the runtime time. This can be done by1866// the simple math of adding the delta as shown above.1867address dumptime_heap_end = header()->heap_end();1868address runtime_heap_end = CompressedOops::end();1869delta = runtime_heap_end - dumptime_heap_end;1870}18711872log_info(cds)("CDS heap data relocation delta = " INTX_FORMAT " bytes", delta);1873HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());18741875FileMapRegion* si = space_at(MetaspaceShared::first_closed_archive_heap_region);1876address relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si);1877if (!is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes)) {1878// Align the bottom of the closed archive heap regions at G1 region boundary.1879// This will avoid the situation where the highest open region and the lowest1880// closed region sharing the same G1 region. Otherwise we will fail to map the1881// open regions.1882size_t align = size_t(relocated_closed_heap_region_bottom) % HeapRegion::GrainBytes;1883delta -= align;1884log_info(cds)("CDS heap data needs to be relocated lower by a further " SIZE_FORMAT1885" bytes to " INTX_FORMAT " to be aligned with HeapRegion::GrainBytes",1886align, delta);1887HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());1888_heap_pointers_need_patching = true;1889relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si);1890}1891assert(is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes),1892"must be");18931894// Map the closed_archive_heap regions, GC does not write into the regions.1895if (map_heap_data(&closed_archive_heap_ranges,1896MetaspaceShared::first_closed_archive_heap_region,1897MetaspaceShared::max_closed_archive_heap_region,1898&num_closed_archive_heap_ranges)) {1899HeapShared::set_closed_archive_heap_region_mapped();19001901// Now, map open_archive heap regions, GC can write into the regions.1902if (map_heap_data(&open_archive_heap_ranges,1903MetaspaceShared::first_open_archive_heap_region,1904MetaspaceShared::max_open_archive_heap_region,1905&num_open_archive_heap_ranges,1906true /* open */)) {1907HeapShared::set_open_archive_heap_region_mapped();1908HeapShared::set_roots(header()->heap_obj_roots());1909}1910}1911}19121913void FileMapInfo::map_heap_regions() {1914if (has_heap_regions()) {1915map_heap_regions_impl();1916}19171918if (!HeapShared::closed_archive_heap_region_mapped()) {1919assert(closed_archive_heap_ranges == NULL &&1920num_closed_archive_heap_ranges == 0, "sanity");1921}19221923if (!HeapShared::open_archive_heap_region_mapped()) {1924assert(open_archive_heap_ranges == NULL && num_open_archive_heap_ranges == 0, "sanity");1925MetaspaceShared::disable_full_module_graph();1926}1927}19281929bool FileMapInfo::map_heap_data(MemRegion **heap_mem, int first,1930int max, int* num, bool is_open_archive) {1931MemRegion* regions = MemRegion::create_array(max, mtInternal);19321933struct Cleanup {1934MemRegion* _regions;1935uint _length;1936bool _aborted;1937Cleanup(MemRegion* regions, uint length) : _regions(regions), _length(length), _aborted(true) { }1938~Cleanup() { if (_aborted) { MemRegion::destroy_array(_regions, _length); } }1939} cleanup(regions, max);19401941FileMapRegion* si;1942int region_num = 0;19431944for (int i = first;1945i < first + max; i++) {1946si = space_at(i);1947size_t size = si->used();1948if (size > 0) {1949HeapWord* start = (HeapWord*)start_address_as_decoded_from_archive(si);1950regions[region_num] = MemRegion(start, size / HeapWordSize);1951region_num ++;1952log_info(cds)("Trying to map heap data: region[%d] at " INTPTR_FORMAT ", size = " SIZE_FORMAT_W(8) " bytes",1953i, p2i(start), size);1954}1955}19561957if (region_num == 0) {1958return false; // no archived java heap data1959}19601961// Check that ranges are within the java heap1962if (!G1CollectedHeap::heap()->check_archive_addresses(regions, region_num)) {1963log_info(cds)("UseSharedSpaces: Unable to allocate region, range is not within java heap.");1964return false;1965}19661967// allocate from java heap1968if (!G1CollectedHeap::heap()->alloc_archive_regions(1969regions, region_num, is_open_archive)) {1970log_info(cds)("UseSharedSpaces: Unable to allocate region, java heap range is already in use.");1971return false;1972}19731974// Map the archived heap data. No need to call MemTracker::record_virtual_memory_type()1975// for mapped regions as they are part of the reserved java heap, which is1976// already recorded.1977for (int i = 0; i < region_num; i++) {1978si = space_at(first + i);1979char* addr = (char*)regions[i].start();1980char* base = os::map_memory(_fd, _full_path, si->file_offset(),1981addr, regions[i].byte_size(), si->read_only(),1982si->allow_exec());1983if (base == NULL || base != addr) {1984// dealloc the regions from java heap1985dealloc_archive_heap_regions(regions, region_num);1986log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap. "1987INTPTR_FORMAT ", size = " SIZE_FORMAT " bytes",1988p2i(addr), regions[i].byte_size());1989return false;1990}19911992if (VerifySharedSpaces && !region_crc_check(addr, regions[i].byte_size(), si->crc())) {1993// dealloc the regions from java heap1994dealloc_archive_heap_regions(regions, region_num);1995log_info(cds)("UseSharedSpaces: mapped heap regions are corrupt");1996return false;1997}1998}19992000cleanup._aborted = false;2001// the shared heap data is mapped successfully2002*heap_mem = regions;2003*num = region_num;2004return true;2005}20062007void FileMapInfo::patch_archived_heap_embedded_pointers() {2008if (!_heap_pointers_need_patching) {2009return;2010}20112012log_info(cds)("patching heap embedded pointers");2013patch_archived_heap_embedded_pointers(closed_archive_heap_ranges,2014num_closed_archive_heap_ranges,2015MetaspaceShared::first_closed_archive_heap_region);20162017patch_archived_heap_embedded_pointers(open_archive_heap_ranges,2018num_open_archive_heap_ranges,2019MetaspaceShared::first_open_archive_heap_region);2020}20212022void FileMapInfo::patch_archived_heap_embedded_pointers(MemRegion* ranges, int num_ranges,2023int first_region_idx) {2024char* bitmap_base = map_bitmap_region();2025if (bitmap_base == NULL) {2026return;2027}2028for (int i=0; i<num_ranges; i++) {2029FileMapRegion* si = space_at(i + first_region_idx);2030HeapShared::patch_archived_heap_embedded_pointers(2031ranges[i],2032(address)(space_at(MetaspaceShared::bm)->mapped_base()) + si->oopmap_offset(),2033si->oopmap_size_in_bits());2034}2035}20362037// This internally allocates objects using vmClasses::Object_klass(), so it2038// must be called after the Object_klass is loaded2039void FileMapInfo::fixup_mapped_heap_regions() {2040assert(vmClasses::Object_klass_loaded(), "must be");2041// If any closed regions were found, call the fill routine to make them parseable.2042// Note that closed_archive_heap_ranges may be non-NULL even if no ranges were found.2043if (num_closed_archive_heap_ranges != 0) {2044assert(closed_archive_heap_ranges != NULL,2045"Null closed_archive_heap_ranges array with non-zero count");2046G1CollectedHeap::heap()->fill_archive_regions(closed_archive_heap_ranges,2047num_closed_archive_heap_ranges);2048}20492050// do the same for mapped open archive heap regions2051if (num_open_archive_heap_ranges != 0) {2052assert(open_archive_heap_ranges != NULL, "NULL open_archive_heap_ranges array with non-zero count");2053G1CollectedHeap::heap()->fill_archive_regions(open_archive_heap_ranges,2054num_open_archive_heap_ranges);20552056// Populate the open archive regions' G1BlockOffsetTableParts. That ensures2057// fast G1BlockOffsetTablePart::block_start operations for any given address2058// within the open archive regions when trying to find start of an object2059// (e.g. during card table scanning).2060//2061// This is only needed for open archive regions but not the closed archive2062// regions, because objects in closed archive regions never reference objects2063// outside the closed archive regions and they are immutable. So we never2064// need their BOT during garbage collection.2065G1CollectedHeap::heap()->populate_archive_regions_bot_part(open_archive_heap_ranges,2066num_open_archive_heap_ranges);2067}2068}20692070// dealloc the archive regions from java heap2071void FileMapInfo::dealloc_archive_heap_regions(MemRegion* regions, int num) {2072if (num > 0) {2073assert(regions != NULL, "Null archive ranges array with non-zero count");2074G1CollectedHeap::heap()->dealloc_archive_regions(regions, num);2075}2076}2077#endif // INCLUDE_CDS_JAVA_HEAP20782079bool FileMapInfo::region_crc_check(char* buf, size_t size, int expected_crc) {2080int crc = ClassLoader::crc32(0, buf, (jint)size);2081if (crc != expected_crc) {2082fail_continue("Checksum verification failed.");2083return false;2084}2085return true;2086}20872088bool FileMapInfo::verify_region_checksum(int i) {2089assert(VerifySharedSpaces, "sanity");2090size_t sz = space_at(i)->used();20912092if (sz == 0) {2093return true; // no data2094} else {2095return region_crc_check(region_addr(i), sz, space_at(i)->crc());2096}2097}20982099void FileMapInfo::unmap_regions(int regions[], int num_regions) {2100for (int r = 0; r < num_regions; r++) {2101int idx = regions[r];2102unmap_region(idx);2103}2104}21052106// Unmap a memory region in the address space.21072108void FileMapInfo::unmap_region(int i) {2109assert(!HeapShared::is_heap_region(i), "sanity");2110FileMapRegion* si = space_at(i);2111char* mapped_base = si->mapped_base();2112size_t size = si->used_aligned();21132114if (mapped_base != NULL) {2115if (size > 0 && si->mapped_from_file()) {2116log_info(cds)("Unmapping region #%d at base " INTPTR_FORMAT " (%s)", i, p2i(mapped_base),2117shared_region_name[i]);2118if (!os::unmap_memory(mapped_base, size)) {2119fatal("os::unmap_memory failed");2120}2121}2122si->set_mapped_base(NULL);2123}2124}21252126void FileMapInfo::assert_mark(bool check) {2127if (!check) {2128fail_stop("Mark mismatch while restoring from shared file.");2129}2130}21312132void FileMapInfo::metaspace_pointers_do(MetaspaceClosure* it, bool use_copy) {2133if (use_copy) {2134_saved_shared_path_table.metaspace_pointers_do(it);2135} else {2136_shared_path_table.metaspace_pointers_do(it);2137}2138}21392140FileMapInfo* FileMapInfo::_current_info = NULL;2141FileMapInfo* FileMapInfo::_dynamic_archive_info = NULL;2142bool FileMapInfo::_heap_pointers_need_patching = false;2143SharedPathTable FileMapInfo::_shared_path_table;2144SharedPathTable FileMapInfo::_saved_shared_path_table;2145bool FileMapInfo::_validating_shared_path_table = false;2146bool FileMapInfo::_memory_mapping_failed = false;2147GrowableArray<const char*>* FileMapInfo::_non_existent_class_paths = NULL;21482149// Open the shared archive file, read and validate the header2150// information (version, boot classpath, etc.). If initialization2151// fails, shared spaces are disabled and the file is closed. [See2152// fail_continue.]2153//2154// Validation of the archive is done in two steps:2155//2156// [1] validate_header() - done here.2157// [2] validate_shared_path_table - this is done later, because the table is in the RW2158// region of the archive, which is not mapped yet.2159bool FileMapInfo::initialize() {2160assert(UseSharedSpaces, "UseSharedSpaces expected.");21612162if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {2163// CDS assumes that no classes resolved in vmClasses::resolve_all()2164// are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved2165// during the JVMTI "early" stage, so we can still use CDS if2166// JvmtiExport::has_early_class_hook_env() is false.2167FileMapInfo::fail_continue("CDS is disabled because early JVMTI ClassFileLoadHook is in use.");2168return false;2169}21702171if (!open_for_read()) {2172return false;2173}2174if (!init_from_file(_fd)) {2175return false;2176}2177if (!validate_header()) {2178return false;2179}2180return true;2181}21822183char* FileMapInfo::region_addr(int idx) {2184FileMapRegion* si = space_at(idx);2185if (HeapShared::is_heap_region(idx)) {2186assert(DumpSharedSpaces, "The following doesn't work at runtime");2187return si->used() > 0 ?2188(char*)start_address_as_decoded_with_current_oop_encoding_mode(si) : NULL;2189} else {2190return si->mapped_base();2191}2192}21932194// The 2 core spaces are RW->RO2195FileMapRegion* FileMapInfo::first_core_space() const {2196return space_at(MetaspaceShared::rw);2197}21982199FileMapRegion* FileMapInfo::last_core_space() const {2200return space_at(MetaspaceShared::ro);2201}22022203void FileMapHeader::set_as_offset(char* p, size_t *offset) {2204*offset = ArchiveBuilder::current()->any_to_offset((address)p);2205}22062207int FileMapHeader::compute_crc() {2208char* start = (char*)this;2209// start computing from the field after _crc2210char* buf = (char*)&_crc + sizeof(_crc);2211size_t sz = _header_size - (buf - start);2212int crc = ClassLoader::crc32(0, buf, (jint)sz);2213return crc;2214}22152216// This function should only be called during run time with UseSharedSpaces enabled.2217bool FileMapHeader::validate() {2218if (_obj_alignment != ObjectAlignmentInBytes) {2219FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"2220" does not equal the current ObjectAlignmentInBytes of " INTX_FORMAT ".",2221_obj_alignment, ObjectAlignmentInBytes);2222return false;2223}2224if (_compact_strings != CompactStrings) {2225FileMapInfo::fail_continue("The shared archive file's CompactStrings setting (%s)"2226" does not equal the current CompactStrings setting (%s).",2227_compact_strings ? "enabled" : "disabled",2228CompactStrings ? "enabled" : "disabled");2229return false;2230}22312232// This must be done after header validation because it might change the2233// header data2234const char* prop = Arguments::get_property("java.system.class.loader");2235if (prop != NULL) {2236warning("Archived non-system classes are disabled because the "2237"java.system.class.loader property is specified (value = \"%s\"). "2238"To use archived non-system classes, this property must not be set", prop);2239_has_platform_or_app_classes = false;2240}224122422243if (!_verify_local && BytecodeVerificationLocal) {2244// we cannot load boot classes, so there's no point of using the CDS archive2245FileMapInfo::fail_continue("The shared archive file's BytecodeVerificationLocal setting (%s)"2246" does not equal the current BytecodeVerificationLocal setting (%s).",2247_verify_local ? "enabled" : "disabled",2248BytecodeVerificationLocal ? "enabled" : "disabled");2249return false;2250}22512252// For backwards compatibility, we don't check the BytecodeVerificationRemote setting2253// if the archive only contains system classes.2254if (_has_platform_or_app_classes2255&& !_verify_remote // we didn't verify the archived platform/app classes2256&& BytecodeVerificationRemote) { // but we want to verify all loaded platform/app classes2257FileMapInfo::fail_continue("The shared archive file was created with less restrictive "2258"verification setting than the current setting.");2259// Pretend that we didn't have any archived platform/app classes, so they won't be loaded2260// by SystemDictionaryShared.2261_has_platform_or_app_classes = false;2262}22632264// Java agents are allowed during run time. Therefore, the following condition is not2265// checked: (!_allow_archiving_with_java_agent && AllowArchivingWithJavaAgent)2266// Note: _allow_archiving_with_java_agent is set in the shared archive during dump time2267// while AllowArchivingWithJavaAgent is set during the current run.2268if (_allow_archiving_with_java_agent && !AllowArchivingWithJavaAgent) {2269FileMapInfo::fail_continue("The setting of the AllowArchivingWithJavaAgent is different "2270"from the setting in the shared archive.");2271return false;2272}22732274if (_allow_archiving_with_java_agent) {2275warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "2276"for testing purposes only and should not be used in a production environment");2277}22782279log_info(cds)("Archive was created with UseCompressedOops = %d, UseCompressedClassPointers = %d",2280compressed_oops(), compressed_class_pointers());2281if (compressed_oops() != UseCompressedOops || compressed_class_pointers() != UseCompressedClassPointers) {2282FileMapInfo::fail_continue("Unable to use shared archive.\nThe saved state of UseCompressedOops and UseCompressedClassPointers is "2283"different from runtime, CDS will be disabled.");2284return false;2285}22862287if (!_use_optimized_module_handling) {2288MetaspaceShared::disable_optimized_module_handling();2289log_info(cds)("optimized module handling: disabled because archive was created without optimized module handling");2290}22912292if (!_use_full_module_graph) {2293MetaspaceShared::disable_full_module_graph();2294log_info(cds)("full module graph: disabled because archive was created without full module graph");2295}22962297return true;2298}22992300bool FileMapInfo::validate_header() {2301if (!header()->validate()) {2302return false;2303}2304if (_is_static) {2305return true;2306} else {2307return DynamicArchive::validate(this);2308}2309}23102311// Check if a given address is within one of the shared regions2312bool FileMapInfo::is_in_shared_region(const void* p, int idx) {2313assert(idx == MetaspaceShared::ro ||2314idx == MetaspaceShared::rw, "invalid region index");2315char* base = region_addr(idx);2316if (p >= base && p < base + space_at(idx)->used()) {2317return true;2318}2319return false;2320}23212322// Unmap mapped regions of shared space.2323void FileMapInfo::stop_sharing_and_unmap(const char* msg) {2324MetaspaceShared::set_shared_metaspace_range(NULL, NULL, NULL);23252326FileMapInfo *map_info = FileMapInfo::current_info();2327if (map_info) {2328map_info->fail_continue("%s", msg);2329for (int i = 0; i < MetaspaceShared::num_non_heap_spaces; i++) {2330if (!HeapShared::is_heap_region(i)) {2331map_info->unmap_region(i);2332}2333}2334// Dealloc the archive heap regions only without unmapping. The regions are part2335// of the java heap. Unmapping of the heap regions are managed by GC.2336map_info->dealloc_archive_heap_regions(open_archive_heap_ranges,2337num_open_archive_heap_ranges);2338map_info->dealloc_archive_heap_regions(closed_archive_heap_ranges,2339num_closed_archive_heap_ranges);2340} else if (DumpSharedSpaces) {2341fail_stop("%s", msg);2342}2343}23442345#if INCLUDE_JVMTI2346ClassPathEntry** FileMapInfo::_classpath_entries_for_jvmti = NULL;23472348ClassPathEntry* FileMapInfo::get_classpath_entry_for_jvmti(int i, TRAPS) {2349ClassPathEntry* ent = _classpath_entries_for_jvmti[i];2350if (ent == NULL) {2351if (i == 0) {2352ent = ClassLoader::get_jrt_entry();2353assert(ent != NULL, "must be");2354} else {2355SharedClassPathEntry* scpe = shared_path(i);2356assert(scpe->is_jar(), "must be"); // other types of scpe will not produce archived classes23572358const char* path = scpe->name();2359struct stat st;2360if (os::stat(path, &st) != 0) {2361char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);2362jio_snprintf(msg, strlen(path) + 127, "error in finding JAR file %s", path);2363THROW_MSG_(vmSymbols::java_io_IOException(), msg, NULL);2364} else {2365ent = ClassLoader::create_class_path_entry(THREAD, path, &st, false, false);2366if (ent == NULL) {2367char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);2368jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);2369THROW_MSG_(vmSymbols::java_io_IOException(), msg, NULL);2370}2371}2372}23732374MutexLocker mu(THREAD, CDSClassFileStream_lock);2375if (_classpath_entries_for_jvmti[i] == NULL) {2376_classpath_entries_for_jvmti[i] = ent;2377} else {2378// Another thread has beat me to creating this entry2379delete ent;2380ent = _classpath_entries_for_jvmti[i];2381}2382}23832384return ent;2385}23862387ClassFileStream* FileMapInfo::open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS) {2388int path_index = ik->shared_classpath_index();2389assert(path_index >= 0, "should be called for shared built-in classes only");2390assert(path_index < (int)get_number_of_shared_paths(), "sanity");23912392ClassPathEntry* cpe = get_classpath_entry_for_jvmti(path_index, CHECK_NULL);2393assert(cpe != NULL, "must be");23942395Symbol* name = ik->name();2396const char* const class_name = name->as_C_string();2397const char* const file_name = ClassLoader::file_name_for_class_name(class_name,2398name->utf8_length());2399ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());2400ClassFileStream* cfs = cpe->open_stream_for_loader(THREAD, file_name, loader_data);2401assert(cfs != NULL, "must be able to read the classfile data of shared classes for built-in loaders.");2402log_debug(cds, jvmti)("classfile data for %s [%d: %s] = %d bytes", class_name, path_index,2403cfs->source(), cfs->length());2404return cfs;2405}24062407#endif240824092410