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