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