1 /* 2 * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "precompiled.hpp" 26 #include "asm/codeBuffer.hpp" 27 #include "code/oopRecorder.inline.hpp" 28 #include "compiler/disassembler.hpp" 29 #include "oops/methodData.hpp" 30 #include "oops/oop.inline.hpp" 31 #include "runtime/icache.hpp" 32 #include "runtime/safepointVerifiers.hpp" 33 #include "utilities/align.hpp" 34 #include "utilities/copy.hpp" 35 #include "utilities/xmlstream.hpp" 36 37 // The structure of a CodeSection: 38 // 39 // _start -> +----------------+ 40 // | machine code...| 41 // _end -> |----------------| 42 // | | 43 // | (empty) | 44 // | | 45 // | | 46 // +----------------+ 47 // _limit -> | | 48 // 49 // _locs_start -> +----------------+ 50 // |reloc records...| 51 // |----------------| 52 // _locs_end -> | | 53 // | | 54 // | (empty) | 55 // | | 56 // | | 57 // +----------------+ 58 // _locs_limit -> | | 59 // The _end (resp. _limit) pointer refers to the first 60 // unused (resp. unallocated) byte. 61 62 // The structure of the CodeBuffer while code is being accumulated: 63 // 64 // _total_start -> \ 65 // _insts._start -> +----------------+ 66 // | | 67 // | Code | 68 // | | 69 // _stubs._start -> |----------------| 70 // | | 71 // | Stubs | (also handlers for deopt/exception) 72 // | | 73 // _consts._start -> |----------------| 74 // | | 75 // | Constants | 76 // | | 77 // +----------------+ 78 // + _total_size -> | | 79 // 80 // When the code and relocations are copied to the code cache, 81 // the empty parts of each section are removed, and everything 82 // is copied into contiguous locations. 83 84 typedef CodeBuffer::csize_t csize_t; // file-local definition 85 86 // External buffer, in a predefined CodeBlob. 87 // Important: The code_start must be taken exactly, and not realigned. 88 CodeBuffer::CodeBuffer(CodeBlob* blob) { 89 initialize_misc("static buffer"); 90 initialize(blob->content_begin(), blob->content_size()); 91 verify_section_allocation(); 92 } 93 94 void CodeBuffer::initialize(csize_t code_size, csize_t locs_size) { 95 // Compute maximal alignment. 96 int align = _insts.alignment(); 97 // Always allow for empty slop around each section. 98 int slop = (int) CodeSection::end_slop(); 99 100 assert(blob() == NULL, "only once"); 101 set_blob(BufferBlob::create(_name, code_size + (align+slop) * (SECT_LIMIT+1))); 102 if (blob() == NULL) { 103 // The assembler constructor will throw a fatal on an empty CodeBuffer. 104 return; // caller must test this 105 } 106 107 // Set up various pointers into the blob. 108 initialize(_total_start, _total_size); 109 110 assert((uintptr_t)insts_begin() % CodeEntryAlignment == 0, "instruction start not code entry aligned"); 111 112 pd_initialize(); 113 114 if (locs_size != 0) { 115 _insts.initialize_locs(locs_size / sizeof(relocInfo)); 116 } 117 118 verify_section_allocation(); 119 } 120 121 122 CodeBuffer::~CodeBuffer() { 123 verify_section_allocation(); 124 125 // If we allocate our code buffer from the CodeCache 126 // via a BufferBlob, and it's not permanent, then 127 // free the BufferBlob. 128 // The rest of the memory will be freed when the ResourceObj 129 // is released. 130 for (CodeBuffer* cb = this; cb != NULL; cb = cb->before_expand()) { 131 // Previous incarnations of this buffer are held live, so that internal 132 // addresses constructed before expansions will not be confused. 133 cb->free_blob(); 134 } 135 136 // free any overflow storage 137 delete _overflow_arena; 138 139 // Claim is that stack allocation ensures resources are cleaned up. 140 // This is resource clean up, let's hope that all were properly copied out. 141 free_strings(); 142 143 #ifdef ASSERT 144 // Save allocation type to execute assert in ~ResourceObj() 145 // which is called after this destructor. 146 assert(_default_oop_recorder.allocated_on_stack(), "should be embedded object"); 147 ResourceObj::allocation_type at = _default_oop_recorder.get_allocation_type(); 148 Copy::fill_to_bytes(this, sizeof(*this), badResourceValue); 149 ResourceObj::set_allocation_type((address)(&_default_oop_recorder), at); 150 #endif 151 } 152 153 void CodeBuffer::initialize_oop_recorder(OopRecorder* r) { 154 assert(_oop_recorder == &_default_oop_recorder && _default_oop_recorder.is_unused(), "do this once"); 155 DEBUG_ONLY(_default_oop_recorder.freeze()); // force unused OR to be frozen 156 _oop_recorder = r; 157 } 158 159 void CodeBuffer::initialize_section_size(CodeSection* cs, csize_t size) { 160 assert(cs != &_insts, "insts is the memory provider, not the consumer"); 161 csize_t slop = CodeSection::end_slop(); // margin between sections 162 int align = cs->alignment(); 163 assert(is_power_of_2(align), "sanity"); 164 address start = _insts._start; 165 address limit = _insts._limit; 166 address middle = limit - size; 167 middle -= (intptr_t)middle & (align-1); // align the division point downward 168 guarantee(middle - slop > start, "need enough space to divide up"); 169 _insts._limit = middle - slop; // subtract desired space, plus slop 170 cs->initialize(middle, limit - middle); 171 assert(cs->start() == middle, "sanity"); 172 assert(cs->limit() == limit, "sanity"); 173 // give it some relocations to start with, if the main section has them 174 if (_insts.has_locs()) cs->initialize_locs(1); 175 } 176 177 void CodeBuffer::freeze_section(CodeSection* cs) { 178 CodeSection* next_cs = (cs == consts())? NULL: code_section(cs->index()+1); 179 csize_t frozen_size = cs->size(); 180 if (next_cs != NULL) { 181 frozen_size = next_cs->align_at_start(frozen_size); 182 } 183 address old_limit = cs->limit(); 184 address new_limit = cs->start() + frozen_size; 185 relocInfo* old_locs_limit = cs->locs_limit(); 186 relocInfo* new_locs_limit = cs->locs_end(); 187 // Patch the limits. 188 cs->_limit = new_limit; 189 cs->_locs_limit = new_locs_limit; 190 cs->_frozen = true; 191 if (next_cs != NULL && !next_cs->is_allocated() && !next_cs->is_frozen()) { 192 // Give remaining buffer space to the following section. 193 next_cs->initialize(new_limit, old_limit - new_limit); 194 next_cs->initialize_shared_locs(new_locs_limit, 195 old_locs_limit - new_locs_limit); 196 } 197 } 198 199 void CodeBuffer::set_blob(BufferBlob* blob) { 200 _blob = blob; 201 if (blob != NULL) { 202 address start = blob->content_begin(); 203 address end = blob->content_end(); 204 // Round up the starting address. 205 int align = _insts.alignment(); 206 start += (-(intptr_t)start) & (align-1); 207 _total_start = start; 208 _total_size = end - start; 209 } else { 210 #ifdef ASSERT 211 // Clean out dangling pointers. 212 _total_start = badAddress; 213 _consts._start = _consts._end = badAddress; 214 _insts._start = _insts._end = badAddress; 215 _stubs._start = _stubs._end = badAddress; 216 #endif //ASSERT 217 } 218 } 219 220 void CodeBuffer::free_blob() { 221 if (_blob != NULL) { 222 BufferBlob::free(_blob); 223 set_blob(NULL); 224 } 225 } 226 227 const char* CodeBuffer::code_section_name(int n) { 228 #ifdef PRODUCT 229 return NULL; 230 #else //PRODUCT 231 switch (n) { 232 case SECT_CONSTS: return "consts"; 233 case SECT_INSTS: return "insts"; 234 case SECT_STUBS: return "stubs"; 235 default: return NULL; 236 } 237 #endif //PRODUCT 238 } 239 240 int CodeBuffer::section_index_of(address addr) const { 241 for (int n = 0; n < (int)SECT_LIMIT; n++) { 242 const CodeSection* cs = code_section(n); 243 if (cs->allocates(addr)) return n; 244 } 245 return SECT_NONE; 246 } 247 248 int CodeBuffer::locator(address addr) const { 249 for (int n = 0; n < (int)SECT_LIMIT; n++) { 250 const CodeSection* cs = code_section(n); 251 if (cs->allocates(addr)) { 252 return locator(addr - cs->start(), n); 253 } 254 } 255 return -1; 256 } 257 258 address CodeBuffer::locator_address(int locator) const { 259 if (locator < 0) return NULL; 260 address start = code_section(locator_sect(locator))->start(); 261 return start + locator_pos(locator); 262 } 263 264 bool CodeBuffer::is_backward_branch(Label& L) { 265 return L.is_bound() && insts_end() <= locator_address(L.loc()); 266 } 267 268 address CodeBuffer::decode_begin() { 269 address begin = _insts.start(); 270 if (_decode_begin != NULL && _decode_begin > begin) 271 begin = _decode_begin; 272 return begin; 273 } 274 275 276 GrowableArray<int>* CodeBuffer::create_patch_overflow() { 277 if (_overflow_arena == NULL) { 278 _overflow_arena = new (mtCode) Arena(mtCode); 279 } 280 return new (_overflow_arena) GrowableArray<int>(_overflow_arena, 8, 0, 0); 281 } 282 283 284 // Helper function for managing labels and their target addresses. 285 // Returns a sensible address, and if it is not the label's final 286 // address, notes the dependency (at 'branch_pc') on the label. 287 address CodeSection::target(Label& L, address branch_pc) { 288 if (L.is_bound()) { 289 int loc = L.loc(); 290 if (index() == CodeBuffer::locator_sect(loc)) { 291 return start() + CodeBuffer::locator_pos(loc); 292 } else { 293 return outer()->locator_address(loc); 294 } 295 } else { 296 assert(allocates2(branch_pc), "sanity"); 297 address base = start(); 298 int patch_loc = CodeBuffer::locator(branch_pc - base, index()); 299 L.add_patch_at(outer(), patch_loc); 300 301 // Need to return a pc, doesn't matter what it is since it will be 302 // replaced during resolution later. 303 // Don't return NULL or badAddress, since branches shouldn't overflow. 304 // Don't return base either because that could overflow displacements 305 // for shorter branches. It will get checked when bound. 306 return branch_pc; 307 } 308 } 309 310 void CodeSection::relocate(address at, relocInfo::relocType rtype, int format, jint method_index) { 311 RelocationHolder rh; 312 switch (rtype) { 313 case relocInfo::none: return; 314 case relocInfo::opt_virtual_call_type: { 315 rh = opt_virtual_call_Relocation::spec(method_index); 316 break; 317 } 318 case relocInfo::static_call_type: { 319 rh = static_call_Relocation::spec(method_index); 320 break; 321 } 322 case relocInfo::virtual_call_type: { 323 assert(method_index == 0, "resolved method overriding is not supported"); 324 rh = Relocation::spec_simple(rtype); 325 break; 326 } 327 default: { 328 rh = Relocation::spec_simple(rtype); 329 break; 330 } 331 } 332 relocate(at, rh, format); 333 } 334 335 void CodeSection::relocate(address at, RelocationHolder const& spec, int format) { 336 // Do not relocate in scratch buffers. 337 if (scratch_emit()) { return; } 338 Relocation* reloc = spec.reloc(); 339 relocInfo::relocType rtype = (relocInfo::relocType) reloc->type(); 340 if (rtype == relocInfo::none) return; 341 342 // The assertion below has been adjusted, to also work for 343 // relocation for fixup. Sometimes we want to put relocation 344 // information for the next instruction, since it will be patched 345 // with a call. 346 assert(start() <= at && at <= end()+1, 347 "cannot relocate data outside code boundaries"); 348 349 if (!has_locs()) { 350 // no space for relocation information provided => code cannot be 351 // relocated. Make sure that relocate is only called with rtypes 352 // that can be ignored for this kind of code. 353 assert(rtype == relocInfo::none || 354 rtype == relocInfo::runtime_call_type || 355 rtype == relocInfo::internal_word_type|| 356 rtype == relocInfo::section_word_type || 357 rtype == relocInfo::external_word_type, 358 "code needs relocation information"); 359 // leave behind an indication that we attempted a relocation 360 DEBUG_ONLY(_locs_start = _locs_limit = (relocInfo*)badAddress); 361 return; 362 } 363 364 // Advance the point, noting the offset we'll have to record. 365 csize_t offset = at - locs_point(); 366 set_locs_point(at); 367 368 // Test for a couple of overflow conditions; maybe expand the buffer. 369 relocInfo* end = locs_end(); 370 relocInfo* req = end + relocInfo::length_limit; 371 // Check for (potential) overflow 372 if (req >= locs_limit() || offset >= relocInfo::offset_limit()) { 373 req += (uint)offset / (uint)relocInfo::offset_limit(); 374 if (req >= locs_limit()) { 375 // Allocate or reallocate. 376 expand_locs(locs_count() + (req - end)); 377 // reload pointer 378 end = locs_end(); 379 } 380 } 381 382 // If the offset is giant, emit filler relocs, of type 'none', but 383 // each carrying the largest possible offset, to advance the locs_point. 384 while (offset >= relocInfo::offset_limit()) { 385 assert(end < locs_limit(), "adjust previous paragraph of code"); 386 *end++ = filler_relocInfo(); 387 offset -= filler_relocInfo().addr_offset(); 388 } 389 390 // If it's a simple reloc with no data, we'll just write (rtype | offset). 391 (*end) = relocInfo(rtype, offset, format); 392 393 // If it has data, insert the prefix, as (data_prefix_tag | data1), data2. 394 end->initialize(this, reloc); 395 } 396 397 void CodeSection::initialize_locs(int locs_capacity) { 398 assert(_locs_start == NULL, "only one locs init step, please"); 399 // Apply a priori lower limits to relocation size: 400 csize_t min_locs = MAX2(size() / 16, (csize_t)4); 401 if (locs_capacity < min_locs) locs_capacity = min_locs; 402 relocInfo* locs_start = NEW_RESOURCE_ARRAY(relocInfo, locs_capacity); 403 _locs_start = locs_start; 404 _locs_end = locs_start; 405 _locs_limit = locs_start + locs_capacity; 406 _locs_own = true; 407 } 408 409 void CodeSection::initialize_shared_locs(relocInfo* buf, int length) { 410 assert(_locs_start == NULL, "do this before locs are allocated"); 411 // Internal invariant: locs buf must be fully aligned. 412 // See copy_relocations_to() below. 413 while ((uintptr_t)buf % HeapWordSize != 0 && length > 0) { 414 ++buf; --length; 415 } 416 if (length > 0) { 417 _locs_start = buf; 418 _locs_end = buf; 419 _locs_limit = buf + length; 420 _locs_own = false; 421 } 422 } 423 424 void CodeSection::initialize_locs_from(const CodeSection* source_cs) { 425 int lcount = source_cs->locs_count(); 426 if (lcount != 0) { 427 initialize_shared_locs(source_cs->locs_start(), lcount); 428 _locs_end = _locs_limit = _locs_start + lcount; 429 assert(is_allocated(), "must have copied code already"); 430 set_locs_point(start() + source_cs->locs_point_off()); 431 } 432 assert(this->locs_count() == source_cs->locs_count(), "sanity"); 433 } 434 435 void CodeSection::expand_locs(int new_capacity) { 436 if (_locs_start == NULL) { 437 initialize_locs(new_capacity); 438 return; 439 } else { 440 int old_count = locs_count(); 441 int old_capacity = locs_capacity(); 442 if (new_capacity < old_capacity * 2) 443 new_capacity = old_capacity * 2; 444 relocInfo* locs_start; 445 if (_locs_own) { 446 locs_start = REALLOC_RESOURCE_ARRAY(relocInfo, _locs_start, old_capacity, new_capacity); 447 } else { 448 locs_start = NEW_RESOURCE_ARRAY(relocInfo, new_capacity); 449 Copy::conjoint_jbytes(_locs_start, locs_start, old_capacity * sizeof(relocInfo)); 450 _locs_own = true; 451 } 452 _locs_start = locs_start; 453 _locs_end = locs_start + old_count; 454 _locs_limit = locs_start + new_capacity; 455 } 456 } 457 458 459 /// Support for emitting the code to its final location. 460 /// The pattern is the same for all functions. 461 /// We iterate over all the sections, padding each to alignment. 462 463 csize_t CodeBuffer::total_content_size() const { 464 csize_t size_so_far = 0; 465 for (int n = 0; n < (int)SECT_LIMIT; n++) { 466 const CodeSection* cs = code_section(n); 467 if (cs->is_empty()) continue; // skip trivial section 468 size_so_far = cs->align_at_start(size_so_far); 469 size_so_far += cs->size(); 470 } 471 return size_so_far; 472 } 473 474 void CodeBuffer::compute_final_layout(CodeBuffer* dest) const { 475 address buf = dest->_total_start; 476 csize_t buf_offset = 0; 477 assert(dest->_total_size >= total_content_size(), "must be big enough"); 478 479 { 480 // not sure why this is here, but why not... 481 int alignSize = MAX2((intx) sizeof(jdouble), CodeEntryAlignment); 482 assert( (dest->_total_start - _insts.start()) % alignSize == 0, "copy must preserve alignment"); 483 } 484 485 const CodeSection* prev_cs = NULL; 486 CodeSection* prev_dest_cs = NULL; 487 488 for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) { 489 // figure compact layout of each section 490 const CodeSection* cs = code_section(n); 491 csize_t csize = cs->size(); 492 493 CodeSection* dest_cs = dest->code_section(n); 494 if (!cs->is_empty()) { 495 // Compute initial padding; assign it to the previous non-empty guy. 496 // Cf. figure_expanded_capacities. 497 csize_t padding = cs->align_at_start(buf_offset) - buf_offset; 498 if (prev_dest_cs != NULL) { 499 if (padding != 0) { 500 buf_offset += padding; 501 prev_dest_cs->_limit += padding; 502 } 503 } else { 504 guarantee(padding == 0, "In first iteration no padding should be needed."); 505 } 506 #ifdef ASSERT 507 if (prev_cs != NULL && prev_cs->is_frozen() && n < (SECT_LIMIT - 1)) { 508 // Make sure the ends still match up. 509 // This is important because a branch in a frozen section 510 // might target code in a following section, via a Label, 511 // and without a relocation record. See Label::patch_instructions. 512 address dest_start = buf+buf_offset; 513 csize_t start2start = cs->start() - prev_cs->start(); 514 csize_t dest_start2start = dest_start - prev_dest_cs->start(); 515 assert(start2start == dest_start2start, "cannot stretch frozen sect"); 516 } 517 #endif //ASSERT 518 prev_dest_cs = dest_cs; 519 prev_cs = cs; 520 } 521 522 debug_only(dest_cs->_start = NULL); // defeat double-initialization assert 523 dest_cs->initialize(buf+buf_offset, csize); 524 dest_cs->set_end(buf+buf_offset+csize); 525 assert(dest_cs->is_allocated(), "must always be allocated"); 526 assert(cs->is_empty() == dest_cs->is_empty(), "sanity"); 527 528 buf_offset += csize; 529 } 530 531 // Done calculating sections; did it come out to the right end? 532 assert(buf_offset == total_content_size(), "sanity"); 533 dest->verify_section_allocation(); 534 } 535 536 // Append an oop reference that keeps the class alive. 537 static void append_oop_references(GrowableArray<oop>* oops, Klass* k) { 538 oop cl = k->klass_holder(); 539 if (cl != NULL && !oops->contains(cl)) { 540 oops->append(cl); 541 } 542 } 543 544 void CodeBuffer::finalize_oop_references(const methodHandle& mh) { 545 NoSafepointVerifier nsv; 546 547 GrowableArray<oop> oops; 548 549 // Make sure that immediate metadata records something in the OopRecorder 550 for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) { 551 // pull code out of each section 552 CodeSection* cs = code_section(n); 553 if (cs->is_empty()) continue; // skip trivial section 554 RelocIterator iter(cs); 555 while (iter.next()) { 556 if (iter.type() == relocInfo::metadata_type) { 557 metadata_Relocation* md = iter.metadata_reloc(); 558 if (md->metadata_is_immediate()) { 559 Metadata* m = md->metadata_value(); 560 if (oop_recorder()->is_real(m)) { 561 if (m->is_methodData()) { 562 m = ((MethodData*)m)->method(); 563 } 564 if (m->is_method()) { 565 m = ((Method*)m)->method_holder(); 566 } 567 if (m->is_klass()) { 568 append_oop_references(&oops, (Klass*)m); 569 } else { 570 // XXX This will currently occur for MDO which don't 571 // have a backpointer. This has to be fixed later. 572 m->print(); 573 ShouldNotReachHere(); 574 } 575 } 576 } 577 } 578 } 579 } 580 581 if (!oop_recorder()->is_unused()) { 582 for (int i = 0; i < oop_recorder()->metadata_count(); i++) { 583 Metadata* m = oop_recorder()->metadata_at(i); 584 if (oop_recorder()->is_real(m)) { 585 if (m->is_methodData()) { 586 m = ((MethodData*)m)->method(); 587 } 588 if (m->is_method()) { 589 m = ((Method*)m)->method_holder(); 590 } 591 if (m->is_klass()) { 592 append_oop_references(&oops, (Klass*)m); 593 } else { 594 m->print(); 595 ShouldNotReachHere(); 596 } 597 } 598 } 599 600 } 601 602 // Add the class loader of Method* for the nmethod itself 603 append_oop_references(&oops, mh->method_holder()); 604 605 // Add any oops that we've found 606 Thread* thread = Thread::current(); 607 for (int i = 0; i < oops.length(); i++) { 608 oop_recorder()->find_index((jobject)thread->handle_area()->allocate_handle(oops.at(i))); 609 } 610 } 611 612 613 614 csize_t CodeBuffer::total_offset_of(const CodeSection* cs) const { 615 csize_t size_so_far = 0; 616 for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) { 617 const CodeSection* cur_cs = code_section(n); 618 if (!cur_cs->is_empty()) { 619 size_so_far = cur_cs->align_at_start(size_so_far); 620 } 621 if (cur_cs->index() == cs->index()) { 622 return size_so_far; 623 } 624 size_so_far += cur_cs->size(); 625 } 626 ShouldNotReachHere(); 627 return -1; 628 } 629 630 csize_t CodeBuffer::total_relocation_size() const { 631 csize_t total = copy_relocations_to(NULL); // dry run only 632 return (csize_t) align_up(total, HeapWordSize); 633 } 634 635 csize_t CodeBuffer::copy_relocations_to(address buf, csize_t buf_limit, bool only_inst) const { 636 csize_t buf_offset = 0; 637 csize_t code_end_so_far = 0; 638 csize_t code_point_so_far = 0; 639 640 assert((uintptr_t)buf % HeapWordSize == 0, "buf must be fully aligned"); 641 assert(buf_limit % HeapWordSize == 0, "buf must be evenly sized"); 642 643 for (int n = (int) SECT_FIRST; n < (int)SECT_LIMIT; n++) { 644 if (only_inst && (n != (int)SECT_INSTS)) { 645 // Need only relocation info for code. 646 continue; 647 } 648 // pull relocs out of each section 649 const CodeSection* cs = code_section(n); 650 assert(!(cs->is_empty() && cs->locs_count() > 0), "sanity"); 651 if (cs->is_empty()) continue; // skip trivial section 652 relocInfo* lstart = cs->locs_start(); 653 relocInfo* lend = cs->locs_end(); 654 csize_t lsize = (csize_t)( (address)lend - (address)lstart ); 655 csize_t csize = cs->size(); 656 code_end_so_far = cs->align_at_start(code_end_so_far); 657 658 if (lsize > 0) { 659 // Figure out how to advance the combined relocation point 660 // first to the beginning of this section. 661 // We'll insert one or more filler relocs to span that gap. 662 // (Don't bother to improve this by editing the first reloc's offset.) 663 csize_t new_code_point = code_end_so_far; 664 for (csize_t jump; 665 code_point_so_far < new_code_point; 666 code_point_so_far += jump) { 667 jump = new_code_point - code_point_so_far; 668 relocInfo filler = filler_relocInfo(); 669 if (jump >= filler.addr_offset()) { 670 jump = filler.addr_offset(); 671 } else { // else shrink the filler to fit 672 filler = relocInfo(relocInfo::none, jump); 673 } 674 if (buf != NULL) { 675 assert(buf_offset + (csize_t)sizeof(filler) <= buf_limit, "filler in bounds"); 676 *(relocInfo*)(buf+buf_offset) = filler; 677 } 678 buf_offset += sizeof(filler); 679 } 680 681 // Update code point and end to skip past this section: 682 csize_t last_code_point = code_end_so_far + cs->locs_point_off(); 683 assert(code_point_so_far <= last_code_point, "sanity"); 684 code_point_so_far = last_code_point; // advance past this guy's relocs 685 } 686 code_end_so_far += csize; // advance past this guy's instructions too 687 688 // Done with filler; emit the real relocations: 689 if (buf != NULL && lsize != 0) { 690 assert(buf_offset + lsize <= buf_limit, "target in bounds"); 691 assert((uintptr_t)lstart % HeapWordSize == 0, "sane start"); 692 if (buf_offset % HeapWordSize == 0) { 693 // Use wordwise copies if possible: 694 Copy::disjoint_words((HeapWord*)lstart, 695 (HeapWord*)(buf+buf_offset), 696 (lsize + HeapWordSize-1) / HeapWordSize); 697 } else { 698 Copy::conjoint_jbytes(lstart, buf+buf_offset, lsize); 699 } 700 } 701 buf_offset += lsize; 702 } 703 704 // Align end of relocation info in target. 705 while (buf_offset % HeapWordSize != 0) { 706 if (buf != NULL) { 707 relocInfo padding = relocInfo(relocInfo::none, 0); 708 assert(buf_offset + (csize_t)sizeof(padding) <= buf_limit, "padding in bounds"); 709 *(relocInfo*)(buf+buf_offset) = padding; 710 } 711 buf_offset += sizeof(relocInfo); 712 } 713 714 assert(only_inst || code_end_so_far == total_content_size(), "sanity"); 715 716 return buf_offset; 717 } 718 719 csize_t CodeBuffer::copy_relocations_to(CodeBlob* dest) const { 720 address buf = NULL; 721 csize_t buf_offset = 0; 722 csize_t buf_limit = 0; 723 724 if (dest != NULL) { 725 buf = (address)dest->relocation_begin(); 726 buf_limit = (address)dest->relocation_end() - buf; 727 } 728 // if dest == NULL, this is just the sizing pass 729 // 730 buf_offset = copy_relocations_to(buf, buf_limit, false); 731 732 return buf_offset; 733 } 734 735 void CodeBuffer::copy_code_to(CodeBlob* dest_blob) { 736 #ifndef PRODUCT 737 if (PrintNMethods && (WizardMode || Verbose)) { 738 tty->print("done with CodeBuffer:"); 739 ((CodeBuffer*)this)->print(); 740 } 741 #endif //PRODUCT 742 743 CodeBuffer dest(dest_blob); 744 assert(dest_blob->content_size() >= total_content_size(), "good sizing"); 745 this->compute_final_layout(&dest); 746 747 // Set beginning of constant table before relocating. 748 dest_blob->set_ctable_begin(dest.consts()->start()); 749 750 relocate_code_to(&dest); 751 752 // transfer strings and comments from buffer to blob 753 dest_blob->set_strings(_code_strings); 754 755 // Done moving code bytes; were they the right size? 756 assert((int)align_up(dest.total_content_size(), oopSize) == dest_blob->content_size(), "sanity"); 757 758 // Flush generated code 759 ICache::invalidate_range(dest_blob->code_begin(), dest_blob->code_size()); 760 } 761 762 // Move all my code into another code buffer. Consult applicable 763 // relocs to repair embedded addresses. The layout in the destination 764 // CodeBuffer is different to the source CodeBuffer: the destination 765 // CodeBuffer gets the final layout (consts, insts, stubs in order of 766 // ascending address). 767 void CodeBuffer::relocate_code_to(CodeBuffer* dest) const { 768 address dest_end = dest->_total_start + dest->_total_size; 769 address dest_filled = NULL; 770 for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) { 771 // pull code out of each section 772 const CodeSection* cs = code_section(n); 773 if (cs->is_empty()) continue; // skip trivial section 774 CodeSection* dest_cs = dest->code_section(n); 775 assert(cs->size() == dest_cs->size(), "sanity"); 776 csize_t usize = dest_cs->size(); 777 csize_t wsize = align_up(usize, HeapWordSize); 778 assert(dest_cs->start() + wsize <= dest_end, "no overflow"); 779 // Copy the code as aligned machine words. 780 // This may also include an uninitialized partial word at the end. 781 Copy::disjoint_words((HeapWord*)cs->start(), 782 (HeapWord*)dest_cs->start(), 783 wsize / HeapWordSize); 784 785 if (dest->blob() == NULL) { 786 // Destination is a final resting place, not just another buffer. 787 // Normalize uninitialized bytes in the final padding. 788 Copy::fill_to_bytes(dest_cs->end(), dest_cs->remaining(), 789 Assembler::code_fill_byte()); 790 } 791 // Keep track of the highest filled address 792 dest_filled = MAX2(dest_filled, dest_cs->end() + dest_cs->remaining()); 793 794 assert(cs->locs_start() != (relocInfo*)badAddress, 795 "this section carries no reloc storage, but reloc was attempted"); 796 797 // Make the new code copy use the old copy's relocations: 798 dest_cs->initialize_locs_from(cs); 799 } 800 801 // Do relocation after all sections are copied. 802 // This is necessary if the code uses constants in stubs, which are 803 // relocated when the corresponding instruction in the code (e.g., a 804 // call) is relocated. Stubs are placed behind the main code 805 // section, so that section has to be copied before relocating. 806 for (int n = (int) SECT_FIRST; n < (int)SECT_LIMIT; n++) { 807 // pull code out of each section 808 const CodeSection* cs = code_section(n); 809 if (cs->is_empty()) continue; // skip trivial section 810 CodeSection* dest_cs = dest->code_section(n); 811 { // Repair the pc relative information in the code after the move 812 RelocIterator iter(dest_cs); 813 while (iter.next()) { 814 iter.reloc()->fix_relocation_after_move(this, dest); 815 } 816 } 817 } 818 819 if (dest->blob() == NULL && dest_filled != NULL) { 820 // Destination is a final resting place, not just another buffer. 821 // Normalize uninitialized bytes in the final padding. 822 Copy::fill_to_bytes(dest_filled, dest_end - dest_filled, 823 Assembler::code_fill_byte()); 824 825 } 826 } 827 828 csize_t CodeBuffer::figure_expanded_capacities(CodeSection* which_cs, 829 csize_t amount, 830 csize_t* new_capacity) { 831 csize_t new_total_cap = 0; 832 833 for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) { 834 const CodeSection* sect = code_section(n); 835 836 if (!sect->is_empty()) { 837 // Compute initial padding; assign it to the previous section, 838 // even if it's empty (e.g. consts section can be empty). 839 // Cf. compute_final_layout 840 csize_t padding = sect->align_at_start(new_total_cap) - new_total_cap; 841 if (padding != 0) { 842 new_total_cap += padding; 843 assert(n - 1 >= SECT_FIRST, "sanity"); 844 new_capacity[n - 1] += padding; 845 } 846 } 847 848 csize_t exp = sect->size(); // 100% increase 849 if ((uint)exp < 4*K) exp = 4*K; // minimum initial increase 850 if (sect == which_cs) { 851 if (exp < amount) exp = amount; 852 if (StressCodeBuffers) exp = amount; // expand only slightly 853 } else if (n == SECT_INSTS) { 854 // scale down inst increases to a more modest 25% 855 exp = 4*K + ((exp - 4*K) >> 2); 856 if (StressCodeBuffers) exp = amount / 2; // expand only slightly 857 } else if (sect->is_empty()) { 858 // do not grow an empty secondary section 859 exp = 0; 860 } 861 // Allow for inter-section slop: 862 exp += CodeSection::end_slop(); 863 csize_t new_cap = sect->size() + exp; 864 if (new_cap < sect->capacity()) { 865 // No need to expand after all. 866 new_cap = sect->capacity(); 867 } 868 new_capacity[n] = new_cap; 869 new_total_cap += new_cap; 870 } 871 872 return new_total_cap; 873 } 874 875 void CodeBuffer::expand(CodeSection* which_cs, csize_t amount) { 876 #ifndef PRODUCT 877 if (PrintNMethods && (WizardMode || Verbose)) { 878 tty->print("expanding CodeBuffer:"); 879 this->print(); 880 } 881 882 if (StressCodeBuffers && blob() != NULL) { 883 static int expand_count = 0; 884 if (expand_count >= 0) expand_count += 1; 885 if (expand_count > 100 && is_power_of_2(expand_count)) { 886 tty->print_cr("StressCodeBuffers: have expanded %d times", expand_count); 887 // simulate an occasional allocation failure: 888 free_blob(); 889 } 890 } 891 #endif //PRODUCT 892 893 // Resizing must be allowed 894 { 895 if (blob() == NULL) return; // caller must check for blob == NULL 896 for (int n = 0; n < (int)SECT_LIMIT; n++) { 897 guarantee(!code_section(n)->is_frozen(), "resizing not allowed when frozen"); 898 } 899 } 900 901 // Figure new capacity for each section. 902 csize_t new_capacity[SECT_LIMIT]; 903 memset(new_capacity, 0, sizeof(csize_t) * SECT_LIMIT); 904 csize_t new_total_cap 905 = figure_expanded_capacities(which_cs, amount, new_capacity); 906 907 // Create a new (temporary) code buffer to hold all the new data 908 CodeBuffer cb(name(), new_total_cap, 0); 909 if (cb.blob() == NULL) { 910 // Failed to allocate in code cache. 911 free_blob(); 912 return; 913 } 914 915 // Create an old code buffer to remember which addresses used to go where. 916 // This will be useful when we do final assembly into the code cache, 917 // because we will need to know how to warp any internal address that 918 // has been created at any time in this CodeBuffer's past. 919 CodeBuffer* bxp = new CodeBuffer(_total_start, _total_size); 920 bxp->take_over_code_from(this); // remember the old undersized blob 921 DEBUG_ONLY(this->_blob = NULL); // silence a later assert 922 bxp->_before_expand = this->_before_expand; 923 this->_before_expand = bxp; 924 925 // Give each section its required (expanded) capacity. 926 for (int n = (int)SECT_LIMIT-1; n >= SECT_FIRST; n--) { 927 CodeSection* cb_sect = cb.code_section(n); 928 CodeSection* this_sect = code_section(n); 929 if (new_capacity[n] == 0) continue; // already nulled out 930 if (n != SECT_INSTS) { 931 cb.initialize_section_size(cb_sect, new_capacity[n]); 932 } 933 assert(cb_sect->capacity() >= new_capacity[n], "big enough"); 934 address cb_start = cb_sect->start(); 935 cb_sect->set_end(cb_start + this_sect->size()); 936 if (this_sect->mark() == NULL) { 937 cb_sect->clear_mark(); 938 } else { 939 cb_sect->set_mark(cb_start + this_sect->mark_off()); 940 } 941 } 942 943 // Needs to be initialized when calling fix_relocation_after_move. 944 cb.blob()->set_ctable_begin(cb.consts()->start()); 945 946 // Move all the code and relocations to the new blob: 947 relocate_code_to(&cb); 948 949 // Copy the temporary code buffer into the current code buffer. 950 // Basically, do {*this = cb}, except for some control information. 951 this->take_over_code_from(&cb); 952 cb.set_blob(NULL); 953 954 // Zap the old code buffer contents, to avoid mistakenly using them. 955 debug_only(Copy::fill_to_bytes(bxp->_total_start, bxp->_total_size, 956 badCodeHeapFreeVal)); 957 958 _decode_begin = NULL; // sanity 959 960 // Make certain that the new sections are all snugly inside the new blob. 961 verify_section_allocation(); 962 963 #ifndef PRODUCT 964 if (PrintNMethods && (WizardMode || Verbose)) { 965 tty->print("expanded CodeBuffer:"); 966 this->print(); 967 } 968 #endif //PRODUCT 969 } 970 971 void CodeBuffer::take_over_code_from(CodeBuffer* cb) { 972 // Must already have disposed of the old blob somehow. 973 assert(blob() == NULL, "must be empty"); 974 // Take the new blob away from cb. 975 set_blob(cb->blob()); 976 // Take over all the section pointers. 977 for (int n = 0; n < (int)SECT_LIMIT; n++) { 978 CodeSection* cb_sect = cb->code_section(n); 979 CodeSection* this_sect = code_section(n); 980 this_sect->take_over_code_from(cb_sect); 981 } 982 _overflow_arena = cb->_overflow_arena; 983 // Make sure the old cb won't try to use it or free it. 984 DEBUG_ONLY(cb->_blob = (BufferBlob*)badAddress); 985 } 986 987 void CodeBuffer::verify_section_allocation() { 988 address tstart = _total_start; 989 if (tstart == badAddress) return; // smashed by set_blob(NULL) 990 address tend = tstart + _total_size; 991 if (_blob != NULL) { 992 993 guarantee(tstart >= _blob->content_begin(), "sanity"); 994 guarantee(tend <= _blob->content_end(), "sanity"); 995 } 996 // Verify disjointness. 997 for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) { 998 CodeSection* sect = code_section(n); 999 if (!sect->is_allocated() || sect->is_empty()) continue; 1000 guarantee((intptr_t)sect->start() % sect->alignment() == 0 1001 || sect->is_empty() || _blob == NULL, 1002 "start is aligned"); 1003 for (int m = (int) SECT_FIRST; m < (int) SECT_LIMIT; m++) { 1004 CodeSection* other = code_section(m); 1005 if (!other->is_allocated() || other == sect) continue; 1006 guarantee(!other->contains(sect->start() ), "sanity"); 1007 // limit is an exclusive address and can be the start of another 1008 // section. 1009 guarantee(!other->contains(sect->limit() - 1), "sanity"); 1010 } 1011 guarantee(sect->end() <= tend, "sanity"); 1012 guarantee(sect->end() <= sect->limit(), "sanity"); 1013 } 1014 } 1015 1016 void CodeBuffer::log_section_sizes(const char* name) { 1017 if (xtty != NULL) { 1018 ttyLocker ttyl; 1019 // log info about buffer usage 1020 xtty->print_cr("<blob name='%s' size='%d'>", name, _total_size); 1021 for (int n = (int) CodeBuffer::SECT_FIRST; n < (int) CodeBuffer::SECT_LIMIT; n++) { 1022 CodeSection* sect = code_section(n); 1023 if (!sect->is_allocated() || sect->is_empty()) continue; 1024 xtty->print_cr("<sect index='%d' size='" SIZE_FORMAT "' free='" SIZE_FORMAT "'/>", 1025 n, sect->limit() - sect->start(), sect->limit() - sect->end()); 1026 } 1027 xtty->print_cr("</blob>"); 1028 } 1029 } 1030 1031 #ifndef PRODUCT 1032 1033 void CodeSection::decode() { 1034 Disassembler::decode(start(), end()); 1035 } 1036 1037 void CodeBuffer::block_comment(intptr_t offset, const char * comment) { 1038 _code_strings.add_comment(offset, comment); 1039 } 1040 1041 const char* CodeBuffer::code_string(const char* str) { 1042 return _code_strings.add_string(str); 1043 } 1044 1045 class CodeString: public CHeapObj<mtCode> { 1046 private: 1047 friend class CodeStrings; 1048 const char * _string; 1049 CodeString* _next; 1050 intptr_t _offset; 1051 1052 ~CodeString() { 1053 assert(_next == NULL, "wrong interface for freeing list"); 1054 os::free((void*)_string); 1055 } 1056 1057 bool is_comment() const { return _offset >= 0; } 1058 1059 public: 1060 CodeString(const char * string, intptr_t offset = -1) 1061 : _next(NULL), _offset(offset) { 1062 _string = os::strdup(string, mtCode); 1063 } 1064 1065 const char * string() const { return _string; } 1066 intptr_t offset() const { assert(_offset >= 0, "offset for non comment?"); return _offset; } 1067 CodeString* next() const { return _next; } 1068 1069 void set_next(CodeString* next) { _next = next; } 1070 1071 CodeString* first_comment() { 1072 if (is_comment()) { 1073 return this; 1074 } else { 1075 return next_comment(); 1076 } 1077 } 1078 CodeString* next_comment() const { 1079 CodeString* s = _next; 1080 while (s != NULL && !s->is_comment()) { 1081 s = s->_next; 1082 } 1083 return s; 1084 } 1085 }; 1086 1087 CodeString* CodeStrings::find(intptr_t offset) const { 1088 CodeString* a = _strings->first_comment(); 1089 while (a != NULL && a->offset() != offset) { 1090 a = a->next_comment(); 1091 } 1092 return a; 1093 } 1094 1095 // Convenience for add_comment. 1096 CodeString* CodeStrings::find_last(intptr_t offset) const { 1097 CodeString* a = find(offset); 1098 if (a != NULL) { 1099 CodeString* c = NULL; 1100 while (((c = a->next_comment()) != NULL) && (c->offset() == offset)) { 1101 a = c; 1102 } 1103 } 1104 return a; 1105 } 1106 1107 void CodeStrings::add_comment(intptr_t offset, const char * comment) { 1108 check_valid(); 1109 CodeString* c = new CodeString(comment, offset); 1110 CodeString* inspos = (_strings == NULL) ? NULL : find_last(offset); 1111 1112 if (inspos) { 1113 // insert after already existing comments with same offset 1114 c->set_next(inspos->next()); 1115 inspos->set_next(c); 1116 } else { 1117 // no comments with such offset, yet. Insert before anything else. 1118 c->set_next(_strings); 1119 _strings = c; 1120 } 1121 } 1122 1123 void CodeStrings::assign(CodeStrings& other) { 1124 other.check_valid(); 1125 assert(is_null(), "Cannot assign onto non-empty CodeStrings"); 1126 _strings = other._strings; 1127 #ifdef ASSERT 1128 _defunct = false; 1129 #endif 1130 other.set_null_and_invalidate(); 1131 } 1132 1133 // Deep copy of CodeStrings for consistent memory management. 1134 // Only used for actual disassembly so this is cheaper than reference counting 1135 // for the "normal" fastdebug case. 1136 void CodeStrings::copy(CodeStrings& other) { 1137 other.check_valid(); 1138 check_valid(); 1139 assert(is_null(), "Cannot copy onto non-empty CodeStrings"); 1140 CodeString* n = other._strings; 1141 CodeString** ps = &_strings; 1142 while (n != NULL) { 1143 *ps = new CodeString(n->string(),n->offset()); 1144 ps = &((*ps)->_next); 1145 n = n->next(); 1146 } 1147 } 1148 1149 const char* CodeStrings::_prefix = " ;; "; // default: can be changed via set_prefix 1150 1151 void CodeStrings::print_block_comment(outputStream* stream, intptr_t offset) const { 1152 check_valid(); 1153 if (_strings != NULL) { 1154 CodeString* c = find(offset); 1155 while (c && c->offset() == offset) { 1156 stream->bol(); 1157 stream->print("%s", _prefix); 1158 // Don't interpret as format strings since it could contain % 1159 stream->print_raw_cr(c->string()); 1160 c = c->next_comment(); 1161 } 1162 } 1163 } 1164 1165 // Also sets isNull() 1166 void CodeStrings::free() { 1167 CodeString* n = _strings; 1168 while (n) { 1169 // unlink the node from the list saving a pointer to the next 1170 CodeString* p = n->next(); 1171 n->set_next(NULL); 1172 delete n; 1173 n = p; 1174 } 1175 set_null_and_invalidate(); 1176 } 1177 1178 const char* CodeStrings::add_string(const char * string) { 1179 check_valid(); 1180 CodeString* s = new CodeString(string); 1181 s->set_next(_strings); 1182 _strings = s; 1183 assert(s->string() != NULL, "should have a string"); 1184 return s->string(); 1185 } 1186 1187 void CodeBuffer::decode() { 1188 ttyLocker ttyl; 1189 Disassembler::decode(decode_begin(), insts_end()); 1190 _decode_begin = insts_end(); 1191 } 1192 1193 void CodeSection::print(const char* name) { 1194 csize_t locs_size = locs_end() - locs_start(); 1195 tty->print_cr(" %7s.code = " PTR_FORMAT " : " PTR_FORMAT " : " PTR_FORMAT " (%d of %d)%s", 1196 name, p2i(start()), p2i(end()), p2i(limit()), size(), capacity(), 1197 is_frozen()? " [frozen]": ""); 1198 tty->print_cr(" %7s.locs = " PTR_FORMAT " : " PTR_FORMAT " : " PTR_FORMAT " (%d of %d) point=%d", 1199 name, p2i(locs_start()), p2i(locs_end()), p2i(locs_limit()), locs_size, locs_capacity(), locs_point_off()); 1200 if (PrintRelocations) { 1201 RelocIterator iter(this); 1202 iter.print(); 1203 } 1204 } 1205 1206 void CodeBuffer::print() { 1207 if (this == NULL) { 1208 tty->print_cr("NULL CodeBuffer pointer"); 1209 return; 1210 } 1211 1212 tty->print_cr("CodeBuffer:"); 1213 for (int n = 0; n < (int)SECT_LIMIT; n++) { 1214 // print each section 1215 CodeSection* cs = code_section(n); 1216 cs->print(code_section_name(n)); 1217 } 1218 } 1219 1220 #endif // PRODUCT