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