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