Path: blob/master/src/hotspot/share/cds/metaspaceShared.cpp
41144 views
/*1* Copyright (c) 2012, 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_io.h"26#include "cds/archiveBuilder.hpp"27#include "cds/classListParser.hpp"28#include "cds/cppVtables.hpp"29#include "cds/dumpAllocStats.hpp"30#include "cds/filemap.hpp"31#include "cds/heapShared.hpp"32#include "cds/lambdaFormInvokers.hpp"33#include "cds/metaspaceShared.hpp"34#include "classfile/classLoaderDataGraph.hpp"35#include "classfile/classLoaderDataShared.hpp"36#include "classfile/classLoaderExt.hpp"37#include "classfile/javaClasses.inline.hpp"38#include "classfile/loaderConstraints.hpp"39#include "classfile/placeholders.hpp"40#include "classfile/symbolTable.hpp"41#include "classfile/stringTable.hpp"42#include "classfile/systemDictionary.hpp"43#include "classfile/systemDictionaryShared.hpp"44#include "classfile/vmClasses.hpp"45#include "classfile/vmSymbols.hpp"46#include "code/codeCache.hpp"47#include "gc/shared/gcVMOperations.hpp"48#include "interpreter/bytecodeStream.hpp"49#include "interpreter/bytecodes.hpp"50#include "logging/log.hpp"51#include "logging/logMessage.hpp"52#include "logging/logStream.hpp"53#include "memory/metaspace.hpp"54#include "memory/metaspaceClosure.hpp"55#include "memory/resourceArea.hpp"56#include "memory/universe.hpp"57#include "oops/compressedOops.inline.hpp"58#include "oops/instanceMirrorKlass.hpp"59#include "oops/klass.inline.hpp"60#include "oops/objArrayOop.hpp"61#include "oops/oop.inline.hpp"62#include "oops/oopHandle.hpp"63#include "prims/jvmtiExport.hpp"64#include "runtime/arguments.hpp"65#include "runtime/handles.inline.hpp"66#include "runtime/os.hpp"67#include "runtime/safepointVerifiers.hpp"68#include "runtime/sharedRuntime.hpp"69#include "runtime/vmThread.hpp"70#include "runtime/vmOperations.hpp"71#include "utilities/align.hpp"72#include "utilities/bitMap.inline.hpp"73#include "utilities/ostream.hpp"74#include "utilities/defaultStream.hpp"75#if INCLUDE_G1GC76#include "gc/g1/g1CollectedHeap.inline.hpp"77#endif7879ReservedSpace MetaspaceShared::_symbol_rs;80VirtualSpace MetaspaceShared::_symbol_vs;81bool MetaspaceShared::_has_error_classes;82bool MetaspaceShared::_archive_loading_failed = false;83bool MetaspaceShared::_remapped_readwrite = false;84void* MetaspaceShared::_shared_metaspace_static_top = NULL;85intx MetaspaceShared::_relocation_delta;86char* MetaspaceShared::_requested_base_address;87bool MetaspaceShared::_use_optimized_module_handling = true;88bool MetaspaceShared::_use_full_module_graph = true;8990// The CDS archive is divided into the following regions:91// rw - read-write metadata92// ro - read-only metadata and read-only tables93//94// ca0 - closed archive heap space #095// ca1 - closed archive heap space #1 (may be empty)96// oa0 - open archive heap space #097// oa1 - open archive heap space #1 (may be empty)98//99// bm - bitmap for relocating the above 7 regions.100//101// The rw and ro regions are linearly allocated, in the order of rw->ro.102// These regions are aligned with MetaspaceShared::core_region_alignment().103//104// These 2 regions are populated in the following steps:105// [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are106// temporarily allocated outside of the shared regions.107// [1] We enter a safepoint and allocate a buffer for the rw/ro regions.108// [2] C++ vtables are copied into the rw region.109// [3] ArchiveBuilder copies RW metadata into the rw region.110// [4] ArchiveBuilder copies RO metadata into the ro region.111// [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data112// are copied into the ro region as read-only tables.113//114// The ca0/ca1 and oa0/oa1 regions are populated inside HeapShared::archive_java_heap_objects.115// Their layout is independent of the rw/ro regions.116117static DumpRegion _symbol_region("symbols");118119char* MetaspaceShared::symbol_space_alloc(size_t num_bytes) {120return _symbol_region.allocate(num_bytes);121}122123// os::vm_allocation_granularity() is usually 4K for most OSes. However, on Linux/aarch64,124// it can be either 4K or 64K and on Macosx-arm it is 16K. To generate archives that are125// compatible for both settings, an alternative cds core region alignment can be enabled126// at building time:127// --enable-compactible-cds-alignment128// Upon successful configuration, the compactible alignment then can be defined as in:129// os_linux_aarch64.hpp130// which is the highest page size configured on the platform.131size_t MetaspaceShared::core_region_alignment() {132#if defined(CDS_CORE_REGION_ALIGNMENT)133return CDS_CORE_REGION_ALIGNMENT;134#else135return (size_t)os::vm_allocation_granularity();136#endif // CDS_CORE_REGION_ALIGNMENT137}138139static bool shared_base_valid(char* shared_base) {140#ifdef _LP64141return CompressedKlassPointers::is_valid_base((address)shared_base);142#else143return true;144#endif145}146147class DumpClassListCLDClosure : public CLDClosure {148fileStream *_stream;149public:150DumpClassListCLDClosure(fileStream* f) : CLDClosure() { _stream = f; }151void do_cld(ClassLoaderData* cld) {152for (Klass* klass = cld->klasses(); klass != NULL; klass = klass->next_link()) {153if (klass->is_instance_klass()) {154InstanceKlass* ik = InstanceKlass::cast(klass);155if (ik->is_shareable()) {156_stream->print_cr("%s", ik->name()->as_C_string());157}158}159}160}161};162163void MetaspaceShared::dump_loaded_classes(const char* file_name, TRAPS) {164fileStream stream(file_name, "w");165if (stream.is_open()) {166MutexLocker lock(ClassLoaderDataGraph_lock);167DumpClassListCLDClosure collect_classes(&stream);168ClassLoaderDataGraph::loaded_cld_do(&collect_classes);169} else {170THROW_MSG(vmSymbols::java_io_IOException(), "Failed to open file");171}172}173174static bool shared_base_too_high(char* specified_base, char* aligned_base, size_t cds_max) {175if (specified_base != NULL && aligned_base < specified_base) {176// SharedBaseAddress is very high (e.g., 0xffffffffffffff00) so177// align_up(SharedBaseAddress, MetaspaceShared::core_region_alignment()) has wrapped around.178return true;179}180if (max_uintx - uintx(aligned_base) < uintx(cds_max)) {181// The end of the archive will wrap around182return true;183}184185return false;186}187188static char* compute_shared_base(size_t cds_max) {189char* specified_base = (char*)SharedBaseAddress;190char* aligned_base = align_up(specified_base, MetaspaceShared::core_region_alignment());191192const char* err = NULL;193if (shared_base_too_high(specified_base, aligned_base, cds_max)) {194err = "too high";195} else if (!shared_base_valid(aligned_base)) {196err = "invalid for this platform";197} else {198return aligned_base;199}200201log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,202p2i((void*)SharedBaseAddress), err,203p2i((void*)Arguments::default_SharedBaseAddress()));204205specified_base = (char*)Arguments::default_SharedBaseAddress();206aligned_base = align_up(specified_base, MetaspaceShared::core_region_alignment());207208// Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.209assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");210assert(shared_base_valid(aligned_base), "Sanity");211return aligned_base;212}213214void MetaspaceShared::initialize_for_static_dump() {215assert(DumpSharedSpaces, "should be called for dump time only");216log_info(cds)("Core region alignment: " SIZE_FORMAT, core_region_alignment());217// The max allowed size for CDS archive. We use this to limit SharedBaseAddress218// to avoid address space wrap around.219size_t cds_max;220const size_t reserve_alignment = core_region_alignment();221222#ifdef _LP64223const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);224cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);225#else226// We don't support archives larger than 256MB on 32-bit due to limited227// virtual address space.228cds_max = align_down(256*M, reserve_alignment);229#endif230231_requested_base_address = compute_shared_base(cds_max);232SharedBaseAddress = (size_t)_requested_base_address;233234size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);235_symbol_rs = ReservedSpace(symbol_rs_size);236if (!_symbol_rs.is_reserved()) {237vm_exit_during_initialization("Unable to reserve memory for symbols",238err_msg(SIZE_FORMAT " bytes.", symbol_rs_size));239}240_symbol_region.init(&_symbol_rs, &_symbol_vs);241}242243// Called by universe_post_init()244void MetaspaceShared::post_initialize(TRAPS) {245if (UseSharedSpaces) {246int size = FileMapInfo::get_number_of_shared_paths();247if (size > 0) {248SystemDictionaryShared::allocate_shared_data_arrays(size, CHECK);249if (!DynamicDumpSharedSpaces) {250FileMapInfo* info;251if (FileMapInfo::dynamic_info() == NULL) {252info = FileMapInfo::current_info();253} else {254info = FileMapInfo::dynamic_info();255}256ClassLoaderExt::init_paths_start_index(info->app_class_paths_start_index());257ClassLoaderExt::init_app_module_paths_start_index(info->app_module_paths_start_index());258}259}260}261}262263static GrowableArrayCHeap<OopHandle, mtClassShared>* _extra_interned_strings = NULL;264static GrowableArrayCHeap<Symbol*, mtClassShared>* _extra_symbols = NULL;265266void MetaspaceShared::read_extra_data(JavaThread* current, const char* filename) {267_extra_interned_strings = new GrowableArrayCHeap<OopHandle, mtClassShared>(10000);268_extra_symbols = new GrowableArrayCHeap<Symbol*, mtClassShared>(1000);269270HashtableTextDump reader(filename);271reader.check_version("VERSION: 1.0");272273while (reader.remain() > 0) {274int utf8_length;275int prefix_type = reader.scan_prefix(&utf8_length);276ResourceMark rm(current);277if (utf8_length == 0x7fffffff) {278// buf_len will overflown 32-bit value.279vm_exit_during_initialization(err_msg("string length too large: %d", utf8_length));280}281int buf_len = utf8_length+1;282char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len);283reader.get_utf8(utf8_buffer, utf8_length);284utf8_buffer[utf8_length] = '\0';285286if (prefix_type == HashtableTextDump::SymbolPrefix) {287_extra_symbols->append(SymbolTable::new_permanent_symbol(utf8_buffer));288} else{289assert(prefix_type == HashtableTextDump::StringPrefix, "Sanity");290ExceptionMark em(current);291JavaThread* THREAD = current; // For exception macros.292oop str = StringTable::intern(utf8_buffer, THREAD);293294if (HAS_PENDING_EXCEPTION) {295log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d",296reader.last_line_no(), utf8_length);297CLEAR_PENDING_EXCEPTION;298} else {299#if INCLUDE_G1GC300if (UseG1GC) {301typeArrayOop body = java_lang_String::value(str);302const HeapRegion* hr = G1CollectedHeap::heap()->heap_region_containing(body);303if (hr->is_humongous()) {304// Don't keep it alive, so it will be GC'ed before we dump the strings, in order305// to maximize free heap space and minimize fragmentation.306log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d",307reader.last_line_no(), utf8_length);308continue;309}310}311#endif312// Make sure this string is included in the dumped interned string table.313assert(str != NULL, "must succeed");314_extra_interned_strings->append(OopHandle(Universe::vm_global(), str));315}316}317}318}319320// Read/write a data stream for restoring/preserving metadata pointers and321// miscellaneous data from/to the shared archive file.322323void MetaspaceShared::serialize(SerializeClosure* soc) {324int tag = 0;325soc->do_tag(--tag);326327// Verify the sizes of various metadata in the system.328soc->do_tag(sizeof(Method));329soc->do_tag(sizeof(ConstMethod));330soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));331soc->do_tag(sizeof(ConstantPool));332soc->do_tag(sizeof(ConstantPoolCache));333soc->do_tag(objArrayOopDesc::base_offset_in_bytes());334soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));335soc->do_tag(sizeof(Symbol));336337// Dump/restore miscellaneous metadata.338JavaClasses::serialize_offsets(soc);339Universe::serialize(soc);340soc->do_tag(--tag);341342// Dump/restore references to commonly used names and signatures.343vmSymbols::serialize(soc);344soc->do_tag(--tag);345346// Dump/restore the symbol/string/subgraph_info tables347SymbolTable::serialize_shared_table_header(soc);348StringTable::serialize_shared_table_header(soc);349HeapShared::serialize_subgraph_info_table_header(soc);350SystemDictionaryShared::serialize_dictionary_headers(soc);351352InstanceMirrorKlass::serialize_offsets(soc);353354// Dump/restore well known classes (pointers)355SystemDictionaryShared::serialize_vm_classes(soc);356soc->do_tag(--tag);357358CppVtables::serialize(soc);359soc->do_tag(--tag);360361CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)362363LambdaFormInvokers::serialize(soc);364soc->do_tag(666);365}366367static void rewrite_nofast_bytecode(const methodHandle& method) {368BytecodeStream bcs(method);369while (!bcs.is_last_bytecode()) {370Bytecodes::Code opcode = bcs.next();371switch (opcode) {372case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break;373case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break;374case Bytecodes::_aload_0: *bcs.bcp() = Bytecodes::_nofast_aload_0; break;375case Bytecodes::_iload: {376if (!bcs.is_wide()) {377*bcs.bcp() = Bytecodes::_nofast_iload;378}379break;380}381default: break;382}383}384}385386// [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified387// at run time by RewriteBytecodes/RewriteFrequentPairs388// [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.389void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) {390for (int i = 0; i < ik->methods()->length(); i++) {391methodHandle m(thread, ik->methods()->at(i));392if (!ik->can_be_verified_at_dumptime()) {393rewrite_nofast_bytecode(m);394}395Fingerprinter fp(m);396// The side effect of this call sets method's fingerprint field.397fp.fingerprint();398}399}400401class VM_PopulateDumpSharedSpace : public VM_GC_Operation {402private:403GrowableArray<MemRegion> *_closed_archive_heap_regions;404GrowableArray<MemRegion> *_open_archive_heap_regions;405406GrowableArray<ArchiveHeapOopmapInfo> *_closed_archive_heap_oopmaps;407GrowableArray<ArchiveHeapOopmapInfo> *_open_archive_heap_oopmaps;408409void dump_java_heap_objects(GrowableArray<Klass*>* klasses) NOT_CDS_JAVA_HEAP_RETURN;410void dump_archive_heap_oopmaps() NOT_CDS_JAVA_HEAP_RETURN;411void dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,412GrowableArray<ArchiveHeapOopmapInfo>* oopmaps);413void dump_shared_symbol_table(GrowableArray<Symbol*>* symbols) {414log_info(cds)("Dumping symbol table ...");415SymbolTable::write_to_archive(symbols);416}417char* dump_read_only_tables();418419public:420421VM_PopulateDumpSharedSpace() :422VM_GC_Operation(0 /* total collections, ignored */, GCCause::_archive_time_gc),423_closed_archive_heap_regions(NULL),424_open_archive_heap_regions(NULL),425_closed_archive_heap_oopmaps(NULL),426_open_archive_heap_oopmaps(NULL) {}427428bool skip_operation() const { return false; }429430VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }431void doit(); // outline because gdb sucks432bool allow_nested_vm_operations() const { return true; }433}; // class VM_PopulateDumpSharedSpace434435class StaticArchiveBuilder : public ArchiveBuilder {436public:437StaticArchiveBuilder() : ArchiveBuilder() {}438439virtual void iterate_roots(MetaspaceClosure* it, bool is_relocating_pointers) {440FileMapInfo::metaspace_pointers_do(it, false);441SystemDictionaryShared::dumptime_classes_do(it);442Universe::metaspace_pointers_do(it);443vmSymbols::metaspace_pointers_do(it);444445// The above code should find all the symbols that are referenced by the446// archived classes. We just need to add the extra symbols which447// may not be used by any of the archived classes -- these are usually448// symbols that we anticipate to be used at run time, so we can store449// them in the RO region, to be shared across multiple processes.450if (_extra_symbols != NULL) {451for (int i = 0; i < _extra_symbols->length(); i++) {452it->push(_extra_symbols->adr_at(i));453}454}455}456};457458char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {459ArchiveBuilder::OtherROAllocMark mark;460461SystemDictionaryShared::write_to_archive();462463// Write lambform lines into archive464LambdaFormInvokers::dump_static_archive_invokers();465// Write the other data to the output array.466DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();467char* start = ro_region->top();468WriteClosure wc(ro_region);469MetaspaceShared::serialize(&wc);470471// Write the bitmaps for patching the archive heap regions472dump_archive_heap_oopmaps();473474return start;475}476477void VM_PopulateDumpSharedSpace::doit() {478HeapShared::run_full_gc_in_vm_thread();479480DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);481482FileMapInfo::check_nonempty_dir_in_shared_path_table();483484NOT_PRODUCT(SystemDictionary::verify();)485486// At this point, many classes have been loaded.487// Gather systemDictionary classes in a global array and do everything to488// that so we don't have to walk the SystemDictionary again.489SystemDictionaryShared::check_excluded_classes();490491StaticArchiveBuilder builder;492builder.gather_source_objs();493builder.reserve_buffer();494495char* cloned_vtables = CppVtables::dumptime_init(&builder);496497builder.dump_rw_metadata();498builder.dump_ro_metadata();499builder.relocate_metaspaceobj_embedded_pointers();500501// Dump supported java heap objects502dump_java_heap_objects(builder.klasses());503504builder.relocate_roots();505dump_shared_symbol_table(builder.symbols());506507builder.relocate_vm_classes();508509log_info(cds)("Make classes shareable");510builder.make_klasses_shareable();511512char* serialized_data = dump_read_only_tables();513514SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();515516// The vtable clones contain addresses of the current process.517// We don't want to write these addresses into the archive.518CppVtables::zero_archived_vtables();519520// relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()521// without runtime relocation.522builder.relocate_to_requested();523524// Write the archive file525FileMapInfo* mapinfo = new FileMapInfo(true);526mapinfo->populate_header(MetaspaceShared::core_region_alignment());527mapinfo->set_serialized_data(serialized_data);528mapinfo->set_cloned_vtables(cloned_vtables);529mapinfo->open_for_write();530builder.write_archive(mapinfo,531_closed_archive_heap_regions,532_open_archive_heap_regions,533_closed_archive_heap_oopmaps,534_open_archive_heap_oopmaps);535536if (PrintSystemDictionaryAtExit) {537SystemDictionary::print();538}539540if (AllowArchivingWithJavaAgent) {541warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "542"for testing purposes only and should not be used in a production environment");543}544545// There may be pending VM operations. We have changed some global states546// (such as vmClasses::_klasses) that may cause these VM operations547// to fail. For safety, forget these operations and exit the VM directly.548vm_direct_exit(0);549}550551class CollectCLDClosure : public CLDClosure {552GrowableArray<ClassLoaderData*> _loaded_cld;553public:554CollectCLDClosure() {}555~CollectCLDClosure() {556for (int i = 0; i < _loaded_cld.length(); i++) {557ClassLoaderData* cld = _loaded_cld.at(i);558cld->dec_keep_alive();559}560}561void do_cld(ClassLoaderData* cld) {562if (!cld->is_unloading()) {563cld->inc_keep_alive();564_loaded_cld.append(cld);565}566}567568int nof_cld() const { return _loaded_cld.length(); }569ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); }570};571572bool MetaspaceShared::linking_required(InstanceKlass* ik) {573// For static CDS dump, do not link old classes.574// For dynamic CDS dump, only link classes loaded by the builtin class loaders.575return DumpSharedSpaces ? !ik->can_be_verified_at_dumptime() : !ik->is_shared_unregistered_class();576}577578bool MetaspaceShared::link_class_for_cds(InstanceKlass* ik, TRAPS) {579// Link the class to cause the bytecodes to be rewritten and the580// cpcache to be created. Class verification is done according581// to -Xverify setting.582bool res = MetaspaceShared::try_link_class(THREAD, ik);583584if (DumpSharedSpaces) {585// The following function is used to resolve all Strings in the statically586// dumped classes to archive all the Strings. The archive heap is not supported587// for the dynamic archive.588ik->constants()->resolve_class_constants(CHECK_(false)); // may throw OOM when interning strings.589}590return res;591}592593void MetaspaceShared::link_and_cleanup_shared_classes(TRAPS) {594// Collect all loaded ClassLoaderData.595ResourceMark rm;596597LambdaFormInvokers::regenerate_holder_classes(CHECK);598CollectCLDClosure collect_cld;599{600// ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.601// We cannot link the classes while holding this lock (or else we may run into deadlock).602// Therefore, we need to first collect all the CLDs, and then link their classes after603// releasing the lock.604MutexLocker lock(ClassLoaderDataGraph_lock);605ClassLoaderDataGraph::loaded_cld_do(&collect_cld);606}607608while (true) {609bool has_linked = false;610for (int i = 0; i < collect_cld.nof_cld(); i++) {611ClassLoaderData* cld = collect_cld.cld_at(i);612for (Klass* klass = cld->klasses(); klass != NULL; klass = klass->next_link()) {613if (klass->is_instance_klass()) {614InstanceKlass* ik = InstanceKlass::cast(klass);615if (linking_required(ik)) {616has_linked |= link_class_for_cds(ik, CHECK);617}618}619}620}621622if (!has_linked) {623break;624}625// Class linking includes verification which may load more classes.626// Keep scanning until we have linked no more classes.627}628}629630void MetaspaceShared::prepare_for_dumping() {631Arguments::assert_is_dumping_archive();632Arguments::check_unsupported_dumping_properties();633634ClassLoader::initialize_shared_path(JavaThread::current());635}636637// Preload classes from a list, populate the shared spaces and dump to a638// file.639void MetaspaceShared::preload_and_dump() {640EXCEPTION_MARK;641ResourceMark rm(THREAD);642preload_and_dump_impl(THREAD);643if (HAS_PENDING_EXCEPTION) {644if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {645vm_direct_exit(-1, err_msg("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "646SIZE_FORMAT "M", MaxHeapSize/M));647} else {648log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),649java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));650vm_direct_exit(-1, "VM exits due to exception, use -Xlog:cds,exceptions=trace for detail");651}652} else {653// On success, the VM_PopulateDumpSharedSpace op should have654// exited the VM.655ShouldNotReachHere();656}657}658659void MetaspaceShared::preload_classes(TRAPS) {660char default_classlist[JVM_MAXPATHLEN];661const char* classlist_path;662663if (SharedClassListFile == NULL) {664// Construct the path to the class list (in jre/lib)665// Walk up two directories from the location of the VM and666// optionally tack on "lib" (depending on platform)667os::jvm_path(default_classlist, sizeof(default_classlist));668for (int i = 0; i < 3; i++) {669char *end = strrchr(default_classlist, *os::file_separator());670if (end != NULL) *end = '\0';671}672int classlist_path_len = (int)strlen(default_classlist);673if (classlist_path_len >= 3) {674if (strcmp(default_classlist + classlist_path_len - 3, "lib") != 0) {675if (classlist_path_len < JVM_MAXPATHLEN - 4) {676jio_snprintf(default_classlist + classlist_path_len,677sizeof(default_classlist) - classlist_path_len,678"%slib", os::file_separator());679classlist_path_len += 4;680}681}682}683if (classlist_path_len < JVM_MAXPATHLEN - 10) {684jio_snprintf(default_classlist + classlist_path_len,685sizeof(default_classlist) - classlist_path_len,686"%sclasslist", os::file_separator());687}688classlist_path = default_classlist;689} else {690classlist_path = SharedClassListFile;691}692693log_info(cds)("Loading classes to share ...");694_has_error_classes = false;695int class_count = parse_classlist(classlist_path, CHECK);696if (ExtraSharedClassListFile) {697class_count += parse_classlist(ExtraSharedClassListFile, CHECK);698}699700// Exercise the manifest processing code to ensure classes used by CDS at runtime701// are always archived702const char* dummy = "Manifest-Version: 1.0\n";703SystemDictionaryShared::create_jar_manifest(dummy, strlen(dummy), CHECK);704705log_info(cds)("Loading classes to share: done.");706log_info(cds)("Shared spaces: preloaded %d classes", class_count);707}708709void MetaspaceShared::preload_and_dump_impl(TRAPS) {710preload_classes(CHECK);711712if (SharedArchiveConfigFile) {713log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);714read_extra_data(THREAD, SharedArchiveConfigFile);715log_info(cds)("Reading extra data: done.");716}717718HeapShared::init_for_dumping(CHECK);719720// Rewrite and link classes721log_info(cds)("Rewriting and linking classes ...");722723// Link any classes which got missed. This would happen if we have loaded classes that724// were not explicitly specified in the classlist. E.g., if an interface implemented by class K725// fails verification, all other interfaces that were not specified in the classlist but726// are implemented by K are not verified.727link_and_cleanup_shared_classes(CHECK);728log_info(cds)("Rewriting and linking classes: done");729730#if INCLUDE_CDS_JAVA_HEAP731if (use_full_module_graph()) {732HeapShared::reset_archived_object_states(CHECK);733}734#endif735736VM_PopulateDumpSharedSpace op;737VMThread::execute(&op);738}739740741int MetaspaceShared::parse_classlist(const char* classlist_path, TRAPS) {742ClassListParser parser(classlist_path);743return parser.parse(THREAD); // returns the number of classes loaded.744}745746// Returns true if the class's status has changed.747bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {748ExceptionMark em(current);749JavaThread* THREAD = current; // For exception macros.750Arguments::assert_is_dumping_archive();751if (ik->is_loaded() && !ik->is_linked() && !ik->can_be_verified_at_dumptime() &&752!SystemDictionaryShared::has_class_failed_verification(ik)) {753bool saved = BytecodeVerificationLocal;754if (ik->is_shared_unregistered_class() && ik->class_loader() == NULL) {755// The verification decision is based on BytecodeVerificationRemote756// for non-system classes. Since we are using the NULL classloader757// to load non-system classes for customized class loaders during dumping,758// we need to temporarily change BytecodeVerificationLocal to be the same as759// BytecodeVerificationRemote. Note this can cause the parent system760// classes also being verified. The extra overhead is acceptable during761// dumping.762BytecodeVerificationLocal = BytecodeVerificationRemote;763}764ik->link_class(THREAD);765if (HAS_PENDING_EXCEPTION) {766ResourceMark rm(THREAD);767log_warning(cds)("Preload Warning: Verification failed for %s",768ik->external_name());769CLEAR_PENDING_EXCEPTION;770SystemDictionaryShared::set_class_has_failed_verification(ik);771_has_error_classes = true;772}773BytecodeVerificationLocal = saved;774return true;775} else {776return false;777}778}779780#if INCLUDE_CDS_JAVA_HEAP781void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) {782if(!HeapShared::is_heap_object_archiving_allowed()) {783log_info(cds)(784"Archived java heap is not supported as UseG1GC, "785"UseCompressedOops and UseCompressedClassPointers are required."786"Current settings: UseG1GC=%s, UseCompressedOops=%s, UseCompressedClassPointers=%s.",787BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedOops),788BOOL_TO_STR(UseCompressedClassPointers));789return;790}791// Find all the interned strings that should be dumped.792int i;793for (i = 0; i < klasses->length(); i++) {794Klass* k = klasses->at(i);795if (k->is_instance_klass()) {796InstanceKlass* ik = InstanceKlass::cast(k);797if (ik->is_linked()) {798ik->constants()->add_dumped_interned_strings();799}800}801}802if (_extra_interned_strings != NULL) {803for (i = 0; i < _extra_interned_strings->length(); i ++) {804OopHandle string = _extra_interned_strings->at(i);805HeapShared::add_to_dumped_interned_strings(string.resolve());806}807}808809// The closed and open archive heap space has maximum two regions.810// See FileMapInfo::write_archive_heap_regions() for details.811_closed_archive_heap_regions = new GrowableArray<MemRegion>(2);812_open_archive_heap_regions = new GrowableArray<MemRegion>(2);813HeapShared::archive_java_heap_objects(_closed_archive_heap_regions,814_open_archive_heap_regions);815ArchiveBuilder::OtherROAllocMark mark;816HeapShared::write_subgraph_info_table();817}818819void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps() {820if (HeapShared::is_heap_object_archiving_allowed()) {821_closed_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);822dump_archive_heap_oopmaps(_closed_archive_heap_regions, _closed_archive_heap_oopmaps);823824_open_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);825dump_archive_heap_oopmaps(_open_archive_heap_regions, _open_archive_heap_oopmaps);826}827}828829void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,830GrowableArray<ArchiveHeapOopmapInfo>* oopmaps) {831for (int i=0; i<regions->length(); i++) {832ResourceBitMap oopmap = HeapShared::calculate_oopmap(regions->at(i));833size_t size_in_bits = oopmap.size();834size_t size_in_bytes = oopmap.size_in_bytes();835uintptr_t* buffer = (uintptr_t*)NEW_C_HEAP_ARRAY(char, size_in_bytes, mtInternal);836oopmap.write_to(buffer, size_in_bytes);837log_info(cds, heap)("Oopmap = " INTPTR_FORMAT " (" SIZE_FORMAT_W(6) " bytes) for heap region "838INTPTR_FORMAT " (" SIZE_FORMAT_W(8) " bytes)",839p2i(buffer), size_in_bytes,840p2i(regions->at(i).start()), regions->at(i).byte_size());841842ArchiveHeapOopmapInfo info;843info._oopmap = (address)buffer;844info._oopmap_size_in_bits = size_in_bits;845info._oopmap_size_in_bytes = size_in_bytes;846oopmaps->append(info);847}848}849#endif // INCLUDE_CDS_JAVA_HEAP850851void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {852assert(base <= static_top && static_top <= top, "must be");853_shared_metaspace_static_top = static_top;854MetaspaceObj::set_shared_metaspace_range(base, top);855}856857// Return true if given address is in the misc data region858bool MetaspaceShared::is_in_shared_region(const void* p, int idx) {859return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx);860}861862bool MetaspaceShared::is_shared_dynamic(void* p) {863if ((p < MetaspaceObj::shared_metaspace_top()) &&864(p >= _shared_metaspace_static_top)) {865return true;866} else {867return false;868}869}870871void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {872assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");873MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;874875FileMapInfo* static_mapinfo = open_static_archive();876FileMapInfo* dynamic_mapinfo = NULL;877878if (static_mapinfo != NULL) {879log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment());880dynamic_mapinfo = open_dynamic_archive();881882// First try to map at the requested address883result = map_archives(static_mapinfo, dynamic_mapinfo, true);884if (result == MAP_ARCHIVE_MMAP_FAILURE) {885// Mapping has failed (probably due to ASLR). Let's map at an address chosen886// by the OS.887log_info(cds)("Try to map archive(s) at an alternative address");888result = map_archives(static_mapinfo, dynamic_mapinfo, false);889}890}891892if (result == MAP_ARCHIVE_SUCCESS) {893bool dynamic_mapped = (dynamic_mapinfo != NULL && dynamic_mapinfo->is_mapped());894char* cds_base = static_mapinfo->mapped_base();895char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();896set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);897_relocation_delta = static_mapinfo->relocation_delta();898_requested_base_address = static_mapinfo->requested_base_address();899if (dynamic_mapped) {900FileMapInfo::set_shared_path_table(dynamic_mapinfo);901} else {902FileMapInfo::set_shared_path_table(static_mapinfo);903}904} else {905set_shared_metaspace_range(NULL, NULL, NULL);906UseSharedSpaces = false;907FileMapInfo::fail_continue("Unable to map shared spaces");908if (PrintSharedArchiveAndExit) {909vm_exit_during_initialization("Unable to use shared archive.");910}911}912913if (static_mapinfo != NULL && !static_mapinfo->is_mapped()) {914delete static_mapinfo;915}916if (dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped()) {917delete dynamic_mapinfo;918}919}920921FileMapInfo* MetaspaceShared::open_static_archive() {922FileMapInfo* mapinfo = new FileMapInfo(true);923if (!mapinfo->initialize()) {924delete(mapinfo);925return NULL;926}927return mapinfo;928}929930FileMapInfo* MetaspaceShared::open_dynamic_archive() {931if (DynamicDumpSharedSpaces) {932return NULL;933}934if (Arguments::GetSharedDynamicArchivePath() == NULL) {935return NULL;936}937938FileMapInfo* mapinfo = new FileMapInfo(false);939if (!mapinfo->initialize()) {940delete(mapinfo);941return NULL;942}943return mapinfo;944}945946// use_requested_addr:947// true = map at FileMapHeader::_requested_base_address948// false = map at an alternative address picked by OS.949MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,950bool use_requested_addr) {951if (use_requested_addr && static_mapinfo->requested_base_address() == NULL) {952log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.");953return MAP_ARCHIVE_MMAP_FAILURE;954}955956PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {957// For product build only -- this is for benchmarking the cost of doing relocation.958// For debug builds, the check is done below, after reserving the space, for better test coverage959// (see comment below).960log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");961return MAP_ARCHIVE_MMAP_FAILURE;962});963964if (ArchiveRelocationMode == 2 && !use_requested_addr) {965log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");966return MAP_ARCHIVE_MMAP_FAILURE;967};968969if (dynamic_mapinfo != NULL) {970// Ensure that the OS won't be able to allocate new memory spaces between the two971// archives, or else it would mess up the simple comparision in MetaspaceObj::is_shared().972assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");973}974975ReservedSpace total_space_rs, archive_space_rs, class_space_rs;976MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;977char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo,978dynamic_mapinfo,979use_requested_addr,980total_space_rs,981archive_space_rs,982class_space_rs);983if (mapped_base_address == NULL) {984result = MAP_ARCHIVE_MMAP_FAILURE;985log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr);986} else {987988#ifdef ASSERT989// Some sanity checks after reserving address spaces for archives990// and class space.991assert(archive_space_rs.is_reserved(), "Sanity");992if (Metaspace::using_class_space()) {993// Class space must closely follow the archive space. Both spaces994// must be aligned correctly.995assert(class_space_rs.is_reserved(),996"A class space should have been reserved");997assert(class_space_rs.base() >= archive_space_rs.end(),998"class space should follow the cds archive space");999assert(is_aligned(archive_space_rs.base(),1000core_region_alignment()),1001"Archive space misaligned");1002assert(is_aligned(class_space_rs.base(),1003Metaspace::reserve_alignment()),1004"class space misaligned");1005}1006#endif // ASSERT10071008log_info(cds)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",1009p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size());1010log_info(cds)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",1011p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());10121013if (MetaspaceShared::use_windows_memory_mapping()) {1014// We have now reserved address space for the archives, and will map in1015// the archive files into this space.1016//1017// Special handling for Windows: on Windows we cannot map a file view1018// into an existing memory mapping. So, we unmap the address range we1019// just reserved again, which will make it available for mapping the1020// archives.1021// Reserving this range has not been for naught however since it makes1022// us reasonably sure the address range is available.1023//1024// But still it may fail, since between unmapping the range and mapping1025// in the archive someone else may grab the address space. Therefore1026// there is a fallback in FileMap::map_region() where we just read in1027// the archive files sequentially instead of mapping it in. We couple1028// this with use_requested_addr, since we're going to patch all the1029// pointers anyway so there's no benefit to mmap.1030if (use_requested_addr) {1031assert(!total_space_rs.is_reserved(), "Should not be reserved for Windows");1032log_info(cds)("Windows mmap workaround: releasing archive space.");1033archive_space_rs.release();1034}1035}1036MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);1037MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?1038map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;10391040DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {1041// This is for simulating mmap failures at the requested address. In1042// debug builds, we do it here (after all archives have possibly been1043// mapped), so we can thoroughly test the code for failure handling1044// (releasing all allocated resource, etc).1045log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");1046if (static_result == MAP_ARCHIVE_SUCCESS) {1047static_result = MAP_ARCHIVE_MMAP_FAILURE;1048}1049if (dynamic_result == MAP_ARCHIVE_SUCCESS) {1050dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;1051}1052});10531054if (static_result == MAP_ARCHIVE_SUCCESS) {1055if (dynamic_result == MAP_ARCHIVE_SUCCESS) {1056result = MAP_ARCHIVE_SUCCESS;1057} else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {1058assert(dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped(), "must have failed");1059// No need to retry mapping the dynamic archive again, as it will never succeed1060// (bad file, etc) -- just keep the base archive.1061log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",1062dynamic_mapinfo->full_path());1063result = MAP_ARCHIVE_SUCCESS;1064// TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no1065// easy API to do that right now.1066} else {1067result = MAP_ARCHIVE_MMAP_FAILURE;1068}1069} else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {1070result = MAP_ARCHIVE_OTHER_FAILURE;1071} else {1072result = MAP_ARCHIVE_MMAP_FAILURE;1073}1074}10751076if (result == MAP_ARCHIVE_SUCCESS) {1077SharedBaseAddress = (size_t)mapped_base_address;1078LP64_ONLY({1079if (Metaspace::using_class_space()) {1080// Set up ccs in metaspace.1081Metaspace::initialize_class_space(class_space_rs);10821083// Set up compressed Klass pointer encoding: the encoding range must1084// cover both archive and class space.1085address cds_base = (address)static_mapinfo->mapped_base();1086address ccs_end = (address)class_space_rs.end();1087assert(ccs_end > cds_base, "Sanity check");1088CompressedKlassPointers::initialize(cds_base, ccs_end - cds_base);10891090// map_heap_regions() compares the current narrow oop and klass encodings1091// with the archived ones, so it must be done after all encodings are determined.1092static_mapinfo->map_heap_regions();1093}1094});1095log_info(cds)("optimized module handling: %s", MetaspaceShared::use_optimized_module_handling() ? "enabled" : "disabled");1096log_info(cds)("full module graph: %s", MetaspaceShared::use_full_module_graph() ? "enabled" : "disabled");1097} else {1098unmap_archive(static_mapinfo);1099unmap_archive(dynamic_mapinfo);1100release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);1101}11021103return result;1104}110511061107// This will reserve two address spaces suitable to house Klass structures, one1108// for the cds archives (static archive and optionally dynamic archive) and1109// optionally one move for ccs.1110//1111// Since both spaces must fall within the compressed class pointer encoding1112// range, they are allocated close to each other.1113//1114// Space for archives will be reserved first, followed by a potential gap,1115// followed by the space for ccs:1116//1117// +-- Base address A B End1118// | | | |1119// v v v v1120// +-------------+--------------+ +----------------------+1121// | static arc | [dyn. arch] | [gap] | compr. class space |1122// +-------------+--------------+ +----------------------+1123//1124// (The gap may result from different alignment requirements between metaspace1125// and CDS)1126//1127// If UseCompressedClassPointers is disabled, only one address space will be1128// reserved:1129//1130// +-- Base address End1131// | |1132// v v1133// +-------------+--------------+1134// | static arc | [dyn. arch] |1135// +-------------+--------------+1136//1137// Base address: If use_archive_base_addr address is true, the Base address is1138// determined by the address stored in the static archive. If1139// use_archive_base_addr address is false, this base address is determined1140// by the platform.1141//1142// If UseCompressedClassPointers=1, the range encompassing both spaces will be1143// suitable to en/decode narrow Klass pointers: the base will be valid for1144// encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax.1145//1146// Return:1147//1148// - On success:1149// - total_space_rs will be reserved as whole for archive_space_rs and1150// class_space_rs if UseCompressedClassPointers is true.1151// On Windows, try reserve archive_space_rs and class_space_rs1152// separately first if use_archive_base_addr is true.1153// - archive_space_rs will be reserved and large enough to host static and1154// if needed dynamic archive: [Base, A).1155// archive_space_rs.base and size will be aligned to CDS reserve1156// granularity.1157// - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will1158// be reserved. Its start address will be aligned to metaspace reserve1159// alignment, which may differ from CDS alignment. It will follow the cds1160// archive space, close enough such that narrow class pointer encoding1161// covers both spaces.1162// If UseCompressedClassPointers=0, class_space_rs remains unreserved.1163// - On error: NULL is returned and the spaces remain unreserved.1164char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,1165FileMapInfo* dynamic_mapinfo,1166bool use_archive_base_addr,1167ReservedSpace& total_space_rs,1168ReservedSpace& archive_space_rs,1169ReservedSpace& class_space_rs) {11701171address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : NULL);1172const size_t archive_space_alignment = core_region_alignment();11731174// Size and requested location of the archive_space_rs (for both static and dynamic archives)1175assert(static_mapinfo->mapping_base_offset() == 0, "Must be");1176size_t archive_end_offset = (dynamic_mapinfo == NULL) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();1177size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);11781179// If a base address is given, it must have valid alignment and be suitable as encoding base.1180if (base_address != NULL) {1181assert(is_aligned(base_address, archive_space_alignment),1182"Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));1183if (Metaspace::using_class_space()) {1184assert(CompressedKlassPointers::is_valid_base(base_address),1185"Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));1186}1187}11881189if (!Metaspace::using_class_space()) {1190// Get the simple case out of the way first:1191// no compressed class space, simple allocation.1192archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,1193os::vm_page_size(), (char*)base_address);1194if (archive_space_rs.is_reserved()) {1195assert(base_address == NULL ||1196(address)archive_space_rs.base() == base_address, "Sanity");1197// Register archive space with NMT.1198MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);1199return archive_space_rs.base();1200}1201return NULL;1202}12031204#ifdef _LP6412051206// Complex case: two spaces adjacent to each other, both to be addressable1207// with narrow class pointers.1208// We reserve the whole range spanning both spaces, then split that range up.12091210const size_t class_space_alignment = Metaspace::reserve_alignment();12111212// To simplify matters, lets assume that metaspace alignment will always be1213// equal or a multiple of archive alignment.1214assert(is_power_of_2(class_space_alignment) &&1215is_power_of_2(archive_space_alignment) &&1216class_space_alignment >= archive_space_alignment,1217"Sanity");12181219const size_t class_space_size = CompressedClassSpaceSize;1220assert(CompressedClassSpaceSize > 0 &&1221is_aligned(CompressedClassSpaceSize, class_space_alignment),1222"CompressedClassSpaceSize malformed: "1223SIZE_FORMAT, CompressedClassSpaceSize);12241225const size_t ccs_begin_offset = align_up(base_address + archive_space_size,1226class_space_alignment) - base_address;1227const size_t gap_size = ccs_begin_offset - archive_space_size;12281229const size_t total_range_size =1230align_up(archive_space_size + gap_size + class_space_size, core_region_alignment());12311232assert(total_range_size > ccs_begin_offset, "must be");1233if (use_windows_memory_mapping() && use_archive_base_addr) {1234if (base_address != nullptr) {1235// On Windows, we cannot safely split a reserved memory space into two (see JDK-8255917).1236// Hence, we optimistically reserve archive space and class space side-by-side. We only1237// do this for use_archive_base_addr=true since for use_archive_base_addr=false case1238// caller will not split the combined space for mapping, instead read the archive data1239// via sequential file IO.1240address ccs_base = base_address + archive_space_size + gap_size;1241archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,1242os::vm_page_size(), (char*)base_address);1243class_space_rs = ReservedSpace(class_space_size, class_space_alignment,1244os::vm_page_size(), (char*)ccs_base);1245}1246if (!archive_space_rs.is_reserved() || !class_space_rs.is_reserved()) {1247release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);1248return NULL;1249}1250} else {1251if (use_archive_base_addr && base_address != nullptr) {1252total_space_rs = ReservedSpace(total_range_size, archive_space_alignment,1253os::vm_page_size(), (char*) base_address);1254} else {1255// Reserve at any address, but leave it up to the platform to choose a good one.1256total_space_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size);1257}12581259if (!total_space_rs.is_reserved()) {1260return NULL;1261}12621263// Paranoid checks:1264assert(base_address == NULL || (address)total_space_rs.base() == base_address,1265"Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_space_rs.base()));1266assert(is_aligned(total_space_rs.base(), archive_space_alignment), "Sanity");1267assert(total_space_rs.size() == total_range_size, "Sanity");1268assert(CompressedKlassPointers::is_valid_base((address)total_space_rs.base()), "Sanity");12691270// Now split up the space into ccs and cds archive. For simplicity, just leave1271// the gap reserved at the end of the archive space. Do not do real splitting.1272archive_space_rs = total_space_rs.first_part(ccs_begin_offset,1273(size_t)archive_space_alignment);1274class_space_rs = total_space_rs.last_part(ccs_begin_offset);1275MemTracker::record_virtual_memory_split_reserved(total_space_rs.base(), total_space_rs.size(),1276ccs_begin_offset);1277}1278assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");1279assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");1280assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");1281assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");12821283// NMT: fix up the space tags1284MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);1285MemTracker::record_virtual_memory_type(class_space_rs.base(), mtClass);12861287return archive_space_rs.base();12881289#else1290ShouldNotReachHere();1291return NULL;1292#endif12931294}12951296void MetaspaceShared::release_reserved_spaces(ReservedSpace& total_space_rs,1297ReservedSpace& archive_space_rs,1298ReservedSpace& class_space_rs) {1299if (total_space_rs.is_reserved()) {1300log_debug(cds)("Released shared space (archive + class) " INTPTR_FORMAT, p2i(total_space_rs.base()));1301total_space_rs.release();1302} else {1303if (archive_space_rs.is_reserved()) {1304log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));1305archive_space_rs.release();1306}1307if (class_space_rs.is_reserved()) {1308log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));1309class_space_rs.release();1310}1311}1312}13131314static int archive_regions[] = { MetaspaceShared::rw, MetaspaceShared::ro };1315static int archive_regions_count = 2;13161317MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {1318assert(UseSharedSpaces, "must be runtime");1319if (mapinfo == NULL) {1320return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.1321}13221323mapinfo->set_is_mapped(false);1324if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {1325log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT1326" actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());1327return MAP_ARCHIVE_OTHER_FAILURE;1328}13291330MapArchiveResult result =1331mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);13321333if (result != MAP_ARCHIVE_SUCCESS) {1334unmap_archive(mapinfo);1335return result;1336}13371338if (!mapinfo->validate_shared_path_table()) {1339unmap_archive(mapinfo);1340return MAP_ARCHIVE_OTHER_FAILURE;1341}13421343mapinfo->set_is_mapped(true);1344return MAP_ARCHIVE_SUCCESS;1345}13461347void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) {1348assert(UseSharedSpaces, "must be runtime");1349if (mapinfo != NULL) {1350mapinfo->unmap_regions(archive_regions, archive_regions_count);1351mapinfo->unmap_region(MetaspaceShared::bm);1352mapinfo->set_is_mapped(false);1353}1354}13551356// For -XX:PrintSharedArchiveAndExit1357class CountSharedSymbols : public SymbolClosure {1358private:1359int _count;1360public:1361CountSharedSymbols() : _count(0) {}1362void do_symbol(Symbol** sym) {1363_count++;1364}1365int total() { return _count; }13661367};13681369// Read the miscellaneous data from the shared file, and1370// serialize it out to its various destinations.13711372void MetaspaceShared::initialize_shared_spaces() {1373FileMapInfo *static_mapinfo = FileMapInfo::current_info();13741375// Verify various attributes of the archive, plus initialize the1376// shared string/symbol tables1377char* buffer = static_mapinfo->serialized_data();1378intptr_t* array = (intptr_t*)buffer;1379ReadClosure rc(&array);1380serialize(&rc);13811382// Initialize the run-time symbol table.1383SymbolTable::create_table();13841385static_mapinfo->patch_archived_heap_embedded_pointers();13861387// Close the mapinfo file1388static_mapinfo->close();13891390static_mapinfo->unmap_region(MetaspaceShared::bm);13911392FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();1393if (dynamic_mapinfo != NULL) {1394intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();1395ReadClosure rc(&buffer);1396SymbolTable::serialize_shared_table_header(&rc, false);1397SystemDictionaryShared::serialize_dictionary_headers(&rc, false);1398dynamic_mapinfo->close();1399dynamic_mapinfo->unmap_region(MetaspaceShared::bm);1400}14011402// Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump1403if (DynamicDumpSharedSpaces) {1404// Read stored LF format lines stored in static archive1405LambdaFormInvokers::read_static_archive_invokers();1406}14071408if (PrintSharedArchiveAndExit) {1409// Print archive names1410if (dynamic_mapinfo != nullptr) {1411tty->print_cr("\n\nBase archive name: %s", Arguments::GetSharedArchivePath());1412tty->print_cr("Base archive version %d", static_mapinfo->version());1413} else {1414tty->print_cr("Static archive name: %s", static_mapinfo->full_path());1415tty->print_cr("Static archive version %d", static_mapinfo->version());1416}14171418SystemDictionaryShared::print_shared_archive(tty);1419if (dynamic_mapinfo != nullptr) {1420tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());1421tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());1422SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);1423}14241425// collect shared symbols and strings1426CountSharedSymbols cl;1427SymbolTable::shared_symbols_do(&cl);1428tty->print_cr("Number of shared symbols: %d", cl.total());1429tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());1430tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());1431if (FileMapInfo::current_info() == NULL || _archive_loading_failed) {1432tty->print_cr("archive is invalid");1433vm_exit(1);1434} else {1435tty->print_cr("archive is valid");1436vm_exit(0);1437}1438}1439}14401441// JVM/TI RedefineClasses() support:1442bool MetaspaceShared::remap_shared_readonly_as_readwrite() {1443assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");14441445if (UseSharedSpaces) {1446// remap the shared readonly space to shared readwrite, private1447FileMapInfo* mapinfo = FileMapInfo::current_info();1448if (!mapinfo->remap_shared_readonly_as_readwrite()) {1449return false;1450}1451if (FileMapInfo::dynamic_info() != NULL) {1452mapinfo = FileMapInfo::dynamic_info();1453if (!mapinfo->remap_shared_readonly_as_readwrite()) {1454return false;1455}1456}1457_remapped_readwrite = true;1458}1459return true;1460}14611462bool MetaspaceShared::use_full_module_graph() {1463#if INCLUDE_CDS_JAVA_HEAP1464if (ClassLoaderDataShared::is_full_module_graph_loaded()) {1465return true;1466}1467#endif1468bool result = _use_optimized_module_handling && _use_full_module_graph &&1469(UseSharedSpaces || DumpSharedSpaces) && HeapShared::is_heap_object_archiving_allowed();1470if (result && UseSharedSpaces) {1471// Classes used by the archived full module graph are loaded in JVMTI early phase.1472assert(!(JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()),1473"CDS should be disabled if early class hooks are enabled");1474}1475return result;1476}14771478void MetaspaceShared::print_on(outputStream* st) {1479if (UseSharedSpaces) {1480st->print("CDS archive(s) mapped at: ");1481address base = (address)MetaspaceObj::shared_metaspace_base();1482address static_top = (address)_shared_metaspace_static_top;1483address top = (address)MetaspaceObj::shared_metaspace_top();1484st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));1485st->print("size " SIZE_FORMAT ", ", top - base);1486st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, (int)ArchiveRelocationMode);1487} else {1488st->print("CDS archive(s) not mapped");1489}1490st->cr();1491}149214931494