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