Path: blob/master/src/hotspot/share/asm/codeBuffer.cpp
40951 views
/*1* Copyright (c) 1997, 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 "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}138139// free any overflow storage140delete _overflow_arena;141142// Claim is that stack allocation ensures resources are cleaned up.143// This is resource clean up, let's hope that all were properly copied out.144NOT_PRODUCT(free_strings();)145146#ifdef ASSERT147// Save allocation type to execute assert in ~ResourceObj()148// which is called after this destructor.149assert(_default_oop_recorder.allocated_on_stack(), "should be embedded object");150ResourceObj::allocation_type at = _default_oop_recorder.get_allocation_type();151Copy::fill_to_bytes(this, sizeof(*this), badResourceValue);152ResourceObj::set_allocation_type((address)(&_default_oop_recorder), at);153#endif154}155156void CodeBuffer::initialize_oop_recorder(OopRecorder* r) {157assert(_oop_recorder == &_default_oop_recorder && _default_oop_recorder.is_unused(), "do this once");158DEBUG_ONLY(_default_oop_recorder.freeze()); // force unused OR to be frozen159_oop_recorder = r;160}161162void CodeBuffer::initialize_section_size(CodeSection* cs, csize_t size) {163assert(cs != &_insts, "insts is the memory provider, not the consumer");164csize_t slop = CodeSection::end_slop(); // margin between sections165int align = cs->alignment();166assert(is_power_of_2(align), "sanity");167address start = _insts._start;168address limit = _insts._limit;169address middle = limit - size;170middle -= (intptr_t)middle & (align-1); // align the division point downward171guarantee(middle - slop > start, "need enough space to divide up");172_insts._limit = middle - slop; // subtract desired space, plus slop173cs->initialize(middle, limit - middle);174assert(cs->start() == middle, "sanity");175assert(cs->limit() == limit, "sanity");176// give it some relocations to start with, if the main section has them177if (_insts.has_locs()) cs->initialize_locs(1);178}179180void CodeBuffer::set_blob(BufferBlob* blob) {181_blob = blob;182if (blob != NULL) {183address start = blob->content_begin();184address end = blob->content_end();185// Round up the starting address.186int align = _insts.alignment();187start += (-(intptr_t)start) & (align-1);188_total_start = start;189_total_size = end - start;190} else {191#ifdef ASSERT192// Clean out dangling pointers.193_total_start = badAddress;194_consts._start = _consts._end = badAddress;195_insts._start = _insts._end = badAddress;196_stubs._start = _stubs._end = badAddress;197#endif //ASSERT198}199}200201void CodeBuffer::free_blob() {202if (_blob != NULL) {203BufferBlob::free(_blob);204set_blob(NULL);205}206}207208const char* CodeBuffer::code_section_name(int n) {209#ifdef PRODUCT210return NULL;211#else //PRODUCT212switch (n) {213case SECT_CONSTS: return "consts";214case SECT_INSTS: return "insts";215case SECT_STUBS: return "stubs";216default: return NULL;217}218#endif //PRODUCT219}220221int CodeBuffer::section_index_of(address addr) const {222for (int n = 0; n < (int)SECT_LIMIT; n++) {223const CodeSection* cs = code_section(n);224if (cs->allocates(addr)) return n;225}226return SECT_NONE;227}228229int CodeBuffer::locator(address addr) const {230for (int n = 0; n < (int)SECT_LIMIT; n++) {231const CodeSection* cs = code_section(n);232if (cs->allocates(addr)) {233return locator(addr - cs->start(), n);234}235}236return -1;237}238239240bool CodeBuffer::is_backward_branch(Label& L) {241return L.is_bound() && insts_end() <= locator_address(L.loc());242}243244#ifndef PRODUCT245address CodeBuffer::decode_begin() {246address begin = _insts.start();247if (_decode_begin != NULL && _decode_begin > begin)248begin = _decode_begin;249return begin;250}251#endif // !PRODUCT252253GrowableArray<int>* CodeBuffer::create_patch_overflow() {254if (_overflow_arena == NULL) {255_overflow_arena = new (mtCode) Arena(mtCode);256}257return new (_overflow_arena) GrowableArray<int>(_overflow_arena, 8, 0, 0);258}259260261// Helper function for managing labels and their target addresses.262// Returns a sensible address, and if it is not the label's final263// address, notes the dependency (at 'branch_pc') on the label.264address CodeSection::target(Label& L, address branch_pc) {265if (L.is_bound()) {266int loc = L.loc();267if (index() == CodeBuffer::locator_sect(loc)) {268return start() + CodeBuffer::locator_pos(loc);269} else {270return outer()->locator_address(loc);271}272} else {273assert(allocates2(branch_pc), "sanity");274address base = start();275int patch_loc = CodeBuffer::locator(branch_pc - base, index());276L.add_patch_at(outer(), patch_loc);277278// Need to return a pc, doesn't matter what it is since it will be279// replaced during resolution later.280// Don't return NULL or badAddress, since branches shouldn't overflow.281// Don't return base either because that could overflow displacements282// for shorter branches. It will get checked when bound.283return branch_pc;284}285}286287void CodeSection::relocate(address at, relocInfo::relocType rtype, int format, jint method_index) {288RelocationHolder rh;289switch (rtype) {290case relocInfo::none: return;291case relocInfo::opt_virtual_call_type: {292rh = opt_virtual_call_Relocation::spec(method_index);293break;294}295case relocInfo::static_call_type: {296rh = static_call_Relocation::spec(method_index);297break;298}299case relocInfo::virtual_call_type: {300assert(method_index == 0, "resolved method overriding is not supported");301rh = Relocation::spec_simple(rtype);302break;303}304default: {305rh = Relocation::spec_simple(rtype);306break;307}308}309relocate(at, rh, format);310}311312void CodeSection::relocate(address at, RelocationHolder const& spec, int format) {313// Do not relocate in scratch buffers.314if (scratch_emit()) { return; }315Relocation* reloc = spec.reloc();316relocInfo::relocType rtype = (relocInfo::relocType) reloc->type();317if (rtype == relocInfo::none) return;318319// The assertion below has been adjusted, to also work for320// relocation for fixup. Sometimes we want to put relocation321// information for the next instruction, since it will be patched322// with a call.323assert(start() <= at && at <= end()+1,324"cannot relocate data outside code boundaries");325326if (!has_locs()) {327// no space for relocation information provided => code cannot be328// relocated. Make sure that relocate is only called with rtypes329// that can be ignored for this kind of code.330assert(rtype == relocInfo::none ||331rtype == relocInfo::runtime_call_type ||332rtype == relocInfo::internal_word_type||333rtype == relocInfo::section_word_type ||334rtype == relocInfo::external_word_type,335"code needs relocation information");336// leave behind an indication that we attempted a relocation337DEBUG_ONLY(_locs_start = _locs_limit = (relocInfo*)badAddress);338return;339}340341// Advance the point, noting the offset we'll have to record.342csize_t offset = at - locs_point();343set_locs_point(at);344345// Test for a couple of overflow conditions; maybe expand the buffer.346relocInfo* end = locs_end();347relocInfo* req = end + relocInfo::length_limit;348// Check for (potential) overflow349if (req >= locs_limit() || offset >= relocInfo::offset_limit()) {350req += (uint)offset / (uint)relocInfo::offset_limit();351if (req >= locs_limit()) {352// Allocate or reallocate.353expand_locs(locs_count() + (req - end));354// reload pointer355end = locs_end();356}357}358359// If the offset is giant, emit filler relocs, of type 'none', but360// each carrying the largest possible offset, to advance the locs_point.361while (offset >= relocInfo::offset_limit()) {362assert(end < locs_limit(), "adjust previous paragraph of code");363*end++ = filler_relocInfo();364offset -= filler_relocInfo().addr_offset();365}366367// If it's a simple reloc with no data, we'll just write (rtype | offset).368(*end) = relocInfo(rtype, offset, format);369370// If it has data, insert the prefix, as (data_prefix_tag | data1), data2.371end->initialize(this, reloc);372}373374void CodeSection::initialize_locs(int locs_capacity) {375assert(_locs_start == NULL, "only one locs init step, please");376// Apply a priori lower limits to relocation size:377csize_t min_locs = MAX2(size() / 16, (csize_t)4);378if (locs_capacity < min_locs) locs_capacity = min_locs;379relocInfo* locs_start = NEW_RESOURCE_ARRAY(relocInfo, locs_capacity);380_locs_start = locs_start;381_locs_end = locs_start;382_locs_limit = locs_start + locs_capacity;383_locs_own = true;384}385386void CodeSection::initialize_shared_locs(relocInfo* buf, int length) {387assert(_locs_start == NULL, "do this before locs are allocated");388// Internal invariant: locs buf must be fully aligned.389// See copy_relocations_to() below.390while ((uintptr_t)buf % HeapWordSize != 0 && length > 0) {391++buf; --length;392}393if (length > 0) {394_locs_start = buf;395_locs_end = buf;396_locs_limit = buf + length;397_locs_own = false;398}399}400401void CodeSection::initialize_locs_from(const CodeSection* source_cs) {402int lcount = source_cs->locs_count();403if (lcount != 0) {404initialize_shared_locs(source_cs->locs_start(), lcount);405_locs_end = _locs_limit = _locs_start + lcount;406assert(is_allocated(), "must have copied code already");407set_locs_point(start() + source_cs->locs_point_off());408}409assert(this->locs_count() == source_cs->locs_count(), "sanity");410}411412void CodeSection::expand_locs(int new_capacity) {413if (_locs_start == NULL) {414initialize_locs(new_capacity);415return;416} else {417int old_count = locs_count();418int old_capacity = locs_capacity();419if (new_capacity < old_capacity * 2)420new_capacity = old_capacity * 2;421relocInfo* locs_start;422if (_locs_own) {423locs_start = REALLOC_RESOURCE_ARRAY(relocInfo, _locs_start, old_capacity, new_capacity);424} else {425locs_start = NEW_RESOURCE_ARRAY(relocInfo, new_capacity);426Copy::conjoint_jbytes(_locs_start, locs_start, old_capacity * sizeof(relocInfo));427_locs_own = true;428}429_locs_start = locs_start;430_locs_end = locs_start + old_count;431_locs_limit = locs_start + new_capacity;432}433}434435436/// Support for emitting the code to its final location.437/// The pattern is the same for all functions.438/// We iterate over all the sections, padding each to alignment.439440csize_t CodeBuffer::total_content_size() const {441csize_t size_so_far = 0;442for (int n = 0; n < (int)SECT_LIMIT; n++) {443const CodeSection* cs = code_section(n);444if (cs->is_empty()) continue; // skip trivial section445size_so_far = cs->align_at_start(size_so_far);446size_so_far += cs->size();447}448return size_so_far;449}450451void CodeBuffer::compute_final_layout(CodeBuffer* dest) const {452address buf = dest->_total_start;453csize_t buf_offset = 0;454assert(dest->_total_size >= total_content_size(), "must be big enough");455456{457// not sure why this is here, but why not...458int alignSize = MAX2((intx) sizeof(jdouble), CodeEntryAlignment);459assert( (dest->_total_start - _insts.start()) % alignSize == 0, "copy must preserve alignment");460}461462const CodeSection* prev_cs = NULL;463CodeSection* prev_dest_cs = NULL;464465for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {466// figure compact layout of each section467const CodeSection* cs = code_section(n);468csize_t csize = cs->size();469470CodeSection* dest_cs = dest->code_section(n);471if (!cs->is_empty()) {472// Compute initial padding; assign it to the previous non-empty guy.473// Cf. figure_expanded_capacities.474csize_t padding = cs->align_at_start(buf_offset) - buf_offset;475if (prev_dest_cs != NULL) {476if (padding != 0) {477buf_offset += padding;478prev_dest_cs->_limit += padding;479}480} else {481guarantee(padding == 0, "In first iteration no padding should be needed.");482}483prev_dest_cs = dest_cs;484prev_cs = cs;485}486487debug_only(dest_cs->_start = NULL); // defeat double-initialization assert488dest_cs->initialize(buf+buf_offset, csize);489dest_cs->set_end(buf+buf_offset+csize);490assert(dest_cs->is_allocated(), "must always be allocated");491assert(cs->is_empty() == dest_cs->is_empty(), "sanity");492493buf_offset += csize;494}495496// Done calculating sections; did it come out to the right end?497assert(buf_offset == total_content_size(), "sanity");498debug_only(dest->verify_section_allocation();)499}500501// Append an oop reference that keeps the class alive.502static void append_oop_references(GrowableArray<oop>* oops, Klass* k) {503oop cl = k->klass_holder();504if (cl != NULL && !oops->contains(cl)) {505oops->append(cl);506}507}508509void CodeBuffer::finalize_oop_references(const methodHandle& mh) {510NoSafepointVerifier nsv;511512GrowableArray<oop> oops;513514// Make sure that immediate metadata records something in the OopRecorder515for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {516// pull code out of each section517CodeSection* cs = code_section(n);518if (cs->is_empty()) continue; // skip trivial section519RelocIterator iter(cs);520while (iter.next()) {521if (iter.type() == relocInfo::metadata_type) {522metadata_Relocation* md = iter.metadata_reloc();523if (md->metadata_is_immediate()) {524Metadata* m = md->metadata_value();525if (oop_recorder()->is_real(m)) {526if (m->is_methodData()) {527m = ((MethodData*)m)->method();528}529if (m->is_method()) {530m = ((Method*)m)->method_holder();531}532if (m->is_klass()) {533append_oop_references(&oops, (Klass*)m);534} else {535// XXX This will currently occur for MDO which don't536// have a backpointer. This has to be fixed later.537m->print();538ShouldNotReachHere();539}540}541}542}543}544}545546if (!oop_recorder()->is_unused()) {547for (int i = 0; i < oop_recorder()->metadata_count(); i++) {548Metadata* m = oop_recorder()->metadata_at(i);549if (oop_recorder()->is_real(m)) {550if (m->is_methodData()) {551m = ((MethodData*)m)->method();552}553if (m->is_method()) {554m = ((Method*)m)->method_holder();555}556if (m->is_klass()) {557append_oop_references(&oops, (Klass*)m);558} else {559m->print();560ShouldNotReachHere();561}562}563}564565}566567// Add the class loader of Method* for the nmethod itself568append_oop_references(&oops, mh->method_holder());569570// Add any oops that we've found571Thread* thread = Thread::current();572for (int i = 0; i < oops.length(); i++) {573oop_recorder()->find_index((jobject)thread->handle_area()->allocate_handle(oops.at(i)));574}575}576577578579csize_t CodeBuffer::total_offset_of(const CodeSection* cs) const {580csize_t size_so_far = 0;581for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {582const CodeSection* cur_cs = code_section(n);583if (!cur_cs->is_empty()) {584size_so_far = cur_cs->align_at_start(size_so_far);585}586if (cur_cs->index() == cs->index()) {587return size_so_far;588}589size_so_far += cur_cs->size();590}591ShouldNotReachHere();592return -1;593}594595csize_t CodeBuffer::total_relocation_size() const {596csize_t total = copy_relocations_to(NULL); // dry run only597return (csize_t) align_up(total, HeapWordSize);598}599600csize_t CodeBuffer::copy_relocations_to(address buf, csize_t buf_limit, bool only_inst) const {601csize_t buf_offset = 0;602csize_t code_end_so_far = 0;603csize_t code_point_so_far = 0;604605assert((uintptr_t)buf % HeapWordSize == 0, "buf must be fully aligned");606assert(buf_limit % HeapWordSize == 0, "buf must be evenly sized");607608for (int n = (int) SECT_FIRST; n < (int)SECT_LIMIT; n++) {609if (only_inst && (n != (int)SECT_INSTS)) {610// Need only relocation info for code.611continue;612}613// pull relocs out of each section614const CodeSection* cs = code_section(n);615assert(!(cs->is_empty() && cs->locs_count() > 0), "sanity");616if (cs->is_empty()) continue; // skip trivial section617relocInfo* lstart = cs->locs_start();618relocInfo* lend = cs->locs_end();619csize_t lsize = (csize_t)( (address)lend - (address)lstart );620csize_t csize = cs->size();621code_end_so_far = cs->align_at_start(code_end_so_far);622623if (lsize > 0) {624// Figure out how to advance the combined relocation point625// first to the beginning of this section.626// We'll insert one or more filler relocs to span that gap.627// (Don't bother to improve this by editing the first reloc's offset.)628csize_t new_code_point = code_end_so_far;629for (csize_t jump;630code_point_so_far < new_code_point;631code_point_so_far += jump) {632jump = new_code_point - code_point_so_far;633relocInfo filler = filler_relocInfo();634if (jump >= filler.addr_offset()) {635jump = filler.addr_offset();636} else { // else shrink the filler to fit637filler = relocInfo(relocInfo::none, jump);638}639if (buf != NULL) {640assert(buf_offset + (csize_t)sizeof(filler) <= buf_limit, "filler in bounds");641*(relocInfo*)(buf+buf_offset) = filler;642}643buf_offset += sizeof(filler);644}645646// Update code point and end to skip past this section:647csize_t last_code_point = code_end_so_far + cs->locs_point_off();648assert(code_point_so_far <= last_code_point, "sanity");649code_point_so_far = last_code_point; // advance past this guy's relocs650}651code_end_so_far += csize; // advance past this guy's instructions too652653// Done with filler; emit the real relocations:654if (buf != NULL && lsize != 0) {655assert(buf_offset + lsize <= buf_limit, "target in bounds");656assert((uintptr_t)lstart % HeapWordSize == 0, "sane start");657if (buf_offset % HeapWordSize == 0) {658// Use wordwise copies if possible:659Copy::disjoint_words((HeapWord*)lstart,660(HeapWord*)(buf+buf_offset),661(lsize + HeapWordSize-1) / HeapWordSize);662} else {663Copy::conjoint_jbytes(lstart, buf+buf_offset, lsize);664}665}666buf_offset += lsize;667}668669// Align end of relocation info in target.670while (buf_offset % HeapWordSize != 0) {671if (buf != NULL) {672relocInfo padding = relocInfo(relocInfo::none, 0);673assert(buf_offset + (csize_t)sizeof(padding) <= buf_limit, "padding in bounds");674*(relocInfo*)(buf+buf_offset) = padding;675}676buf_offset += sizeof(relocInfo);677}678679assert(only_inst || code_end_so_far == total_content_size(), "sanity");680681return buf_offset;682}683684csize_t CodeBuffer::copy_relocations_to(CodeBlob* dest) const {685address buf = NULL;686csize_t buf_offset = 0;687csize_t buf_limit = 0;688689if (dest != NULL) {690buf = (address)dest->relocation_begin();691buf_limit = (address)dest->relocation_end() - buf;692}693// if dest == NULL, this is just the sizing pass694//695buf_offset = copy_relocations_to(buf, buf_limit, false);696697return buf_offset;698}699700void CodeBuffer::copy_code_to(CodeBlob* dest_blob) {701#ifndef PRODUCT702if (PrintNMethods && (WizardMode || Verbose)) {703tty->print("done with CodeBuffer:");704((CodeBuffer*)this)->print();705}706#endif //PRODUCT707708CodeBuffer dest(dest_blob);709assert(dest_blob->content_size() >= total_content_size(), "good sizing");710this->compute_final_layout(&dest);711712// Set beginning of constant table before relocating.713dest_blob->set_ctable_begin(dest.consts()->start());714715relocate_code_to(&dest);716717// transfer strings and comments from buffer to blob718NOT_PRODUCT(dest_blob->set_strings(_code_strings);)719720// Done moving code bytes; were they the right size?721assert((int)align_up(dest.total_content_size(), oopSize) == dest_blob->content_size(), "sanity");722723// Flush generated code724ICache::invalidate_range(dest_blob->code_begin(), dest_blob->code_size());725}726727// Move all my code into another code buffer. Consult applicable728// relocs to repair embedded addresses. The layout in the destination729// CodeBuffer is different to the source CodeBuffer: the destination730// CodeBuffer gets the final layout (consts, insts, stubs in order of731// ascending address).732void CodeBuffer::relocate_code_to(CodeBuffer* dest) const {733address dest_end = dest->_total_start + dest->_total_size;734address dest_filled = NULL;735for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {736// pull code out of each section737const CodeSection* cs = code_section(n);738if (cs->is_empty()) continue; // skip trivial section739CodeSection* dest_cs = dest->code_section(n);740assert(cs->size() == dest_cs->size(), "sanity");741csize_t usize = dest_cs->size();742csize_t wsize = align_up(usize, HeapWordSize);743assert(dest_cs->start() + wsize <= dest_end, "no overflow");744// Copy the code as aligned machine words.745// This may also include an uninitialized partial word at the end.746Copy::disjoint_words((HeapWord*)cs->start(),747(HeapWord*)dest_cs->start(),748wsize / HeapWordSize);749750if (dest->blob() == NULL) {751// Destination is a final resting place, not just another buffer.752// Normalize uninitialized bytes in the final padding.753Copy::fill_to_bytes(dest_cs->end(), dest_cs->remaining(),754Assembler::code_fill_byte());755}756// Keep track of the highest filled address757dest_filled = MAX2(dest_filled, dest_cs->end() + dest_cs->remaining());758759assert(cs->locs_start() != (relocInfo*)badAddress,760"this section carries no reloc storage, but reloc was attempted");761762// Make the new code copy use the old copy's relocations:763dest_cs->initialize_locs_from(cs);764}765766// Do relocation after all sections are copied.767// This is necessary if the code uses constants in stubs, which are768// relocated when the corresponding instruction in the code (e.g., a769// call) is relocated. Stubs are placed behind the main code770// section, so that section has to be copied before relocating.771for (int n = (int) SECT_FIRST; n < (int)SECT_LIMIT; n++) {772// pull code out of each section773const CodeSection* cs = code_section(n);774if (cs->is_empty()) continue; // skip trivial section775CodeSection* dest_cs = dest->code_section(n);776{ // Repair the pc relative information in the code after the move777RelocIterator iter(dest_cs);778while (iter.next()) {779iter.reloc()->fix_relocation_after_move(this, dest);780}781}782}783784if (dest->blob() == NULL && dest_filled != NULL) {785// Destination is a final resting place, not just another buffer.786// Normalize uninitialized bytes in the final padding.787Copy::fill_to_bytes(dest_filled, dest_end - dest_filled,788Assembler::code_fill_byte());789790}791}792793csize_t CodeBuffer::figure_expanded_capacities(CodeSection* which_cs,794csize_t amount,795csize_t* new_capacity) {796csize_t new_total_cap = 0;797798for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {799const CodeSection* sect = code_section(n);800801if (!sect->is_empty()) {802// Compute initial padding; assign it to the previous section,803// even if it's empty (e.g. consts section can be empty).804// Cf. compute_final_layout805csize_t padding = sect->align_at_start(new_total_cap) - new_total_cap;806if (padding != 0) {807new_total_cap += padding;808assert(n - 1 >= SECT_FIRST, "sanity");809new_capacity[n - 1] += padding;810}811}812813csize_t exp = sect->size(); // 100% increase814if ((uint)exp < 4*K) exp = 4*K; // minimum initial increase815if (sect == which_cs) {816if (exp < amount) exp = amount;817if (StressCodeBuffers) exp = amount; // expand only slightly818} else if (n == SECT_INSTS) {819// scale down inst increases to a more modest 25%820exp = 4*K + ((exp - 4*K) >> 2);821if (StressCodeBuffers) exp = amount / 2; // expand only slightly822} else if (sect->is_empty()) {823// do not grow an empty secondary section824exp = 0;825}826// Allow for inter-section slop:827exp += CodeSection::end_slop();828csize_t new_cap = sect->size() + exp;829if (new_cap < sect->capacity()) {830// No need to expand after all.831new_cap = sect->capacity();832}833new_capacity[n] = new_cap;834new_total_cap += new_cap;835}836837return new_total_cap;838}839840void CodeBuffer::expand(CodeSection* which_cs, csize_t amount) {841#ifndef PRODUCT842if (PrintNMethods && (WizardMode || Verbose)) {843tty->print("expanding CodeBuffer:");844this->print();845}846847if (StressCodeBuffers && blob() != NULL) {848static int expand_count = 0;849if (expand_count >= 0) expand_count += 1;850if (expand_count > 100 && is_power_of_2(expand_count)) {851tty->print_cr("StressCodeBuffers: have expanded %d times", expand_count);852// simulate an occasional allocation failure:853free_blob();854}855}856#endif //PRODUCT857858// Resizing must be allowed859{860if (blob() == NULL) return; // caller must check for blob == NULL861}862863// Figure new capacity for each section.864csize_t new_capacity[SECT_LIMIT];865memset(new_capacity, 0, sizeof(csize_t) * SECT_LIMIT);866csize_t new_total_cap867= figure_expanded_capacities(which_cs, amount, new_capacity);868869// Create a new (temporary) code buffer to hold all the new data870CodeBuffer cb(name(), new_total_cap, 0);871if (cb.blob() == NULL) {872// Failed to allocate in code cache.873free_blob();874return;875}876877// Create an old code buffer to remember which addresses used to go where.878// This will be useful when we do final assembly into the code cache,879// because we will need to know how to warp any internal address that880// has been created at any time in this CodeBuffer's past.881CodeBuffer* bxp = new CodeBuffer(_total_start, _total_size);882bxp->take_over_code_from(this); // remember the old undersized blob883DEBUG_ONLY(this->_blob = NULL); // silence a later assert884bxp->_before_expand = this->_before_expand;885this->_before_expand = bxp;886887// Give each section its required (expanded) capacity.888for (int n = (int)SECT_LIMIT-1; n >= SECT_FIRST; n--) {889CodeSection* cb_sect = cb.code_section(n);890CodeSection* this_sect = code_section(n);891if (new_capacity[n] == 0) continue; // already nulled out892if (n != SECT_INSTS) {893cb.initialize_section_size(cb_sect, new_capacity[n]);894}895assert(cb_sect->capacity() >= new_capacity[n], "big enough");896address cb_start = cb_sect->start();897cb_sect->set_end(cb_start + this_sect->size());898if (this_sect->mark() == NULL) {899cb_sect->clear_mark();900} else {901cb_sect->set_mark(cb_start + this_sect->mark_off());902}903}904905// Needs to be initialized when calling fix_relocation_after_move.906cb.blob()->set_ctable_begin(cb.consts()->start());907908// Move all the code and relocations to the new blob:909relocate_code_to(&cb);910911// Copy the temporary code buffer into the current code buffer.912// Basically, do {*this = cb}, except for some control information.913this->take_over_code_from(&cb);914cb.set_blob(NULL);915916// Zap the old code buffer contents, to avoid mistakenly using them.917debug_only(Copy::fill_to_bytes(bxp->_total_start, bxp->_total_size,918badCodeHeapFreeVal);)919920// Make certain that the new sections are all snugly inside the new blob.921debug_only(verify_section_allocation();)922923#ifndef PRODUCT924_decode_begin = NULL; // sanity925if (PrintNMethods && (WizardMode || Verbose)) {926tty->print("expanded CodeBuffer:");927this->print();928}929#endif //PRODUCT930}931932void CodeBuffer::take_over_code_from(CodeBuffer* cb) {933// Must already have disposed of the old blob somehow.934assert(blob() == NULL, "must be empty");935// Take the new blob away from cb.936set_blob(cb->blob());937// Take over all the section pointers.938for (int n = 0; n < (int)SECT_LIMIT; n++) {939CodeSection* cb_sect = cb->code_section(n);940CodeSection* this_sect = code_section(n);941this_sect->take_over_code_from(cb_sect);942}943_overflow_arena = cb->_overflow_arena;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