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