1 /*
   2  * Copyright 2008 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any 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_virtual";
  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 
 157     // Output pc bucket ticks if we have any
 158     if (total_ticks() != 0) {
 159       address bucket_pc = FlatProfiler::bucket_start_for(pc);
 160       if (bucket_pc != NULL && bucket_pc > pc0 && bucket_pc <= pc) {
 161         int bucket_count = FlatProfiler::bucket_count_for(pc0);
 162         if (bucket_count != 0) {
 163           st->bol();
 164           st->print_cr("%3.1f%% [%d]", bucket_count*100.0/total_ticks(), bucket_count);
 165         }
 166       }
 167     }
 168     // follow each complete insn by a nice newline
 169     st->cr();
 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       obj->print_value_on(st);
 280       return;
 281     }
 282   }
 283 
 284   // Fall through to a simple numeral.
 285   st->print(INTPTR_FORMAT, (intptr_t)adr);
 286 }
 287 
 288 void decode_env::print_insn_labels() {
 289   address p = cur_insn();
 290   outputStream* st = output();
 291   nmethod* nm = _nm;
 292   if (nm != NULL) {
 293     if (p == nm->entry_point())             st->print_cr("[Entry Point]");
 294     if (p == nm->verified_entry_point())    st->print_cr("[Verified Entry Point]");
 295     if (p == nm->exception_begin())         st->print_cr("[Exception Handler]");
 296     if (p == nm->stub_begin())              st->print_cr("[Stub Code]");
 297     if (p == nm->consts_begin())            st->print_cr("[Constants]");
 298   }
 299   CodeBlob* cb = _code;
 300   if (cb != NULL) {
 301     cb->print_block_comment(st, (intptr_t)(p - cb->instructions_begin()));
 302   }
 303   if (_print_pc) {
 304     st->print("  " INTPTR_FORMAT ": ", (intptr_t) p);
 305   }
 306 }
 307 
 308 void decode_env::print_insn_bytes(address pc, address pc_limit) {
 309   outputStream* st = output();
 310   size_t incr = 1;
 311   size_t perline = _bytes_per_line;
 312   if ((size_t) Disassembler::pd_instruction_alignment() >= sizeof(int)
 313       && !((uintptr_t)pc % sizeof(int))
 314       && !((uintptr_t)pc_limit % sizeof(int))) {
 315     incr = sizeof(int);
 316     if (perline % incr)  perline += incr - (perline % incr);
 317   }
 318   while (pc < pc_limit) {
 319     // tab to the desired column:
 320     st->move_to(COMMENT_COLUMN);
 321     address pc0 = pc;
 322     address pc1 = pc + perline;
 323     if (pc1 > pc_limit)  pc1 = pc_limit;
 324     for (; pc < pc1; pc += incr) {
 325       if (pc == pc0)
 326         st->print(BYTES_COMMENT);
 327       else if ((uint)(pc - pc0) % sizeof(int) == 0)
 328         st->print(" ");         // put out a space on word boundaries
 329       if (incr == sizeof(int))
 330             st->print("%08lx", *(int*)pc);
 331       else  st->print("%02x",   (*pc)&0xFF);
 332     }
 333     st->cr();
 334   }
 335 }
 336 
 337 
 338 static void* event_to_env(void* env_pv, const char* event, void* arg) {
 339   decode_env* env = (decode_env*) env_pv;
 340   return env->handle_event(event, (address) arg);
 341 }
 342 
 343 static int printf_to_env(void* env_pv, const char* format, ...) {
 344   decode_env* env = (decode_env*) env_pv;
 345   outputStream* st = env->output();
 346   size_t flen = strlen(format);
 347   const char* raw = NULL;
 348   if (flen == 0)  return 0;
 349   if (flen == 1 && format[0] == '\n') { st->bol(); return 1; }
 350   if (flen < 2 ||
 351       strchr(format, '%') == NULL) {
 352     raw = format;
 353   } else if (format[0] == '%' && format[1] == '%' &&
 354              strchr(format+2, '%') == NULL) {
 355     // happens a lot on machines with names like %foo
 356     flen--;
 357     raw = format+1;
 358   }
 359   if (raw != NULL) {
 360     st->print_raw(raw, (int) flen);
 361     return (int) flen;
 362   }
 363   va_list ap;
 364   va_start(ap, format);
 365   julong cnt0 = st->count();
 366   st->vprint(format, ap);
 367   julong cnt1 = st->count();
 368   va_end(ap);
 369   return (int)(cnt1 - cnt0);
 370 }
 371 
 372 address decode_env::decode_instructions(address start, address end) {
 373   _start = start; _end = end;
 374 
 375   assert((((intptr_t)start | (intptr_t)end) % Disassembler::pd_instruction_alignment() == 0), "misaligned insn addr");
 376 
 377   const int show_bytes = false; // for disassembler debugging
 378 
 379   //_version = Disassembler::pd_cpu_version();
 380 
 381   if (!Disassembler::can_decode()) {
 382     return NULL;
 383   }
 384 
 385   // decode a series of instructions and return the end of the last instruction
 386 
 387   if (_print_raw) {
 388     // Print whatever the library wants to print, w/o fancy callbacks.
 389     // This is mainly for debugging the library itself.
 390     FILE* out = stdout;
 391     FILE* xmlout = (_print_raw > 1 ? out : NULL);
 392     return (address)
 393       (*Disassembler::_decode_instructions)((uintptr_t)start, (uintptr_t)end,
 394                                             start, end - start,
 395                                             NULL, (void*) xmlout,
 396                                             NULL, (void*) out,
 397                                             options());
 398   }
 399 
 400   return (address)
 401     (*Disassembler::_decode_instructions)((uintptr_t)start, (uintptr_t)end,
 402                                           start, end - start,
 403                                           &event_to_env,  (void*) this,
 404                                           &printf_to_env, (void*) this,
 405                                           options());
 406 }
 407 
 408 
 409 void Disassembler::decode(CodeBlob* cb, outputStream* st) {
 410   if (!load_library())  return;
 411   decode_env env(cb, st);
 412   env.output()->print_cr("Decoding CodeBlob " INTPTR_FORMAT, cb);
 413   env.decode_instructions(cb->instructions_begin(), cb->instructions_end());
 414 }
 415 
 416 
 417 void Disassembler::decode(address start, address end, outputStream* st) {
 418   if (!load_library())  return;
 419   decode_env env(CodeCache::find_blob_unsafe(start), st);
 420   env.decode_instructions(start, end);
 421 }
 422 
 423 void Disassembler::decode(nmethod* nm, outputStream* st) {
 424   if (!load_library())  return;
 425   decode_env env(nm, st);
 426   env.output()->print_cr("Decoding compiled method " INTPTR_FORMAT ":", nm);
 427   env.output()->print_cr("Code:");
 428 
 429   unsigned char* p = nm->instructions_begin();
 430   unsigned char* end = nm->instructions_end();
 431 
 432   // If there has been profiling, print the buckets.
 433   if (FlatProfiler::bucket_start_for(p) != NULL) {
 434     unsigned char* p1 = p;
 435     int total_bucket_count = 0;
 436     while (p1 < end) {
 437       unsigned char* p0 = p1;
 438       p1 += pd_instruction_alignment();
 439       address bucket_pc = FlatProfiler::bucket_start_for(p1);
 440       if (bucket_pc != NULL && bucket_pc > p0 && bucket_pc <= p1)
 441         total_bucket_count += FlatProfiler::bucket_count_for(p0);
 442     }
 443     env.set_total_ticks(total_bucket_count);
 444   }
 445 
 446   env.decode_instructions(p, end);
 447 }