Path: blob/master/src/hotspot/share/cds/archiveBuilder.cpp
41145 views
/*1* Copyright (c) 2020, 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 "cds/archiveBuilder.hpp"26#include "cds/archiveUtils.hpp"27#include "cds/cppVtables.hpp"28#include "cds/dumpAllocStats.hpp"29#include "cds/metaspaceShared.hpp"30#include "classfile/classLoaderDataShared.hpp"31#include "classfile/symbolTable.hpp"32#include "classfile/systemDictionaryShared.hpp"33#include "classfile/vmClasses.hpp"34#include "interpreter/abstractInterpreter.hpp"35#include "logging/log.hpp"36#include "logging/logStream.hpp"37#include "memory/allStatic.hpp"38#include "memory/memRegion.hpp"39#include "memory/resourceArea.hpp"40#include "oops/instanceKlass.hpp"41#include "oops/objArrayKlass.hpp"42#include "oops/oopHandle.inline.hpp"43#include "runtime/arguments.hpp"44#include "runtime/globals_extension.hpp"45#include "runtime/sharedRuntime.hpp"46#include "runtime/thread.hpp"47#include "utilities/align.hpp"48#include "utilities/bitMap.inline.hpp"49#include "utilities/formatBuffer.hpp"50#include "utilities/hashtable.inline.hpp"5152ArchiveBuilder* ArchiveBuilder::_current = NULL;5354ArchiveBuilder::OtherROAllocMark::~OtherROAllocMark() {55char* newtop = ArchiveBuilder::current()->_ro_region.top();56ArchiveBuilder::alloc_stats()->record_other_type(int(newtop - _oldtop), true);57}5859ArchiveBuilder::SourceObjList::SourceObjList() : _ptrmap(16 * K) {60_total_bytes = 0;61_objs = new (ResourceObj::C_HEAP, mtClassShared) GrowableArray<SourceObjInfo*>(128 * K, mtClassShared);62}6364ArchiveBuilder::SourceObjList::~SourceObjList() {65delete _objs;66}6768void ArchiveBuilder::SourceObjList::append(MetaspaceClosure::Ref* enclosing_ref, SourceObjInfo* src_info) {69// Save this source object for copying70_objs->append(src_info);7172// Prepare for marking the pointers in this source object73assert(is_aligned(_total_bytes, sizeof(address)), "must be");74src_info->set_ptrmap_start(_total_bytes / sizeof(address));75_total_bytes = align_up(_total_bytes + (uintx)src_info->size_in_bytes(), sizeof(address));76src_info->set_ptrmap_end(_total_bytes / sizeof(address));7778BitMap::idx_t bitmap_size_needed = BitMap::idx_t(src_info->ptrmap_end());79if (_ptrmap.size() <= bitmap_size_needed) {80_ptrmap.resize((bitmap_size_needed + 1) * 2);81}82}8384void ArchiveBuilder::SourceObjList::remember_embedded_pointer(SourceObjInfo* src_info, MetaspaceClosure::Ref* ref) {85// src_obj contains a pointer. Remember the location of this pointer in _ptrmap,86// so that we can copy/relocate it later. E.g., if we have87// class Foo { intx scala; Bar* ptr; }88// Foo *f = 0x100;89// To mark the f->ptr pointer on 64-bit platform, this function is called with90// src_info()->obj() == 0x10091// ref->addr() == 0x10892address src_obj = src_info->obj();93address* field_addr = ref->addr();94assert(src_info->ptrmap_start() < _total_bytes, "sanity");95assert(src_info->ptrmap_end() <= _total_bytes, "sanity");96assert(*field_addr != NULL, "should have checked");9798intx field_offset_in_bytes = ((address)field_addr) - src_obj;99DEBUG_ONLY(int src_obj_size = src_info->size_in_bytes();)100assert(field_offset_in_bytes >= 0, "must be");101assert(field_offset_in_bytes + intx(sizeof(intptr_t)) <= intx(src_obj_size), "must be");102assert(is_aligned(field_offset_in_bytes, sizeof(address)), "must be");103104BitMap::idx_t idx = BitMap::idx_t(src_info->ptrmap_start() + (uintx)(field_offset_in_bytes / sizeof(address)));105_ptrmap.set_bit(BitMap::idx_t(idx));106}107108class RelocateEmbeddedPointers : public BitMapClosure {109ArchiveBuilder* _builder;110address _dumped_obj;111BitMap::idx_t _start_idx;112public:113RelocateEmbeddedPointers(ArchiveBuilder* builder, address dumped_obj, BitMap::idx_t start_idx) :114_builder(builder), _dumped_obj(dumped_obj), _start_idx(start_idx) {}115116bool do_bit(BitMap::idx_t bit_offset) {117uintx FLAG_MASK = 0x03; // See comments around MetaspaceClosure::FLAG_MASK118size_t field_offset = size_t(bit_offset - _start_idx) * sizeof(address);119address* ptr_loc = (address*)(_dumped_obj + field_offset);120121uintx old_p_and_bits = (uintx)(*ptr_loc);122uintx flag_bits = (old_p_and_bits & FLAG_MASK);123address old_p = (address)(old_p_and_bits & (~FLAG_MASK));124address new_p = _builder->get_dumped_addr(old_p);125uintx new_p_and_bits = ((uintx)new_p) | flag_bits;126127log_trace(cds)("Ref: [" PTR_FORMAT "] -> " PTR_FORMAT " => " PTR_FORMAT,128p2i(ptr_loc), p2i(old_p), p2i(new_p));129130ArchivePtrMarker::set_and_mark_pointer(ptr_loc, (address)(new_p_and_bits));131return true; // keep iterating the bitmap132}133};134135void ArchiveBuilder::SourceObjList::relocate(int i, ArchiveBuilder* builder) {136SourceObjInfo* src_info = objs()->at(i);137assert(src_info->should_copy(), "must be");138BitMap::idx_t start = BitMap::idx_t(src_info->ptrmap_start()); // inclusive139BitMap::idx_t end = BitMap::idx_t(src_info->ptrmap_end()); // exclusive140141RelocateEmbeddedPointers relocator(builder, src_info->dumped_addr(), start);142_ptrmap.iterate(&relocator, start, end);143}144145ArchiveBuilder::ArchiveBuilder() :146_current_dump_space(NULL),147_buffer_bottom(NULL),148_last_verified_top(NULL),149_num_dump_regions_used(0),150_other_region_used_bytes(0),151_requested_static_archive_bottom(NULL),152_requested_static_archive_top(NULL),153_requested_dynamic_archive_bottom(NULL),154_requested_dynamic_archive_top(NULL),155_mapped_static_archive_bottom(NULL),156_mapped_static_archive_top(NULL),157_buffer_to_requested_delta(0),158_rw_region("rw", MAX_SHARED_DELTA),159_ro_region("ro", MAX_SHARED_DELTA),160_rw_src_objs(),161_ro_src_objs(),162_src_obj_table(INITIAL_TABLE_SIZE),163_num_instance_klasses(0),164_num_obj_array_klasses(0),165_num_type_array_klasses(0),166_total_closed_heap_region_size(0),167_total_open_heap_region_size(0),168_estimated_metaspaceobj_bytes(0),169_estimated_hashtable_bytes(0)170{171_klasses = new (ResourceObj::C_HEAP, mtClassShared) GrowableArray<Klass*>(4 * K, mtClassShared);172_symbols = new (ResourceObj::C_HEAP, mtClassShared) GrowableArray<Symbol*>(256 * K, mtClassShared);173_special_refs = new (ResourceObj::C_HEAP, mtClassShared) GrowableArray<SpecialRefInfo>(24 * K, mtClassShared);174175assert(_current == NULL, "must be");176_current = this;177}178179ArchiveBuilder::~ArchiveBuilder() {180assert(_current == this, "must be");181_current = NULL;182183clean_up_src_obj_table();184185for (int i = 0; i < _symbols->length(); i++) {186_symbols->at(i)->decrement_refcount();187}188189delete _klasses;190delete _symbols;191delete _special_refs;192}193194bool ArchiveBuilder::is_dumping_full_module_graph() {195return DumpSharedSpaces && MetaspaceShared::use_full_module_graph();196}197198class GatherKlassesAndSymbols : public UniqueMetaspaceClosure {199ArchiveBuilder* _builder;200201public:202GatherKlassesAndSymbols(ArchiveBuilder* builder) : _builder(builder) {}203204virtual bool do_unique_ref(Ref* ref, bool read_only) {205return _builder->gather_klass_and_symbol(ref, read_only);206}207};208209bool ArchiveBuilder::gather_klass_and_symbol(MetaspaceClosure::Ref* ref, bool read_only) {210if (ref->obj() == NULL) {211return false;212}213if (get_follow_mode(ref) != make_a_copy) {214return false;215}216if (ref->msotype() == MetaspaceObj::ClassType) {217Klass* klass = (Klass*)ref->obj();218assert(klass->is_klass(), "must be");219if (!is_excluded(klass)) {220_klasses->append(klass);221if (klass->is_instance_klass()) {222_num_instance_klasses ++;223} else if (klass->is_objArray_klass()) {224_num_obj_array_klasses ++;225} else {226assert(klass->is_typeArray_klass(), "sanity");227_num_type_array_klasses ++;228}229}230// See RunTimeSharedClassInfo::get_for()231_estimated_metaspaceobj_bytes += align_up(BytesPerWord, SharedSpaceObjectAlignment);232} else if (ref->msotype() == MetaspaceObj::SymbolType) {233// Make sure the symbol won't be GC'ed while we are dumping the archive.234Symbol* sym = (Symbol*)ref->obj();235sym->increment_refcount();236_symbols->append(sym);237}238239int bytes = ref->size() * BytesPerWord;240_estimated_metaspaceobj_bytes += align_up(bytes, SharedSpaceObjectAlignment);241242return true; // recurse243}244245void ArchiveBuilder::gather_klasses_and_symbols() {246ResourceMark rm;247log_info(cds)("Gathering classes and symbols ... ");248GatherKlassesAndSymbols doit(this);249iterate_roots(&doit, /*is_relocating_pointers=*/false);250#if INCLUDE_CDS_JAVA_HEAP251if (is_dumping_full_module_graph()) {252ClassLoaderDataShared::iterate_symbols(&doit);253}254#endif255doit.finish();256257log_info(cds)("Number of classes %d", _num_instance_klasses + _num_obj_array_klasses + _num_type_array_klasses);258log_info(cds)(" instance classes = %5d", _num_instance_klasses);259log_info(cds)(" obj array classes = %5d", _num_obj_array_klasses);260log_info(cds)(" type array classes = %5d", _num_type_array_klasses);261log_info(cds)(" symbols = %5d", _symbols->length());262263if (DumpSharedSpaces) {264// To ensure deterministic contents in the static archive, we need to ensure that265// we iterate the MetaspaceObjs in a deterministic order. It doesn't matter where266// the MetaspaceObjs are located originally, as they are copied sequentially into267// the archive during the iteration.268//269// The only issue here is that the symbol table and the system directories may be270// randomly ordered, so we copy the symbols and klasses into two arrays and sort271// them deterministically.272//273// During -Xshare:dump, the order of Symbol creation is strictly determined by274// the SharedClassListFile (class loading is done in a single thread and the JIT275// is disabled). Also, Symbols are allocated in monotonically increasing addresses276// (see Symbol::operator new(size_t, int)). So if we iterate the Symbols by277// ascending address order, we ensure that all Symbols are copied into deterministic278// locations in the archive.279//280// TODO: in the future, if we want to produce deterministic contents in the281// dynamic archive, we might need to sort the symbols alphabetically (also see282// DynamicArchiveBuilder::sort_methods()).283sort_symbols_and_fix_hash();284sort_klasses();285286// TODO -- we need a proper estimate for the archived modules, etc,287// but this should be enough for now288_estimated_metaspaceobj_bytes += 200 * 1024 * 1024;289}290}291292int ArchiveBuilder::compare_symbols_by_address(Symbol** a, Symbol** b) {293if (a[0] < b[0]) {294return -1;295} else {296assert(a[0] > b[0], "Duplicated symbol %s unexpected", (*a)->as_C_string());297return 1;298}299}300301void ArchiveBuilder::sort_symbols_and_fix_hash() {302log_info(cds)("Sorting symbols and fixing identity hash ... ");303os::init_random(0x12345678);304_symbols->sort(compare_symbols_by_address);305for (int i = 0; i < _symbols->length(); i++) {306assert(_symbols->at(i)->is_permanent(), "archived symbols must be permanent");307_symbols->at(i)->update_identity_hash();308}309}310311int ArchiveBuilder::compare_klass_by_name(Klass** a, Klass** b) {312return a[0]->name()->fast_compare(b[0]->name());313}314315void ArchiveBuilder::sort_klasses() {316log_info(cds)("Sorting classes ... ");317_klasses->sort(compare_klass_by_name);318}319320size_t ArchiveBuilder::estimate_archive_size() {321// size of the symbol table and two dictionaries, plus the RunTimeSharedClassInfo's322size_t symbol_table_est = SymbolTable::estimate_size_for_archive();323size_t dictionary_est = SystemDictionaryShared::estimate_size_for_archive();324_estimated_hashtable_bytes = symbol_table_est + dictionary_est;325326size_t total = 0;327328total += _estimated_metaspaceobj_bytes;329total += _estimated_hashtable_bytes;330331// allow fragmentation at the end of each dump region332total += _total_dump_regions * MetaspaceShared::core_region_alignment();333334log_info(cds)("_estimated_hashtable_bytes = " SIZE_FORMAT " + " SIZE_FORMAT " = " SIZE_FORMAT,335symbol_table_est, dictionary_est, _estimated_hashtable_bytes);336log_info(cds)("_estimated_metaspaceobj_bytes = " SIZE_FORMAT, _estimated_metaspaceobj_bytes);337log_info(cds)("total estimate bytes = " SIZE_FORMAT, total);338339return align_up(total, MetaspaceShared::core_region_alignment());340}341342address ArchiveBuilder::reserve_buffer() {343size_t buffer_size = estimate_archive_size();344ReservedSpace rs(buffer_size, MetaspaceShared::core_region_alignment(), os::vm_page_size());345if (!rs.is_reserved()) {346log_error(cds)("Failed to reserve " SIZE_FORMAT " bytes of output buffer.", buffer_size);347vm_direct_exit(0);348}349350// buffer_bottom is the lowest address of the 2 core regions (rw, ro) when351// we are copying the class metadata into the buffer.352address buffer_bottom = (address)rs.base();353log_info(cds)("Reserved output buffer space at " PTR_FORMAT " [" SIZE_FORMAT " bytes]",354p2i(buffer_bottom), buffer_size);355_shared_rs = rs;356357_buffer_bottom = buffer_bottom;358_last_verified_top = buffer_bottom;359_current_dump_space = &_rw_region;360_num_dump_regions_used = 1;361_other_region_used_bytes = 0;362_current_dump_space->init(&_shared_rs, &_shared_vs);363364ArchivePtrMarker::initialize(&_ptrmap, &_shared_vs);365366// The bottom of the static archive should be mapped at this address by default.367_requested_static_archive_bottom = (address)MetaspaceShared::requested_base_address();368369// The bottom of the archive (that I am writing now) should be mapped at this address by default.370address my_archive_requested_bottom;371372if (DumpSharedSpaces) {373my_archive_requested_bottom = _requested_static_archive_bottom;374} else {375_mapped_static_archive_bottom = (address)MetaspaceObj::shared_metaspace_base();376_mapped_static_archive_top = (address)MetaspaceObj::shared_metaspace_top();377assert(_mapped_static_archive_top >= _mapped_static_archive_bottom, "must be");378size_t static_archive_size = _mapped_static_archive_top - _mapped_static_archive_bottom;379380// At run time, we will mmap the dynamic archive at my_archive_requested_bottom381_requested_static_archive_top = _requested_static_archive_bottom + static_archive_size;382my_archive_requested_bottom = align_up(_requested_static_archive_top, MetaspaceShared::core_region_alignment());383384_requested_dynamic_archive_bottom = my_archive_requested_bottom;385}386387_buffer_to_requested_delta = my_archive_requested_bottom - _buffer_bottom;388389address my_archive_requested_top = my_archive_requested_bottom + buffer_size;390if (my_archive_requested_bottom < _requested_static_archive_bottom ||391my_archive_requested_top <= _requested_static_archive_bottom) {392// Size overflow.393log_error(cds)("my_archive_requested_bottom = " INTPTR_FORMAT, p2i(my_archive_requested_bottom));394log_error(cds)("my_archive_requested_top = " INTPTR_FORMAT, p2i(my_archive_requested_top));395log_error(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is too high. "396"Please rerun java -Xshare:dump with a lower value", p2i(_requested_static_archive_bottom));397vm_direct_exit(0);398}399400if (DumpSharedSpaces) {401// We don't want any valid object to be at the very bottom of the archive.402// See ArchivePtrMarker::mark_pointer().403rw_region()->allocate(16);404}405406return buffer_bottom;407}408409void ArchiveBuilder::iterate_sorted_roots(MetaspaceClosure* it, bool is_relocating_pointers) {410int i;411412if (!is_relocating_pointers) {413// Don't relocate _symbol, so we can safely call decrement_refcount on the414// original symbols.415int num_symbols = _symbols->length();416for (i = 0; i < num_symbols; i++) {417it->push(_symbols->adr_at(i));418}419}420421int num_klasses = _klasses->length();422for (i = 0; i < num_klasses; i++) {423it->push(_klasses->adr_at(i));424}425426iterate_roots(it, is_relocating_pointers);427}428429class GatherSortedSourceObjs : public MetaspaceClosure {430ArchiveBuilder* _builder;431432public:433GatherSortedSourceObjs(ArchiveBuilder* builder) : _builder(builder) {}434435virtual bool do_ref(Ref* ref, bool read_only) {436return _builder->gather_one_source_obj(enclosing_ref(), ref, read_only);437}438439virtual void push_special(SpecialRef type, Ref* ref, intptr_t* p) {440assert(type == _method_entry_ref, "only special type allowed for now");441address src_obj = ref->obj();442size_t field_offset = pointer_delta(p, src_obj, sizeof(u1));443_builder->add_special_ref(type, src_obj, field_offset);444};445446virtual void do_pending_ref(Ref* ref) {447if (ref->obj() != NULL) {448_builder->remember_embedded_pointer_in_copied_obj(enclosing_ref(), ref);449}450}451};452453bool ArchiveBuilder::gather_one_source_obj(MetaspaceClosure::Ref* enclosing_ref,454MetaspaceClosure::Ref* ref, bool read_only) {455address src_obj = ref->obj();456if (src_obj == NULL) {457return false;458}459ref->set_keep_after_pushing();460remember_embedded_pointer_in_copied_obj(enclosing_ref, ref);461462FollowMode follow_mode = get_follow_mode(ref);463SourceObjInfo src_info(ref, read_only, follow_mode);464bool created;465SourceObjInfo* p = _src_obj_table.add_if_absent(src_obj, src_info, &created);466if (created) {467if (_src_obj_table.maybe_grow(MAX_TABLE_SIZE)) {468log_info(cds, hashtables)("Expanded _src_obj_table table to %d", _src_obj_table.table_size());469}470}471472assert(p->read_only() == src_info.read_only(), "must be");473474if (created && src_info.should_copy()) {475ref->set_user_data((void*)p);476if (read_only) {477_ro_src_objs.append(enclosing_ref, p);478} else {479_rw_src_objs.append(enclosing_ref, p);480}481return true; // Need to recurse into this ref only if we are copying it482} else {483return false;484}485}486487void ArchiveBuilder::add_special_ref(MetaspaceClosure::SpecialRef type, address src_obj, size_t field_offset) {488_special_refs->append(SpecialRefInfo(type, src_obj, field_offset));489}490491void ArchiveBuilder::remember_embedded_pointer_in_copied_obj(MetaspaceClosure::Ref* enclosing_ref,492MetaspaceClosure::Ref* ref) {493assert(ref->obj() != NULL, "should have checked");494495if (enclosing_ref != NULL) {496SourceObjInfo* src_info = (SourceObjInfo*)enclosing_ref->user_data();497if (src_info == NULL) {498// source objects of point_to_it/set_to_null types are not copied499// so we don't need to remember their pointers.500} else {501if (src_info->read_only()) {502_ro_src_objs.remember_embedded_pointer(src_info, ref);503} else {504_rw_src_objs.remember_embedded_pointer(src_info, ref);505}506}507}508}509510void ArchiveBuilder::gather_source_objs() {511ResourceMark rm;512log_info(cds)("Gathering all archivable objects ... ");513gather_klasses_and_symbols();514GatherSortedSourceObjs doit(this);515iterate_sorted_roots(&doit, /*is_relocating_pointers=*/false);516doit.finish();517}518519bool ArchiveBuilder::is_excluded(Klass* klass) {520if (klass->is_instance_klass()) {521InstanceKlass* ik = InstanceKlass::cast(klass);522return SystemDictionaryShared::is_excluded_class(ik);523} else if (klass->is_objArray_klass()) {524if (DynamicDumpSharedSpaces) {525// Don't support archiving of array klasses for now (WHY???)526return true;527}528Klass* bottom = ObjArrayKlass::cast(klass)->bottom_klass();529if (bottom->is_instance_klass()) {530return SystemDictionaryShared::is_excluded_class(InstanceKlass::cast(bottom));531}532}533534return false;535}536537ArchiveBuilder::FollowMode ArchiveBuilder::get_follow_mode(MetaspaceClosure::Ref *ref) {538address obj = ref->obj();539if (MetaspaceShared::is_in_shared_metaspace(obj)) {540// Don't dump existing shared metadata again.541return point_to_it;542} else if (ref->msotype() == MetaspaceObj::MethodDataType) {543return set_to_null;544} else {545if (ref->msotype() == MetaspaceObj::ClassType) {546Klass* klass = (Klass*)ref->obj();547assert(klass->is_klass(), "must be");548if (is_excluded(klass)) {549ResourceMark rm;550log_debug(cds, dynamic)("Skipping class (excluded): %s", klass->external_name());551return set_to_null;552}553}554555return make_a_copy;556}557}558559void ArchiveBuilder::start_dump_space(DumpRegion* next) {560address bottom = _last_verified_top;561address top = (address)(current_dump_space()->top());562_other_region_used_bytes += size_t(top - bottom);563564current_dump_space()->pack(next);565_current_dump_space = next;566_num_dump_regions_used ++;567568_last_verified_top = (address)(current_dump_space()->top());569}570571void ArchiveBuilder::verify_estimate_size(size_t estimate, const char* which) {572address bottom = _last_verified_top;573address top = (address)(current_dump_space()->top());574size_t used = size_t(top - bottom) + _other_region_used_bytes;575int diff = int(estimate) - int(used);576577log_info(cds)("%s estimate = " SIZE_FORMAT " used = " SIZE_FORMAT "; diff = %d bytes", which, estimate, used, diff);578assert(diff >= 0, "Estimate is too small");579580_last_verified_top = top;581_other_region_used_bytes = 0;582}583584void ArchiveBuilder::dump_rw_metadata() {585ResourceMark rm;586log_info(cds)("Allocating RW objects ... ");587make_shallow_copies(&_rw_region, &_rw_src_objs);588589#if INCLUDE_CDS_JAVA_HEAP590if (is_dumping_full_module_graph()) {591// Archive the ModuleEntry's and PackageEntry's of the 3 built-in loaders592char* start = rw_region()->top();593ClassLoaderDataShared::allocate_archived_tables();594alloc_stats()->record_modules(rw_region()->top() - start, /*read_only*/false);595}596#endif597}598599void ArchiveBuilder::dump_ro_metadata() {600ResourceMark rm;601log_info(cds)("Allocating RO objects ... ");602603start_dump_space(&_ro_region);604make_shallow_copies(&_ro_region, &_ro_src_objs);605606#if INCLUDE_CDS_JAVA_HEAP607if (is_dumping_full_module_graph()) {608char* start = ro_region()->top();609ClassLoaderDataShared::init_archived_tables();610alloc_stats()->record_modules(ro_region()->top() - start, /*read_only*/true);611}612#endif613}614615void ArchiveBuilder::make_shallow_copies(DumpRegion *dump_region,616const ArchiveBuilder::SourceObjList* src_objs) {617for (int i = 0; i < src_objs->objs()->length(); i++) {618make_shallow_copy(dump_region, src_objs->objs()->at(i));619}620log_info(cds)("done (%d objects)", src_objs->objs()->length());621}622623void ArchiveBuilder::make_shallow_copy(DumpRegion *dump_region, SourceObjInfo* src_info) {624MetaspaceClosure::Ref* ref = src_info->ref();625address src = ref->obj();626int bytes = src_info->size_in_bytes();627char* dest;628char* oldtop;629char* newtop;630631oldtop = dump_region->top();632if (ref->msotype() == MetaspaceObj::ClassType) {633// Save a pointer immediate in front of an InstanceKlass, so634// we can do a quick lookup from InstanceKlass* -> RunTimeSharedClassInfo*635// without building another hashtable. See RunTimeSharedClassInfo::get_for()636// in systemDictionaryShared.cpp.637Klass* klass = (Klass*)src;638if (klass->is_instance_klass()) {639SystemDictionaryShared::validate_before_archiving(InstanceKlass::cast(klass));640dump_region->allocate(sizeof(address));641}642}643dest = dump_region->allocate(bytes);644newtop = dump_region->top();645646memcpy(dest, src, bytes);647648intptr_t* archived_vtable = CppVtables::get_archived_vtable(ref->msotype(), (address)dest);649if (archived_vtable != NULL) {650*(address*)dest = (address)archived_vtable;651ArchivePtrMarker::mark_pointer((address*)dest);652}653654log_trace(cds)("Copy: " PTR_FORMAT " ==> " PTR_FORMAT " %d", p2i(src), p2i(dest), bytes);655src_info->set_dumped_addr((address)dest);656657_alloc_stats.record(ref->msotype(), int(newtop - oldtop), src_info->read_only());658}659660address ArchiveBuilder::get_dumped_addr(address src_obj) const {661SourceObjInfo* p = _src_obj_table.lookup(src_obj);662assert(p != NULL, "must be");663664return p->dumped_addr();665}666667void ArchiveBuilder::relocate_embedded_pointers(ArchiveBuilder::SourceObjList* src_objs) {668for (int i = 0; i < src_objs->objs()->length(); i++) {669src_objs->relocate(i, this);670}671}672673void ArchiveBuilder::update_special_refs() {674for (int i = 0; i < _special_refs->length(); i++) {675SpecialRefInfo s = _special_refs->at(i);676size_t field_offset = s.field_offset();677address src_obj = s.src_obj();678address dst_obj = get_dumped_addr(src_obj);679intptr_t* src_p = (intptr_t*)(src_obj + field_offset);680intptr_t* dst_p = (intptr_t*)(dst_obj + field_offset);681assert(s.type() == MetaspaceClosure::_method_entry_ref, "only special type allowed for now");682683assert(*src_p == *dst_p, "must be a copy");684ArchivePtrMarker::mark_pointer((address*)dst_p);685}686}687688class RefRelocator: public MetaspaceClosure {689ArchiveBuilder* _builder;690691public:692RefRelocator(ArchiveBuilder* builder) : _builder(builder) {}693694virtual bool do_ref(Ref* ref, bool read_only) {695if (ref->not_null()) {696ref->update(_builder->get_dumped_addr(ref->obj()));697ArchivePtrMarker::mark_pointer(ref->addr());698}699return false; // Do not recurse.700}701};702703void ArchiveBuilder::relocate_roots() {704log_info(cds)("Relocating external roots ... ");705ResourceMark rm;706RefRelocator doit(this);707iterate_sorted_roots(&doit, /*is_relocating_pointers=*/true);708doit.finish();709log_info(cds)("done");710}711712void ArchiveBuilder::relocate_metaspaceobj_embedded_pointers() {713log_info(cds)("Relocating embedded pointers in core regions ... ");714relocate_embedded_pointers(&_rw_src_objs);715relocate_embedded_pointers(&_ro_src_objs);716update_special_refs();717}718719// We must relocate vmClasses::_klasses[] only after we have copied the720// java objects in during dump_java_heap_objects(): during the object copy, we operate on721// old objects which assert that their klass is the original klass.722void ArchiveBuilder::relocate_vm_classes() {723log_info(cds)("Relocating vmClasses::_klasses[] ... ");724ResourceMark rm;725RefRelocator doit(this);726vmClasses::metaspace_pointers_do(&doit);727}728729void ArchiveBuilder::make_klasses_shareable() {730for (int i = 0; i < klasses()->length(); i++) {731Klass* k = klasses()->at(i);732k->remove_java_mirror();733if (k->is_objArray_klass()) {734// InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info735// on their array classes.736} else if (k->is_typeArray_klass()) {737k->remove_unshareable_info();738} else {739assert(k->is_instance_klass(), " must be");740InstanceKlass* ik = InstanceKlass::cast(k);741if (DynamicDumpSharedSpaces) {742// For static dump, class loader type are already set.743ik->assign_class_loader_type();744}745746MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread::current(), ik);747ik->remove_unshareable_info();748749if (log_is_enabled(Debug, cds, class)) {750ResourceMark rm;751log_debug(cds, class)("klasses[%4d] = " PTR_FORMAT " %s", i, p2i(to_requested(ik)), ik->external_name());752}753}754}755}756757uintx ArchiveBuilder::buffer_to_offset(address p) const {758address requested_p = to_requested(p);759assert(requested_p >= _requested_static_archive_bottom, "must be");760return requested_p - _requested_static_archive_bottom;761}762763uintx ArchiveBuilder::any_to_offset(address p) const {764if (is_in_mapped_static_archive(p)) {765assert(DynamicDumpSharedSpaces, "must be");766return p - _mapped_static_archive_bottom;767}768return buffer_to_offset(p);769}770771// Update a Java object to point its Klass* to the new location after772// shared archive has been compacted.773void ArchiveBuilder::relocate_klass_ptr(oop o) {774assert(DumpSharedSpaces, "sanity");775Klass* k = get_relocated_klass(o->klass());776Klass* requested_k = to_requested(k);777narrowKlass nk = CompressedKlassPointers::encode_not_null(requested_k, _requested_static_archive_bottom);778o->set_narrow_klass(nk);779}780781// RelocateBufferToRequested --- Relocate all the pointers in rw/ro,782// so that the archive can be mapped to the "requested" location without runtime relocation.783//784// - See ArchiveBuilder header for the definition of "buffer", "mapped" and "requested"785// - ArchivePtrMarker::ptrmap() marks all the pointers in the rw/ro regions786// - Every pointer must have one of the following values:787// [a] NULL:788// No relocation is needed. Remove this pointer from ptrmap so we don't need to789// consider it at runtime.790// [b] Points into an object X which is inside the buffer:791// Adjust this pointer by _buffer_to_requested_delta, so it points to X792// when the archive is mapped at the requested location.793// [c] Points into an object Y which is inside mapped static archive:794// - This happens only during dynamic dump795// - Adjust this pointer by _mapped_to_requested_static_archive_delta,796// so it points to Y when the static archive is mapped at the requested location.797template <bool STATIC_DUMP>798class RelocateBufferToRequested : public BitMapClosure {799ArchiveBuilder* _builder;800address _buffer_bottom;801intx _buffer_to_requested_delta;802intx _mapped_to_requested_static_archive_delta;803size_t _max_non_null_offset;804805public:806RelocateBufferToRequested(ArchiveBuilder* builder) {807_builder = builder;808_buffer_bottom = _builder->buffer_bottom();809_buffer_to_requested_delta = builder->buffer_to_requested_delta();810_mapped_to_requested_static_archive_delta = builder->requested_static_archive_bottom() - builder->mapped_static_archive_bottom();811_max_non_null_offset = 0;812813address bottom = _builder->buffer_bottom();814address top = _builder->buffer_top();815address new_bottom = bottom + _buffer_to_requested_delta;816address new_top = top + _buffer_to_requested_delta;817log_debug(cds)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT "] to "818"[" INTPTR_FORMAT " - " INTPTR_FORMAT "]",819p2i(bottom), p2i(top),820p2i(new_bottom), p2i(new_top));821}822823bool do_bit(size_t offset) {824address* p = (address*)_buffer_bottom + offset;825assert(_builder->is_in_buffer_space(p), "pointer must live in buffer space");826827if (*p == NULL) {828// todo -- clear bit, etc829ArchivePtrMarker::ptrmap()->clear_bit(offset);830} else {831if (STATIC_DUMP) {832assert(_builder->is_in_buffer_space(*p), "old pointer must point inside buffer space");833*p += _buffer_to_requested_delta;834assert(_builder->is_in_requested_static_archive(*p), "new pointer must point inside requested archive");835} else {836if (_builder->is_in_buffer_space(*p)) {837*p += _buffer_to_requested_delta;838// assert is in requested dynamic archive839} else {840assert(_builder->is_in_mapped_static_archive(*p), "old pointer must point inside buffer space or mapped static archive");841*p += _mapped_to_requested_static_archive_delta;842assert(_builder->is_in_requested_static_archive(*p), "new pointer must point inside requested archive");843}844}845_max_non_null_offset = offset;846}847848return true; // keep iterating849}850851void doit() {852ArchivePtrMarker::ptrmap()->iterate(this);853ArchivePtrMarker::compact(_max_non_null_offset);854}855};856857858void ArchiveBuilder::relocate_to_requested() {859ro_region()->pack();860861size_t my_archive_size = buffer_top() - buffer_bottom();862863if (DumpSharedSpaces) {864_requested_static_archive_top = _requested_static_archive_bottom + my_archive_size;865RelocateBufferToRequested<true> patcher(this);866patcher.doit();867} else {868assert(DynamicDumpSharedSpaces, "must be");869_requested_dynamic_archive_top = _requested_dynamic_archive_bottom + my_archive_size;870RelocateBufferToRequested<false> patcher(this);871patcher.doit();872}873}874875// Write detailed info to a mapfile to analyze contents of the archive.876// static dump:877// java -Xshare:dump -Xlog:cds+map=trace:file=cds.map:none:filesize=0878// dynamic dump:879// java -cp MyApp.jar -XX:ArchiveClassesAtExit=MyApp.jsa \880// -Xlog:cds+map=trace:file=cds.map:none:filesize=0 MyApp881//882// We need to do some address translation because the buffers used at dump time may be mapped to883// a different location at runtime. At dump time, the buffers may be at arbitrary locations884// picked by the OS. At runtime, we try to map at a fixed location (SharedBaseAddress). For885// consistency, we log everything using runtime addresses.886class ArchiveBuilder::CDSMapLogger : AllStatic {887static intx buffer_to_runtime_delta() {888// Translate the buffers used by the RW/RO regions to their eventual (requested) locations889// at runtime.890return ArchiveBuilder::current()->buffer_to_requested_delta();891}892893// rw/ro regions only894static void write_dump_region(const char* name, DumpRegion* region) {895address region_base = address(region->base());896address region_top = address(region->top());897write_region(name, region_base, region_top, region_base + buffer_to_runtime_delta());898}899900#define _LOG_PREFIX PTR_FORMAT ": @@ %-17s %d"901902static void write_klass(Klass* k, address runtime_dest, const char* type_name, int bytes, Thread* current) {903ResourceMark rm(current);904log_debug(cds, map)(_LOG_PREFIX " %s",905p2i(runtime_dest), type_name, bytes, k->external_name());906}907static void write_method(Method* m, address runtime_dest, const char* type_name, int bytes, Thread* current) {908ResourceMark rm(current);909log_debug(cds, map)(_LOG_PREFIX " %s",910p2i(runtime_dest), type_name, bytes, m->external_name());911}912913// rw/ro regions only914static void write_objects(DumpRegion* region, const ArchiveBuilder::SourceObjList* src_objs) {915address last_obj_base = address(region->base());916address last_obj_end = address(region->base());917address region_end = address(region->end());918Thread* current = Thread::current();919for (int i = 0; i < src_objs->objs()->length(); i++) {920SourceObjInfo* src_info = src_objs->at(i);921address src = src_info->orig_obj();922address dest = src_info->dumped_addr();923write_data(last_obj_base, dest, last_obj_base + buffer_to_runtime_delta());924address runtime_dest = dest + buffer_to_runtime_delta();925int bytes = src_info->size_in_bytes();926927MetaspaceObj::Type type = src_info->msotype();928const char* type_name = MetaspaceObj::type_name(type);929930switch (type) {931case MetaspaceObj::ClassType:932write_klass((Klass*)src, runtime_dest, type_name, bytes, current);933break;934case MetaspaceObj::ConstantPoolType:935write_klass(((ConstantPool*)src)->pool_holder(),936runtime_dest, type_name, bytes, current);937break;938case MetaspaceObj::ConstantPoolCacheType:939write_klass(((ConstantPoolCache*)src)->constant_pool()->pool_holder(),940runtime_dest, type_name, bytes, current);941break;942case MetaspaceObj::MethodType:943write_method((Method*)src, runtime_dest, type_name, bytes, current);944break;945case MetaspaceObj::ConstMethodType:946write_method(((ConstMethod*)src)->method(), runtime_dest, type_name, bytes, current);947break;948case MetaspaceObj::SymbolType:949{950ResourceMark rm(current);951Symbol* s = (Symbol*)src;952log_debug(cds, map)(_LOG_PREFIX " %s", p2i(runtime_dest), type_name, bytes,953s->as_quoted_ascii());954}955break;956default:957log_debug(cds, map)(_LOG_PREFIX, p2i(runtime_dest), type_name, bytes);958break;959}960961last_obj_base = dest;962last_obj_end = dest + bytes;963}964965write_data(last_obj_base, last_obj_end, last_obj_base + buffer_to_runtime_delta());966if (last_obj_end < region_end) {967log_debug(cds, map)(PTR_FORMAT ": @@ Misc data " SIZE_FORMAT " bytes",968p2i(last_obj_end + buffer_to_runtime_delta()),969size_t(region_end - last_obj_end));970write_data(last_obj_end, region_end, last_obj_end + buffer_to_runtime_delta());971}972}973974#undef _LOG_PREFIX975976// Write information about a region, whose address at dump time is [base .. top). At977// runtime, this region will be mapped to runtime_base. runtime_base is 0 if this978// region will be mapped at os-selected addresses (such as the bitmap region), or will979// be accessed with os::read (the header).980static void write_region(const char* name, address base, address top, address runtime_base) {981size_t size = top - base;982base = runtime_base;983top = runtime_base + size;984log_info(cds, map)("[%-18s " PTR_FORMAT " - " PTR_FORMAT " " SIZE_FORMAT_W(9) " bytes]",985name, p2i(base), p2i(top), size);986}987988// open and closed archive regions989static void write_heap_region(const char* which, GrowableArray<MemRegion> *regions) {990for (int i = 0; i < regions->length(); i++) {991address start = address(regions->at(i).start());992address end = address(regions->at(i).end());993write_region(which, start, end, start);994write_data(start, end, start);995}996}997998// Dump all the data [base...top). Pretend that the base address999// will be mapped to runtime_base at run-time.1000static void write_data(address base, address top, address runtime_base) {1001assert(top >= base, "must be");10021003LogStreamHandle(Trace, cds, map) lsh;1004if (lsh.is_enabled()) {1005os::print_hex_dump(&lsh, base, top, sizeof(address), 32, runtime_base);1006}1007}10081009static void write_header(FileMapInfo* mapinfo) {1010LogStreamHandle(Info, cds, map) lsh;1011if (lsh.is_enabled()) {1012mapinfo->print(&lsh);1013}1014}10151016public:1017static void write(ArchiveBuilder* builder, FileMapInfo* mapinfo,1018GrowableArray<MemRegion> *closed_heap_regions,1019GrowableArray<MemRegion> *open_heap_regions,1020char* bitmap, size_t bitmap_size_in_bytes) {1021log_info(cds, map)("%s CDS archive map for %s", DumpSharedSpaces ? "Static" : "Dynamic", mapinfo->full_path());10221023address header = address(mapinfo->header());1024address header_end = header + mapinfo->header()->header_size();1025write_region("header", header, header_end, 0);1026write_header(mapinfo);1027write_data(header, header_end, 0);10281029DumpRegion* rw_region = &builder->_rw_region;1030DumpRegion* ro_region = &builder->_ro_region;10311032write_dump_region("rw region", rw_region);1033write_objects(rw_region, &builder->_rw_src_objs);10341035write_dump_region("ro region", ro_region);1036write_objects(ro_region, &builder->_ro_src_objs);10371038address bitmap_end = address(bitmap + bitmap_size_in_bytes);1039write_region("bitmap", address(bitmap), bitmap_end, 0);1040write_data(header, header_end, 0);10411042if (closed_heap_regions != NULL) {1043write_heap_region("closed heap region", closed_heap_regions);1044}1045if (open_heap_regions != NULL) {1046write_heap_region("open heap region", open_heap_regions);1047}10481049log_info(cds, map)("[End of CDS archive map]");1050}1051};10521053void ArchiveBuilder::print_stats() {1054_alloc_stats.print_stats(int(_ro_region.used()), int(_rw_region.used()));1055}10561057void ArchiveBuilder::clean_up_src_obj_table() {1058SrcObjTableCleaner cleaner;1059_src_obj_table.iterate(&cleaner);1060}10611062void ArchiveBuilder::write_archive(FileMapInfo* mapinfo,1063GrowableArray<MemRegion>* closed_heap_regions,1064GrowableArray<MemRegion>* open_heap_regions,1065GrowableArray<ArchiveHeapOopmapInfo>* closed_heap_oopmaps,1066GrowableArray<ArchiveHeapOopmapInfo>* open_heap_oopmaps) {1067// Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with1068// MetaspaceShared::n_regions (internal to hotspot).1069assert(NUM_CDS_REGIONS == MetaspaceShared::n_regions, "sanity");10701071write_region(mapinfo, MetaspaceShared::rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);1072write_region(mapinfo, MetaspaceShared::ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);10731074size_t bitmap_size_in_bytes;1075char* bitmap = mapinfo->write_bitmap_region(ArchivePtrMarker::ptrmap(), closed_heap_oopmaps, open_heap_oopmaps,1076bitmap_size_in_bytes);10771078if (closed_heap_regions != NULL) {1079_total_closed_heap_region_size = mapinfo->write_archive_heap_regions(1080closed_heap_regions,1081closed_heap_oopmaps,1082MetaspaceShared::first_closed_archive_heap_region,1083MetaspaceShared::max_closed_archive_heap_region);1084_total_open_heap_region_size = mapinfo->write_archive_heap_regions(1085open_heap_regions,1086open_heap_oopmaps,1087MetaspaceShared::first_open_archive_heap_region,1088MetaspaceShared::max_open_archive_heap_region);1089}10901091print_region_stats(mapinfo, closed_heap_regions, open_heap_regions);10921093mapinfo->set_requested_base((char*)MetaspaceShared::requested_base_address());1094if (mapinfo->header()->magic() == CDS_DYNAMIC_ARCHIVE_MAGIC) {1095mapinfo->set_header_base_archive_name_size(strlen(Arguments::GetSharedArchivePath()) + 1);1096mapinfo->set_header_base_archive_is_default(FLAG_IS_DEFAULT(SharedArchiveFile));1097}1098mapinfo->set_header_crc(mapinfo->compute_header_crc());1099// After this point, we should not write any data into mapinfo->header() since this1100// would corrupt its checksum we have calculated before.1101mapinfo->write_header();1102mapinfo->close();11031104if (log_is_enabled(Info, cds)) {1105print_stats();1106}11071108if (log_is_enabled(Info, cds, map)) {1109CDSMapLogger::write(this, mapinfo, closed_heap_regions, open_heap_regions,1110bitmap, bitmap_size_in_bytes);1111}1112FREE_C_HEAP_ARRAY(char, bitmap);1113}11141115void ArchiveBuilder::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only, bool allow_exec) {1116mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);1117}11181119void ArchiveBuilder::print_region_stats(FileMapInfo *mapinfo,1120GrowableArray<MemRegion>* closed_heap_regions,1121GrowableArray<MemRegion>* open_heap_regions) {1122// Print statistics of all the regions1123const size_t bitmap_used = mapinfo->space_at(MetaspaceShared::bm)->used();1124const size_t bitmap_reserved = mapinfo->space_at(MetaspaceShared::bm)->used_aligned();1125const size_t total_reserved = _ro_region.reserved() + _rw_region.reserved() +1126bitmap_reserved +1127_total_closed_heap_region_size +1128_total_open_heap_region_size;1129const size_t total_bytes = _ro_region.used() + _rw_region.used() +1130bitmap_used +1131_total_closed_heap_region_size +1132_total_open_heap_region_size;1133const double total_u_perc = percent_of(total_bytes, total_reserved);11341135_rw_region.print(total_reserved);1136_ro_region.print(total_reserved);11371138print_bitmap_region_stats(bitmap_used, total_reserved);11391140if (closed_heap_regions != NULL) {1141print_heap_region_stats(closed_heap_regions, "ca", total_reserved);1142print_heap_region_stats(open_heap_regions, "oa", total_reserved);1143}11441145log_debug(cds)("total : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]",1146total_bytes, total_reserved, total_u_perc);1147}11481149void ArchiveBuilder::print_bitmap_region_stats(size_t size, size_t total_size) {1150log_debug(cds)("bm space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used]",1151size, size/double(total_size)*100.0, size);1152}11531154void ArchiveBuilder::print_heap_region_stats(GrowableArray<MemRegion> *heap_mem,1155const char *name, size_t total_size) {1156int arr_len = heap_mem == NULL ? 0 : heap_mem->length();1157for (int i = 0; i < arr_len; i++) {1158char* start = (char*)heap_mem->at(i).start();1159size_t size = heap_mem->at(i).byte_size();1160char* top = start + size;1161log_debug(cds)("%s%d space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used] at " INTPTR_FORMAT,1162name, i, size, size/double(total_size)*100.0, size, p2i(start));1163}1164}11651166void ArchiveBuilder::report_out_of_space(const char* name, size_t needed_bytes) {1167// This is highly unlikely to happen on 64-bits because we have reserved a 4GB space.1168// On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes1169// or so.1170_rw_region.print_out_of_space_msg(name, needed_bytes);1171_ro_region.print_out_of_space_msg(name, needed_bytes);11721173vm_exit_during_initialization(err_msg("Unable to allocate from '%s' region", name),1174"Please reduce the number of shared classes.");1175}117611771178#ifndef PRODUCT1179void ArchiveBuilder::assert_is_vm_thread() {1180assert(Thread::current()->is_VM_thread(), "ArchiveBuilder should be used only inside the VMThread");1181}1182#endif118311841185