Path: blob/master/src/hotspot/share/cds/metaspaceShared.cpp
64441 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// Block concurrent class unloading from changing the _dumptime_table487MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);488SystemDictionaryShared::check_excluded_classes();489SystemDictionaryShared::cleanup_lambda_proxy_class_dictionary();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;553GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive554Thread* _current_thread;555public:556CollectCLDClosure(Thread* thread) : _current_thread(thread) {}557~CollectCLDClosure() {558for (int i = 0; i < _loaded_cld_handles.length(); i++) {559_loaded_cld_handles.at(i).release(Universe::vm_global());560}561}562void do_cld(ClassLoaderData* cld) {563assert(cld->is_alive(), "must be");564_loaded_cld.append(cld);565_loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder_phantom()));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) {594LambdaFormInvokers::regenerate_holder_classes(CHECK);595596// Collect all loaded ClassLoaderData.597CollectCLDClosure collect_cld(THREAD);598{599// ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.600// We cannot link the classes while holding this lock (or else we may run into deadlock).601// Therefore, we need to first collect all the CLDs, and then link their classes after602// releasing the lock.603MutexLocker lock(ClassLoaderDataGraph_lock);604ClassLoaderDataGraph::loaded_cld_do(&collect_cld);605}606607while (true) {608bool has_linked = false;609for (int i = 0; i < collect_cld.nof_cld(); i++) {610ClassLoaderData* cld = collect_cld.cld_at(i);611for (Klass* klass = cld->klasses(); klass != NULL; klass = klass->next_link()) {612if (klass->is_instance_klass()) {613InstanceKlass* ik = InstanceKlass::cast(klass);614if (linking_required(ik)) {615has_linked |= link_class_for_cds(ik, CHECK);616}617}618}619}620621if (!has_linked) {622break;623}624// Class linking includes verification which may load more classes.625// Keep scanning until we have linked no more classes.626}627}628629void MetaspaceShared::prepare_for_dumping() {630Arguments::assert_is_dumping_archive();631Arguments::check_unsupported_dumping_properties();632633ClassLoader::initialize_shared_path(JavaThread::current());634}635636// Preload classes from a list, populate the shared spaces and dump to a637// file.638void MetaspaceShared::preload_and_dump() {639EXCEPTION_MARK;640ResourceMark rm(THREAD);641preload_and_dump_impl(THREAD);642if (HAS_PENDING_EXCEPTION) {643if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {644vm_direct_exit(-1, err_msg("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "645SIZE_FORMAT "M", MaxHeapSize/M));646} else {647log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),648java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));649vm_direct_exit(-1, "VM exits due to exception, use -Xlog:cds,exceptions=trace for detail");650}651} else {652// On success, the VM_PopulateDumpSharedSpace op should have653// exited the VM.654ShouldNotReachHere();655}656}657658void MetaspaceShared::preload_classes(TRAPS) {659char default_classlist[JVM_MAXPATHLEN];660const char* classlist_path;661662if (SharedClassListFile == NULL) {663// Construct the path to the class list (in jre/lib)664// Walk up two directories from the location of the VM and665// optionally tack on "lib" (depending on platform)666os::jvm_path(default_classlist, sizeof(default_classlist));667for (int i = 0; i < 3; i++) {668char *end = strrchr(default_classlist, *os::file_separator());669if (end != NULL) *end = '\0';670}671int classlist_path_len = (int)strlen(default_classlist);672if (classlist_path_len >= 3) {673if (strcmp(default_classlist + classlist_path_len - 3, "lib") != 0) {674if (classlist_path_len < JVM_MAXPATHLEN - 4) {675jio_snprintf(default_classlist + classlist_path_len,676sizeof(default_classlist) - classlist_path_len,677"%slib", os::file_separator());678classlist_path_len += 4;679}680}681}682if (classlist_path_len < JVM_MAXPATHLEN - 10) {683jio_snprintf(default_classlist + classlist_path_len,684sizeof(default_classlist) - classlist_path_len,685"%sclasslist", os::file_separator());686}687classlist_path = default_classlist;688} else {689classlist_path = SharedClassListFile;690}691692log_info(cds)("Loading classes to share ...");693_has_error_classes = false;694int class_count = parse_classlist(classlist_path, CHECK);695if (ExtraSharedClassListFile) {696class_count += parse_classlist(ExtraSharedClassListFile, CHECK);697}698699// Exercise the manifest processing code to ensure classes used by CDS at runtime700// are always archived701const char* dummy = "Manifest-Version: 1.0\n";702SystemDictionaryShared::create_jar_manifest(dummy, strlen(dummy), CHECK);703704log_info(cds)("Loading classes to share: done.");705log_info(cds)("Shared spaces: preloaded %d classes", class_count);706}707708void MetaspaceShared::preload_and_dump_impl(TRAPS) {709preload_classes(CHECK);710711if (SharedArchiveConfigFile) {712log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);713read_extra_data(THREAD, SharedArchiveConfigFile);714log_info(cds)("Reading extra data: done.");715}716717HeapShared::init_for_dumping(CHECK);718719// Rewrite and link classes720log_info(cds)("Rewriting and linking classes ...");721722// Link any classes which got missed. This would happen if we have loaded classes that723// were not explicitly specified in the classlist. E.g., if an interface implemented by class K724// fails verification, all other interfaces that were not specified in the classlist but725// are implemented by K are not verified.726link_and_cleanup_shared_classes(CHECK);727log_info(cds)("Rewriting and linking classes: done");728729#if INCLUDE_CDS_JAVA_HEAP730if (use_full_module_graph()) {731HeapShared::reset_archived_object_states(CHECK);732}733#endif734735VM_PopulateDumpSharedSpace op;736VMThread::execute(&op);737}738739740int MetaspaceShared::parse_classlist(const char* classlist_path, TRAPS) {741ClassListParser parser(classlist_path);742return parser.parse(THREAD); // returns the number of classes loaded.743}744745// Returns true if the class's status has changed.746bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {747ExceptionMark em(current);748JavaThread* THREAD = current; // For exception macros.749Arguments::assert_is_dumping_archive();750if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&751!SystemDictionaryShared::has_class_failed_verification(ik)) {752bool saved = BytecodeVerificationLocal;753if (ik->is_shared_unregistered_class() && ik->class_loader() == NULL) {754// The verification decision is based on BytecodeVerificationRemote755// for non-system classes. Since we are using the NULL classloader756// to load non-system classes for customized class loaders during dumping,757// we need to temporarily change BytecodeVerificationLocal to be the same as758// BytecodeVerificationRemote. Note this can cause the parent system759// classes also being verified. The extra overhead is acceptable during760// dumping.761BytecodeVerificationLocal = BytecodeVerificationRemote;762}763ik->link_class(THREAD);764if (HAS_PENDING_EXCEPTION) {765ResourceMark rm(THREAD);766log_warning(cds)("Preload Warning: Verification failed for %s",767ik->external_name());768CLEAR_PENDING_EXCEPTION;769SystemDictionaryShared::set_class_has_failed_verification(ik);770_has_error_classes = true;771}772BytecodeVerificationLocal = saved;773return true;774} else {775return false;776}777}778779#if INCLUDE_CDS_JAVA_HEAP780void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) {781if(!HeapShared::is_heap_object_archiving_allowed()) {782log_info(cds)(783"Archived java heap is not supported as UseG1GC, "784"UseCompressedOops and UseCompressedClassPointers are required."785"Current settings: UseG1GC=%s, UseCompressedOops=%s, UseCompressedClassPointers=%s.",786BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedOops),787BOOL_TO_STR(UseCompressedClassPointers));788return;789}790// Find all the interned strings that should be dumped.791int i;792for (i = 0; i < klasses->length(); i++) {793Klass* k = klasses->at(i);794if (k->is_instance_klass()) {795InstanceKlass* ik = InstanceKlass::cast(k);796if (ik->is_linked()) {797ik->constants()->add_dumped_interned_strings();798}799}800}801if (_extra_interned_strings != NULL) {802for (i = 0; i < _extra_interned_strings->length(); i ++) {803OopHandle string = _extra_interned_strings->at(i);804HeapShared::add_to_dumped_interned_strings(string.resolve());805}806}807808// The closed and open archive heap space has maximum two regions.809// See FileMapInfo::write_archive_heap_regions() for details.810_closed_archive_heap_regions = new GrowableArray<MemRegion>(2);811_open_archive_heap_regions = new GrowableArray<MemRegion>(2);812HeapShared::archive_java_heap_objects(_closed_archive_heap_regions,813_open_archive_heap_regions);814ArchiveBuilder::OtherROAllocMark mark;815HeapShared::write_subgraph_info_table();816}817818void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps() {819if (HeapShared::is_heap_object_archiving_allowed()) {820_closed_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);821dump_archive_heap_oopmaps(_closed_archive_heap_regions, _closed_archive_heap_oopmaps);822823_open_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);824dump_archive_heap_oopmaps(_open_archive_heap_regions, _open_archive_heap_oopmaps);825}826}827828void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,829GrowableArray<ArchiveHeapOopmapInfo>* oopmaps) {830for (int i=0; i<regions->length(); i++) {831ResourceBitMap oopmap = HeapShared::calculate_oopmap(regions->at(i));832size_t size_in_bits = oopmap.size();833size_t size_in_bytes = oopmap.size_in_bytes();834uintptr_t* buffer = (uintptr_t*)NEW_C_HEAP_ARRAY(char, size_in_bytes, mtInternal);835oopmap.write_to(buffer, size_in_bytes);836log_info(cds, heap)("Oopmap = " INTPTR_FORMAT " (" SIZE_FORMAT_W(6) " bytes) for heap region "837INTPTR_FORMAT " (" SIZE_FORMAT_W(8) " bytes)",838p2i(buffer), size_in_bytes,839p2i(regions->at(i).start()), regions->at(i).byte_size());840841ArchiveHeapOopmapInfo info;842info._oopmap = (address)buffer;843info._oopmap_size_in_bits = size_in_bits;844info._oopmap_size_in_bytes = size_in_bytes;845oopmaps->append(info);846}847}848#endif // INCLUDE_CDS_JAVA_HEAP849850void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {851assert(base <= static_top && static_top <= top, "must be");852_shared_metaspace_static_top = static_top;853MetaspaceObj::set_shared_metaspace_range(base, top);854}855856// Return true if given address is in the misc data region857bool MetaspaceShared::is_in_shared_region(const void* p, int idx) {858return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx);859}860861bool MetaspaceShared::is_shared_dynamic(void* p) {862if ((p < MetaspaceObj::shared_metaspace_top()) &&863(p >= _shared_metaspace_static_top)) {864return true;865} else {866return false;867}868}869870void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {871assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");872MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;873874FileMapInfo* static_mapinfo = open_static_archive();875FileMapInfo* dynamic_mapinfo = NULL;876877if (static_mapinfo != NULL) {878log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment());879dynamic_mapinfo = open_dynamic_archive();880881// First try to map at the requested address882result = map_archives(static_mapinfo, dynamic_mapinfo, true);883if (result == MAP_ARCHIVE_MMAP_FAILURE) {884// Mapping has failed (probably due to ASLR). Let's map at an address chosen885// by the OS.886log_info(cds)("Try to map archive(s) at an alternative address");887result = map_archives(static_mapinfo, dynamic_mapinfo, false);888}889}890891if (result == MAP_ARCHIVE_SUCCESS) {892bool dynamic_mapped = (dynamic_mapinfo != NULL && dynamic_mapinfo->is_mapped());893char* cds_base = static_mapinfo->mapped_base();894char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();895set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);896_relocation_delta = static_mapinfo->relocation_delta();897_requested_base_address = static_mapinfo->requested_base_address();898if (dynamic_mapped) {899FileMapInfo::set_shared_path_table(dynamic_mapinfo);900} else {901FileMapInfo::set_shared_path_table(static_mapinfo);902}903} else {904set_shared_metaspace_range(NULL, NULL, NULL);905UseSharedSpaces = false;906FileMapInfo::fail_continue("Unable to map shared spaces");907if (PrintSharedArchiveAndExit) {908vm_exit_during_initialization("Unable to use shared archive.");909}910}911912if (static_mapinfo != NULL && !static_mapinfo->is_mapped()) {913delete static_mapinfo;914}915if (dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped()) {916delete dynamic_mapinfo;917}918}919920FileMapInfo* MetaspaceShared::open_static_archive() {921FileMapInfo* mapinfo = new FileMapInfo(true);922if (!mapinfo->initialize()) {923delete(mapinfo);924return NULL;925}926return mapinfo;927}928929FileMapInfo* MetaspaceShared::open_dynamic_archive() {930if (DynamicDumpSharedSpaces) {931return NULL;932}933if (Arguments::GetSharedDynamicArchivePath() == NULL) {934return NULL;935}936937FileMapInfo* mapinfo = new FileMapInfo(false);938if (!mapinfo->initialize()) {939delete(mapinfo);940return NULL;941}942return mapinfo;943}944945// use_requested_addr:946// true = map at FileMapHeader::_requested_base_address947// false = map at an alternative address picked by OS.948MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,949bool use_requested_addr) {950if (use_requested_addr && static_mapinfo->requested_base_address() == NULL) {951log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.");952return MAP_ARCHIVE_MMAP_FAILURE;953}954955PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {956// For product build only -- this is for benchmarking the cost of doing relocation.957// For debug builds, the check is done below, after reserving the space, for better test coverage958// (see comment below).959log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");960return MAP_ARCHIVE_MMAP_FAILURE;961});962963if (ArchiveRelocationMode == 2 && !use_requested_addr) {964log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");965return MAP_ARCHIVE_MMAP_FAILURE;966};967968if (dynamic_mapinfo != NULL) {969// Ensure that the OS won't be able to allocate new memory spaces between the two970// archives, or else it would mess up the simple comparision in MetaspaceObj::is_shared().971assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");972}973974ReservedSpace total_space_rs, archive_space_rs, class_space_rs;975MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;976char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo,977dynamic_mapinfo,978use_requested_addr,979total_space_rs,980archive_space_rs,981class_space_rs);982if (mapped_base_address == NULL) {983result = MAP_ARCHIVE_MMAP_FAILURE;984log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr);985} else {986987#ifdef ASSERT988// Some sanity checks after reserving address spaces for archives989// and class space.990assert(archive_space_rs.is_reserved(), "Sanity");991if (Metaspace::using_class_space()) {992// Class space must closely follow the archive space. Both spaces993// must be aligned correctly.994assert(class_space_rs.is_reserved(),995"A class space should have been reserved");996assert(class_space_rs.base() >= archive_space_rs.end(),997"class space should follow the cds archive space");998assert(is_aligned(archive_space_rs.base(),999core_region_alignment()),1000"Archive space misaligned");1001assert(is_aligned(class_space_rs.base(),1002Metaspace::reserve_alignment()),1003"class space misaligned");1004}1005#endif // ASSERT10061007log_info(cds)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",1008p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size());1009log_info(cds)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",1010p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());10111012if (MetaspaceShared::use_windows_memory_mapping()) {1013// We have now reserved address space for the archives, and will map in1014// the archive files into this space.1015//1016// Special handling for Windows: on Windows we cannot map a file view1017// into an existing memory mapping. So, we unmap the address range we1018// just reserved again, which will make it available for mapping the1019// archives.1020// Reserving this range has not been for naught however since it makes1021// us reasonably sure the address range is available.1022//1023// But still it may fail, since between unmapping the range and mapping1024// in the archive someone else may grab the address space. Therefore1025// there is a fallback in FileMap::map_region() where we just read in1026// the archive files sequentially instead of mapping it in. We couple1027// this with use_requested_addr, since we're going to patch all the1028// pointers anyway so there's no benefit to mmap.1029if (use_requested_addr) {1030assert(!total_space_rs.is_reserved(), "Should not be reserved for Windows");1031log_info(cds)("Windows mmap workaround: releasing archive space.");1032archive_space_rs.release();1033}1034}1035MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);1036MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?1037map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;10381039DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {1040// This is for simulating mmap failures at the requested address. In1041// debug builds, we do it here (after all archives have possibly been1042// mapped), so we can thoroughly test the code for failure handling1043// (releasing all allocated resource, etc).1044log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");1045if (static_result == MAP_ARCHIVE_SUCCESS) {1046static_result = MAP_ARCHIVE_MMAP_FAILURE;1047}1048if (dynamic_result == MAP_ARCHIVE_SUCCESS) {1049dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;1050}1051});10521053if (static_result == MAP_ARCHIVE_SUCCESS) {1054if (dynamic_result == MAP_ARCHIVE_SUCCESS) {1055result = MAP_ARCHIVE_SUCCESS;1056} else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {1057assert(dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped(), "must have failed");1058// No need to retry mapping the dynamic archive again, as it will never succeed1059// (bad file, etc) -- just keep the base archive.1060log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",1061dynamic_mapinfo->full_path());1062result = MAP_ARCHIVE_SUCCESS;1063// TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no1064// easy API to do that right now.1065} else {1066result = MAP_ARCHIVE_MMAP_FAILURE;1067}1068} else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {1069result = MAP_ARCHIVE_OTHER_FAILURE;1070} else {1071result = MAP_ARCHIVE_MMAP_FAILURE;1072}1073}10741075if (result == MAP_ARCHIVE_SUCCESS) {1076SharedBaseAddress = (size_t)mapped_base_address;1077LP64_ONLY({1078if (Metaspace::using_class_space()) {1079// Set up ccs in metaspace.1080Metaspace::initialize_class_space(class_space_rs);10811082// Set up compressed Klass pointer encoding: the encoding range must1083// cover both archive and class space.1084address cds_base = (address)static_mapinfo->mapped_base();1085address ccs_end = (address)class_space_rs.end();1086assert(ccs_end > cds_base, "Sanity check");1087CompressedKlassPointers::initialize(cds_base, ccs_end - cds_base);10881089// map_heap_regions() compares the current narrow oop and klass encodings1090// with the archived ones, so it must be done after all encodings are determined.1091static_mapinfo->map_heap_regions();1092}1093});1094log_info(cds)("optimized module handling: %s", MetaspaceShared::use_optimized_module_handling() ? "enabled" : "disabled");1095log_info(cds)("full module graph: %s", MetaspaceShared::use_full_module_graph() ? "enabled" : "disabled");1096} else {1097unmap_archive(static_mapinfo);1098unmap_archive(dynamic_mapinfo);1099release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);1100}11011102return result;1103}110411051106// This will reserve two address spaces suitable to house Klass structures, one1107// for the cds archives (static archive and optionally dynamic archive) and1108// optionally one move for ccs.1109//1110// Since both spaces must fall within the compressed class pointer encoding1111// range, they are allocated close to each other.1112//1113// Space for archives will be reserved first, followed by a potential gap,1114// followed by the space for ccs:1115//1116// +-- Base address A B End1117// | | | |1118// v v v v1119// +-------------+--------------+ +----------------------+1120// | static arc | [dyn. arch] | [gap] | compr. class space |1121// +-------------+--------------+ +----------------------+1122//1123// (The gap may result from different alignment requirements between metaspace1124// and CDS)1125//1126// If UseCompressedClassPointers is disabled, only one address space will be1127// reserved:1128//1129// +-- Base address End1130// | |1131// v v1132// +-------------+--------------+1133// | static arc | [dyn. arch] |1134// +-------------+--------------+1135//1136// Base address: If use_archive_base_addr address is true, the Base address is1137// determined by the address stored in the static archive. If1138// use_archive_base_addr address is false, this base address is determined1139// by the platform.1140//1141// If UseCompressedClassPointers=1, the range encompassing both spaces will be1142// suitable to en/decode narrow Klass pointers: the base will be valid for1143// encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax.1144//1145// Return:1146//1147// - On success:1148// - total_space_rs will be reserved as whole for archive_space_rs and1149// class_space_rs if UseCompressedClassPointers is true.1150// On Windows, try reserve archive_space_rs and class_space_rs1151// separately first if use_archive_base_addr is true.1152// - archive_space_rs will be reserved and large enough to host static and1153// if needed dynamic archive: [Base, A).1154// archive_space_rs.base and size will be aligned to CDS reserve1155// granularity.1156// - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will1157// be reserved. Its start address will be aligned to metaspace reserve1158// alignment, which may differ from CDS alignment. It will follow the cds1159// archive space, close enough such that narrow class pointer encoding1160// covers both spaces.1161// If UseCompressedClassPointers=0, class_space_rs remains unreserved.1162// - On error: NULL is returned and the spaces remain unreserved.1163char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,1164FileMapInfo* dynamic_mapinfo,1165bool use_archive_base_addr,1166ReservedSpace& total_space_rs,1167ReservedSpace& archive_space_rs,1168ReservedSpace& class_space_rs) {11691170address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : NULL);1171const size_t archive_space_alignment = core_region_alignment();11721173// Size and requested location of the archive_space_rs (for both static and dynamic archives)1174assert(static_mapinfo->mapping_base_offset() == 0, "Must be");1175size_t archive_end_offset = (dynamic_mapinfo == NULL) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();1176size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);11771178// If a base address is given, it must have valid alignment and be suitable as encoding base.1179if (base_address != NULL) {1180assert(is_aligned(base_address, archive_space_alignment),1181"Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));1182if (Metaspace::using_class_space()) {1183assert(CompressedKlassPointers::is_valid_base(base_address),1184"Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));1185}1186}11871188if (!Metaspace::using_class_space()) {1189// Get the simple case out of the way first:1190// no compressed class space, simple allocation.1191archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,1192os::vm_page_size(), (char*)base_address);1193if (archive_space_rs.is_reserved()) {1194assert(base_address == NULL ||1195(address)archive_space_rs.base() == base_address, "Sanity");1196// Register archive space with NMT.1197MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);1198return archive_space_rs.base();1199}1200return NULL;1201}12021203#ifdef _LP6412041205// Complex case: two spaces adjacent to each other, both to be addressable1206// with narrow class pointers.1207// We reserve the whole range spanning both spaces, then split that range up.12081209const size_t class_space_alignment = Metaspace::reserve_alignment();12101211// To simplify matters, lets assume that metaspace alignment will always be1212// equal or a multiple of archive alignment.1213assert(is_power_of_2(class_space_alignment) &&1214is_power_of_2(archive_space_alignment) &&1215class_space_alignment >= archive_space_alignment,1216"Sanity");12171218const size_t class_space_size = CompressedClassSpaceSize;1219assert(CompressedClassSpaceSize > 0 &&1220is_aligned(CompressedClassSpaceSize, class_space_alignment),1221"CompressedClassSpaceSize malformed: "1222SIZE_FORMAT, CompressedClassSpaceSize);12231224const size_t ccs_begin_offset = align_up(base_address + archive_space_size,1225class_space_alignment) - base_address;1226const size_t gap_size = ccs_begin_offset - archive_space_size;12271228const size_t total_range_size =1229align_up(archive_space_size + gap_size + class_space_size, core_region_alignment());12301231assert(total_range_size > ccs_begin_offset, "must be");1232if (use_windows_memory_mapping() && use_archive_base_addr) {1233if (base_address != nullptr) {1234// On Windows, we cannot safely split a reserved memory space into two (see JDK-8255917).1235// Hence, we optimistically reserve archive space and class space side-by-side. We only1236// do this for use_archive_base_addr=true since for use_archive_base_addr=false case1237// caller will not split the combined space for mapping, instead read the archive data1238// via sequential file IO.1239address ccs_base = base_address + archive_space_size + gap_size;1240archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,1241os::vm_page_size(), (char*)base_address);1242class_space_rs = ReservedSpace(class_space_size, class_space_alignment,1243os::vm_page_size(), (char*)ccs_base);1244}1245if (!archive_space_rs.is_reserved() || !class_space_rs.is_reserved()) {1246release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);1247return NULL;1248}1249} else {1250if (use_archive_base_addr && base_address != nullptr) {1251total_space_rs = ReservedSpace(total_range_size, archive_space_alignment,1252os::vm_page_size(), (char*) base_address);1253} else {1254// Reserve at any address, but leave it up to the platform to choose a good one.1255total_space_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size);1256}12571258if (!total_space_rs.is_reserved()) {1259return NULL;1260}12611262// Paranoid checks:1263assert(base_address == NULL || (address)total_space_rs.base() == base_address,1264"Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_space_rs.base()));1265assert(is_aligned(total_space_rs.base(), archive_space_alignment), "Sanity");1266assert(total_space_rs.size() == total_range_size, "Sanity");1267assert(CompressedKlassPointers::is_valid_base((address)total_space_rs.base()), "Sanity");12681269// Now split up the space into ccs and cds archive. For simplicity, just leave1270// the gap reserved at the end of the archive space. Do not do real splitting.1271archive_space_rs = total_space_rs.first_part(ccs_begin_offset,1272(size_t)archive_space_alignment);1273class_space_rs = total_space_rs.last_part(ccs_begin_offset);1274MemTracker::record_virtual_memory_split_reserved(total_space_rs.base(), total_space_rs.size(),1275ccs_begin_offset);1276}1277assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");1278assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");1279assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");1280assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");12811282// NMT: fix up the space tags1283MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);1284MemTracker::record_virtual_memory_type(class_space_rs.base(), mtClass);12851286return archive_space_rs.base();12871288#else1289ShouldNotReachHere();1290return NULL;1291#endif12921293}12941295void MetaspaceShared::release_reserved_spaces(ReservedSpace& total_space_rs,1296ReservedSpace& archive_space_rs,1297ReservedSpace& class_space_rs) {1298if (total_space_rs.is_reserved()) {1299log_debug(cds)("Released shared space (archive + class) " INTPTR_FORMAT, p2i(total_space_rs.base()));1300total_space_rs.release();1301} else {1302if (archive_space_rs.is_reserved()) {1303log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));1304archive_space_rs.release();1305}1306if (class_space_rs.is_reserved()) {1307log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));1308class_space_rs.release();1309}1310}1311}13121313static int archive_regions[] = { MetaspaceShared::rw, MetaspaceShared::ro };1314static int archive_regions_count = 2;13151316MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {1317assert(UseSharedSpaces, "must be runtime");1318if (mapinfo == NULL) {1319return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.1320}13211322mapinfo->set_is_mapped(false);1323if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {1324log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT1325" actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());1326return MAP_ARCHIVE_OTHER_FAILURE;1327}13281329MapArchiveResult result =1330mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);13311332if (result != MAP_ARCHIVE_SUCCESS) {1333unmap_archive(mapinfo);1334return result;1335}13361337if (!mapinfo->validate_shared_path_table()) {1338unmap_archive(mapinfo);1339return MAP_ARCHIVE_OTHER_FAILURE;1340}13411342mapinfo->set_is_mapped(true);1343return MAP_ARCHIVE_SUCCESS;1344}13451346void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) {1347assert(UseSharedSpaces, "must be runtime");1348if (mapinfo != NULL) {1349mapinfo->unmap_regions(archive_regions, archive_regions_count);1350mapinfo->unmap_region(MetaspaceShared::bm);1351mapinfo->set_is_mapped(false);1352}1353}13541355// For -XX:PrintSharedArchiveAndExit1356class CountSharedSymbols : public SymbolClosure {1357private:1358int _count;1359public:1360CountSharedSymbols() : _count(0) {}1361void do_symbol(Symbol** sym) {1362_count++;1363}1364int total() { return _count; }13651366};13671368// Read the miscellaneous data from the shared file, and1369// serialize it out to its various destinations.13701371void MetaspaceShared::initialize_shared_spaces() {1372FileMapInfo *static_mapinfo = FileMapInfo::current_info();13731374// Verify various attributes of the archive, plus initialize the1375// shared string/symbol tables1376char* buffer = static_mapinfo->serialized_data();1377intptr_t* array = (intptr_t*)buffer;1378ReadClosure rc(&array);1379serialize(&rc);13801381// Initialize the run-time symbol table.1382SymbolTable::create_table();13831384static_mapinfo->patch_archived_heap_embedded_pointers();13851386// Close the mapinfo file1387static_mapinfo->close();13881389static_mapinfo->unmap_region(MetaspaceShared::bm);13901391FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();1392if (dynamic_mapinfo != NULL) {1393intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();1394ReadClosure rc(&buffer);1395SymbolTable::serialize_shared_table_header(&rc, false);1396SystemDictionaryShared::serialize_dictionary_headers(&rc, false);1397dynamic_mapinfo->close();1398dynamic_mapinfo->unmap_region(MetaspaceShared::bm);1399}14001401// Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump1402if (DynamicDumpSharedSpaces) {1403// Read stored LF format lines stored in static archive1404LambdaFormInvokers::read_static_archive_invokers();1405}14061407if (PrintSharedArchiveAndExit) {1408// Print archive names1409if (dynamic_mapinfo != nullptr) {1410tty->print_cr("\n\nBase archive name: %s", Arguments::GetSharedArchivePath());1411tty->print_cr("Base archive version %d", static_mapinfo->version());1412} else {1413tty->print_cr("Static archive name: %s", static_mapinfo->full_path());1414tty->print_cr("Static archive version %d", static_mapinfo->version());1415}14161417SystemDictionaryShared::print_shared_archive(tty);1418if (dynamic_mapinfo != nullptr) {1419tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());1420tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());1421SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);1422}14231424// collect shared symbols and strings1425CountSharedSymbols cl;1426SymbolTable::shared_symbols_do(&cl);1427tty->print_cr("Number of shared symbols: %d", cl.total());1428tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());1429tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());1430if (FileMapInfo::current_info() == NULL || _archive_loading_failed) {1431tty->print_cr("archive is invalid");1432vm_exit(1);1433} else {1434tty->print_cr("archive is valid");1435vm_exit(0);1436}1437}1438}14391440// JVM/TI RedefineClasses() support:1441bool MetaspaceShared::remap_shared_readonly_as_readwrite() {1442assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");14431444if (UseSharedSpaces) {1445// remap the shared readonly space to shared readwrite, private1446FileMapInfo* mapinfo = FileMapInfo::current_info();1447if (!mapinfo->remap_shared_readonly_as_readwrite()) {1448return false;1449}1450if (FileMapInfo::dynamic_info() != NULL) {1451mapinfo = FileMapInfo::dynamic_info();1452if (!mapinfo->remap_shared_readonly_as_readwrite()) {1453return false;1454}1455}1456_remapped_readwrite = true;1457}1458return true;1459}14601461bool MetaspaceShared::use_full_module_graph() {1462#if INCLUDE_CDS_JAVA_HEAP1463if (ClassLoaderDataShared::is_full_module_graph_loaded()) {1464return true;1465}1466#endif1467bool result = _use_optimized_module_handling && _use_full_module_graph &&1468(UseSharedSpaces || DumpSharedSpaces) && HeapShared::is_heap_object_archiving_allowed();1469if (result && UseSharedSpaces) {1470// Classes used by the archived full module graph are loaded in JVMTI early phase.1471assert(!(JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()),1472"CDS should be disabled if early class hooks are enabled");1473}1474return result;1475}14761477void MetaspaceShared::print_on(outputStream* st) {1478if (UseSharedSpaces) {1479st->print("CDS archive(s) mapped at: ");1480address base = (address)MetaspaceObj::shared_metaspace_base();1481address static_top = (address)_shared_metaspace_static_top;1482address top = (address)MetaspaceObj::shared_metaspace_top();1483st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));1484st->print("size " SIZE_FORMAT ", ", top - base);1485st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, (int)ArchiveRelocationMode);1486} else {1487st->print("CDS archive(s) not mapped");1488}1489st->cr();1490}149114921493