disassembler.cpp revision 8266:4cf3113c8f42
1/*
2 * Copyright (c) 2008, 2015, 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 "classfile/javaClasses.hpp"
27#include "code/codeCache.hpp"
28#include "compiler/disassembler.hpp"
29#include "gc_interface/collectedHeap.hpp"
30#include "memory/cardTableModRefBS.hpp"
31#include "oops/oop.inline.hpp"
32#include "runtime/fprofiler.hpp"
33#include "runtime/handles.inline.hpp"
34#include "runtime/os.hpp"
35#include "runtime/stubCodeGenerator.hpp"
36#include "runtime/stubRoutines.hpp"
37#ifdef TARGET_ARCH_x86
38# include "depChecker_x86.hpp"
39#endif
40#ifdef TARGET_ARCH_sparc
41# include "depChecker_sparc.hpp"
42#endif
43#ifdef TARGET_ARCH_zero
44# include "depChecker_zero.hpp"
45#endif
46#ifdef TARGET_ARCH_arm
47# include "depChecker_arm.hpp"
48#endif
49#ifdef TARGET_ARCH_ppc
50# include "depChecker_ppc.hpp"
51#endif
52#ifdef TARGET_ARCH_aarch64
53# include "depChecker_aarch64.hpp"
54#endif
55#ifdef SHARK
56#include "shark/sharkEntry.hpp"
57#endif
58
59PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
60
61void*       Disassembler::_library               = NULL;
62bool        Disassembler::_tried_to_load_library = false;
63
64// This routine is in the shared library:
65Disassembler::decode_func_virtual Disassembler::_decode_instructions_virtual = NULL;
66Disassembler::decode_func Disassembler::_decode_instructions = NULL;
67
68static const char hsdis_library_name[] = "hsdis-"HOTSPOT_LIB_ARCH;
69static const char decode_instructions_virtual_name[] = "decode_instructions_virtual";
70static const char decode_instructions_name[] = "decode_instructions";
71static bool use_new_version = true;
72#define COMMENT_COLUMN  40 LP64_ONLY(+8) /*could be an option*/
73#define BYTES_COMMENT   ";..."  /* funky byte display comment */
74
75bool Disassembler::load_library() {
76  if (_decode_instructions_virtual != NULL || _decode_instructions != NULL) {
77    // Already succeeded.
78    return true;
79  }
80  if (_tried_to_load_library) {
81    // Do not try twice.
82    // To force retry in debugger: assign _tried_to_load_library=0
83    return false;
84  }
85  // Try to load it.
86  char ebuf[1024];
87  char buf[JVM_MAXPATHLEN];
88  os::jvm_path(buf, sizeof(buf));
89  int jvm_offset = -1;
90  int lib_offset = -1;
91  {
92    // Match "jvm[^/]*" in jvm_path.
93    const char* base = buf;
94    const char* p = strrchr(buf, *os::file_separator());
95    if (p != NULL) lib_offset = p - base + 1;
96    p = strstr(p ? p : base, "jvm");
97    if (p != NULL)  jvm_offset = p - base;
98  }
99  // Find the disassembler shared library.
100  // Search for several paths derived from libjvm, in this order:
101  // 1. <home>/jre/lib/<arch>/<vm>/libhsdis-<arch>.so  (for compatibility)
102  // 2. <home>/jre/lib/<arch>/<vm>/hsdis-<arch>.so
103  // 3. <home>/jre/lib/<arch>/hsdis-<arch>.so
104  // 4. hsdis-<arch>.so  (using LD_LIBRARY_PATH)
105  if (jvm_offset >= 0) {
106    // 1. <home>/jre/lib/<arch>/<vm>/libhsdis-<arch>.so
107    strcpy(&buf[jvm_offset], hsdis_library_name);
108    strcat(&buf[jvm_offset], os::dll_file_extension());
109    _library = os::dll_load(buf, ebuf, sizeof ebuf);
110    if (_library == NULL) {
111      // 2. <home>/jre/lib/<arch>/<vm>/hsdis-<arch>.so
112      strcpy(&buf[lib_offset], hsdis_library_name);
113      strcat(&buf[lib_offset], os::dll_file_extension());
114      _library = os::dll_load(buf, ebuf, sizeof ebuf);
115    }
116    if (_library == NULL) {
117      // 3. <home>/jre/lib/<arch>/hsdis-<arch>.so
118      buf[lib_offset - 1] = '\0';
119      const char* p = strrchr(buf, *os::file_separator());
120      if (p != NULL) {
121        lib_offset = p - buf + 1;
122        strcpy(&buf[lib_offset], hsdis_library_name);
123        strcat(&buf[lib_offset], os::dll_file_extension());
124        _library = os::dll_load(buf, ebuf, sizeof ebuf);
125      }
126    }
127  }
128  if (_library == NULL) {
129    // 4. hsdis-<arch>.so  (using LD_LIBRARY_PATH)
130    strcpy(&buf[0], hsdis_library_name);
131    strcat(&buf[0], os::dll_file_extension());
132    _library = os::dll_load(buf, ebuf, sizeof ebuf);
133  }
134  if (_library != NULL) {
135    _decode_instructions_virtual = CAST_TO_FN_PTR(Disassembler::decode_func_virtual,
136                                          os::dll_lookup(_library, decode_instructions_virtual_name));
137  }
138  if (_decode_instructions_virtual == NULL) {
139    // could not spot in new version, try old version
140    _decode_instructions = CAST_TO_FN_PTR(Disassembler::decode_func,
141                                          os::dll_lookup(_library, decode_instructions_name));
142    use_new_version = false;
143  } else {
144    use_new_version = true;
145  }
146  _tried_to_load_library = true;
147  if (_decode_instructions_virtual == NULL && _decode_instructions == NULL) {
148    tty->print_cr("Could not load %s; %s; %s", buf,
149                  ((_library != NULL)
150                   ? "entry point is missing"
151                   : (WizardMode || PrintMiscellaneous)
152                   ? (const char*)ebuf
153                   : "library not loadable"),
154                  "PrintAssembly is disabled");
155    return false;
156  }
157
158  // Success.
159  tty->print_cr("Loaded disassembler from %s", buf);
160  return true;
161}
162
163
164class decode_env {
165 private:
166  nmethod*      _nm;
167  CodeBlob*     _code;
168  CodeStrings   _strings;
169  outputStream* _output;
170  address       _start, _end;
171
172  char          _option_buf[512];
173  char          _print_raw;
174  bool          _print_pc;
175  bool          _print_bytes;
176  address       _cur_insn;
177  int           _total_ticks;
178  int           _bytes_per_line; // arch-specific formatting option
179
180  static bool match(const char* event, const char* tag) {
181    size_t taglen = strlen(tag);
182    if (strncmp(event, tag, taglen) != 0)
183      return false;
184    char delim = event[taglen];
185    return delim == '\0' || delim == ' ' || delim == '/' || delim == '=';
186  }
187
188  void collect_options(const char* p) {
189    if (p == NULL || p[0] == '\0')  return;
190    size_t opt_so_far = strlen(_option_buf);
191    if (opt_so_far + 1 + strlen(p) + 1 > sizeof(_option_buf))  return;
192    char* fillp = &_option_buf[opt_so_far];
193    if (opt_so_far > 0) *fillp++ = ',';
194    strcat(fillp, p);
195    // replace white space by commas:
196    char* q = fillp;
197    while ((q = strpbrk(q, " \t\n")) != NULL)
198      *q++ = ',';
199    // Note that multiple PrintAssemblyOptions flags accumulate with \n,
200    // which we want to be changed to a comma...
201  }
202
203  void print_insn_labels();
204  void print_insn_bytes(address pc0, address pc);
205  void print_address(address value);
206
207 public:
208  decode_env(CodeBlob* code, outputStream* output, CodeStrings c = CodeStrings());
209
210  address decode_instructions(address start, address end);
211
212  void start_insn(address pc) {
213    _cur_insn = pc;
214    output()->bol();
215    print_insn_labels();
216  }
217
218  void end_insn(address pc) {
219    address pc0 = cur_insn();
220    outputStream* st = output();
221    if (_print_bytes && pc > pc0)
222      print_insn_bytes(pc0, pc);
223    if (_nm != NULL) {
224      _nm->print_code_comment_on(st, COMMENT_COLUMN, pc0, pc);
225      // this calls reloc_string_for which calls oop::print_value_on
226    }
227
228    // Output pc bucket ticks if we have any
229    if (total_ticks() != 0) {
230      address bucket_pc = FlatProfiler::bucket_start_for(pc);
231      if (bucket_pc != NULL && bucket_pc > pc0 && bucket_pc <= pc) {
232        int bucket_count = FlatProfiler::bucket_count_for(pc0);
233        if (bucket_count != 0) {
234          st->bol();
235          st->print_cr("%3.1f%% [%d]", bucket_count*100.0/total_ticks(), bucket_count);
236        }
237      }
238    }
239    // follow each complete insn by a nice newline
240    st->cr();
241  }
242
243  address handle_event(const char* event, address arg);
244
245  outputStream* output() { return _output; }
246  address cur_insn() { return _cur_insn; }
247  int total_ticks() { return _total_ticks; }
248  void set_total_ticks(int n) { _total_ticks = n; }
249  const char* options() { return _option_buf; }
250};
251
252decode_env::decode_env(CodeBlob* code, outputStream* output, CodeStrings c) {
253  memset(this, 0, sizeof(*this)); // Beware, this zeroes bits of fields.
254  _output = output ? output : tty;
255  _code = code;
256  if (code != NULL && code->is_nmethod())
257    _nm = (nmethod*) code;
258  _strings.copy(c);
259
260  // by default, output pc but not bytes:
261  _print_pc       = true;
262  _print_bytes    = false;
263  _bytes_per_line = Disassembler::pd_instruction_alignment();
264
265  // parse the global option string:
266  collect_options(Disassembler::pd_cpu_opts());
267  collect_options(PrintAssemblyOptions);
268
269  if (strstr(options(), "hsdis-")) {
270    if (strstr(options(), "hsdis-print-raw"))
271      _print_raw = (strstr(options(), "xml") ? 2 : 1);
272    if (strstr(options(), "hsdis-print-pc"))
273      _print_pc = !_print_pc;
274    if (strstr(options(), "hsdis-print-bytes"))
275      _print_bytes = !_print_bytes;
276  }
277  if (strstr(options(), "help")) {
278    tty->print_cr("PrintAssemblyOptions help:");
279    tty->print_cr("  hsdis-print-raw       test plugin by requesting raw output");
280    tty->print_cr("  hsdis-print-raw-xml   test plugin by requesting raw xml");
281    tty->print_cr("  hsdis-print-pc        turn off PC printing (on by default)");
282    tty->print_cr("  hsdis-print-bytes     turn on instruction byte output");
283    tty->print_cr("combined options: %s", options());
284  }
285}
286
287address decode_env::handle_event(const char* event, address arg) {
288  if (match(event, "insn")) {
289    start_insn(arg);
290  } else if (match(event, "/insn")) {
291    end_insn(arg);
292  } else if (match(event, "addr")) {
293    if (arg != NULL) {
294      print_address(arg);
295      return arg;
296    }
297  } else if (match(event, "mach")) {
298    static char buffer[32] = { 0, };
299    if (strcmp(buffer, (const char*)arg) != 0 ||
300        strlen((const char*)arg) > sizeof(buffer) - 1) {
301      // Only print this when the mach changes
302      strncpy(buffer, (const char*)arg, sizeof(buffer) - 1);
303      buffer[sizeof(buffer) - 1] = '\0';
304      output()->print_cr("[Disassembling for mach='%s']", arg);
305    }
306  } else if (match(event, "format bytes-per-line")) {
307    _bytes_per_line = (int) (intptr_t) arg;
308  } else {
309    // ignore unrecognized markup
310  }
311  return NULL;
312}
313
314// called by the disassembler to print out jump targets and data addresses
315void decode_env::print_address(address adr) {
316  outputStream* st = _output;
317
318  if (adr == NULL) {
319    st->print("NULL");
320    return;
321  }
322
323  int small_num = (int)(intptr_t)adr;
324  if ((intptr_t)adr == (intptr_t)small_num
325      && -1 <= small_num && small_num <= 9) {
326    st->print("%d", small_num);
327    return;
328  }
329
330  if (Universe::is_fully_initialized()) {
331    if (StubRoutines::contains(adr)) {
332      StubCodeDesc* desc = StubCodeDesc::desc_for(adr);
333      if (desc == NULL)
334        desc = StubCodeDesc::desc_for(adr + frame::pc_return_offset);
335      if (desc != NULL) {
336        st->print("Stub::%s", desc->name());
337        if (desc->begin() != adr)
338          st->print("%+d 0x%p",adr - desc->begin(), adr);
339        else if (WizardMode) st->print(" " PTR_FORMAT, adr);
340        return;
341      }
342      st->print("Stub::<unknown> " PTR_FORMAT, adr);
343      return;
344    }
345
346    BarrierSet* bs = Universe::heap()->barrier_set();
347    if (bs->is_a(BarrierSet::CardTableModRef) &&
348        adr == (address)(barrier_set_cast<CardTableModRefBS>(bs)->byte_map_base)) {
349      st->print("word_map_base");
350      if (WizardMode) st->print(" " INTPTR_FORMAT, (intptr_t)adr);
351      return;
352    }
353  }
354
355  // Fall through to a simple (hexadecimal) numeral.
356  st->print(PTR_FORMAT, adr);
357}
358
359void decode_env::print_insn_labels() {
360  address p = cur_insn();
361  outputStream* st = output();
362  CodeBlob* cb = _code;
363  if (cb != NULL) {
364    cb->print_block_comment(st, p);
365  }
366  _strings.print_block_comment(st, (intptr_t)(p - _start));
367  if (_print_pc) {
368    st->print("  " PTR_FORMAT ": ", p);
369  }
370}
371
372void decode_env::print_insn_bytes(address pc, address pc_limit) {
373  outputStream* st = output();
374  size_t incr = 1;
375  size_t perline = _bytes_per_line;
376  if ((size_t) Disassembler::pd_instruction_alignment() >= sizeof(int)
377      && !((uintptr_t)pc % sizeof(int))
378      && !((uintptr_t)pc_limit % sizeof(int))) {
379    incr = sizeof(int);
380    if (perline % incr)  perline += incr - (perline % incr);
381  }
382  while (pc < pc_limit) {
383    // tab to the desired column:
384    st->move_to(COMMENT_COLUMN);
385    address pc0 = pc;
386    address pc1 = pc + perline;
387    if (pc1 > pc_limit)  pc1 = pc_limit;
388    for (; pc < pc1; pc += incr) {
389      if (pc == pc0)
390        st->print(BYTES_COMMENT);
391      else if ((uint)(pc - pc0) % sizeof(int) == 0)
392        st->print(" ");         // put out a space on word boundaries
393      if (incr == sizeof(int))
394            st->print("%08lx", *(int*)pc);
395      else  st->print("%02x",   (*pc)&0xFF);
396    }
397    st->cr();
398  }
399}
400
401
402static void* event_to_env(void* env_pv, const char* event, void* arg) {
403  decode_env* env = (decode_env*) env_pv;
404  return env->handle_event(event, (address) arg);
405}
406
407ATTRIBUTE_PRINTF(2, 3)
408static int printf_to_env(void* env_pv, const char* format, ...) {
409  decode_env* env = (decode_env*) env_pv;
410  outputStream* st = env->output();
411  size_t flen = strlen(format);
412  const char* raw = NULL;
413  if (flen == 0)  return 0;
414  if (flen == 1 && format[0] == '\n') { st->bol(); return 1; }
415  if (flen < 2 ||
416      strchr(format, '%') == NULL) {
417    raw = format;
418  } else if (format[0] == '%' && format[1] == '%' &&
419             strchr(format+2, '%') == NULL) {
420    // happens a lot on machines with names like %foo
421    flen--;
422    raw = format+1;
423  }
424  if (raw != NULL) {
425    st->print_raw(raw, (int) flen);
426    return (int) flen;
427  }
428  va_list ap;
429  va_start(ap, format);
430  julong cnt0 = st->count();
431  st->vprint(format, ap);
432  julong cnt1 = st->count();
433  va_end(ap);
434  return (int)(cnt1 - cnt0);
435}
436
437address decode_env::decode_instructions(address start, address end) {
438  _start = start; _end = end;
439
440  assert(((((intptr_t)start | (intptr_t)end) % Disassembler::pd_instruction_alignment()) == 0), "misaligned insn addr");
441
442  const int show_bytes = false; // for disassembler debugging
443
444  //_version = Disassembler::pd_cpu_version();
445
446  if (!Disassembler::can_decode()) {
447    return NULL;
448  }
449
450  // decode a series of instructions and return the end of the last instruction
451
452  if (_print_raw) {
453    // Print whatever the library wants to print, w/o fancy callbacks.
454    // This is mainly for debugging the library itself.
455    FILE* out = stdout;
456    FILE* xmlout = (_print_raw > 1 ? out : NULL);
457    return use_new_version ?
458      (address)
459      (*Disassembler::_decode_instructions_virtual)((uintptr_t)start, (uintptr_t)end,
460                                                    start, end - start,
461                                                    NULL, (void*) xmlout,
462                                                    NULL, (void*) out,
463                                                    options(), 0/*nice new line*/)
464      :
465      (address)
466      (*Disassembler::_decode_instructions)(start, end,
467                                            NULL, (void*) xmlout,
468                                            NULL, (void*) out,
469                                            options());
470  }
471
472  return use_new_version ?
473    (address)
474    (*Disassembler::_decode_instructions_virtual)((uintptr_t)start, (uintptr_t)end,
475                                                  start, end - start,
476                                                  &event_to_env,  (void*) this,
477                                                  &printf_to_env, (void*) this,
478                                                  options(), 0/*nice new line*/)
479    :
480    (address)
481    (*Disassembler::_decode_instructions)(start, end,
482                                          &event_to_env,  (void*) this,
483                                          &printf_to_env, (void*) this,
484                                          options());
485}
486
487
488void Disassembler::decode(CodeBlob* cb, outputStream* st) {
489  if (!load_library())  return;
490  decode_env env(cb, st);
491  env.output()->print_cr("Decoding CodeBlob " PTR_FORMAT, cb);
492  env.decode_instructions(cb->code_begin(), cb->code_end());
493}
494
495void Disassembler::decode(address start, address end, outputStream* st, CodeStrings c) {
496  if (!load_library())  return;
497  decode_env env(CodeCache::find_blob_unsafe(start), st, c);
498  env.decode_instructions(start, end);
499}
500
501void Disassembler::decode(nmethod* nm, outputStream* st) {
502  if (!load_library())  return;
503  decode_env env(nm, st);
504  env.output()->print_cr("Decoding compiled method " PTR_FORMAT ":", nm);
505  env.output()->print_cr("Code:");
506
507#ifdef SHARK
508  SharkEntry* entry = (SharkEntry *) nm->code_begin();
509  unsigned char* p   = entry->code_start();
510  unsigned char* end = entry->code_limit();
511#else
512  unsigned char* p   = nm->code_begin();
513  unsigned char* end = nm->code_end();
514#endif // SHARK
515
516  // If there has been profiling, print the buckets.
517  if (FlatProfiler::bucket_start_for(p) != NULL) {
518    unsigned char* p1 = p;
519    int total_bucket_count = 0;
520    while (p1 < end) {
521      unsigned char* p0 = p1;
522      p1 += pd_instruction_alignment();
523      address bucket_pc = FlatProfiler::bucket_start_for(p1);
524      if (bucket_pc != NULL && bucket_pc > p0 && bucket_pc <= p1)
525        total_bucket_count += FlatProfiler::bucket_count_for(p0);
526    }
527    env.set_total_ticks(total_bucket_count);
528  }
529
530  // Print constant table.
531  if (nm->consts_size() > 0) {
532    nm->print_nmethod_labels(env.output(), nm->consts_begin());
533    int offset = 0;
534    for (address p = nm->consts_begin(); p < nm->consts_end(); p += 4, offset += 4) {
535      if ((offset % 8) == 0) {
536        env.output()->print_cr("  " PTR_FORMAT " (offset: %4d): " PTR32_FORMAT "   " PTR64_FORMAT, p, offset, *((int32_t*) p), *((int64_t*) p));
537      } else {
538        env.output()->print_cr("  " PTR_FORMAT " (offset: %4d): " PTR32_FORMAT,                    p, offset, *((int32_t*) p));
539      }
540    }
541  }
542
543  env.decode_instructions(p, end);
544}
545