Path: blob/master/src/hotspot/share/asm/codeBuffer.cpp
64440 views
/*1* Copyright (c) 1997, 2022, 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 "asm/codeBuffer.hpp"26#include "code/oopRecorder.inline.hpp"27#include "compiler/disassembler.hpp"28#include "logging/log.hpp"29#include "oops/klass.inline.hpp"30#include "oops/methodData.hpp"31#include "oops/oop.inline.hpp"32#include "runtime/icache.hpp"33#include "runtime/safepointVerifiers.hpp"34#include "utilities/align.hpp"35#include "utilities/copy.hpp"36#include "utilities/powerOfTwo.hpp"37#include "utilities/xmlstream.hpp"3839// The structure of a CodeSection:40//41// _start -> +----------------+42// | machine code...|43// _end -> |----------------|44// | |45// | (empty) |46// | |47// | |48// +----------------+49// _limit -> | |50//51// _locs_start -> +----------------+52// |reloc records...|53// |----------------|54// _locs_end -> | |55// | |56// | (empty) |57// | |58// | |59// +----------------+60// _locs_limit -> | |61// The _end (resp. _limit) pointer refers to the first62// unused (resp. unallocated) byte.6364// The structure of the CodeBuffer while code is being accumulated:65//66// _total_start -> \67// _insts._start -> +----------------+68// | |69// | Code |70// | |71// _stubs._start -> |----------------|72// | |73// | Stubs | (also handlers for deopt/exception)74// | |75// _consts._start -> |----------------|76// | |77// | Constants |78// | |79// +----------------+80// + _total_size -> | |81//82// When the code and relocations are copied to the code cache,83// the empty parts of each section are removed, and everything84// is copied into contiguous locations.8586typedef CodeBuffer::csize_t csize_t; // file-local definition8788// External buffer, in a predefined CodeBlob.89// Important: The code_start must be taken exactly, and not realigned.90CodeBuffer::CodeBuffer(CodeBlob* blob) {91// Provide code buffer with meaningful name92initialize_misc(blob->name());93initialize(blob->content_begin(), blob->content_size());94debug_only(verify_section_allocation();)95}9697void CodeBuffer::initialize(csize_t code_size, csize_t locs_size) {98// Compute maximal alignment.99int align = _insts.alignment();100// Always allow for empty slop around each section.101int slop = (int) CodeSection::end_slop();102103assert(blob() == NULL, "only once");104set_blob(BufferBlob::create(_name, code_size + (align+slop) * (SECT_LIMIT+1)));105if (blob() == NULL) {106// The assembler constructor will throw a fatal on an empty CodeBuffer.107return; // caller must test this108}109110// Set up various pointers into the blob.111initialize(_total_start, _total_size);112113assert((uintptr_t)insts_begin() % CodeEntryAlignment == 0, "instruction start not code entry aligned");114115pd_initialize();116117if (locs_size != 0) {118_insts.initialize_locs(locs_size / sizeof(relocInfo));119}120121debug_only(verify_section_allocation();)122}123124125CodeBuffer::~CodeBuffer() {126verify_section_allocation();127128// If we allocate our code buffer from the CodeCache129// via a BufferBlob, and it's not permanent, then130// free the BufferBlob.131// The rest of the memory will be freed when the ResourceObj132// is released.133for (CodeBuffer* cb = this; cb != NULL; cb = cb->before_expand()) {134// Previous incarnations of this buffer are held live, so that internal135// addresses constructed before expansions will not be confused.136cb->free_blob();137// free any overflow storage138delete cb->_overflow_arena;139}140141// Claim is that stack allocation ensures resources are cleaned up.142// This is resource clean up, let's hope that all were properly copied out.143NOT_PRODUCT(free_strings();)144145#ifdef ASSERT146// Save allocation type to execute assert in ~ResourceObj()147// which is called after this destructor.148assert(_default_oop_recorder.allocated_on_stack(), "should be embedded object");149ResourceObj::allocation_type at = _default_oop_recorder.get_allocation_type();150Copy::fill_to_bytes(this, sizeof(*this), badResourceValue);151ResourceObj::set_allocation_type((address)(&_default_oop_recorder), at);152#endif153}154155void CodeBuffer::initialize_oop_recorder(OopRecorder* r) {156assert(_oop_recorder == &_default_oop_recorder && _default_oop_recorder.is_unused(), "do this once");157DEBUG_ONLY(_default_oop_recorder.freeze()); // force unused OR to be frozen158_oop_recorder = r;159}160161void CodeBuffer::initialize_section_size(CodeSection* cs, csize_t size) {162assert(cs != &_insts, "insts is the memory provider, not the consumer");163csize_t slop = CodeSection::end_slop(); // margin between sections164int align = cs->alignment();165assert(is_power_of_2(align), "sanity");166address start = _insts._start;167address limit = _insts._limit;168address middle = limit - size;169middle -= (intptr_t)middle & (align-1); // align the division point downward170guarantee(middle - slop > start, "need enough space to divide up");171_insts._limit = middle - slop; // subtract desired space, plus slop172cs->initialize(middle, limit - middle);173assert(cs->start() == middle, "sanity");174assert(cs->limit() == limit, "sanity");175// give it some relocations to start with, if the main section has them176if (_insts.has_locs()) cs->initialize_locs(1);177}178179void CodeBuffer::set_blob(BufferBlob* blob) {180_blob = blob;181if (blob != NULL) {182address start = blob->content_begin();183address end = blob->content_end();184// Round up the starting address.185int align = _insts.alignment();186start += (-(intptr_t)start) & (align-1);187_total_start = start;188_total_size = end - start;189} else {190#ifdef ASSERT191// Clean out dangling pointers.192_total_start = badAddress;193_consts._start = _consts._end = badAddress;194_insts._start = _insts._end = badAddress;195_stubs._start = _stubs._end = badAddress;196#endif //ASSERT197}198}199200void CodeBuffer::free_blob() {201if (_blob != NULL) {202BufferBlob::free(_blob);203set_blob(NULL);204}205}206207const char* CodeBuffer::code_section_name(int n) {208#ifdef PRODUCT209return NULL;210#else //PRODUCT211switch (n) {212case SECT_CONSTS: return "consts";213case SECT_INSTS: return "insts";214case SECT_STUBS: return "stubs";215default: return NULL;216}217#endif //PRODUCT218}219220int CodeBuffer::section_index_of(address addr) const {221for (int n = 0; n < (int)SECT_LIMIT; n++) {222const CodeSection* cs = code_section(n);223if (cs->allocates(addr)) return n;224}225return SECT_NONE;226}227228int CodeBuffer::locator(address addr) const {229for (int n = 0; n < (int)SECT_LIMIT; n++) {230const CodeSection* cs = code_section(n);231if (cs->allocates(addr)) {232return locator(addr - cs->start(), n);233}234}235return -1;236}237238239bool CodeBuffer::is_backward_branch(Label& L) {240return L.is_bound() && insts_end() <= locator_address(L.loc());241}242243#ifndef PRODUCT244address CodeBuffer::decode_begin() {245address begin = _insts.start();246if (_decode_begin != NULL && _decode_begin > begin)247begin = _decode_begin;248return begin;249}250#endif // !PRODUCT251252GrowableArray<int>* CodeBuffer::create_patch_overflow() {253if (_overflow_arena == NULL) {254_overflow_arena = new (mtCode) Arena(mtCode);255}256return new (_overflow_arena) GrowableArray<int>(_overflow_arena, 8, 0, 0);257}258259260// Helper function for managing labels and their target addresses.261// Returns a sensible address, and if it is not the label's final262// address, notes the dependency (at 'branch_pc') on the label.263address CodeSection::target(Label& L, address branch_pc) {264if (L.is_bound()) {265int loc = L.loc();266if (index() == CodeBuffer::locator_sect(loc)) {267return start() + CodeBuffer::locator_pos(loc);268} else {269return outer()->locator_address(loc);270}271} else {272assert(allocates2(branch_pc), "sanity");273address base = start();274int patch_loc = CodeBuffer::locator(branch_pc - base, index());275L.add_patch_at(outer(), patch_loc);276277// Need to return a pc, doesn't matter what it is since it will be278// replaced during resolution later.279// Don't return NULL or badAddress, since branches shouldn't overflow.280// Don't return base either because that could overflow displacements281// for shorter branches. It will get checked when bound.282return branch_pc;283}284}285286void CodeSection::relocate(address at, relocInfo::relocType rtype, int format, jint method_index) {287RelocationHolder rh;288switch (rtype) {289case relocInfo::none: return;290case relocInfo::opt_virtual_call_type: {291rh = opt_virtual_call_Relocation::spec(method_index);292break;293}294case relocInfo::static_call_type: {295rh = static_call_Relocation::spec(method_index);296break;297}298case relocInfo::virtual_call_type: {299assert(method_index == 0, "resolved method overriding is not supported");300rh = Relocation::spec_simple(rtype);301break;302}303default: {304rh = Relocation::spec_simple(rtype);305break;306}307}308relocate(at, rh, format);309}310311void CodeSection::relocate(address at, RelocationHolder const& spec, int format) {312// Do not relocate in scratch buffers.313if (scratch_emit()) { return; }314Relocation* reloc = spec.reloc();315relocInfo::relocType rtype = (relocInfo::relocType) reloc->type();316if (rtype == relocInfo::none) return;317318// The assertion below has been adjusted, to also work for319// relocation for fixup. Sometimes we want to put relocation320// information for the next instruction, since it will be patched321// with a call.322assert(start() <= at && at <= end()+1,323"cannot relocate data outside code boundaries");324325if (!has_locs()) {326// no space for relocation information provided => code cannot be327// relocated. Make sure that relocate is only called with rtypes328// that can be ignored for this kind of code.329assert(rtype == relocInfo::none ||330rtype == relocInfo::runtime_call_type ||331rtype == relocInfo::internal_word_type||332rtype == relocInfo::section_word_type ||333rtype == relocInfo::external_word_type,334"code needs relocation information");335// leave behind an indication that we attempted a relocation336DEBUG_ONLY(_locs_start = _locs_limit = (relocInfo*)badAddress);337return;338}339340// Advance the point, noting the offset we'll have to record.341csize_t offset = at - locs_point();342set_locs_point(at);343344// Test for a couple of overflow conditions; maybe expand the buffer.345relocInfo* end = locs_end();346relocInfo* req = end + relocInfo::length_limit;347// Check for (potential) overflow348if (req >= locs_limit() || offset >= relocInfo::offset_limit()) {349req += (uint)offset / (uint)relocInfo::offset_limit();350if (req >= locs_limit()) {351// Allocate or reallocate.352expand_locs(locs_count() + (req - end));353// reload pointer354end = locs_end();355}356}357358// If the offset is giant, emit filler relocs, of type 'none', but359// each carrying the largest possible offset, to advance the locs_point.360while (offset >= relocInfo::offset_limit()) {361assert(end < locs_limit(), "adjust previous paragraph of code");362*end++ = filler_relocInfo();363offset -= filler_relocInfo().addr_offset();364}365366// If it's a simple reloc with no data, we'll just write (rtype | offset).367(*end) = relocInfo(rtype, offset, format);368369// If it has data, insert the prefix, as (data_prefix_tag | data1), data2.370end->initialize(this, reloc);371}372373void CodeSection::initialize_locs(int locs_capacity) {374assert(_locs_start == NULL, "only one locs init step, please");375// Apply a priori lower limits to relocation size:376csize_t min_locs = MAX2(size() / 16, (csize_t)4);377if (locs_capacity < min_locs) locs_capacity = min_locs;378relocInfo* locs_start = NEW_RESOURCE_ARRAY(relocInfo, locs_capacity);379_locs_start = locs_start;380_locs_end = locs_start;381_locs_limit = locs_start + locs_capacity;382_locs_own = true;383}384385void CodeSection::initialize_shared_locs(relocInfo* buf, int length) {386assert(_locs_start == NULL, "do this before locs are allocated");387// Internal invariant: locs buf must be fully aligned.388// See copy_relocations_to() below.389while ((uintptr_t)buf % HeapWordSize != 0 && length > 0) {390++buf; --length;391}392if (length > 0) {393_locs_start = buf;394_locs_end = buf;395_locs_limit = buf + length;396_locs_own = false;397}398}399400void CodeSection::initialize_locs_from(const CodeSection* source_cs) {401int lcount = source_cs->locs_count();402if (lcount != 0) {403initialize_shared_locs(source_cs->locs_start(), lcount);404_locs_end = _locs_limit = _locs_start + lcount;405assert(is_allocated(), "must have copied code already");406set_locs_point(start() + source_cs->locs_point_off());407}408assert(this->locs_count() == source_cs->locs_count(), "sanity");409}410411void CodeSection::expand_locs(int new_capacity) {412if (_locs_start == NULL) {413initialize_locs(new_capacity);414return;415} else {416int old_count = locs_count();417int old_capacity = locs_capacity();418if (new_capacity < old_capacity * 2)419new_capacity = old_capacity * 2;420relocInfo* locs_start;421if (_locs_own) {422locs_start = REALLOC_RESOURCE_ARRAY(relocInfo, _locs_start, old_capacity, new_capacity);423} else {424locs_start = NEW_RESOURCE_ARRAY(relocInfo, new_capacity);425Copy::conjoint_jbytes(_locs_start, locs_start, old_capacity * sizeof(relocInfo));426_locs_own = true;427}428_locs_start = locs_start;429_locs_end = locs_start + old_count;430_locs_limit = locs_start + new_capacity;431}432}433434435/// Support for emitting the code to its final location.436/// The pattern is the same for all functions.437/// We iterate over all the sections, padding each to alignment.438439csize_t CodeBuffer::total_content_size() const {440csize_t size_so_far = 0;441for (int n = 0; n < (int)SECT_LIMIT; n++) {442const CodeSection* cs = code_section(n);443if (cs->is_empty()) continue; // skip trivial section444size_so_far = cs->align_at_start(size_so_far);445size_so_far += cs->size();446}447return size_so_far;448}449450void CodeBuffer::compute_final_layout(CodeBuffer* dest) const {451address buf = dest->_total_start;452csize_t buf_offset = 0;453assert(dest->_total_size >= total_content_size(), "must be big enough");454455{456// not sure why this is here, but why not...457int alignSize = MAX2((intx) sizeof(jdouble), CodeEntryAlignment);458assert( (dest->_total_start - _insts.start()) % alignSize == 0, "copy must preserve alignment");459}460461const CodeSection* prev_cs = NULL;462CodeSection* prev_dest_cs = NULL;463464for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {465// figure compact layout of each section466const CodeSection* cs = code_section(n);467csize_t csize = cs->size();468469CodeSection* dest_cs = dest->code_section(n);470if (!cs->is_empty()) {471// Compute initial padding; assign it to the previous non-empty guy.472// Cf. figure_expanded_capacities.473csize_t padding = cs->align_at_start(buf_offset) - buf_offset;474if (prev_dest_cs != NULL) {475if (padding != 0) {476buf_offset += padding;477prev_dest_cs->_limit += padding;478}479} else {480guarantee(padding == 0, "In first iteration no padding should be needed.");481}482prev_dest_cs = dest_cs;483prev_cs = cs;484}485486debug_only(dest_cs->_start = NULL); // defeat double-initialization assert487dest_cs->initialize(buf+buf_offset, csize);488dest_cs->set_end(buf+buf_offset+csize);489assert(dest_cs->is_allocated(), "must always be allocated");490assert(cs->is_empty() == dest_cs->is_empty(), "sanity");491492buf_offset += csize;493}494495// Done calculating sections; did it come out to the right end?496assert(buf_offset == total_content_size(), "sanity");497debug_only(dest->verify_section_allocation();)498}499500// Append an oop reference that keeps the class alive.501static void append_oop_references(GrowableArray<oop>* oops, Klass* k) {502oop cl = k->klass_holder();503if (cl != NULL && !oops->contains(cl)) {504oops->append(cl);505}506}507508void CodeBuffer::finalize_oop_references(const methodHandle& mh) {509NoSafepointVerifier nsv;510511GrowableArray<oop> oops;512513// Make sure that immediate metadata records something in the OopRecorder514for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {515// pull code out of each section516CodeSection* cs = code_section(n);517if (cs->is_empty()) continue; // skip trivial section518RelocIterator iter(cs);519while (iter.next()) {520if (iter.type() == relocInfo::metadata_type) {521metadata_Relocation* md = iter.metadata_reloc();522if (md->metadata_is_immediate()) {523Metadata* m = md->metadata_value();524if (oop_recorder()->is_real(m)) {525if (m->is_methodData()) {526m = ((MethodData*)m)->method();527}528if (m->is_method()) {529m = ((Method*)m)->method_holder();530}531if (m->is_klass()) {532append_oop_references(&oops, (Klass*)m);533} else {534// XXX This will currently occur for MDO which don't535// have a backpointer. This has to be fixed later.536m->print();537ShouldNotReachHere();538}539}540}541}542}543}544545if (!oop_recorder()->is_unused()) {546for (int i = 0; i < oop_recorder()->metadata_count(); i++) {547Metadata* m = oop_recorder()->metadata_at(i);548if (oop_recorder()->is_real(m)) {549if (m->is_methodData()) {550m = ((MethodData*)m)->method();551}552if (m->is_method()) {553m = ((Method*)m)->method_holder();554}555if (m->is_klass()) {556append_oop_references(&oops, (Klass*)m);557} else {558m->print();559ShouldNotReachHere();560}561}562}563564}565566// Add the class loader of Method* for the nmethod itself567append_oop_references(&oops, mh->method_holder());568569// Add any oops that we've found570Thread* thread = Thread::current();571for (int i = 0; i < oops.length(); i++) {572oop_recorder()->find_index((jobject)thread->handle_area()->allocate_handle(oops.at(i)));573}574}575576577578csize_t CodeBuffer::total_offset_of(const CodeSection* cs) const {579csize_t size_so_far = 0;580for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {581const CodeSection* cur_cs = code_section(n);582if (!cur_cs->is_empty()) {583size_so_far = cur_cs->align_at_start(size_so_far);584}585if (cur_cs->index() == cs->index()) {586return size_so_far;587}588size_so_far += cur_cs->size();589}590ShouldNotReachHere();591return -1;592}593594csize_t CodeBuffer::total_relocation_size() const {595csize_t total = copy_relocations_to(NULL); // dry run only596return (csize_t) align_up(total, HeapWordSize);597}598599csize_t CodeBuffer::copy_relocations_to(address buf, csize_t buf_limit, bool only_inst) const {600csize_t buf_offset = 0;601csize_t code_end_so_far = 0;602csize_t code_point_so_far = 0;603604assert((uintptr_t)buf % HeapWordSize == 0, "buf must be fully aligned");605assert(buf_limit % HeapWordSize == 0, "buf must be evenly sized");606607for (int n = (int) SECT_FIRST; n < (int)SECT_LIMIT; n++) {608if (only_inst && (n != (int)SECT_INSTS)) {609// Need only relocation info for code.610continue;611}612// pull relocs out of each section613const CodeSection* cs = code_section(n);614assert(!(cs->is_empty() && cs->locs_count() > 0), "sanity");615if (cs->is_empty()) continue; // skip trivial section616relocInfo* lstart = cs->locs_start();617relocInfo* lend = cs->locs_end();618csize_t lsize = (csize_t)( (address)lend - (address)lstart );619csize_t csize = cs->size();620code_end_so_far = cs->align_at_start(code_end_so_far);621622if (lsize > 0) {623// Figure out how to advance the combined relocation point624// first to the beginning of this section.625// We'll insert one or more filler relocs to span that gap.626// (Don't bother to improve this by editing the first reloc's offset.)627csize_t new_code_point = code_end_so_far;628for (csize_t jump;629code_point_so_far < new_code_point;630code_point_so_far += jump) {631jump = new_code_point - code_point_so_far;632relocInfo filler = filler_relocInfo();633if (jump >= filler.addr_offset()) {634jump = filler.addr_offset();635} else { // else shrink the filler to fit636filler = relocInfo(relocInfo::none, jump);637}638if (buf != NULL) {639assert(buf_offset + (csize_t)sizeof(filler) <= buf_limit, "filler in bounds");640*(relocInfo*)(buf+buf_offset) = filler;641}642buf_offset += sizeof(filler);643}644645// Update code point and end to skip past this section:646csize_t last_code_point = code_end_so_far + cs->locs_point_off();647assert(code_point_so_far <= last_code_point, "sanity");648code_point_so_far = last_code_point; // advance past this guy's relocs649}650code_end_so_far += csize; // advance past this guy's instructions too651652// Done with filler; emit the real relocations:653if (buf != NULL && lsize != 0) {654assert(buf_offset + lsize <= buf_limit, "target in bounds");655assert((uintptr_t)lstart % HeapWordSize == 0, "sane start");656if (buf_offset % HeapWordSize == 0) {657// Use wordwise copies if possible:658Copy::disjoint_words((HeapWord*)lstart,659(HeapWord*)(buf+buf_offset),660(lsize + HeapWordSize-1) / HeapWordSize);661} else {662Copy::conjoint_jbytes(lstart, buf+buf_offset, lsize);663}664}665buf_offset += lsize;666}667668// Align end of relocation info in target.669while (buf_offset % HeapWordSize != 0) {670if (buf != NULL) {671relocInfo padding = relocInfo(relocInfo::none, 0);672assert(buf_offset + (csize_t)sizeof(padding) <= buf_limit, "padding in bounds");673*(relocInfo*)(buf+buf_offset) = padding;674}675buf_offset += sizeof(relocInfo);676}677678assert(only_inst || code_end_so_far == total_content_size(), "sanity");679680return buf_offset;681}682683csize_t CodeBuffer::copy_relocations_to(CodeBlob* dest) const {684address buf = NULL;685csize_t buf_offset = 0;686csize_t buf_limit = 0;687688if (dest != NULL) {689buf = (address)dest->relocation_begin();690buf_limit = (address)dest->relocation_end() - buf;691}692// if dest == NULL, this is just the sizing pass693//694buf_offset = copy_relocations_to(buf, buf_limit, false);695696return buf_offset;697}698699void CodeBuffer::copy_code_to(CodeBlob* dest_blob) {700#ifndef PRODUCT701if (PrintNMethods && (WizardMode || Verbose)) {702tty->print("done with CodeBuffer:");703((CodeBuffer*)this)->print();704}705#endif //PRODUCT706707CodeBuffer dest(dest_blob);708assert(dest_blob->content_size() >= total_content_size(), "good sizing");709this->compute_final_layout(&dest);710711// Set beginning of constant table before relocating.712dest_blob->set_ctable_begin(dest.consts()->start());713714relocate_code_to(&dest);715716// transfer strings and comments from buffer to blob717NOT_PRODUCT(dest_blob->set_strings(_code_strings);)718719// Done moving code bytes; were they the right size?720assert((int)align_up(dest.total_content_size(), oopSize) == dest_blob->content_size(), "sanity");721722// Flush generated code723ICache::invalidate_range(dest_blob->code_begin(), dest_blob->code_size());724}725726// Move all my code into another code buffer. Consult applicable727// relocs to repair embedded addresses. The layout in the destination728// CodeBuffer is different to the source CodeBuffer: the destination729// CodeBuffer gets the final layout (consts, insts, stubs in order of730// ascending address).731void CodeBuffer::relocate_code_to(CodeBuffer* dest) const {732address dest_end = dest->_total_start + dest->_total_size;733address dest_filled = NULL;734for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {735// pull code out of each section736const CodeSection* cs = code_section(n);737if (cs->is_empty()) continue; // skip trivial section738CodeSection* dest_cs = dest->code_section(n);739assert(cs->size() == dest_cs->size(), "sanity");740csize_t usize = dest_cs->size();741csize_t wsize = align_up(usize, HeapWordSize);742assert(dest_cs->start() + wsize <= dest_end, "no overflow");743// Copy the code as aligned machine words.744// This may also include an uninitialized partial word at the end.745Copy::disjoint_words((HeapWord*)cs->start(),746(HeapWord*)dest_cs->start(),747wsize / HeapWordSize);748749if (dest->blob() == NULL) {750// Destination is a final resting place, not just another buffer.751// Normalize uninitialized bytes in the final padding.752Copy::fill_to_bytes(dest_cs->end(), dest_cs->remaining(),753Assembler::code_fill_byte());754}755// Keep track of the highest filled address756dest_filled = MAX2(dest_filled, dest_cs->end() + dest_cs->remaining());757758assert(cs->locs_start() != (relocInfo*)badAddress,759"this section carries no reloc storage, but reloc was attempted");760761// Make the new code copy use the old copy's relocations:762dest_cs->initialize_locs_from(cs);763}764765// Do relocation after all sections are copied.766// This is necessary if the code uses constants in stubs, which are767// relocated when the corresponding instruction in the code (e.g., a768// call) is relocated. Stubs are placed behind the main code769// section, so that section has to be copied before relocating.770for (int n = (int) SECT_FIRST; n < (int)SECT_LIMIT; n++) {771// pull code out of each section772const CodeSection* cs = code_section(n);773if (cs->is_empty()) continue; // skip trivial section774CodeSection* dest_cs = dest->code_section(n);775{ // Repair the pc relative information in the code after the move776RelocIterator iter(dest_cs);777while (iter.next()) {778iter.reloc()->fix_relocation_after_move(this, dest);779}780}781}782783if (dest->blob() == NULL && dest_filled != NULL) {784// Destination is a final resting place, not just another buffer.785// Normalize uninitialized bytes in the final padding.786Copy::fill_to_bytes(dest_filled, dest_end - dest_filled,787Assembler::code_fill_byte());788789}790}791792csize_t CodeBuffer::figure_expanded_capacities(CodeSection* which_cs,793csize_t amount,794csize_t* new_capacity) {795csize_t new_total_cap = 0;796797for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {798const CodeSection* sect = code_section(n);799800if (!sect->is_empty()) {801// Compute initial padding; assign it to the previous section,802// even if it's empty (e.g. consts section can be empty).803// Cf. compute_final_layout804csize_t padding = sect->align_at_start(new_total_cap) - new_total_cap;805if (padding != 0) {806new_total_cap += padding;807assert(n - 1 >= SECT_FIRST, "sanity");808new_capacity[n - 1] += padding;809}810}811812csize_t exp = sect->size(); // 100% increase813if ((uint)exp < 4*K) exp = 4*K; // minimum initial increase814if (sect == which_cs) {815if (exp < amount) exp = amount;816if (StressCodeBuffers) exp = amount; // expand only slightly817} else if (n == SECT_INSTS) {818// scale down inst increases to a more modest 25%819exp = 4*K + ((exp - 4*K) >> 2);820if (StressCodeBuffers) exp = amount / 2; // expand only slightly821} else if (sect->is_empty()) {822// do not grow an empty secondary section823exp = 0;824}825// Allow for inter-section slop:826exp += CodeSection::end_slop();827csize_t new_cap = sect->size() + exp;828if (new_cap < sect->capacity()) {829// No need to expand after all.830new_cap = sect->capacity();831}832new_capacity[n] = new_cap;833new_total_cap += new_cap;834}835836return new_total_cap;837}838839void CodeBuffer::expand(CodeSection* which_cs, csize_t amount) {840#ifndef PRODUCT841if (PrintNMethods && (WizardMode || Verbose)) {842tty->print("expanding CodeBuffer:");843this->print();844}845846if (StressCodeBuffers && blob() != NULL) {847static int expand_count = 0;848if (expand_count >= 0) expand_count += 1;849if (expand_count > 100 && is_power_of_2(expand_count)) {850tty->print_cr("StressCodeBuffers: have expanded %d times", expand_count);851// simulate an occasional allocation failure:852free_blob();853}854}855#endif //PRODUCT856857// Resizing must be allowed858{859if (blob() == NULL) return; // caller must check for blob == NULL860}861862// Figure new capacity for each section.863csize_t new_capacity[SECT_LIMIT];864memset(new_capacity, 0, sizeof(csize_t) * SECT_LIMIT);865csize_t new_total_cap866= figure_expanded_capacities(which_cs, amount, new_capacity);867868// Create a new (temporary) code buffer to hold all the new data869CodeBuffer cb(name(), new_total_cap, 0);870if (cb.blob() == NULL) {871// Failed to allocate in code cache.872free_blob();873return;874}875876// Create an old code buffer to remember which addresses used to go where.877// This will be useful when we do final assembly into the code cache,878// because we will need to know how to warp any internal address that879// has been created at any time in this CodeBuffer's past.880CodeBuffer* bxp = new CodeBuffer(_total_start, _total_size);881bxp->take_over_code_from(this); // remember the old undersized blob882DEBUG_ONLY(this->_blob = NULL); // silence a later assert883bxp->_before_expand = this->_before_expand;884this->_before_expand = bxp;885886// Give each section its required (expanded) capacity.887for (int n = (int)SECT_LIMIT-1; n >= SECT_FIRST; n--) {888CodeSection* cb_sect = cb.code_section(n);889CodeSection* this_sect = code_section(n);890if (new_capacity[n] == 0) continue; // already nulled out891if (n != SECT_INSTS) {892cb.initialize_section_size(cb_sect, new_capacity[n]);893}894assert(cb_sect->capacity() >= new_capacity[n], "big enough");895address cb_start = cb_sect->start();896cb_sect->set_end(cb_start + this_sect->size());897if (this_sect->mark() == NULL) {898cb_sect->clear_mark();899} else {900cb_sect->set_mark(cb_start + this_sect->mark_off());901}902}903904// Needs to be initialized when calling fix_relocation_after_move.905cb.blob()->set_ctable_begin(cb.consts()->start());906907// Move all the code and relocations to the new blob:908relocate_code_to(&cb);909910// Copy the temporary code buffer into the current code buffer.911// Basically, do {*this = cb}, except for some control information.912this->take_over_code_from(&cb);913cb.set_blob(NULL);914915// Zap the old code buffer contents, to avoid mistakenly using them.916debug_only(Copy::fill_to_bytes(bxp->_total_start, bxp->_total_size,917badCodeHeapFreeVal);)918919// Make certain that the new sections are all snugly inside the new blob.920debug_only(verify_section_allocation();)921922#ifndef PRODUCT923_decode_begin = NULL; // sanity924if (PrintNMethods && (WizardMode || Verbose)) {925tty->print("expanded CodeBuffer:");926this->print();927}928#endif //PRODUCT929}930931void CodeBuffer::take_over_code_from(CodeBuffer* cb) {932// Must already have disposed of the old blob somehow.933assert(blob() == NULL, "must be empty");934// Take the new blob away from cb.935set_blob(cb->blob());936// Take over all the section pointers.937for (int n = 0; n < (int)SECT_LIMIT; n++) {938CodeSection* cb_sect = cb->code_section(n);939CodeSection* this_sect = code_section(n);940this_sect->take_over_code_from(cb_sect);941}942_overflow_arena = cb->_overflow_arena;943cb->_overflow_arena = NULL;944// Make sure the old cb won't try to use it or free it.945DEBUG_ONLY(cb->_blob = (BufferBlob*)badAddress);946}947948void CodeBuffer::verify_section_allocation() {949address tstart = _total_start;950if (tstart == badAddress) return; // smashed by set_blob(NULL)951address tend = tstart + _total_size;952if (_blob != NULL) {953guarantee(tstart >= _blob->content_begin(), "sanity");954guarantee(tend <= _blob->content_end(), "sanity");955}956// Verify disjointness.957for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {958CodeSection* sect = code_section(n);959if (!sect->is_allocated() || sect->is_empty()) {960continue;961}962guarantee(_blob == nullptr || is_aligned(sect->start(), sect->alignment()),963"start is aligned");964for (int m = n + 1; m < (int) SECT_LIMIT; m++) {965CodeSection* other = code_section(m);966if (!other->is_allocated() || other == sect) {967continue;968}969guarantee(other->disjoint(sect), "sanity");970}971guarantee(sect->end() <= tend, "sanity");972guarantee(sect->end() <= sect->limit(), "sanity");973}974}975976void CodeBuffer::log_section_sizes(const char* name) {977if (xtty != NULL) {978ttyLocker ttyl;979// log info about buffer usage980xtty->print_cr("<blob name='%s' size='%d'>", name, _total_size);981for (int n = (int) CodeBuffer::SECT_FIRST; n < (int) CodeBuffer::SECT_LIMIT; n++) {982CodeSection* sect = code_section(n);983if (!sect->is_allocated() || sect->is_empty()) continue;984xtty->print_cr("<sect index='%d' size='" SIZE_FORMAT "' free='" SIZE_FORMAT "'/>",985n, sect->limit() - sect->start(), sect->limit() - sect->end());986}987xtty->print_cr("</blob>");988}989}990991#ifndef PRODUCT992993void CodeBuffer::block_comment(intptr_t offset, const char * comment) {994if (_collect_comments) {995_code_strings.add_comment(offset, comment);996}997}998999const char* CodeBuffer::code_string(const char* str) {1000return _code_strings.add_string(str);1001}10021003class CodeString: public CHeapObj<mtCode> {1004private:1005friend class CodeStrings;1006const char * _string;1007CodeString* _next;1008CodeString* _prev;1009intptr_t _offset;10101011static long allocated_code_strings;10121013~CodeString() {1014assert(_next == NULL && _prev == NULL, "wrong interface for freeing list");1015allocated_code_strings--;1016log_trace(codestrings)("Freeing CodeString [%s] (%p)", _string, (void*)_string);1017os::free((void*)_string);1018}10191020bool is_comment() const { return _offset >= 0; }10211022public:1023CodeString(const char * string, intptr_t offset = -1)1024: _next(NULL), _prev(NULL), _offset(offset) {1025allocated_code_strings++;1026_string = os::strdup(string, mtCode);1027log_trace(codestrings)("Created CodeString [%s] (%p)", _string, (void*)_string);1028}10291030const char * string() const { return _string; }1031intptr_t offset() const { assert(_offset >= 0, "offset for non comment?"); return _offset; }1032CodeString* next() const { return _next; }10331034void set_next(CodeString* next) {1035_next = next;1036if (next != NULL) {1037next->_prev = this;1038}1039}10401041CodeString* first_comment() {1042if (is_comment()) {1043return this;1044} else {1045return next_comment();1046}1047}1048CodeString* next_comment() const {1049CodeString* s = _next;1050while (s != NULL && !s->is_comment()) {1051s = s->_next;1052}1053return s;1054}1055};10561057// For tracing statistics. Will use raw increment/decrement, so it might not be1058// exact1059long CodeString::allocated_code_strings = 0;10601061CodeString* CodeStrings::find(intptr_t offset) const {1062CodeString* a = _strings->first_comment();1063while (a != NULL && a->offset() != offset) {1064a = a->next_comment();1065}1066return a;1067}10681069// Convenience for add_comment.1070CodeString* CodeStrings::find_last(intptr_t offset) const {1071CodeString* a = _strings_last;1072while (a != NULL && !(a->is_comment() && a->offset() == offset)) {1073a = a->_prev;1074}1075return a;1076}10771078void CodeStrings::add_comment(intptr_t offset, const char * comment) {1079check_valid();1080CodeString* c = new CodeString(comment, offset);1081CodeString* inspos = (_strings == NULL) ? NULL : find_last(offset);10821083if (inspos != NULL) {1084// insert after already existing comments with same offset1085c->set_next(inspos->next());1086inspos->set_next(c);1087} else {1088// no comments with such offset, yet. Insert before anything else.1089c->set_next(_strings);1090_strings = c;1091}1092if (c->next() == NULL) {1093_strings_last = c;1094}1095}10961097// Deep copy of CodeStrings for consistent memory management.1098void CodeStrings::copy(CodeStrings& other) {1099log_debug(codestrings)("Copying %d Codestring(s)", other.count());11001101other.check_valid();1102check_valid();1103assert(is_null(), "Cannot copy onto non-empty CodeStrings");1104CodeString* n = other._strings;1105CodeString** ps = &_strings;1106CodeString* prev = NULL;1107while (n != NULL) {1108if (n->is_comment()) {1109*ps = new CodeString(n->string(), n->offset());1110} else {1111*ps = new CodeString(n->string());1112}1113(*ps)->_prev = prev;1114prev = *ps;1115ps = &((*ps)->_next);1116n = n->next();1117}1118}11191120const char* CodeStrings::_prefix = " ;; "; // default: can be changed via set_prefix11211122void CodeStrings::print_block_comment(outputStream* stream, intptr_t offset) const {1123check_valid();1124if (_strings != NULL) {1125CodeString* c = find(offset);1126while (c && c->offset() == offset) {1127stream->bol();1128stream->print("%s", _prefix);1129// Don't interpret as format strings since it could contain %1130stream->print_raw(c->string());1131stream->bol(); // advance to next line only if string didn't contain a cr() at the end.1132c = c->next_comment();1133}1134}1135}11361137int CodeStrings::count() const {1138int i = 0;1139CodeString* s = _strings;1140while (s != NULL) {1141i++;1142s = s->_next;1143}1144return i;1145}11461147// Also sets is_null()1148void CodeStrings::free() {1149log_debug(codestrings)("Freeing %d out of approx. %ld CodeString(s), ", count(), CodeString::allocated_code_strings);1150CodeString* n = _strings;1151while (n) {1152// unlink the node from the list saving a pointer to the next1153CodeString* p = n->next();1154n->set_next(NULL);1155if (p != NULL) {1156assert(p->_prev == n, "missing prev link");1157p->_prev = NULL;1158}1159delete n;1160n = p;1161}1162set_null_and_invalidate();1163}11641165const char* CodeStrings::add_string(const char * string) {1166check_valid();1167CodeString* s = new CodeString(string);1168s->set_next(_strings);1169if (_strings == NULL) {1170_strings_last = s;1171}1172_strings = s;1173assert(s->string() != NULL, "should have a string");1174return s->string();1175}11761177void CodeBuffer::decode() {1178ttyLocker ttyl;1179Disassembler::decode(decode_begin(), insts_end(), tty NOT_PRODUCT(COMMA &strings()));1180_decode_begin = insts_end();1181}11821183void CodeSection::print(const char* name) {1184csize_t locs_size = locs_end() - locs_start();1185tty->print_cr(" %7s.code = " PTR_FORMAT " : " PTR_FORMAT " : " PTR_FORMAT " (%d of %d)",1186name, p2i(start()), p2i(end()), p2i(limit()), size(), capacity());1187tty->print_cr(" %7s.locs = " PTR_FORMAT " : " PTR_FORMAT " : " PTR_FORMAT " (%d of %d) point=%d",1188name, p2i(locs_start()), p2i(locs_end()), p2i(locs_limit()), locs_size, locs_capacity(), locs_point_off());1189if (PrintRelocations) {1190RelocIterator iter(this);1191iter.print();1192}1193}11941195void CodeBuffer::print() {1196if (this == NULL) {1197tty->print_cr("NULL CodeBuffer pointer");1198return;1199}12001201tty->print_cr("CodeBuffer:");1202for (int n = 0; n < (int)SECT_LIMIT; n++) {1203// print each section1204CodeSection* cs = code_section(n);1205cs->print(code_section_name(n));1206}1207}12081209#endif // PRODUCT121012111212