1 /*
   2  * Copyright (c) 2008, 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 "incls/_precompiled.incl"
  26 # include "incls/_disassembler.cpp.incl"
  27 
  28 void*       Disassembler::_library               = NULL;
  29 bool        Disassembler::_tried_to_load_library = false;
  30 
  31 // This routine is in the shared library:
  32 Disassembler::decode_func Disassembler::_decode_instructions = NULL;
  33 
  34 static const char hsdis_library_name[] = "hsdis-"HOTSPOT_LIB_ARCH;
  35 static const char decode_instructions_name[] = "decode_instructions";
  36 
  37 #define COMMENT_COLUMN  40 LP64_ONLY(+8) /*could be an option*/
  38 #define BYTES_COMMENT   ";..."  /* funky byte display comment */
  39 
  40 bool Disassembler::load_library() {
  41   if (_decode_instructions != NULL) {
  42     // Already succeeded.
  43     return true;
  44   }
  45   if (_tried_to_load_library) {
  46     // Do not try twice.
  47     // To force retry in debugger: assign _tried_to_load_library=0
  48     return false;
  49   }
  50   // Try to load it.
  51   char ebuf[1024];
  52   char buf[JVM_MAXPATHLEN];
  53   os::jvm_path(buf, sizeof(buf));
  54   int jvm_offset = -1;
  55   {
  56     // Match "jvm[^/]*" in jvm_path.
  57     const char* base = buf;
  58     const char* p = strrchr(buf, '/');
  59     p = strstr(p ? p : base, "jvm");
  60     if (p != NULL)  jvm_offset = p - base;
  61   }
  62   if (jvm_offset >= 0) {
  63     // Find the disassembler next to libjvm.so.
  64     strcpy(&buf[jvm_offset], hsdis_library_name);
  65     strcat(&buf[jvm_offset], os::dll_file_extension());
  66     _library = hpi::dll_load(buf, ebuf, sizeof ebuf);
  67   }
  68   if (_library == NULL) {
  69     // Try a free-floating lookup.
  70     strcpy(&buf[0], hsdis_library_name);
  71     strcat(&buf[0], os::dll_file_extension());
  72     _library = hpi::dll_load(buf, ebuf, sizeof ebuf);
  73   }
  74   if (_library != NULL) {
  75     _decode_instructions = CAST_TO_FN_PTR(Disassembler::decode_func,
  76                                           hpi::dll_lookup(_library, decode_instructions_name));
  77   }
  78   _tried_to_load_library = true;
  79   if (_decode_instructions == NULL) {
  80     tty->print_cr("Could not load %s; %s; %s", buf,
  81                   ((_library != NULL)
  82                    ? "entry point is missing"
  83                    : (WizardMode || PrintMiscellaneous)
  84                    ? (const char*)ebuf
  85                    : "library not loadable"),
  86                   "PrintAssembly is disabled");
  87     return false;
  88   }
  89 
  90   // Success.
  91   tty->print_cr("Loaded disassembler from %s", buf);
  92   return true;
  93 }
  94 
  95 
  96 class decode_env {
  97  private:
  98   nmethod*      _nm;
  99   CodeBlob*     _code;
 100   outputStream* _output;
 101   address       _start, _end;
 102 
 103   char          _option_buf[512];
 104   char          _print_raw;
 105   bool          _print_pc;
 106   bool          _print_bytes;
 107   address       _cur_insn;
 108   int           _total_ticks;
 109   int           _bytes_per_line; // arch-specific formatting option
 110 
 111   static bool match(const char* event, const char* tag) {
 112     size_t taglen = strlen(tag);
 113     if (strncmp(event, tag, taglen) != 0)
 114       return false;
 115     char delim = event[taglen];
 116     return delim == '\0' || delim == ' ' || delim == '/' || delim == '=';
 117   }
 118 
 119   void collect_options(const char* p) {
 120     if (p == NULL || p[0] == '\0')  return;
 121     size_t opt_so_far = strlen(_option_buf);
 122     if (opt_so_far + 1 + strlen(p) + 1 > sizeof(_option_buf))  return;
 123     char* fillp = &_option_buf[opt_so_far];
 124     if (opt_so_far > 0) *fillp++ = ',';
 125     strcat(fillp, p);
 126     // replace white space by commas:
 127     char* q = fillp;
 128     while ((q = strpbrk(q, " \t\n")) != NULL)
 129       *q++ = ',';
 130     // Note that multiple PrintAssemblyOptions flags accumulate with \n,
 131     // which we want to be changed to a comma...
 132   }
 133 
 134   void print_insn_labels();
 135   void print_insn_bytes(address pc0, address pc);
 136   void print_address(address value);
 137 
 138  public:
 139   decode_env(CodeBlob* code, outputStream* output);
 140 
 141   address decode_instructions(address start, address end);
 142 
 143   void start_insn(address pc) {
 144     _cur_insn = pc;
 145     output()->bol();
 146     print_insn_labels();
 147   }
 148 
 149   void end_insn(address pc) {
 150     address pc0 = cur_insn();
 151     outputStream* st = output();
 152     if (_print_bytes && pc > pc0)
 153       print_insn_bytes(pc0, pc);
 154     if (_nm != NULL) {
 155       _nm->print_code_comment_on(st, COMMENT_COLUMN, pc0, pc);
 156       // this calls reloc_string_for which calls oop::print_value_on
 157     }
 158 
 159     // Output pc bucket ticks if we have any
 160     if (total_ticks() != 0) {
 161       address bucket_pc = FlatProfiler::bucket_start_for(pc);
 162       if (bucket_pc != NULL && bucket_pc > pc0 && bucket_pc <= pc) {
 163         int bucket_count = FlatProfiler::bucket_count_for(pc0);
 164         if (bucket_count != 0) {
 165           st->bol();
 166           st->print_cr("%3.1f%% [%d]", bucket_count*100.0/total_ticks(), bucket_count);
 167         }
 168       }
 169     }
 170   }
 171 
 172   address handle_event(const char* event, address arg);
 173 
 174   outputStream* output() { return _output; }
 175   address cur_insn() { return _cur_insn; }
 176   int total_ticks() { return _total_ticks; }
 177   void set_total_ticks(int n) { _total_ticks = n; }
 178   const char* options() { return _option_buf; }
 179 };
 180 
 181 decode_env::decode_env(CodeBlob* code, outputStream* output) {
 182   memset(this, 0, sizeof(*this));
 183   _output = output ? output : tty;
 184   _code = code;
 185   if (code != NULL && code->is_nmethod())
 186     _nm = (nmethod*) code;
 187 
 188   // by default, output pc but not bytes:
 189   _print_pc       = true;
 190   _print_bytes    = false;
 191   _bytes_per_line = Disassembler::pd_instruction_alignment();
 192 
 193   // parse the global option string:
 194   collect_options(Disassembler::pd_cpu_opts());
 195   collect_options(PrintAssemblyOptions);
 196 
 197   if (strstr(options(), "hsdis-")) {
 198     if (strstr(options(), "hsdis-print-raw"))
 199       _print_raw = (strstr(options(), "xml") ? 2 : 1);
 200     if (strstr(options(), "hsdis-print-pc"))
 201       _print_pc = !_print_pc;
 202     if (strstr(options(), "hsdis-print-bytes"))
 203       _print_bytes = !_print_bytes;
 204   }
 205   if (strstr(options(), "help")) {
 206     tty->print_cr("PrintAssemblyOptions help:");
 207     tty->print_cr("  hsdis-print-raw       test plugin by requesting raw output");
 208     tty->print_cr("  hsdis-print-raw-xml   test plugin by requesting raw xml");
 209     tty->print_cr("  hsdis-print-pc        turn off PC printing (on by default)");
 210     tty->print_cr("  hsdis-print-bytes     turn on instruction byte output");
 211     tty->print_cr("combined options: %s", options());
 212   }
 213 }
 214 
 215 address decode_env::handle_event(const char* event, address arg) {
 216   if (match(event, "insn")) {
 217     start_insn(arg);
 218   } else if (match(event, "/insn")) {
 219     end_insn(arg);
 220   } else if (match(event, "addr")) {
 221     if (arg != NULL) {
 222       print_address(arg);
 223       return arg;
 224     }
 225   } else if (match(event, "mach")) {
 226    output()->print_cr("[Disassembling for mach='%s']", arg);
 227   } else if (match(event, "format bytes-per-line")) {
 228     _bytes_per_line = (int) (intptr_t) arg;
 229   } else {
 230     // ignore unrecognized markup
 231   }
 232   return NULL;
 233 }
 234 
 235 // called by the disassembler to print out jump targets and data addresses
 236 void decode_env::print_address(address adr) {
 237   outputStream* st = _output;
 238 
 239   if (adr == NULL) {
 240     st->print("NULL");
 241     return;
 242   }
 243 
 244   int small_num = (int)(intptr_t)adr;
 245   if ((intptr_t)adr == (intptr_t)small_num
 246       && -1 <= small_num && small_num <= 9) {
 247     st->print("%d", small_num);
 248     return;
 249   }
 250 
 251   if (Universe::is_fully_initialized()) {
 252     if (StubRoutines::contains(adr)) {
 253       StubCodeDesc* desc = StubCodeDesc::desc_for(adr);
 254       if (desc == NULL)
 255         desc = StubCodeDesc::desc_for(adr + frame::pc_return_offset);
 256       if (desc != NULL) {
 257         st->print("Stub::%s", desc->name());
 258         if (desc->begin() != adr)
 259           st->print("%+d 0x%p",adr - desc->begin(), adr);
 260         else if (WizardMode) st->print(" " INTPTR_FORMAT, adr);
 261         return;
 262       }
 263       st->print("Stub::<unknown> " INTPTR_FORMAT, adr);
 264       return;
 265     }
 266 
 267     BarrierSet* bs = Universe::heap()->barrier_set();
 268     if (bs->kind() == BarrierSet::CardTableModRef &&
 269         adr == (address)((CardTableModRefBS*)(bs))->byte_map_base) {
 270       st->print("word_map_base");
 271       if (WizardMode) st->print(" " INTPTR_FORMAT, (intptr_t)adr);
 272       return;
 273     }
 274 
 275     oop obj;
 276     if (_nm != NULL
 277         && (obj = _nm->embeddedOop_at(cur_insn())) != NULL
 278         && (address) obj == adr
 279         && Universe::heap()->is_in(obj)
 280         && Universe::heap()->is_in(obj->klass())) {
 281       julong c = st->count();
 282       obj->print_value_on(st);
 283       if (st->count() == c) {
 284         // No output.  (Can happen in product builds.)
 285         st->print("(a %s)", Klass::cast(obj->klass())->external_name());
 286       }
 287       return;
 288     }
 289   }
 290 
 291   // Fall through to a simple numeral.
 292   st->print(INTPTR_FORMAT, (intptr_t)adr);
 293 }
 294 
 295 void decode_env::print_insn_labels() {
 296   address p = cur_insn();
 297   outputStream* st = output();
 298   CodeBlob* cb = _code;
 299   if (cb != NULL) {
 300     cb->print_block_comment(st, p);
 301   }
 302   if (_print_pc) {
 303     st->print("  " INTPTR_FORMAT ": ", (intptr_t) p);
 304   }
 305 }
 306 
 307 void decode_env::print_insn_bytes(address pc, address pc_limit) {
 308   outputStream* st = output();
 309   size_t incr = 1;
 310   size_t perline = _bytes_per_line;
 311   if ((size_t) Disassembler::pd_instruction_alignment() >= sizeof(int)
 312       && !((uintptr_t)pc % sizeof(int))
 313       && !((uintptr_t)pc_limit % sizeof(int))) {
 314     incr = sizeof(int);
 315     if (perline % incr)  perline += incr - (perline % incr);
 316   }
 317   while (pc < pc_limit) {
 318     // tab to the desired column:
 319     st->move_to(COMMENT_COLUMN);
 320     address pc0 = pc;
 321     address pc1 = pc + perline;
 322     if (pc1 > pc_limit)  pc1 = pc_limit;
 323     for (; pc < pc1; pc += incr) {
 324       if (pc == pc0)
 325         st->print(BYTES_COMMENT);
 326       else if ((uint)(pc - pc0) % sizeof(int) == 0)
 327         st->print(" ");         // put out a space on word boundaries
 328       if (incr == sizeof(int))
 329             st->print("%08lx", *(int*)pc);
 330       else  st->print("%02x",   (*pc)&0xFF);
 331     }
 332     st->cr();
 333   }
 334 }
 335 
 336 
 337 static void* event_to_env(void* env_pv, const char* event, void* arg) {
 338   decode_env* env = (decode_env*) env_pv;
 339   return env->handle_event(event, (address) arg);
 340 }
 341 
 342 static int printf_to_env(void* env_pv, const char* format, ...) {
 343   decode_env* env = (decode_env*) env_pv;
 344   outputStream* st = env->output();
 345   size_t flen = strlen(format);
 346   const char* raw = NULL;
 347   if (flen == 0)  return 0;
 348   if (flen == 1 && format[0] == '\n') { st->bol(); return 1; }
 349   if (flen < 2 ||
 350       strchr(format, '%') == NULL) {
 351     raw = format;
 352   } else if (format[0] == '%' && format[1] == '%' &&
 353              strchr(format+2, '%') == NULL) {
 354     // happens a lot on machines with names like %foo
 355     flen--;
 356     raw = format+1;
 357   }
 358   if (raw != NULL) {
 359     st->print_raw(raw, (int) flen);
 360     return (int) flen;
 361   }
 362   va_list ap;
 363   va_start(ap, format);
 364   julong cnt0 = st->count();
 365   st->vprint(format, ap);
 366   julong cnt1 = st->count();
 367   va_end(ap);
 368   return (int)(cnt1 - cnt0);
 369 }
 370 
 371 address decode_env::decode_instructions(address start, address end) {
 372   _start = start; _end = end;
 373 
 374   assert((((intptr_t)start | (intptr_t)end) % Disassembler::pd_instruction_alignment() == 0), "misaligned insn addr");
 375 
 376   const int show_bytes = false; // for disassembler debugging
 377 
 378   //_version = Disassembler::pd_cpu_version();
 379 
 380   if (!Disassembler::can_decode()) {
 381     return NULL;
 382   }
 383 
 384   // decode a series of instructions and return the end of the last instruction
 385 
 386   if (_print_raw) {
 387     // Print whatever the library wants to print, w/o fancy callbacks.
 388     // This is mainly for debugging the library itself.
 389     FILE* out = stdout;
 390     FILE* xmlout = (_print_raw > 1 ? out : NULL);
 391     return (address)
 392       (*Disassembler::_decode_instructions)(start, end,
 393                                             NULL, (void*) xmlout,
 394                                             NULL, (void*) out,
 395                                             options());
 396   }
 397 
 398   return (address)
 399     (*Disassembler::_decode_instructions)(start, end,
 400                                           &event_to_env,  (void*) this,
 401                                           &printf_to_env, (void*) this,
 402                                           options());
 403 }
 404 
 405 
 406 void Disassembler::decode(CodeBlob* cb, outputStream* st) {
 407   if (!load_library())  return;
 408   decode_env env(cb, st);
 409   env.output()->print_cr("Decoding CodeBlob " INTPTR_FORMAT, cb);
 410   env.decode_instructions(cb->instructions_begin(), cb->instructions_end());
 411 }
 412 
 413 
 414 void Disassembler::decode(address start, address end, outputStream* st) {
 415   if (!load_library())  return;
 416   decode_env env(CodeCache::find_blob_unsafe(start), st);
 417   env.decode_instructions(start, end);
 418 }
 419 
 420 void Disassembler::decode(nmethod* nm, outputStream* st) {
 421   if (!load_library())  return;
 422   decode_env env(nm, st);
 423   env.output()->print_cr("Decoding compiled method " INTPTR_FORMAT ":", nm);
 424   env.output()->print_cr("Code:");
 425 
 426   unsigned char* p = nm->instructions_begin();
 427   unsigned char* end = nm->instructions_end();
 428 
 429   // If there has been profiling, print the buckets.
 430   if (FlatProfiler::bucket_start_for(p) != NULL) {
 431     unsigned char* p1 = p;
 432     int total_bucket_count = 0;
 433     while (p1 < end) {
 434       unsigned char* p0 = p1;
 435       p1 += pd_instruction_alignment();
 436       address bucket_pc = FlatProfiler::bucket_start_for(p1);
 437       if (bucket_pc != NULL && bucket_pc > p0 && bucket_pc <= p1)
 438         total_bucket_count += FlatProfiler::bucket_count_for(p0);
 439     }
 440     env.set_total_ticks(total_bucket_count);
 441   }
 442 
 443   env.decode_instructions(p, end);
 444 }