1 /*
2 * Copyright (c) 2008, 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/assembler.inline.hpp"
27 #include "asm/macroAssembler.hpp"
28 #include "ci/ciUtilities.hpp"
29 #include "classfile/javaClasses.hpp"
30 #include "code/codeCache.hpp"
31 #include "compiler/disassembler.hpp"
32 #include "gc/shared/cardTable.hpp"
33 #include "gc/shared/cardTableBarrierSet.hpp"
34 #include "gc/shared/collectedHeap.hpp"
35 #include "memory/resourceArea.hpp"
36 #include "memory/universe.hpp"
37 #include "oops/oop.inline.hpp"
38 #include "runtime/handles.inline.hpp"
39 #include "runtime/os.inline.hpp"
40 #include "runtime/stubCodeGenerator.hpp"
41 #include "runtime/stubRoutines.hpp"
42 #include "utilities/resourceHash.hpp"
43 #include CPU_HEADER(depChecker)
44
45 void* Disassembler::_library = NULL;
46 bool Disassembler::_tried_to_load_library = false;
47 bool Disassembler::_library_usable = false;
48
49 // This routine is in the shared library:
50 Disassembler::decode_func_virtual Disassembler::_decode_instructions_virtual = NULL;
51 Disassembler::decode_func Disassembler::_decode_instructions = NULL;
52
53 static const char hsdis_library_name[] = "hsdis-" HOTSPOT_LIB_ARCH;
54 static const char decode_instructions_virtual_name[] = "decode_instructions_virtual";
55 static const char decode_instructions_name[] = "decode_instructions";
56 static bool use_new_version = true;
57 #define COMMENT_COLUMN 52 LP64_ONLY(+8) /*could be an option*/
58 #define BYTES_COMMENT ";..." /* funky byte display comment */
59
60 class decode_env {
61 private:
62 outputStream* _output; // where the disassembly is directed to
63 CodeBuffer* _codeBuffer; // != NULL only when decoding a CodeBuffer
64 CodeBlob* _codeBlob; // != NULL only when decoding a CodeBlob
65 nmethod* _nm; // != NULL only when decoding a nmethod
66 CodeStrings _strings;
67 address _start; // != NULL when decoding a range of unknown type
68 address _end; // != NULL when decoding a range of unknown type
69
70 char _option_buf[512];
71 char _print_raw;
72 address _cur_insn; // address of instruction currently being decoded
73 int _bytes_per_line; // arch-specific formatting option
74 int _pre_decode_alignment;
75 int _post_decode_alignment;
76 bool _print_file_name;
77 bool _print_help;
78 bool _helpPrinted;
79 static bool _optionsParsed;
80
81 enum {
82 tabspacing = 8
83 };
84
85 // Check if the event matches the expected tag
86 // The tag must be a substring of the event, and
87 // the tag must be a token in the event, i.e. separated by delimiters
match(const char * event,const char * tag)88 static bool match(const char* event, const char* tag) {
89 size_t eventlen = strlen(event);
90 size_t taglen = strlen(tag);
91 if (eventlen < taglen) // size mismatch
92 return false;
93 if (strncmp(event, tag, taglen) != 0) // string mismatch
94 return false;
95 char delim = event[taglen];
96 return delim == '\0' || delim == ' ' || delim == '/' || delim == '=';
97 }
98
99 // Merge new option string with previously recorded options
collect_options(const char * p)100 void collect_options(const char* p) {
101 if (p == NULL || p[0] == '\0') return;
102 size_t opt_so_far = strlen(_option_buf);
103 if (opt_so_far + 1 + strlen(p) + 1 > sizeof(_option_buf)) return;
104 char* fillp = &_option_buf[opt_so_far];
105 if (opt_so_far > 0) *fillp++ = ',';
106 strcat(fillp, p);
107 // replace white space by commas:
108 char* q = fillp;
109 while ((q = strpbrk(q, " \t\n")) != NULL)
110 *q++ = ',';
111 }
112
113 void process_options(outputStream* ost);
114
115 void print_insn_labels();
116 void print_insn_prefix();
117 void print_address(address value);
118
119 // Properly initializes _start/_end. Overwritten too often if
120 // printing of instructions is called for each instruction.
set_start(address s)121 void set_start(address s) { _start = s; }
set_end(address e)122 void set_end (address e) { _end = e; }
set_nm(nmethod * nm)123 void set_nm (nmethod* nm) { _nm = nm; }
set_output(outputStream * st)124 void set_output(outputStream* st) { _output = st; }
125
126 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
127 // The disassembler library (sometimes) uses tabs to nicely align the instruction operands.
128 // Depending on the mnemonic length and the column position where the
129 // mnemonic is printed, alignment may turn out to be not so nice.
130 // To improve, we assume 8-character tab spacing and left-align the mnemonic on a tab position.
131 // Instruction comments are aligned 4 tab positions to the right of the mnemonic.
calculate_alignment()132 void calculate_alignment() {
133 _pre_decode_alignment = ((output()->position()+tabspacing-1)/tabspacing)*tabspacing;
134 _post_decode_alignment = _pre_decode_alignment + 4*tabspacing;
135 }
136
start_insn(address pc)137 void start_insn(address pc) {
138 _cur_insn = pc;
139 output()->bol();
140 print_insn_labels();
141 print_insn_prefix();
142 }
143
end_insn(address pc)144 void end_insn(address pc) {
145 address pc0 = cur_insn();
146 outputStream* st = output();
147
148 if (AbstractDisassembler::show_comment()) {
149 if ((_nm != NULL) && _nm->has_code_comment(pc0, pc)) {
150 _nm->print_code_comment_on
151 (st,
152 _post_decode_alignment ? _post_decode_alignment : COMMENT_COLUMN,
153 pc0, pc);
154 // this calls reloc_string_for which calls oop::print_value_on
155 }
156 print_hook_comments(pc0, _nm != NULL);
157 }
158 Disassembler::annotate(pc0, output());
159 // follow each complete insn by a nice newline
160 st->bol();
161 }
162 #endif
163
164 struct SourceFileInfo {
165 struct Link : public CHeapObj<mtCode> {
166 const char* file;
167 int line;
168 Link* next;
Linkdecode_env::SourceFileInfo::Link169 Link(const char* f, int l) : file(f), line(l), next(NULL) {}
170 };
171 Link *head, *tail;
172
hashdecode_env::SourceFileInfo173 static unsigned hash(const address& a) {
174 return primitive_hash<address>(a);
175 }
equalsdecode_env::SourceFileInfo176 static bool equals(const address& a0, const address& a1) {
177 return primitive_equals<address>(a0, a1);
178 }
appenddecode_env::SourceFileInfo179 void append(const char* file, int line) {
180 if (tail != NULL && tail->file == file && tail->line == line) {
181 // Don't print duplicated lines at the same address. This could happen with C
182 // macros that end up having multiple "__" tokens on the same __LINE__.
183 return;
184 }
185 Link *link = new Link(file, line);
186 if (head == NULL) {
187 head = tail = link;
188 } else {
189 tail->next = link;
190 tail = link;
191 }
192 }
SourceFileInfodecode_env::SourceFileInfo193 SourceFileInfo(const char* file, int line) : head(NULL), tail(NULL) {
194 append(file, line);
195 }
196 };
197
198 typedef ResourceHashtable<
199 address, SourceFileInfo,
200 SourceFileInfo::hash,
201 SourceFileInfo::equals,
202 15889, // prime number
203 ResourceObj::C_HEAP> SourceFileInfoTable;
204
205 static SourceFileInfoTable _src_table;
206 static const char* _cached_src;
207 static GrowableArray<const char*>* _cached_src_lines;
208
209 public:
210 decode_env(CodeBuffer* code, outputStream* output);
211 decode_env(CodeBlob* code, outputStream* output, CodeStrings c = CodeStrings() /* , ptrdiff_t offset */);
212 decode_env(nmethod* code, outputStream* output, CodeStrings c = CodeStrings());
213 // Constructor for a 'decode_env' to decode an arbitrary
214 // piece of memory, hopefully containing code.
215 decode_env(address start, address end, outputStream* output);
216
217 // Add 'original_start' argument which is the the original address
218 // the instructions were located at (if this is not equal to 'start').
219 address decode_instructions(address start, address end, address original_start = NULL);
220
221 address handle_event(const char* event, address arg);
222
output()223 outputStream* output() { return _output; }
cur_insn()224 address cur_insn() { return _cur_insn; }
options()225 const char* options() { return _option_buf; }
226 static void hook(const char* file, int line, address pc);
227 void print_hook_comments(address pc, bool newline);
228 };
229
230 bool decode_env::_optionsParsed = false;
231
232 decode_env::SourceFileInfoTable decode_env::_src_table;
233 const char* decode_env::_cached_src = NULL;
234 GrowableArray<const char*>* decode_env::_cached_src_lines = NULL;
235
hook(const char * file,int line,address pc)236 void decode_env::hook(const char* file, int line, address pc) {
237 // For simplication, we never free from this table. It's really not
238 // necessary as we add to the table only when PrintInterpreter is true,
239 // which means we are debugging the VM and a little bit of extra
240 // memory usage doesn't matter.
241 SourceFileInfo* found = _src_table.get(pc);
242 if (found != NULL) {
243 found->append(file, line);
244 } else {
245 SourceFileInfo sfi(file, line);
246 _src_table.put(pc, sfi); // sfi is copied by value
247 }
248 }
249
print_hook_comments(address pc,bool newline)250 void decode_env::print_hook_comments(address pc, bool newline) {
251 SourceFileInfo* found = _src_table.get(pc);
252 outputStream* st = output();
253 if (found != NULL) {
254 for (SourceFileInfo::Link *link = found->head; link; link = link->next) {
255 const char* file = link->file;
256 int line = link->line;
257 if (_cached_src == NULL || strcmp(_cached_src, file) != 0) {
258 FILE* fp;
259
260 // _cached_src_lines is a single cache of the lines of a source file, and we refill this cache
261 // every time we need to print a line from a different source file. It's not the fastest,
262 // but seems bearable.
263 if (_cached_src_lines != NULL) {
264 for (int i=0; i<_cached_src_lines->length(); i++) {
265 os::free((void*)_cached_src_lines->at(i));
266 }
267 _cached_src_lines->clear();
268 } else {
269 _cached_src_lines = new (ResourceObj::C_HEAP, mtCode)GrowableArray<const char*>(0, true);
270 }
271
272 if ((fp = fopen(file, "r")) == NULL) {
273 _cached_src = NULL;
274 return;
275 }
276 _cached_src = file;
277
278 char line[500]; // don't write lines that are too long in your source files!
279 while (fgets(line, sizeof(line), fp) != NULL) {
280 size_t len = strlen(line);
281 if (len > 0 && line[len-1] == '\n') {
282 line[len-1] = '\0';
283 }
284 _cached_src_lines->append(os::strdup(line));
285 }
286 fclose(fp);
287 _print_file_name = true;
288 }
289
290 if (_print_file_name) {
291 // We print the file name whenever we switch to a new file, or when
292 // Disassembler::decode is called to disassemble a new block of code.
293 _print_file_name = false;
294 if (newline) {
295 st->cr();
296 }
297 st->move_to(COMMENT_COLUMN);
298 st->print(";;@FILE: %s", file);
299 newline = true;
300 }
301
302 int index = line - 1; // 1-based line number -> 0-based index.
303 if (index >= _cached_src_lines->length()) {
304 // This could happen if source file is mismatched.
305 } else {
306 const char* source_line = _cached_src_lines->at(index);
307 if (newline) {
308 st->cr();
309 }
310 st->move_to(COMMENT_COLUMN);
311 st->print(";;%5d: %s", line, source_line);
312 newline = true;
313 }
314 }
315 }
316 }
317
decode_env(CodeBuffer * code,outputStream * output)318 decode_env::decode_env(CodeBuffer* code, outputStream* output) :
319 _output(output ? output : tty),
320 _codeBuffer(code),
321 _codeBlob(NULL),
322 _nm(NULL),
323 _strings(),
324 _start(NULL),
325 _end(NULL),
326 _option_buf(),
327 _print_raw(0),
328 _cur_insn(NULL),
329 _bytes_per_line(0),
330 _pre_decode_alignment(0),
331 _post_decode_alignment(0),
332 _print_file_name(false),
333 _print_help(false),
334 _helpPrinted(false) {
335
336 memset(_option_buf, 0, sizeof(_option_buf));
337 process_options(_output);
338 }
339
decode_env(CodeBlob * code,outputStream * output,CodeStrings c)340 decode_env::decode_env(CodeBlob* code, outputStream* output, CodeStrings c) :
341 _output(output ? output : tty),
342 _codeBuffer(NULL),
343 _codeBlob(code),
344 _nm(_codeBlob != NULL && _codeBlob->is_nmethod() ? (nmethod*) code : NULL),
345 _strings(),
346 _start(NULL),
347 _end(NULL),
348 _option_buf(),
349 _print_raw(0),
350 _cur_insn(NULL),
351 _bytes_per_line(0),
352 _pre_decode_alignment(0),
353 _post_decode_alignment(0),
354 _print_file_name(false),
355 _print_help(false),
356 _helpPrinted(false) {
357
358 memset(_option_buf, 0, sizeof(_option_buf));
359 _strings.copy(c);
360 process_options(_output);
361 }
362
decode_env(nmethod * code,outputStream * output,CodeStrings c)363 decode_env::decode_env(nmethod* code, outputStream* output, CodeStrings c) :
364 _output(output ? output : tty),
365 _codeBuffer(NULL),
366 _codeBlob(NULL),
367 _nm(code),
368 _strings(),
369 _start(_nm->code_begin()),
370 _end(_nm->code_end()),
371 _option_buf(),
372 _print_raw(0),
373 _cur_insn(NULL),
374 _bytes_per_line(0),
375 _pre_decode_alignment(0),
376 _post_decode_alignment(0),
377 _print_file_name(false),
378 _print_help(false),
379 _helpPrinted(false) {
380
381 memset(_option_buf, 0, sizeof(_option_buf));
382 _strings.copy(c);
383 process_options(_output);
384 }
385
386 // Constructor for a 'decode_env' to decode a memory range [start, end)
387 // of unknown origin, assuming it contains code.
decode_env(address start,address end,outputStream * output)388 decode_env::decode_env(address start, address end, outputStream* output) :
389 _output(output ? output : tty),
390 _codeBuffer(NULL),
391 _codeBlob(NULL),
392 _nm(NULL),
393 _strings(),
394 _start(start),
395 _end(end),
396 _option_buf(),
397 _print_raw(0),
398 _cur_insn(NULL),
399 _bytes_per_line(0),
400 _pre_decode_alignment(0),
401 _post_decode_alignment(0),
402 _print_file_name(false),
403 _print_help(false),
404 _helpPrinted(false) {
405
406 assert(start < end, "Range must have a positive size, [" PTR_FORMAT ".." PTR_FORMAT ").", p2i(start), p2i(end));
407 memset(_option_buf, 0, sizeof(_option_buf));
408 process_options(_output);
409 }
410
process_options(outputStream * ost)411 void decode_env::process_options(outputStream* ost) {
412 // by default, output pc but not bytes:
413 _print_help = false;
414 _bytes_per_line = Disassembler::pd_instruction_alignment();
415 _print_file_name = true;
416
417 // parse the global option string
418 // We need to fill the options buffer for each newly created
419 // decode_env instance. The hsdis_* library looks for options
420 // in that buffer.
421 collect_options(Disassembler::pd_cpu_opts());
422 collect_options(PrintAssemblyOptions);
423
424 if (strstr(options(), "print-raw")) {
425 _print_raw = (strstr(options(), "xml") ? 2 : 1);
426 }
427
428 if (_optionsParsed) return; // parse only once
429
430 if (strstr(options(), "help")) {
431 _print_help = true;
432 }
433 if (strstr(options(), "align-instr")) {
434 AbstractDisassembler::toggle_align_instr();
435 }
436 if (strstr(options(), "show-pc")) {
437 AbstractDisassembler::toggle_show_pc();
438 }
439 if (strstr(options(), "show-offset")) {
440 AbstractDisassembler::toggle_show_offset();
441 }
442 if (strstr(options(), "show-bytes")) {
443 AbstractDisassembler::toggle_show_bytes();
444 }
445 if (strstr(options(), "show-data-hex")) {
446 AbstractDisassembler::toggle_show_data_hex();
447 }
448 if (strstr(options(), "show-data-int")) {
449 AbstractDisassembler::toggle_show_data_int();
450 }
451 if (strstr(options(), "show-data-float")) {
452 AbstractDisassembler::toggle_show_data_float();
453 }
454 if (strstr(options(), "show-structs")) {
455 AbstractDisassembler::toggle_show_structs();
456 }
457 if (strstr(options(), "show-comment")) {
458 AbstractDisassembler::toggle_show_comment();
459 }
460 if (strstr(options(), "show-block-comment")) {
461 AbstractDisassembler::toggle_show_block_comment();
462 }
463 _optionsParsed = true;
464
465 if (_print_help && ! _helpPrinted) {
466 _helpPrinted = true;
467 ost->print_cr("PrintAssemblyOptions help:");
468 ost->print_cr(" print-raw test plugin by requesting raw output");
469 ost->print_cr(" print-raw-xml test plugin by requesting raw xml");
470 ost->cr();
471 ost->print_cr(" show-pc toggle printing current pc, currently %s", AbstractDisassembler::show_pc() ? "ON" : "OFF");
472 ost->print_cr(" show-offset toggle printing current offset, currently %s", AbstractDisassembler::show_offset() ? "ON" : "OFF");
473 ost->print_cr(" show-bytes toggle printing instruction bytes, currently %s", AbstractDisassembler::show_bytes() ? "ON" : "OFF");
474 ost->print_cr(" show-data-hex toggle formatting data as hex, currently %s", AbstractDisassembler::show_data_hex() ? "ON" : "OFF");
475 ost->print_cr(" show-data-int toggle formatting data as int, currently %s", AbstractDisassembler::show_data_int() ? "ON" : "OFF");
476 ost->print_cr(" show-data-float toggle formatting data as float, currently %s", AbstractDisassembler::show_data_float() ? "ON" : "OFF");
477 ost->print_cr(" show-structs toggle compiler data structures, currently %s", AbstractDisassembler::show_structs() ? "ON" : "OFF");
478 ost->print_cr(" show-comment toggle instruction comments, currently %s", AbstractDisassembler::show_comment() ? "ON" : "OFF");
479 ost->print_cr(" show-block-comment toggle block comments, currently %s", AbstractDisassembler::show_block_comment() ? "ON" : "OFF");
480 ost->print_cr(" align-instr toggle instruction alignment, currently %s", AbstractDisassembler::align_instr() ? "ON" : "OFF");
481 ost->print_cr("combined options: %s", options());
482 }
483 }
484
485 // Disassembly Event Handler.
486 // This method receives events from the disassembler library hsdis
487 // via event_to_env for each decoding step (installed by
488 // Disassembler::decode_instructions(), replacing the default
489 // callback method). This enables dumping additional info
490 // and custom line formatting.
491 // In a future extension, calling a custom decode method will be
492 // supported. We can use such a method to decode instructions the
493 // binutils decoder does not handle to our liking (suboptimal
494 // formatting, incomplete information, ...).
495 // Returns:
496 // - NULL for all standard invocations. The function result is not
497 // examined (as of now, 20190409) by the hsdis decoder loop.
498 // - next for 'insn0' invocations.
499 // next == arg: the custom decoder didn't do anything.
500 // next > arg: the custom decoder did decode the instruction.
501 // next points to the next undecoded instruction
502 // (continuation point for decoder loop).
503 //
504 // "Normal" sequence of events:
505 // insns - start of instruction stream decoding
506 // mach - display architecture
507 // format - display bytes-per-line
508 // for each instruction:
509 // insn - start of instruction decoding
510 // insn0 - custom decoder invocation (if any)
511 // addr - print address value
512 // /insn - end of instruction decoding
513 // /insns - premature end of instruction stream due to no progress
514 //
handle_event(const char * event,address arg)515 address decode_env::handle_event(const char* event, address arg) {
516
517 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
518
519 //---< Event: end decoding loop (error, no progress) >---
520 if (decode_env::match(event, "/insns")) {
521 // Nothing to be done here.
522 return NULL;
523 }
524
525 //---< Event: start decoding loop >---
526 if (decode_env::match(event, "insns")) {
527 // Nothing to be done here.
528 return NULL;
529 }
530
531 //---< Event: finish decoding an instruction >---
532 if (decode_env::match(event, "/insn")) {
533 output()->fill_to(_post_decode_alignment);
534 end_insn(arg);
535 return NULL;
536 }
537
538 //---< Event: start decoding an instruction >---
539 if (decode_env::match(event, "insn")) {
540 start_insn(arg);
541 } else if (match(event, "/insn")) {
542 end_insn(arg);
543 } else if (match(event, "addr")) {
544 if (arg != NULL) {
545 print_address(arg);
546 return arg;
547 }
548 calculate_alignment();
549 output()->fill_to(_pre_decode_alignment);
550 return NULL;
551 }
552
553 //---< Event: call custom decoder (platform specific) >---
554 if (decode_env::match(event, "insn0")) {
555 return Disassembler::decode_instruction0(arg, output(), arg);
556 }
557
558 //---< Event: Print address >---
559 if (decode_env::match(event, "addr")) {
560 print_address(arg);
561 return arg;
562 }
563
564 //---< Event: mach (inform about machine architecture) >---
565 // This event is problematic because it messes up the output.
566 // The event is fired after the instruction address has already
567 // been printed. The decoded instruction (event "insn") is
568 // printed afterwards. That doesn't look nice.
569 if (decode_env::match(event, "mach")) {
570 guarantee(arg != NULL, "event_to_env - arg must not be NULL for event 'mach'");
571 static char buffer[64] = { 0, };
572 // Output suppressed because it messes up disassembly.
573 // Only print this when the mach changes.
574 if (false && (strcmp(buffer, (const char*)arg) != 0 ||
575 strlen((const char*)arg) > sizeof(buffer) - 1)) {
576 // Only print this when the mach changes
577 strncpy(buffer, (const char*)arg, sizeof(buffer) - 1);
578 buffer[sizeof(buffer) - 1] = '\0';
579 output()->print_cr("[Disassembling for mach='%s']", (const char*)arg);
580 }
581 return NULL;
582 }
583
584 //---< Event: format bytes-per-line >---
585 if (decode_env::match(event, "format bytes-per-line")) {
586 _bytes_per_line = (int) (intptr_t) arg;
587 return NULL;
588 }
589 #endif
590 return NULL;
591 }
592
event_to_env(void * env_pv,const char * event,void * arg)593 static void* event_to_env(void* env_pv, const char* event, void* arg) {
594 decode_env* env = (decode_env*) env_pv;
595 return env->handle_event(event, (address) arg);
596 }
597
598 // called by the disassembler to print out jump targets and data addresses
print_address(address adr)599 void decode_env::print_address(address adr) {
600 outputStream* st = output();
601
602 if (adr == NULL) {
603 st->print("NULL");
604 return;
605 }
606
607 int small_num = (int)(intptr_t)adr;
608 if ((intptr_t)adr == (intptr_t)small_num
609 && -1 <= small_num && small_num <= 9) {
610 st->print("%d", small_num);
611 return;
612 }
613
614 if (Universe::is_fully_initialized()) {
615 if (StubRoutines::contains(adr)) {
616 StubCodeDesc* desc = StubCodeDesc::desc_for(adr);
617 if (desc == NULL) {
618 desc = StubCodeDesc::desc_for(adr + frame::pc_return_offset);
619 }
620 if (desc != NULL) {
621 st->print("Stub::%s", desc->name());
622 if (desc->begin() != adr) {
623 st->print(INTX_FORMAT_W(+) " " PTR_FORMAT, adr - desc->begin(), p2i(adr));
624 } else if (WizardMode) {
625 st->print(" " PTR_FORMAT, p2i(adr));
626 }
627 return;
628 }
629 st->print("Stub::<unknown> " PTR_FORMAT, p2i(adr));
630 return;
631 }
632
633 BarrierSet* bs = BarrierSet::barrier_set();
634 if (bs->is_a(BarrierSet::CardTableBarrierSet) &&
635 adr == ci_card_table_address_as<address>()) {
636 st->print("word_map_base");
637 if (WizardMode) st->print(" " INTPTR_FORMAT, p2i(adr));
638 return;
639 }
640 }
641
642 if (_nm == NULL) {
643 // Don't do this for native methods, as the function name will be printed in
644 // nmethod::reloc_string_for().
645 // Allocate the buffer on the stack instead of as RESOURCE array.
646 // In case we do DecodeErrorFile, Thread will not be initialized,
647 // causing a "assert(current != __null) failed" failure.
648 const int buflen = 1024;
649 char buf[buflen];
650 int offset;
651 if (os::dll_address_to_function_name(adr, buf, buflen, &offset)) {
652 st->print(PTR_FORMAT " = %s", p2i(adr), buf);
653 if (offset != 0) {
654 st->print("+%d", offset);
655 }
656 return;
657 }
658 }
659
660 // Fall through to a simple (hexadecimal) numeral.
661 st->print(PTR_FORMAT, p2i(adr));
662 }
663
print_insn_labels()664 void decode_env::print_insn_labels() {
665 if (AbstractDisassembler::show_block_comment()) {
666 address p = cur_insn();
667 outputStream* st = output();
668
669 //---< Block comments for nmethod >---
670 // Outputs a bol() before and a cr() after, but only if a comment is printed.
671 // Prints nmethod_section_label as well.
672 if (_nm != NULL) {
673 _nm->print_block_comment(st, p);
674 }
675 if (_codeBlob != NULL) {
676 _codeBlob->print_block_comment(st, p);
677 }
678 if (_codeBuffer != NULL) {
679 _codeBuffer->print_block_comment(st, p);
680 }
681 _strings.print_block_comment(st, (intptr_t)(p - _start));
682 }
683 }
684
print_insn_prefix()685 void decode_env::print_insn_prefix() {
686 address p = cur_insn();
687 outputStream* st = output();
688 AbstractDisassembler::print_location(p, _start, _end, st, false, false);
689 AbstractDisassembler::print_instruction(p, Assembler::instr_len(p), Assembler::instr_maxlen(), st, true, false);
690 }
691
692 ATTRIBUTE_PRINTF(2, 3)
printf_to_env(void * env_pv,const char * format,...)693 static int printf_to_env(void* env_pv, const char* format, ...) {
694 decode_env* env = (decode_env*) env_pv;
695 outputStream* st = env->output();
696 size_t flen = strlen(format);
697 const char* raw = NULL;
698 if (flen == 0) return 0;
699 if (flen == 1 && format[0] == '\n') { st->bol(); return 1; }
700 if (flen < 2 ||
701 strchr(format, '%') == NULL) {
702 raw = format;
703 } else if (format[0] == '%' && format[1] == '%' &&
704 strchr(format+2, '%') == NULL) {
705 // happens a lot on machines with names like %foo
706 flen--;
707 raw = format+1;
708 }
709 if (raw != NULL) {
710 st->print_raw(raw, (int) flen);
711 return (int) flen;
712 }
713 va_list ap;
714 va_start(ap, format);
715 julong cnt0 = st->count();
716 st->vprint(format, ap);
717 julong cnt1 = st->count();
718 va_end(ap);
719 return (int)(cnt1 - cnt0);
720 }
721
722 // The 'original_start' argument holds the the original address where
723 // the instructions were located in the originating system. If zero (NULL)
724 // is passed in, there is no original address.
decode_instructions(address start,address end,address original_start)725 address decode_env::decode_instructions(address start, address end, address original_start /* = 0*/) {
726 // CodeComment in Stubs.
727 // Properly initialize _start/_end. Overwritten too often if
728 // printing of instructions is called for each instruction.
729 assert((_start == NULL) || (start == NULL) || (_start == start), "don't overwrite CTOR values");
730 assert((_end == NULL) || (end == NULL) || (_end == end ), "don't overwrite CTOR values");
731 if (start != NULL) set_start(start);
732 if (end != NULL) set_end(end);
733 if (original_start == NULL) {
734 original_start = start;
735 }
736
737 //---< Check (and correct) alignment >---
738 // Don't check alignment of end, it is not aligned.
739 if (((uint64_t)start & ((uint64_t)Disassembler::pd_instruction_alignment() - 1)) != 0) {
740 output()->print_cr("Decode range start:" PTR_FORMAT ": ... (unaligned)", p2i(start));
741 start = (address)((uint64_t)start & ~((uint64_t)Disassembler::pd_instruction_alignment() - 1));
742 }
743
744 // Trying to decode instructions doesn't make sense if we
745 // couldn't load the disassembler library.
746 if (Disassembler::is_abstract()) {
747 return NULL;
748 }
749
750 // decode a series of instructions and return the end of the last instruction
751
752 if (_print_raw) {
753 // Print whatever the library wants to print, w/o fancy callbacks.
754 // This is mainly for debugging the library itself.
755 FILE* out = stdout;
756 FILE* xmlout = (_print_raw > 1 ? out : NULL);
757 return use_new_version ?
758 (address)
759 (*Disassembler::_decode_instructions_virtual)((uintptr_t)start, (uintptr_t)end,
760 start, end - start,
761 NULL, (void*) xmlout,
762 NULL, (void*) out,
763 options(), 0/*nice new line*/)
764 :
765 (address)
766 (*Disassembler::_decode_instructions)(start, end,
767 NULL, (void*) xmlout,
768 NULL, (void*) out,
769 options());
770 }
771
772 return use_new_version ?
773 (address)
774 (*Disassembler::_decode_instructions_virtual)((uintptr_t)start, (uintptr_t)end,
775 start, end - start,
776 &event_to_env, (void*) this,
777 &printf_to_env, (void*) this,
778 options(), 0/*nice new line*/)
779 :
780 (address)
781 (*Disassembler::_decode_instructions)(start, end,
782 &event_to_env, (void*) this,
783 &printf_to_env, (void*) this,
784 options());
785 }
786
787 // ----------------------------------------------------------------------------
788 // Disassembler
789 // Used as a static wrapper for decode_env.
790 // Each method will create a decode_env before decoding.
791 // You can call the decode_env methods directly if you already have one.
792
793
load_library(outputStream * st)794 bool Disassembler::load_library(outputStream* st) {
795 // Do not try to load multiple times. Failed once -> fails always.
796 // To force retry in debugger: assign _tried_to_load_library=0
797 if (_tried_to_load_library) {
798 return _library_usable;
799 }
800
801 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
802 // Print to given stream, if any.
803 // Print to tty if Verbose is on and no stream given.
804 st = ((st == NULL) && Verbose) ? tty : st;
805
806 // Compute fully qualified library name.
807 char ebuf[1024];
808 char buf[JVM_MAXPATHLEN];
809 os::jvm_path(buf, sizeof(buf));
810 int jvm_offset = -1;
811 int lib_offset = -1;
812 #ifdef STATIC_BUILD
813 char* p = strrchr(buf, '/');
814 *p = '\0';
815 strcat(p, "/lib/");
816 lib_offset = jvm_offset = strlen(buf);
817 #else
818 {
819 // Match "libjvm" instead of "jvm" on *nix platforms. Creates better matches.
820 // Match "[lib]jvm[^/]*" in jvm_path.
821 const char* base = buf;
822 const char* p = strrchr(buf, *os::file_separator());
823 if (p != NULL) lib_offset = p - base + 1; // this points to the first char after separator
824 #ifdef _WIN32
825 p = strstr(p ? p : base, "jvm");
826 if (p != NULL) jvm_offset = p - base; // this points to 'j' in jvm.
827 #else
828 p = strstr(p ? p : base, "libjvm");
829 if (p != NULL) jvm_offset = p - base + 3; // this points to 'j' in libjvm.
830 #endif
831 }
832 #endif
833
834 // Find the disassembler shared library.
835 // Search for several paths derived from libjvm, in this order:
836 // 1. <home>/jre/lib/<arch>/<vm>/libhsdis-<arch>.so (for compatibility)
837 // 2. <home>/jre/lib/<arch>/<vm>/hsdis-<arch>.so
838 // 3. <home>/jre/lib/<arch>/hsdis-<arch>.so
839 // 4. hsdis-<arch>.so (using LD_LIBRARY_PATH)
840 if (jvm_offset >= 0) {
841 // 1. <home>/jre/lib/<arch>/<vm>/libhsdis-<arch>.so
842 strcpy(&buf[jvm_offset], hsdis_library_name);
843 strcat(&buf[jvm_offset], os::dll_file_extension());
844 if (Verbose) st->print_cr("Trying to load: %s", buf);
845 _library = os::dll_load(buf, ebuf, sizeof ebuf);
846 if (_library == NULL && lib_offset >= 0) {
847 // 2. <home>/jre/lib/<arch>/<vm>/hsdis-<arch>.so
848 strcpy(&buf[lib_offset], hsdis_library_name);
849 strcat(&buf[lib_offset], os::dll_file_extension());
850 if (Verbose) st->print_cr("Trying to load: %s", buf);
851 _library = os::dll_load(buf, ebuf, sizeof ebuf);
852 }
853 if (_library == NULL && lib_offset > 0) {
854 // 3. <home>/jre/lib/<arch>/hsdis-<arch>.so
855 buf[lib_offset - 1] = '\0';
856 const char* p = strrchr(buf, *os::file_separator());
857 if (p != NULL) {
858 lib_offset = p - buf + 1;
859 strcpy(&buf[lib_offset], hsdis_library_name);
860 strcat(&buf[lib_offset], os::dll_file_extension());
861 if (Verbose) st->print_cr("Trying to load: %s", buf);
862 _library = os::dll_load(buf, ebuf, sizeof ebuf);
863 }
864 }
865 }
866 if (_library == NULL) {
867 // 4. hsdis-<arch>.so (using LD_LIBRARY_PATH)
868 strcpy(&buf[0], hsdis_library_name);
869 strcat(&buf[0], os::dll_file_extension());
870 if (Verbose) st->print_cr("Trying to load: %s via LD_LIBRARY_PATH or equivalent", buf);
871 _library = os::dll_load(buf, ebuf, sizeof ebuf);
872 }
873
874 // load the decoder function to use (new or old version).
875 if (_library != NULL) {
876 _decode_instructions_virtual = CAST_TO_FN_PTR(Disassembler::decode_func_virtual,
877 os::dll_lookup(_library, decode_instructions_virtual_name));
878 }
879 if (_decode_instructions_virtual == NULL && _library != NULL) {
880 // could not spot in new version, try old version
881 _decode_instructions = CAST_TO_FN_PTR(Disassembler::decode_func,
882 os::dll_lookup(_library, decode_instructions_name));
883 use_new_version = false;
884 } else {
885 use_new_version = true;
886 }
887 _tried_to_load_library = true;
888 _library_usable = _decode_instructions_virtual != NULL || _decode_instructions != NULL;
889
890 // Create a dummy environment to initialize PrintAssemblyOptions.
891 // The PrintAssemblyOptions must be known for abstract disassemblies as well.
892 decode_env dummy((unsigned char*)(&buf[0]), (unsigned char*)(&buf[1]), st);
893
894 // Report problems during dll_load or dll_lookup, if any.
895 if (st != NULL) {
896 // Success.
897 if (_library_usable) {
898 st->print_cr("Loaded disassembler from %s", buf);
899 } else {
900 st->print_cr("Could not load %s; %s; %s",
901 buf,
902 ((_library != NULL)
903 ? "entry point is missing"
904 : ((WizardMode || PrintMiscellaneous)
905 ? (const char*)ebuf
906 : "library not loadable")),
907 "PrintAssembly defaults to abstract disassembly.");
908 }
909 }
910 #endif
911 return _library_usable;
912 }
913
914
915 // Directly disassemble code buffer.
decode(CodeBuffer * cb,address start,address end,outputStream * st)916 void Disassembler::decode(CodeBuffer* cb, address start, address end, outputStream* st) {
917 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
918 //---< Test memory before decoding >---
919 if (!(cb->contains(start) && cb->contains(end))) {
920 //---< Allow output suppression, but prevent writing to a NULL stream. Could happen with +PrintStubCode. >---
921 if (st != NULL) {
922 st->print("Memory range [" PTR_FORMAT ".." PTR_FORMAT "] not contained in CodeBuffer", p2i(start), p2i(end));
923 }
924 return;
925 }
926 if (!os::is_readable_range(start, end)) {
927 //---< Allow output suppression, but prevent writing to a NULL stream. Could happen with +PrintStubCode. >---
928 if (st != NULL) {
929 st->print("Memory range [" PTR_FORMAT ".." PTR_FORMAT "] not readable", p2i(start), p2i(end));
930 }
931 return;
932 }
933
934 decode_env env(cb, st);
935 env.output()->print_cr("--------------------------------------------------------------------------------");
936 env.output()->print("Decoding CodeBuffer (" PTR_FORMAT ")", p2i(cb));
937 if (cb->name() != NULL) {
938 env.output()->print(", name: %s,", cb->name());
939 }
940 env.output()->print_cr(" at [" PTR_FORMAT ", " PTR_FORMAT "] " JLONG_FORMAT " bytes", p2i(start), p2i(end), ((jlong)(end - start)));
941
942 if (is_abstract()) {
943 AbstractDisassembler::decode_abstract(start, end, env.output(), Assembler::instr_maxlen());
944 } else {
945 env.decode_instructions(start, end);
946 }
947 env.output()->print_cr("--------------------------------------------------------------------------------");
948 #endif
949 }
950
951 // Directly disassemble code blob.
decode(CodeBlob * cb,outputStream * st,CodeStrings c)952 void Disassembler::decode(CodeBlob* cb, outputStream* st, CodeStrings c) {
953 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
954 if (cb->is_nmethod()) {
955 // If we have an nmethod at hand,
956 // call the specialized decoder directly.
957 decode((nmethod*)cb, st, c);
958 return;
959 }
960
961 decode_env env(cb, st);
962 env.output()->print_cr("--------------------------------------------------------------------------------");
963 if (cb->is_aot()) {
964 env.output()->print("A ");
965 if (cb->is_compiled()) {
966 CompiledMethod* cm = (CompiledMethod*)cb;
967 env.output()->print("%d ",cm->compile_id());
968 cm->method()->method_holder()->name()->print_symbol_on(env.output());
969 env.output()->print(".");
970 cm->method()->name()->print_symbol_on(env.output());
971 cm->method()->signature()->print_symbol_on(env.output());
972 } else {
973 env.output()->print_cr("%s", cb->name());
974 }
975 } else {
976 env.output()->print("Decoding CodeBlob");
977 if (cb->name() != NULL) {
978 env.output()->print(", name: %s,", cb->name());
979 }
980 }
981 env.output()->print_cr(" at [" PTR_FORMAT ", " PTR_FORMAT "] " JLONG_FORMAT " bytes", p2i(cb->code_begin()), p2i(cb->code_end()), ((jlong)(cb->code_end() - cb->code_begin())));
982
983 if (is_abstract()) {
984 AbstractDisassembler::decode_abstract(cb->code_begin(), cb->code_end(), env.output(), Assembler::instr_maxlen());
985 } else {
986 env.decode_instructions(cb->code_begin(), cb->code_end());
987 }
988 env.output()->print_cr("--------------------------------------------------------------------------------");
989 #endif
990 }
991
992 // Decode a nmethod.
993 // This includes printing the constant pool and all code segments.
994 // The nmethod data structures (oop maps, relocations and the like) are not printed.
decode(nmethod * nm,outputStream * st,CodeStrings c)995 void Disassembler::decode(nmethod* nm, outputStream* st, CodeStrings c) {
996 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
997 ttyLocker ttyl;
998
999 decode_env env(nm, st);
1000 env.output()->print_cr("--------------------------------------------------------------------------------");
1001 nm->print_constant_pool(env.output());
1002 env.output()->print_cr("--------------------------------------------------------------------------------");
1003 env.output()->cr();
1004 if (is_abstract()) {
1005 AbstractDisassembler::decode_abstract(nm->code_begin(), nm->code_end(), env.output(), Assembler::instr_maxlen());
1006 } else {
1007 env.decode_instructions(nm->code_begin(), nm->code_end());
1008 }
1009 env.output()->print_cr("--------------------------------------------------------------------------------");
1010 #endif
1011 }
1012
1013 // Decode a range, given as [start address, end address)
decode(address start,address end,outputStream * st,CodeStrings c)1014 void Disassembler::decode(address start, address end, outputStream* st, CodeStrings c /*, ptrdiff_t offset */) {
1015 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
1016 //---< Test memory before decoding >---
1017 if (!os::is_readable_range(start, end)) {
1018 //---< Allow output suppression, but prevent writing to a NULL stream. Could happen with +PrintStubCode. >---
1019 if (st != NULL) {
1020 st->print("Memory range [" PTR_FORMAT ".." PTR_FORMAT "] not readable", p2i(start), p2i(end));
1021 }
1022 return;
1023 }
1024
1025 if (is_abstract()) {
1026 AbstractDisassembler::decode_abstract(start, end, st, Assembler::instr_maxlen());
1027 return;
1028 }
1029
1030 // Don't do that fancy stuff. If we just have two addresses, live with it
1031 // and treat the memory contents as "amorphic" piece of code.
1032 #if 0
1033 CodeBlob* cb = CodeCache::find_blob_unsafe(start);
1034 if (cb != NULL) {
1035 // If we have an CodeBlob at hand,
1036 // call the specialized decoder directly.
1037 decode(cb, st, c);
1038 } else
1039 #endif
1040 {
1041 // This seems to be just a chunk of memory.
1042 decode_env env(start, end, st);
1043 env.output()->print_cr("--------------------------------------------------------------------------------");
1044 env.decode_instructions(start, end);
1045 env.output()->print_cr("--------------------------------------------------------------------------------");
1046 }
1047 #endif
1048 }
1049
1050 // To prevent excessive code expansion in the interpreter generator, we
1051 // do not inline this function into Disassembler::hook().
_hook(const char * file,int line,MacroAssembler * masm)1052 void Disassembler::_hook(const char* file, int line, MacroAssembler* masm) {
1053 decode_env::hook(file, line, masm->code_section()->end());
1054 }
1055