Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/src/hotspot/share/asm/codeBuffer.cpp
64440 views
1
/*
2
* Copyright (c) 1997, 2022, 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
// free any overflow storage
139
delete cb->_overflow_arena;
140
}
141
142
// 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.
144
NOT_PRODUCT(free_strings();)
145
146
#ifdef ASSERT
147
// Save allocation type to execute assert in ~ResourceObj()
148
// which is called after this destructor.
149
assert(_default_oop_recorder.allocated_on_stack(), "should be embedded object");
150
ResourceObj::allocation_type at = _default_oop_recorder.get_allocation_type();
151
Copy::fill_to_bytes(this, sizeof(*this), badResourceValue);
152
ResourceObj::set_allocation_type((address)(&_default_oop_recorder), at);
153
#endif
154
}
155
156
void CodeBuffer::initialize_oop_recorder(OopRecorder* r) {
157
assert(_oop_recorder == &_default_oop_recorder && _default_oop_recorder.is_unused(), "do this once");
158
DEBUG_ONLY(_default_oop_recorder.freeze()); // force unused OR to be frozen
159
_oop_recorder = r;
160
}
161
162
void CodeBuffer::initialize_section_size(CodeSection* cs, csize_t size) {
163
assert(cs != &_insts, "insts is the memory provider, not the consumer");
164
csize_t slop = CodeSection::end_slop(); // margin between sections
165
int align = cs->alignment();
166
assert(is_power_of_2(align), "sanity");
167
address start = _insts._start;
168
address limit = _insts._limit;
169
address middle = limit - size;
170
middle -= (intptr_t)middle & (align-1); // align the division point downward
171
guarantee(middle - slop > start, "need enough space to divide up");
172
_insts._limit = middle - slop; // subtract desired space, plus slop
173
cs->initialize(middle, limit - middle);
174
assert(cs->start() == middle, "sanity");
175
assert(cs->limit() == limit, "sanity");
176
// give it some relocations to start with, if the main section has them
177
if (_insts.has_locs()) cs->initialize_locs(1);
178
}
179
180
void CodeBuffer::set_blob(BufferBlob* blob) {
181
_blob = blob;
182
if (blob != NULL) {
183
address start = blob->content_begin();
184
address end = blob->content_end();
185
// Round up the starting address.
186
int align = _insts.alignment();
187
start += (-(intptr_t)start) & (align-1);
188
_total_start = start;
189
_total_size = end - start;
190
} else {
191
#ifdef ASSERT
192
// 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 //ASSERT
198
}
199
}
200
201
void CodeBuffer::free_blob() {
202
if (_blob != NULL) {
203
BufferBlob::free(_blob);
204
set_blob(NULL);
205
}
206
}
207
208
const char* CodeBuffer::code_section_name(int n) {
209
#ifdef PRODUCT
210
return NULL;
211
#else //PRODUCT
212
switch (n) {
213
case SECT_CONSTS: return "consts";
214
case SECT_INSTS: return "insts";
215
case SECT_STUBS: return "stubs";
216
default: return NULL;
217
}
218
#endif //PRODUCT
219
}
220
221
int CodeBuffer::section_index_of(address addr) const {
222
for (int n = 0; n < (int)SECT_LIMIT; n++) {
223
const CodeSection* cs = code_section(n);
224
if (cs->allocates(addr)) return n;
225
}
226
return SECT_NONE;
227
}
228
229
int CodeBuffer::locator(address addr) const {
230
for (int n = 0; n < (int)SECT_LIMIT; n++) {
231
const CodeSection* cs = code_section(n);
232
if (cs->allocates(addr)) {
233
return locator(addr - cs->start(), n);
234
}
235
}
236
return -1;
237
}
238
239
240
bool CodeBuffer::is_backward_branch(Label& L) {
241
return L.is_bound() && insts_end() <= locator_address(L.loc());
242
}
243
244
#ifndef PRODUCT
245
address CodeBuffer::decode_begin() {
246
address begin = _insts.start();
247
if (_decode_begin != NULL && _decode_begin > begin)
248
begin = _decode_begin;
249
return begin;
250
}
251
#endif // !PRODUCT
252
253
GrowableArray<int>* CodeBuffer::create_patch_overflow() {
254
if (_overflow_arena == NULL) {
255
_overflow_arena = new (mtCode) Arena(mtCode);
256
}
257
return new (_overflow_arena) GrowableArray<int>(_overflow_arena, 8, 0, 0);
258
}
259
260
261
// Helper function for managing labels and their target addresses.
262
// Returns a sensible address, and if it is not the label's final
263
// address, notes the dependency (at 'branch_pc') on the label.
264
address CodeSection::target(Label& L, address branch_pc) {
265
if (L.is_bound()) {
266
int loc = L.loc();
267
if (index() == CodeBuffer::locator_sect(loc)) {
268
return start() + CodeBuffer::locator_pos(loc);
269
} else {
270
return outer()->locator_address(loc);
271
}
272
} else {
273
assert(allocates2(branch_pc), "sanity");
274
address base = start();
275
int patch_loc = CodeBuffer::locator(branch_pc - base, index());
276
L.add_patch_at(outer(), patch_loc);
277
278
// Need to return a pc, doesn't matter what it is since it will be
279
// 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 displacements
282
// for shorter branches. It will get checked when bound.
283
return branch_pc;
284
}
285
}
286
287
void CodeSection::relocate(address at, relocInfo::relocType rtype, int format, jint method_index) {
288
RelocationHolder rh;
289
switch (rtype) {
290
case relocInfo::none: return;
291
case relocInfo::opt_virtual_call_type: {
292
rh = opt_virtual_call_Relocation::spec(method_index);
293
break;
294
}
295
case relocInfo::static_call_type: {
296
rh = static_call_Relocation::spec(method_index);
297
break;
298
}
299
case relocInfo::virtual_call_type: {
300
assert(method_index == 0, "resolved method overriding is not supported");
301
rh = Relocation::spec_simple(rtype);
302
break;
303
}
304
default: {
305
rh = Relocation::spec_simple(rtype);
306
break;
307
}
308
}
309
relocate(at, rh, format);
310
}
311
312
void CodeSection::relocate(address at, RelocationHolder const& spec, int format) {
313
// Do not relocate in scratch buffers.
314
if (scratch_emit()) { return; }
315
Relocation* reloc = spec.reloc();
316
relocInfo::relocType rtype = (relocInfo::relocType) reloc->type();
317
if (rtype == relocInfo::none) return;
318
319
// The assertion below has been adjusted, to also work for
320
// relocation for fixup. Sometimes we want to put relocation
321
// information for the next instruction, since it will be patched
322
// with a call.
323
assert(start() <= at && at <= end()+1,
324
"cannot relocate data outside code boundaries");
325
326
if (!has_locs()) {
327
// no space for relocation information provided => code cannot be
328
// relocated. Make sure that relocate is only called with rtypes
329
// that can be ignored for this kind of code.
330
assert(rtype == relocInfo::none ||
331
rtype == relocInfo::runtime_call_type ||
332
rtype == relocInfo::internal_word_type||
333
rtype == relocInfo::section_word_type ||
334
rtype == relocInfo::external_word_type,
335
"code needs relocation information");
336
// leave behind an indication that we attempted a relocation
337
DEBUG_ONLY(_locs_start = _locs_limit = (relocInfo*)badAddress);
338
return;
339
}
340
341
// Advance the point, noting the offset we'll have to record.
342
csize_t offset = at - locs_point();
343
set_locs_point(at);
344
345
// Test for a couple of overflow conditions; maybe expand the buffer.
346
relocInfo* end = locs_end();
347
relocInfo* req = end + relocInfo::length_limit;
348
// Check for (potential) overflow
349
if (req >= locs_limit() || offset >= relocInfo::offset_limit()) {
350
req += (uint)offset / (uint)relocInfo::offset_limit();
351
if (req >= locs_limit()) {
352
// Allocate or reallocate.
353
expand_locs(locs_count() + (req - end));
354
// reload pointer
355
end = locs_end();
356
}
357
}
358
359
// If the offset is giant, emit filler relocs, of type 'none', but
360
// each carrying the largest possible offset, to advance the locs_point.
361
while (offset >= relocInfo::offset_limit()) {
362
assert(end < locs_limit(), "adjust previous paragraph of code");
363
*end++ = filler_relocInfo();
364
offset -= filler_relocInfo().addr_offset();
365
}
366
367
// If it's a simple reloc with no data, we'll just write (rtype | offset).
368
(*end) = relocInfo(rtype, offset, format);
369
370
// If it has data, insert the prefix, as (data_prefix_tag | data1), data2.
371
end->initialize(this, reloc);
372
}
373
374
void CodeSection::initialize_locs(int locs_capacity) {
375
assert(_locs_start == NULL, "only one locs init step, please");
376
// Apply a priori lower limits to relocation size:
377
csize_t min_locs = MAX2(size() / 16, (csize_t)4);
378
if (locs_capacity < min_locs) locs_capacity = min_locs;
379
relocInfo* 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
}
385
386
void CodeSection::initialize_shared_locs(relocInfo* buf, int length) {
387
assert(_locs_start == NULL, "do this before locs are allocated");
388
// Internal invariant: locs buf must be fully aligned.
389
// See copy_relocations_to() below.
390
while ((uintptr_t)buf % HeapWordSize != 0 && length > 0) {
391
++buf; --length;
392
}
393
if (length > 0) {
394
_locs_start = buf;
395
_locs_end = buf;
396
_locs_limit = buf + length;
397
_locs_own = false;
398
}
399
}
400
401
void CodeSection::initialize_locs_from(const CodeSection* source_cs) {
402
int lcount = source_cs->locs_count();
403
if (lcount != 0) {
404
initialize_shared_locs(source_cs->locs_start(), lcount);
405
_locs_end = _locs_limit = _locs_start + lcount;
406
assert(is_allocated(), "must have copied code already");
407
set_locs_point(start() + source_cs->locs_point_off());
408
}
409
assert(this->locs_count() == source_cs->locs_count(), "sanity");
410
}
411
412
void CodeSection::expand_locs(int new_capacity) {
413
if (_locs_start == NULL) {
414
initialize_locs(new_capacity);
415
return;
416
} else {
417
int old_count = locs_count();
418
int old_capacity = locs_capacity();
419
if (new_capacity < old_capacity * 2)
420
new_capacity = old_capacity * 2;
421
relocInfo* locs_start;
422
if (_locs_own) {
423
locs_start = REALLOC_RESOURCE_ARRAY(relocInfo, _locs_start, old_capacity, new_capacity);
424
} else {
425
locs_start = NEW_RESOURCE_ARRAY(relocInfo, new_capacity);
426
Copy::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
}
434
435
436
/// 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.
439
440
csize_t CodeBuffer::total_content_size() const {
441
csize_t size_so_far = 0;
442
for (int n = 0; n < (int)SECT_LIMIT; n++) {
443
const CodeSection* cs = code_section(n);
444
if (cs->is_empty()) continue; // skip trivial section
445
size_so_far = cs->align_at_start(size_so_far);
446
size_so_far += cs->size();
447
}
448
return size_so_far;
449
}
450
451
void CodeBuffer::compute_final_layout(CodeBuffer* dest) const {
452
address buf = dest->_total_start;
453
csize_t buf_offset = 0;
454
assert(dest->_total_size >= total_content_size(), "must be big enough");
455
456
{
457
// not sure why this is here, but why not...
458
int alignSize = MAX2((intx) sizeof(jdouble), CodeEntryAlignment);
459
assert( (dest->_total_start - _insts.start()) % alignSize == 0, "copy must preserve alignment");
460
}
461
462
const CodeSection* prev_cs = NULL;
463
CodeSection* prev_dest_cs = NULL;
464
465
for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {
466
// figure compact layout of each section
467
const CodeSection* cs = code_section(n);
468
csize_t csize = cs->size();
469
470
CodeSection* dest_cs = dest->code_section(n);
471
if (!cs->is_empty()) {
472
// Compute initial padding; assign it to the previous non-empty guy.
473
// Cf. figure_expanded_capacities.
474
csize_t padding = cs->align_at_start(buf_offset) - buf_offset;
475
if (prev_dest_cs != NULL) {
476
if (padding != 0) {
477
buf_offset += padding;
478
prev_dest_cs->_limit += padding;
479
}
480
} else {
481
guarantee(padding == 0, "In first iteration no padding should be needed.");
482
}
483
prev_dest_cs = dest_cs;
484
prev_cs = cs;
485
}
486
487
debug_only(dest_cs->_start = NULL); // defeat double-initialization assert
488
dest_cs->initialize(buf+buf_offset, csize);
489
dest_cs->set_end(buf+buf_offset+csize);
490
assert(dest_cs->is_allocated(), "must always be allocated");
491
assert(cs->is_empty() == dest_cs->is_empty(), "sanity");
492
493
buf_offset += csize;
494
}
495
496
// Done calculating sections; did it come out to the right end?
497
assert(buf_offset == total_content_size(), "sanity");
498
debug_only(dest->verify_section_allocation();)
499
}
500
501
// Append an oop reference that keeps the class alive.
502
static void append_oop_references(GrowableArray<oop>* oops, Klass* k) {
503
oop cl = k->klass_holder();
504
if (cl != NULL && !oops->contains(cl)) {
505
oops->append(cl);
506
}
507
}
508
509
void CodeBuffer::finalize_oop_references(const methodHandle& mh) {
510
NoSafepointVerifier nsv;
511
512
GrowableArray<oop> oops;
513
514
// Make sure that immediate metadata records something in the OopRecorder
515
for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {
516
// pull code out of each section
517
CodeSection* cs = code_section(n);
518
if (cs->is_empty()) continue; // skip trivial section
519
RelocIterator iter(cs);
520
while (iter.next()) {
521
if (iter.type() == relocInfo::metadata_type) {
522
metadata_Relocation* md = iter.metadata_reloc();
523
if (md->metadata_is_immediate()) {
524
Metadata* m = md->metadata_value();
525
if (oop_recorder()->is_real(m)) {
526
if (m->is_methodData()) {
527
m = ((MethodData*)m)->method();
528
}
529
if (m->is_method()) {
530
m = ((Method*)m)->method_holder();
531
}
532
if (m->is_klass()) {
533
append_oop_references(&oops, (Klass*)m);
534
} else {
535
// XXX This will currently occur for MDO which don't
536
// have a backpointer. This has to be fixed later.
537
m->print();
538
ShouldNotReachHere();
539
}
540
}
541
}
542
}
543
}
544
}
545
546
if (!oop_recorder()->is_unused()) {
547
for (int i = 0; i < oop_recorder()->metadata_count(); i++) {
548
Metadata* m = oop_recorder()->metadata_at(i);
549
if (oop_recorder()->is_real(m)) {
550
if (m->is_methodData()) {
551
m = ((MethodData*)m)->method();
552
}
553
if (m->is_method()) {
554
m = ((Method*)m)->method_holder();
555
}
556
if (m->is_klass()) {
557
append_oop_references(&oops, (Klass*)m);
558
} else {
559
m->print();
560
ShouldNotReachHere();
561
}
562
}
563
}
564
565
}
566
567
// Add the class loader of Method* for the nmethod itself
568
append_oop_references(&oops, mh->method_holder());
569
570
// Add any oops that we've found
571
Thread* thread = Thread::current();
572
for (int i = 0; i < oops.length(); i++) {
573
oop_recorder()->find_index((jobject)thread->handle_area()->allocate_handle(oops.at(i)));
574
}
575
}
576
577
578
579
csize_t CodeBuffer::total_offset_of(const CodeSection* cs) const {
580
csize_t size_so_far = 0;
581
for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {
582
const CodeSection* cur_cs = code_section(n);
583
if (!cur_cs->is_empty()) {
584
size_so_far = cur_cs->align_at_start(size_so_far);
585
}
586
if (cur_cs->index() == cs->index()) {
587
return size_so_far;
588
}
589
size_so_far += cur_cs->size();
590
}
591
ShouldNotReachHere();
592
return -1;
593
}
594
595
csize_t CodeBuffer::total_relocation_size() const {
596
csize_t total = copy_relocations_to(NULL); // dry run only
597
return (csize_t) align_up(total, HeapWordSize);
598
}
599
600
csize_t CodeBuffer::copy_relocations_to(address buf, csize_t buf_limit, bool only_inst) const {
601
csize_t buf_offset = 0;
602
csize_t code_end_so_far = 0;
603
csize_t code_point_so_far = 0;
604
605
assert((uintptr_t)buf % HeapWordSize == 0, "buf must be fully aligned");
606
assert(buf_limit % HeapWordSize == 0, "buf must be evenly sized");
607
608
for (int n = (int) SECT_FIRST; n < (int)SECT_LIMIT; n++) {
609
if (only_inst && (n != (int)SECT_INSTS)) {
610
// Need only relocation info for code.
611
continue;
612
}
613
// pull relocs out of each section
614
const CodeSection* cs = code_section(n);
615
assert(!(cs->is_empty() && cs->locs_count() > 0), "sanity");
616
if (cs->is_empty()) continue; // skip trivial section
617
relocInfo* lstart = cs->locs_start();
618
relocInfo* lend = cs->locs_end();
619
csize_t lsize = (csize_t)( (address)lend - (address)lstart );
620
csize_t csize = cs->size();
621
code_end_so_far = cs->align_at_start(code_end_so_far);
622
623
if (lsize > 0) {
624
// Figure out how to advance the combined relocation point
625
// 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.)
628
csize_t new_code_point = code_end_so_far;
629
for (csize_t jump;
630
code_point_so_far < new_code_point;
631
code_point_so_far += jump) {
632
jump = new_code_point - code_point_so_far;
633
relocInfo filler = filler_relocInfo();
634
if (jump >= filler.addr_offset()) {
635
jump = filler.addr_offset();
636
} else { // else shrink the filler to fit
637
filler = relocInfo(relocInfo::none, jump);
638
}
639
if (buf != NULL) {
640
assert(buf_offset + (csize_t)sizeof(filler) <= buf_limit, "filler in bounds");
641
*(relocInfo*)(buf+buf_offset) = filler;
642
}
643
buf_offset += sizeof(filler);
644
}
645
646
// Update code point and end to skip past this section:
647
csize_t last_code_point = code_end_so_far + cs->locs_point_off();
648
assert(code_point_so_far <= last_code_point, "sanity");
649
code_point_so_far = last_code_point; // advance past this guy's relocs
650
}
651
code_end_so_far += csize; // advance past this guy's instructions too
652
653
// Done with filler; emit the real relocations:
654
if (buf != NULL && lsize != 0) {
655
assert(buf_offset + lsize <= buf_limit, "target in bounds");
656
assert((uintptr_t)lstart % HeapWordSize == 0, "sane start");
657
if (buf_offset % HeapWordSize == 0) {
658
// Use wordwise copies if possible:
659
Copy::disjoint_words((HeapWord*)lstart,
660
(HeapWord*)(buf+buf_offset),
661
(lsize + HeapWordSize-1) / HeapWordSize);
662
} else {
663
Copy::conjoint_jbytes(lstart, buf+buf_offset, lsize);
664
}
665
}
666
buf_offset += lsize;
667
}
668
669
// Align end of relocation info in target.
670
while (buf_offset % HeapWordSize != 0) {
671
if (buf != NULL) {
672
relocInfo padding = relocInfo(relocInfo::none, 0);
673
assert(buf_offset + (csize_t)sizeof(padding) <= buf_limit, "padding in bounds");
674
*(relocInfo*)(buf+buf_offset) = padding;
675
}
676
buf_offset += sizeof(relocInfo);
677
}
678
679
assert(only_inst || code_end_so_far == total_content_size(), "sanity");
680
681
return buf_offset;
682
}
683
684
csize_t CodeBuffer::copy_relocations_to(CodeBlob* dest) const {
685
address buf = NULL;
686
csize_t buf_offset = 0;
687
csize_t buf_limit = 0;
688
689
if (dest != NULL) {
690
buf = (address)dest->relocation_begin();
691
buf_limit = (address)dest->relocation_end() - buf;
692
}
693
// if dest == NULL, this is just the sizing pass
694
//
695
buf_offset = copy_relocations_to(buf, buf_limit, false);
696
697
return buf_offset;
698
}
699
700
void CodeBuffer::copy_code_to(CodeBlob* dest_blob) {
701
#ifndef PRODUCT
702
if (PrintNMethods && (WizardMode || Verbose)) {
703
tty->print("done with CodeBuffer:");
704
((CodeBuffer*)this)->print();
705
}
706
#endif //PRODUCT
707
708
CodeBuffer dest(dest_blob);
709
assert(dest_blob->content_size() >= total_content_size(), "good sizing");
710
this->compute_final_layout(&dest);
711
712
// Set beginning of constant table before relocating.
713
dest_blob->set_ctable_begin(dest.consts()->start());
714
715
relocate_code_to(&dest);
716
717
// transfer strings and comments from buffer to blob
718
NOT_PRODUCT(dest_blob->set_strings(_code_strings);)
719
720
// Done moving code bytes; were they the right size?
721
assert((int)align_up(dest.total_content_size(), oopSize) == dest_blob->content_size(), "sanity");
722
723
// Flush generated code
724
ICache::invalidate_range(dest_blob->code_begin(), dest_blob->code_size());
725
}
726
727
// Move all my code into another code buffer. Consult applicable
728
// relocs to repair embedded addresses. The layout in the destination
729
// CodeBuffer is different to the source CodeBuffer: the destination
730
// CodeBuffer gets the final layout (consts, insts, stubs in order of
731
// ascending address).
732
void CodeBuffer::relocate_code_to(CodeBuffer* dest) const {
733
address dest_end = dest->_total_start + dest->_total_size;
734
address dest_filled = NULL;
735
for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {
736
// pull code out of each section
737
const CodeSection* cs = code_section(n);
738
if (cs->is_empty()) continue; // skip trivial section
739
CodeSection* dest_cs = dest->code_section(n);
740
assert(cs->size() == dest_cs->size(), "sanity");
741
csize_t usize = dest_cs->size();
742
csize_t wsize = align_up(usize, HeapWordSize);
743
assert(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.
746
Copy::disjoint_words((HeapWord*)cs->start(),
747
(HeapWord*)dest_cs->start(),
748
wsize / HeapWordSize);
749
750
if (dest->blob() == NULL) {
751
// Destination is a final resting place, not just another buffer.
752
// Normalize uninitialized bytes in the final padding.
753
Copy::fill_to_bytes(dest_cs->end(), dest_cs->remaining(),
754
Assembler::code_fill_byte());
755
}
756
// Keep track of the highest filled address
757
dest_filled = MAX2(dest_filled, dest_cs->end() + dest_cs->remaining());
758
759
assert(cs->locs_start() != (relocInfo*)badAddress,
760
"this section carries no reloc storage, but reloc was attempted");
761
762
// Make the new code copy use the old copy's relocations:
763
dest_cs->initialize_locs_from(cs);
764
}
765
766
// Do relocation after all sections are copied.
767
// This is necessary if the code uses constants in stubs, which are
768
// relocated when the corresponding instruction in the code (e.g., a
769
// call) is relocated. Stubs are placed behind the main code
770
// section, so that section has to be copied before relocating.
771
for (int n = (int) SECT_FIRST; n < (int)SECT_LIMIT; n++) {
772
// pull code out of each section
773
const CodeSection* cs = code_section(n);
774
if (cs->is_empty()) continue; // skip trivial section
775
CodeSection* dest_cs = dest->code_section(n);
776
{ // Repair the pc relative information in the code after the move
777
RelocIterator iter(dest_cs);
778
while (iter.next()) {
779
iter.reloc()->fix_relocation_after_move(this, dest);
780
}
781
}
782
}
783
784
if (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.
787
Copy::fill_to_bytes(dest_filled, dest_end - dest_filled,
788
Assembler::code_fill_byte());
789
790
}
791
}
792
793
csize_t CodeBuffer::figure_expanded_capacities(CodeSection* which_cs,
794
csize_t amount,
795
csize_t* new_capacity) {
796
csize_t new_total_cap = 0;
797
798
for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {
799
const CodeSection* sect = code_section(n);
800
801
if (!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_layout
805
csize_t padding = sect->align_at_start(new_total_cap) - new_total_cap;
806
if (padding != 0) {
807
new_total_cap += padding;
808
assert(n - 1 >= SECT_FIRST, "sanity");
809
new_capacity[n - 1] += padding;
810
}
811
}
812
813
csize_t exp = sect->size(); // 100% increase
814
if ((uint)exp < 4*K) exp = 4*K; // minimum initial increase
815
if (sect == which_cs) {
816
if (exp < amount) exp = amount;
817
if (StressCodeBuffers) exp = amount; // expand only slightly
818
} else if (n == SECT_INSTS) {
819
// scale down inst increases to a more modest 25%
820
exp = 4*K + ((exp - 4*K) >> 2);
821
if (StressCodeBuffers) exp = amount / 2; // expand only slightly
822
} else if (sect->is_empty()) {
823
// do not grow an empty secondary section
824
exp = 0;
825
}
826
// Allow for inter-section slop:
827
exp += CodeSection::end_slop();
828
csize_t new_cap = sect->size() + exp;
829
if (new_cap < sect->capacity()) {
830
// No need to expand after all.
831
new_cap = sect->capacity();
832
}
833
new_capacity[n] = new_cap;
834
new_total_cap += new_cap;
835
}
836
837
return new_total_cap;
838
}
839
840
void CodeBuffer::expand(CodeSection* which_cs, csize_t amount) {
841
#ifndef PRODUCT
842
if (PrintNMethods && (WizardMode || Verbose)) {
843
tty->print("expanding CodeBuffer:");
844
this->print();
845
}
846
847
if (StressCodeBuffers && blob() != NULL) {
848
static int expand_count = 0;
849
if (expand_count >= 0) expand_count += 1;
850
if (expand_count > 100 && is_power_of_2(expand_count)) {
851
tty->print_cr("StressCodeBuffers: have expanded %d times", expand_count);
852
// simulate an occasional allocation failure:
853
free_blob();
854
}
855
}
856
#endif //PRODUCT
857
858
// Resizing must be allowed
859
{
860
if (blob() == NULL) return; // caller must check for blob == NULL
861
}
862
863
// Figure new capacity for each section.
864
csize_t new_capacity[SECT_LIMIT];
865
memset(new_capacity, 0, sizeof(csize_t) * SECT_LIMIT);
866
csize_t new_total_cap
867
= figure_expanded_capacities(which_cs, amount, new_capacity);
868
869
// Create a new (temporary) code buffer to hold all the new data
870
CodeBuffer cb(name(), new_total_cap, 0);
871
if (cb.blob() == NULL) {
872
// Failed to allocate in code cache.
873
free_blob();
874
return;
875
}
876
877
// 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 that
880
// has been created at any time in this CodeBuffer's past.
881
CodeBuffer* bxp = new CodeBuffer(_total_start, _total_size);
882
bxp->take_over_code_from(this); // remember the old undersized blob
883
DEBUG_ONLY(this->_blob = NULL); // silence a later assert
884
bxp->_before_expand = this->_before_expand;
885
this->_before_expand = bxp;
886
887
// Give each section its required (expanded) capacity.
888
for (int n = (int)SECT_LIMIT-1; n >= SECT_FIRST; n--) {
889
CodeSection* cb_sect = cb.code_section(n);
890
CodeSection* this_sect = code_section(n);
891
if (new_capacity[n] == 0) continue; // already nulled out
892
if (n != SECT_INSTS) {
893
cb.initialize_section_size(cb_sect, new_capacity[n]);
894
}
895
assert(cb_sect->capacity() >= new_capacity[n], "big enough");
896
address cb_start = cb_sect->start();
897
cb_sect->set_end(cb_start + this_sect->size());
898
if (this_sect->mark() == NULL) {
899
cb_sect->clear_mark();
900
} else {
901
cb_sect->set_mark(cb_start + this_sect->mark_off());
902
}
903
}
904
905
// Needs to be initialized when calling fix_relocation_after_move.
906
cb.blob()->set_ctable_begin(cb.consts()->start());
907
908
// Move all the code and relocations to the new blob:
909
relocate_code_to(&cb);
910
911
// Copy the temporary code buffer into the current code buffer.
912
// Basically, do {*this = cb}, except for some control information.
913
this->take_over_code_from(&cb);
914
cb.set_blob(NULL);
915
916
// Zap the old code buffer contents, to avoid mistakenly using them.
917
debug_only(Copy::fill_to_bytes(bxp->_total_start, bxp->_total_size,
918
badCodeHeapFreeVal);)
919
920
// Make certain that the new sections are all snugly inside the new blob.
921
debug_only(verify_section_allocation();)
922
923
#ifndef PRODUCT
924
_decode_begin = NULL; // sanity
925
if (PrintNMethods && (WizardMode || Verbose)) {
926
tty->print("expanded CodeBuffer:");
927
this->print();
928
}
929
#endif //PRODUCT
930
}
931
932
void CodeBuffer::take_over_code_from(CodeBuffer* cb) {
933
// Must already have disposed of the old blob somehow.
934
assert(blob() == NULL, "must be empty");
935
// Take the new blob away from cb.
936
set_blob(cb->blob());
937
// Take over all the section pointers.
938
for (int n = 0; n < (int)SECT_LIMIT; n++) {
939
CodeSection* cb_sect = cb->code_section(n);
940
CodeSection* this_sect = code_section(n);
941
this_sect->take_over_code_from(cb_sect);
942
}
943
_overflow_arena = cb->_overflow_arena;
944
cb->_overflow_arena = NULL;
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