1 /*
   2  * Copyright (c) 2008, 2019, 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 "asm/assembler.inline.hpp"
  27 #include "asm/macroAssembler.hpp"
  28 #include "ci/ciUtilities.hpp"
  29 #include "classfile/javaClasses.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "compiler/disassembler.hpp"
  32 #include "gc/shared/cardTable.hpp"
  33 #include "gc/shared/cardTableBarrierSet.hpp"
  34 #include "gc/shared/collectedHeap.hpp"
  35 #include "memory/resourceArea.hpp"
  36 #include "memory/universe.hpp"
  37 #include "oops/oop.inline.hpp"
  38 #include "runtime/handles.inline.hpp"
  39 #include "runtime/os.inline.hpp"
  40 #include "runtime/stubCodeGenerator.hpp"
  41 #include "runtime/stubRoutines.hpp"
  42 #include "utilities/resourceHash.hpp"
  43 #include CPU_HEADER(depChecker)
  44 
  45 void*       Disassembler::_library               = NULL;
  46 bool        Disassembler::_tried_to_load_library = false;
  47 bool        Disassembler::_library_usable        = false;
  48 
  49 // This routine is in the shared library:
  50 Disassembler::decode_func_virtual Disassembler::_decode_instructions_virtual = NULL;
  51 Disassembler::decode_func Disassembler::_decode_instructions = NULL;
  52 
  53 static const char hsdis_library_name[] = "hsdis-" HOTSPOT_LIB_ARCH;
  54 static const char decode_instructions_virtual_name[] = "decode_instructions_virtual";
  55 static const char decode_instructions_name[] = "decode_instructions";
  56 static bool use_new_version = true;
  57 #define COMMENT_COLUMN  52 LP64_ONLY(+8) /*could be an option*/
  58 #define BYTES_COMMENT   ";..."  /* funky byte display comment */
  59 
  60 class decode_env {
  61  private:
  62   outputStream* _output;      // where the disassembly is directed to
  63   CodeBuffer*   _codeBuffer;  // != NULL only when decoding a CodeBuffer
  64   CodeBlob*     _codeBlob;    // != NULL only when decoding a CodeBlob
  65   nmethod*      _nm;          // != NULL only when decoding a nmethod
  66   CodeStrings   _strings;
  67   address       _start;       // != NULL when decoding a range of unknown type
  68   address       _end;         // != NULL when decoding a range of unknown type
  69 
  70   char          _option_buf[512];
  71   char          _print_raw;
  72   address       _cur_insn;        // address of instruction currently being decoded
  73   int           _bytes_per_line;  // arch-specific formatting option
  74   int           _pre_decode_alignment;
  75   int           _post_decode_alignment;
  76   bool          _print_file_name;
  77   bool          _print_help;
  78   bool          _helpPrinted;
  79   static bool   _optionsParsed;
  80 
  81   enum {
  82     tabspacing = 8
  83   };
  84 
  85   // Check if the event matches the expected tag
  86   // The tag must be a substring of the event, and
  87   // the tag must be a token in the event, i.e. separated by delimiters
  88   static bool match(const char* event, const char* tag) {
  89     size_t eventlen = strlen(event);
  90     size_t taglen   = strlen(tag);
  91     if (eventlen < taglen)  // size mismatch
  92       return false;
  93     if (strncmp(event, tag, taglen) != 0)  // string mismatch
  94       return false;
  95     char delim = event[taglen];
  96     return delim == '\0' || delim == ' ' || delim == '/' || delim == '=';
  97   }
  98 
  99   // Merge new option string with previously recorded options
 100   void collect_options(const char* p) {
 101     if (p == NULL || p[0] == '\0')  return;
 102     size_t opt_so_far = strlen(_option_buf);
 103     if (opt_so_far + 1 + strlen(p) + 1 > sizeof(_option_buf))  return;
 104     char* fillp = &_option_buf[opt_so_far];
 105     if (opt_so_far > 0) *fillp++ = ',';
 106     strcat(fillp, p);
 107     // replace white space by commas:
 108     char* q = fillp;
 109     while ((q = strpbrk(q, " \t\n")) != NULL)
 110       *q++ = ',';
 111   }
 112 
 113   void process_options(outputStream* ost);
 114 
 115   void print_insn_labels();
 116   void print_insn_prefix();
 117   void print_address(address value);
 118 
 119   // Properly initializes _start/_end. Overwritten too often if
 120   // printing of instructions is called for each instruction.
 121   void set_start(address s)   { _start = s; }
 122   void set_end  (address e)   { _end = e; }
 123   void set_nm   (nmethod* nm) { _nm = nm; }
 124   void set_output(outputStream* st) { _output = st; }
 125 
 126 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 127   // The disassembler library (sometimes) uses tabs to nicely align the instruction operands.
 128   // Depending on the mnemonic length and the column position where the
 129   // mnemonic is printed, alignment may turn out to be not so nice.
 130   // To improve, we assume 8-character tab spacing and left-align the mnemonic on a tab position.
 131   // Instruction comments are aligned 4 tab positions to the right of the mnemonic.
 132   void calculate_alignment() {
 133     _pre_decode_alignment  = ((output()->position()+tabspacing-1)/tabspacing)*tabspacing;
 134     _post_decode_alignment = _pre_decode_alignment + 4*tabspacing;
 135   }
 136 
 137   void start_insn(address pc) {
 138     _cur_insn = pc;
 139     output()->bol();
 140     print_insn_labels();
 141     print_insn_prefix();
 142   }
 143 
 144   void end_insn(address pc) {
 145     address pc0 = cur_insn();
 146     outputStream* st = output();
 147 
 148     if (AbstractDisassembler::show_comment()) {
 149       if ((_nm != NULL) && _nm->has_code_comment(pc0, pc)) {
 150         _nm->print_code_comment_on
 151                (st,
 152                 _post_decode_alignment ? _post_decode_alignment : COMMENT_COLUMN,
 153                 pc0, pc);
 154         // this calls reloc_string_for which calls oop::print_value_on
 155       }
 156       print_hook_comments(pc0, _nm != NULL);
 157     }
 158     Disassembler::annotate(pc0, output());
 159     // follow each complete insn by a nice newline
 160     st->bol();
 161   }
 162 #endif
 163 
 164   struct SourceFileInfo {
 165     struct Link : public CHeapObj<mtCode> {
 166       const char* file;
 167       int line;
 168       Link* next;
 169       Link(const char* f, int l) : file(f), line(l), next(NULL) {}
 170     };
 171     Link *head, *tail;
 172 
 173     static unsigned hash(const address& a) {
 174       return primitive_hash<address>(a);
 175     }
 176     static bool equals(const address& a0, const address& a1) {
 177       return primitive_equals<address>(a0, a1);
 178     }
 179     void append(const char* file, int line) {
 180       if (tail != NULL && tail->file == file && tail->line == line) {
 181         // Don't print duplicated lines at the same address. This could happen with C
 182         // macros that end up having multiple "__" tokens on the same __LINE__.
 183         return;
 184       }
 185       Link *link = new Link(file, line);
 186       if (head == NULL) {
 187         head = tail = link;
 188       } else {
 189         tail->next = link;
 190         tail = link;
 191       }
 192     }
 193     SourceFileInfo(const char* file, int line) : head(NULL), tail(NULL) {
 194       append(file, line);
 195     }
 196   };
 197 
 198   typedef ResourceHashtable<
 199       address, SourceFileInfo,
 200       SourceFileInfo::hash,
 201       SourceFileInfo::equals,
 202       15889,      // prime number
 203       ResourceObj::C_HEAP> SourceFileInfoTable;
 204 
 205   static SourceFileInfoTable _src_table;
 206   static const char* _cached_src;
 207   static GrowableArray<const char*>* _cached_src_lines;
 208 
 209  public:
 210   decode_env(CodeBuffer* code, outputStream* output);
 211   decode_env(CodeBlob*   code, outputStream* output, CodeStrings c = CodeStrings() /* , ptrdiff_t offset */);
 212   decode_env(nmethod*    code, outputStream* output, CodeStrings c = CodeStrings());
 213   // Constructor for a 'decode_env' to decode an arbitrary
 214   // piece of memory, hopefully containing code.
 215   decode_env(address start, address end, outputStream* output);
 216 
 217   // Add 'original_start' argument which is the the original address
 218   // the instructions were located at (if this is not equal to 'start').
 219   address decode_instructions(address start, address end, address original_start = NULL);
 220 
 221   address handle_event(const char* event, address arg);
 222 
 223   outputStream* output()   { return _output; }
 224   address       cur_insn() { return _cur_insn; }
 225   const char*   options()  { return _option_buf; }
 226   static void   hook(const char* file, int line, address pc);
 227   void print_hook_comments(address pc, bool newline);
 228 };
 229 
 230 bool decode_env::_optionsParsed = false;
 231 
 232 decode_env::SourceFileInfoTable decode_env::_src_table;
 233 const char* decode_env::_cached_src = NULL;
 234 GrowableArray<const char*>* decode_env::_cached_src_lines = NULL;
 235 
 236 void decode_env::hook(const char* file, int line, address pc) {
 237   // For simplication, we never free from this table. It's really not
 238   // necessary as we add to the table only when PrintInterpreter is true,
 239   // which means we are debugging the VM and a little bit of extra
 240   // memory usage doesn't matter.
 241   SourceFileInfo* found = _src_table.get(pc);
 242   if (found != NULL) {
 243     found->append(file, line);
 244   } else {
 245     SourceFileInfo sfi(file, line);
 246     _src_table.put(pc, sfi); // sfi is copied by value
 247   }
 248 }
 249 
 250 void decode_env::print_hook_comments(address pc, bool newline) {
 251   SourceFileInfo* found = _src_table.get(pc);
 252   outputStream* st = output();
 253   if (found != NULL) {
 254     for (SourceFileInfo::Link *link = found->head; link; link = link->next) {
 255       const char* file = link->file;
 256       int line = link->line;
 257       if (_cached_src == NULL || strcmp(_cached_src, file) != 0) {
 258         FILE* fp;
 259 
 260         // _cached_src_lines is a single cache of the lines of a source file, and we refill this cache
 261         // every time we need to print a line from a different source file. It's not the fastest,
 262         // but seems bearable.
 263         if (_cached_src_lines != NULL) {
 264           for (int i=0; i<_cached_src_lines->length(); i++) {
 265             os::free((void*)_cached_src_lines->at(i));
 266           }
 267           _cached_src_lines->clear();
 268         } else {
 269           _cached_src_lines = new (ResourceObj::C_HEAP, mtCode)GrowableArray<const char*>(0, true);
 270         }
 271 
 272         if ((fp = fopen(file, "r")) == NULL) {
 273           _cached_src = NULL;
 274           return;
 275         }
 276         _cached_src = file;
 277 
 278         char line[500]; // don't write lines that are too long in your source files!
 279         while (fgets(line, sizeof(line), fp) != NULL) {
 280           size_t len = strlen(line);
 281           if (len > 0 && line[len-1] == '\n') {
 282             line[len-1] = '\0';
 283           }
 284           _cached_src_lines->append(os::strdup(line));
 285         }
 286         fclose(fp);
 287         _print_file_name = true;
 288       }
 289 
 290       if (_print_file_name) {
 291         // We print the file name whenever we switch to a new file, or when
 292         // Disassembler::decode is called to disassemble a new block of code.
 293         _print_file_name = false;
 294         if (newline) {
 295           st->cr();
 296         }
 297         st->move_to(COMMENT_COLUMN);
 298         st->print(";;@FILE: %s", file);
 299         newline = true;
 300       }
 301 
 302       int index = line - 1; // 1-based line number -> 0-based index.
 303       if (index >= _cached_src_lines->length()) {
 304         // This could happen if source file is mismatched.
 305       } else {
 306         const char* source_line = _cached_src_lines->at(index);
 307         if (newline) {
 308           st->cr();
 309         }
 310         st->move_to(COMMENT_COLUMN);
 311         st->print(";;%5d: %s", line, source_line);
 312         newline = true;
 313       }
 314     }
 315   }
 316 }
 317 
 318 decode_env::decode_env(CodeBuffer* code, outputStream* output) {
 319   memset(this, 0, sizeof(*this));
 320   _output = output ? output : tty;
 321   _codeBlob    = NULL;
 322   _codeBuffer  = code;
 323   _helpPrinted = false;
 324 
 325   process_options(_output);
 326 }
 327 
 328 decode_env::decode_env(CodeBlob* code, outputStream* output, CodeStrings c) {
 329    memset(this, 0, sizeof(*this)); // Beware, this zeroes bits of fields.
 330    _output = output ? output : tty;
 331   _codeBlob    = code;
 332   _codeBuffer  = NULL;
 333   _helpPrinted = false;
 334   if (_codeBlob != NULL && _codeBlob->is_nmethod()) {
 335     _nm = (nmethod*) code;
 336   }
 337   _strings.copy(c);
 338 
 339   process_options(_output);
 340 }
 341 
 342 decode_env::decode_env(nmethod* code, outputStream* output, CodeStrings c) {
 343   memset(this, 0, sizeof(*this)); // Beware, this zeroes bits of fields.
 344   _output = output ? output : tty;
 345   _codeBlob    = NULL;
 346   _codeBuffer  = NULL;
 347   _nm          = code;
 348   _start       = _nm->code_begin();
 349   _end         = _nm->code_end();
 350   _helpPrinted = false;
 351   _strings.copy(c);
 352 
 353   process_options(_output);
 354 }
 355 
 356 // Constructor for a 'decode_env' to decode a memory range [start, end)
 357 // of unknown origin, assuming it contains code.
 358 decode_env::decode_env(address start, address end, outputStream* output) {
 359   assert(start < end, "Range must have a positive size, [" PTR_FORMAT ".." PTR_FORMAT ").", p2i(start), p2i(end));
 360   memset(this, 0, sizeof(*this));
 361   _output = output ? output : tty;
 362   _codeBlob    = NULL;
 363   _codeBuffer  = NULL;
 364   _start       = start;
 365   _end         = end;
 366   _helpPrinted = false;
 367 
 368   process_options(_output);
 369 }
 370 
 371 void decode_env::process_options(outputStream* ost) {
 372   // by default, output pc but not bytes:
 373   _print_help      = false;
 374   _bytes_per_line  = Disassembler::pd_instruction_alignment();
 375   _print_file_name = true;
 376 
 377   if (_optionsParsed) return;  // parse only once
 378 
 379   // parse the global option string:
 380   collect_options(Disassembler::pd_cpu_opts());
 381   collect_options(PrintAssemblyOptions);
 382 
 383   if (strstr(options(), "print-raw")) {
 384     _print_raw = (strstr(options(), "xml") ? 2 : 1);
 385   }
 386 
 387   if (strstr(options(), "help")) {
 388     _print_help = true;
 389   }
 390   if (strstr(options(), "align-instr")) {
 391     AbstractDisassembler::toggle_align_instr();
 392   }
 393   if (strstr(options(), "show-pc")) {
 394     AbstractDisassembler::toggle_show_pc();
 395   }
 396   if (strstr(options(), "show-offset")) {
 397     AbstractDisassembler::toggle_show_offset();
 398   }
 399   if (strstr(options(), "show-bytes")) {
 400     AbstractDisassembler::toggle_show_bytes();
 401   }
 402   if (strstr(options(), "show-data-hex")) {
 403     AbstractDisassembler::toggle_show_data_hex();
 404   }
 405   if (strstr(options(), "show-data-int")) {
 406     AbstractDisassembler::toggle_show_data_int();
 407   }
 408   if (strstr(options(), "show-data-float")) {
 409     AbstractDisassembler::toggle_show_data_float();
 410   }
 411   if (strstr(options(), "show-structs")) {
 412     AbstractDisassembler::toggle_show_structs();
 413   }
 414   if (strstr(options(), "show-comment")) {
 415     AbstractDisassembler::toggle_show_comment();
 416   }
 417   if (strstr(options(), "show-block-comment")) {
 418     AbstractDisassembler::toggle_show_block_comment();
 419   }
 420   _optionsParsed = true;
 421 
 422   if (_print_help && ! _helpPrinted) {
 423     _helpPrinted = true;
 424     ost->print_cr("PrintAssemblyOptions help:");
 425     ost->print_cr("  print-raw       test plugin by requesting raw output");
 426     ost->print_cr("  print-raw-xml   test plugin by requesting raw xml");
 427     ost->cr();
 428     ost->print_cr("  show-pc            toggle printing current pc,        currently %s", AbstractDisassembler::show_pc()            ? "ON" : "OFF");
 429     ost->print_cr("  show-offset        toggle printing current offset,    currently %s", AbstractDisassembler::show_offset()        ? "ON" : "OFF");
 430     ost->print_cr("  show-bytes         toggle printing instruction bytes, currently %s", AbstractDisassembler::show_bytes()         ? "ON" : "OFF");
 431     ost->print_cr("  show-data-hex      toggle formatting data as hex,     currently %s", AbstractDisassembler::show_data_hex()      ? "ON" : "OFF");
 432     ost->print_cr("  show-data-int      toggle formatting data as int,     currently %s", AbstractDisassembler::show_data_int()      ? "ON" : "OFF");
 433     ost->print_cr("  show-data-float    toggle formatting data as float,   currently %s", AbstractDisassembler::show_data_float()    ? "ON" : "OFF");
 434     ost->print_cr("  show-structs       toggle compiler data structures,   currently %s", AbstractDisassembler::show_structs()       ? "ON" : "OFF");
 435     ost->print_cr("  show-comment       toggle instruction comments,       currently %s", AbstractDisassembler::show_comment()       ? "ON" : "OFF");
 436     ost->print_cr("  show-block-comment toggle block comments,             currently %s", AbstractDisassembler::show_block_comment() ? "ON" : "OFF");
 437     ost->print_cr("  align-instr        toggle instruction alignment,      currently %s", AbstractDisassembler::align_instr()        ? "ON" : "OFF");
 438     ost->print_cr("combined options: %s", options());
 439   }
 440 }
 441 
 442 // Disassembly Event Handler.
 443 // This method receives events from the disassembler library hsdis
 444 // via event_to_env for each decoding step (installed by
 445 // Disassembler::decode_instructions(), replacing the default
 446 // callback method). This enables dumping additional info
 447 // and custom line formatting.
 448 // In a future extension, calling a custom decode method will be
 449 // supported. We can use such a method to decode instructions the
 450 // binutils decoder does not handle to our liking (suboptimal
 451 // formatting, incomplete information, ...).
 452 // Returns:
 453 // - NULL for all standard invocations. The function result is not
 454 //        examined (as of now, 20190409) by the hsdis decoder loop.
 455 // - next for 'insn0' invocations.
 456 //        next == arg: the custom decoder didn't do anything.
 457 //        next >  arg: the custom decoder did decode the instruction.
 458 //                     next points to the next undecoded instruction
 459 //                     (continuation point for decoder loop).
 460 //
 461 // "Normal" sequence of events:
 462 //  insns   - start of instruction stream decoding
 463 //  mach    - display architecture
 464 //  format  - display bytes-per-line
 465 //  for each instruction:
 466 //    insn    - start of instruction decoding
 467 //    insn0   - custom decoder invocation (if any)
 468 //    addr    - print address value
 469 //    /insn   - end of instruction decoding
 470 //  /insns  - premature end of instruction stream due to no progress
 471 //
 472 address decode_env::handle_event(const char* event, address arg) {
 473 
 474 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 475 
 476   //---<  Event: end decoding loop (error, no progress)  >---
 477   if (decode_env::match(event, "/insns")) {
 478     // Nothing to be done here.
 479     return NULL;
 480   }
 481 
 482   //---<  Event: start decoding loop  >---
 483   if (decode_env::match(event, "insns")) {
 484     // Nothing to be done here.
 485     return NULL;
 486   }
 487 
 488   //---<  Event: finish decoding an instruction  >---
 489   if (decode_env::match(event, "/insn")) {
 490     output()->fill_to(_post_decode_alignment);
 491     end_insn(arg);
 492     return NULL;
 493   }
 494 
 495   //---<  Event: start decoding an instruction  >---
 496   if (decode_env::match(event, "insn")) {
 497     start_insn(arg);
 498   } else if (match(event, "/insn")) {
 499     end_insn(arg);
 500   } else if (match(event, "addr")) {
 501     if (arg != NULL) {
 502       print_address(arg);
 503       return arg;
 504     }
 505     calculate_alignment();
 506     output()->fill_to(_pre_decode_alignment);
 507     return NULL;
 508   }
 509 
 510   //---<  Event: call custom decoder (platform specific)  >---
 511   if (decode_env::match(event, "insn0")) {
 512     return Disassembler::decode_instruction0(arg, output(), arg);
 513   }
 514 
 515   //---<  Event: Print address  >---
 516   if (decode_env::match(event, "addr")) {
 517     print_address(arg);
 518     return arg;
 519   }
 520 
 521   //---<  Event: mach (inform about machine architecture)  >---
 522   // This event is problematic because it messes up the output.
 523   // The event is fired after the instruction address has already
 524   // been printed. The decoded instruction (event "insn") is
 525   // printed afterwards. That doesn't look nice.
 526   if (decode_env::match(event, "mach")) {
 527     guarantee(arg != NULL, "event_to_env - arg must not be NULL for event 'mach'");
 528     static char buffer[64] = { 0, };
 529     // Output suppressed because it messes up disassembly.
 530     // Only print this when the mach changes.
 531     if (false && (strcmp(buffer, (const char*)arg) != 0 ||
 532                   strlen((const char*)arg) > sizeof(buffer) - 1)) {
 533       // Only print this when the mach changes
 534       strncpy(buffer, (const char*)arg, sizeof(buffer) - 1);
 535       buffer[sizeof(buffer) - 1] = '\0';
 536       output()->print_cr("[Disassembling for mach='%s']", (const char*)arg);
 537     }
 538     return NULL;
 539   }
 540 
 541   //---<  Event: format bytes-per-line  >---
 542   if (decode_env::match(event, "format bytes-per-line")) {
 543     _bytes_per_line = (int) (intptr_t) arg;
 544     return NULL;
 545   }
 546 #endif
 547   return NULL;
 548 }
 549 
 550 static void* event_to_env(void* env_pv, const char* event, void* arg) {
 551   decode_env* env = (decode_env*) env_pv;
 552   return env->handle_event(event, (address) arg);
 553 }
 554 
 555 // called by the disassembler to print out jump targets and data addresses
 556 void decode_env::print_address(address adr) {
 557   outputStream* st = output();
 558 
 559   if (adr == NULL) {
 560     st->print("NULL");
 561     return;
 562   }
 563 
 564   int small_num = (int)(intptr_t)adr;
 565   if ((intptr_t)adr == (intptr_t)small_num
 566       && -1 <= small_num && small_num <= 9) {
 567     st->print("%d", small_num);
 568     return;
 569   }
 570 
 571   if (Universe::is_fully_initialized()) {
 572     if (StubRoutines::contains(adr)) {
 573       StubCodeDesc* desc = StubCodeDesc::desc_for(adr);
 574       if (desc == NULL) {
 575         desc = StubCodeDesc::desc_for(adr + frame::pc_return_offset);
 576       }
 577       if (desc != NULL) {
 578         st->print("Stub::%s", desc->name());
 579         if (desc->begin() != adr) {
 580           st->print(INTX_FORMAT_W(+) " " PTR_FORMAT, adr - desc->begin(), p2i(adr));
 581         } else if (WizardMode) {
 582           st->print(" " PTR_FORMAT, p2i(adr));
 583         }
 584         return;
 585       }
 586       st->print("Stub::<unknown> " PTR_FORMAT, p2i(adr));
 587       return;
 588     }
 589 
 590     BarrierSet* bs = BarrierSet::barrier_set();
 591     if (bs->is_a(BarrierSet::CardTableBarrierSet) &&
 592         adr == ci_card_table_address_as<address>()) {
 593       st->print("word_map_base");
 594       if (WizardMode) st->print(" " INTPTR_FORMAT, p2i(adr));
 595       return;
 596     }
 597   }
 598 
 599   if (_nm == NULL) {
 600     // Don't do this for native methods, as the function name will be printed in
 601     // nmethod::reloc_string_for().
 602     // Allocate the buffer on the stack instead of as RESOURCE array.
 603     // In case we do DecodeErrorFile, Thread will not be initialized,
 604     // causing a "assert(current != __null) failed" failure.
 605     const int buflen = 1024;
 606     char buf[buflen];
 607     int offset;
 608     if (os::dll_address_to_function_name(adr, buf, buflen, &offset)) {
 609       st->print(PTR_FORMAT " = %s",  p2i(adr), buf);
 610       if (offset != 0) {
 611         st->print("+%d", offset);
 612       }
 613       return;
 614     }
 615   }
 616 
 617   // Fall through to a simple (hexadecimal) numeral.
 618   st->print(PTR_FORMAT, p2i(adr));
 619 }
 620 
 621 void decode_env::print_insn_labels() {
 622   if (AbstractDisassembler::show_block_comment()) {
 623     address       p  = cur_insn();
 624     outputStream* st = output();
 625 
 626     //---<  Block comments for nmethod  >---
 627     // Outputs a bol() before and a cr() after, but only if a comment is printed.
 628     // Prints nmethod_section_label as well.
 629     if (_nm != NULL) {
 630       _nm->print_block_comment(st, p);
 631     }
 632     if (_codeBlob != NULL) {
 633       _codeBlob->print_block_comment(st, p);
 634     }
 635     if (_codeBuffer != NULL) {
 636       _codeBuffer->print_block_comment(st, p);
 637     }
 638     _strings.print_block_comment(st, (intptr_t)(p - _start));
 639   }
 640 }
 641 
 642 void decode_env::print_insn_prefix() {
 643   address       p  = cur_insn();
 644   outputStream* st = output();
 645   AbstractDisassembler::print_location(p, _start, _end, st, false, false);
 646   AbstractDisassembler::print_instruction(p, Assembler::instr_len(p), Assembler::instr_maxlen(), st, true, false);
 647 }
 648 
 649 ATTRIBUTE_PRINTF(2, 3)
 650 static int printf_to_env(void* env_pv, const char* format, ...) {
 651   decode_env* env = (decode_env*) env_pv;
 652   outputStream* st = env->output();
 653   size_t flen = strlen(format);
 654   const char* raw = NULL;
 655   if (flen == 0)  return 0;
 656   if (flen == 1 && format[0] == '\n') { st->bol(); return 1; }
 657   if (flen < 2 ||
 658       strchr(format, '%') == NULL) {
 659     raw = format;
 660   } else if (format[0] == '%' && format[1] == '%' &&
 661              strchr(format+2, '%') == NULL) {
 662     // happens a lot on machines with names like %foo
 663     flen--;
 664     raw = format+1;
 665   }
 666   if (raw != NULL) {
 667     st->print_raw(raw, (int) flen);
 668     return (int) flen;
 669   }
 670   va_list ap;
 671   va_start(ap, format);
 672   julong cnt0 = st->count();
 673   st->vprint(format, ap);
 674   julong cnt1 = st->count();
 675   va_end(ap);
 676   return (int)(cnt1 - cnt0);
 677 }
 678 
 679 // The 'original_start' argument holds the the original address where
 680 // the instructions were located in the originating system. If zero (NULL)
 681 // is passed in, there is no original address.
 682 address decode_env::decode_instructions(address start, address end, address original_start /* = 0*/) {
 683   // CodeComment in Stubs.
 684   // Properly initialize _start/_end. Overwritten too often if
 685   // printing of instructions is called for each instruction.
 686   assert((_start == NULL) || (start == NULL) || (_start == start), "don't overwrite CTOR values");
 687   assert((_end   == NULL) || (end   == NULL) || (_end   == end  ), "don't overwrite CTOR values");
 688   if (start != NULL) set_start(start);
 689   if (end   != NULL) set_end(end);
 690   if (original_start == NULL) {
 691     original_start = start;
 692   }
 693 
 694   //---<  Check (and correct) alignment  >---
 695   // Don't check alignment of end, it is not aligned.
 696   if (((uint64_t)start & ((uint64_t)Disassembler::pd_instruction_alignment() - 1)) != 0) {
 697     output()->print_cr("Decode range start:" PTR_FORMAT ": ... (unaligned)", p2i(start));
 698     start = (address)((uint64_t)start & ~((uint64_t)Disassembler::pd_instruction_alignment() - 1));
 699   }
 700 
 701   // Trying to decode instructions doesn't make sense if we
 702   // couldn't load the disassembler library.
 703   if (Disassembler::is_abstract()) {
 704     return NULL;
 705   }
 706 
 707   // decode a series of instructions and return the end of the last instruction
 708 
 709   if (_print_raw) {
 710     // Print whatever the library wants to print, w/o fancy callbacks.
 711     // This is mainly for debugging the library itself.
 712     FILE* out = stdout;
 713     FILE* xmlout = (_print_raw > 1 ? out : NULL);
 714     return use_new_version ?
 715       (address)
 716       (*Disassembler::_decode_instructions_virtual)((uintptr_t)start, (uintptr_t)end,
 717                                                     start, end - start,
 718                                                     NULL, (void*) xmlout,
 719                                                     NULL, (void*) out,
 720                                                     options(), 0/*nice new line*/)
 721       :
 722       (address)
 723       (*Disassembler::_decode_instructions)(start, end,
 724                                             NULL, (void*) xmlout,
 725                                             NULL, (void*) out,
 726                                             options());
 727   }
 728 
 729   return use_new_version ?
 730     (address)
 731     (*Disassembler::_decode_instructions_virtual)((uintptr_t)start, (uintptr_t)end,
 732                                                   start, end - start,
 733                                                   &event_to_env,  (void*) this,
 734                                                   &printf_to_env, (void*) this,
 735                                                   options(), 0/*nice new line*/)
 736     :
 737     (address)
 738     (*Disassembler::_decode_instructions)(start, end,
 739                                           &event_to_env,  (void*) this,
 740                                           &printf_to_env, (void*) this,
 741                                           options());
 742 }
 743 
 744 // ----------------------------------------------------------------------------
 745 // Disassembler
 746 // Used as a static wrapper for decode_env.
 747 // Each method will create a decode_env before decoding.
 748 // You can call the decode_env methods directly if you already have one.
 749 
 750 
 751 bool Disassembler::load_library(outputStream* st) {
 752   // Do not try to load multiple times. Failed once -> fails always.
 753   // To force retry in debugger: assign _tried_to_load_library=0
 754   if (_tried_to_load_library) {
 755     return _library_usable;
 756   }
 757 
 758 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 759   // Print to given stream, if any.
 760   // Print to tty if Verbose is on and no stream given.
 761   st = ((st == NULL) && Verbose) ? tty : st;
 762 
 763   // Compute fully qualified library name.
 764   char ebuf[1024];
 765   char buf[JVM_MAXPATHLEN];
 766   os::jvm_path(buf, sizeof(buf));
 767   int jvm_offset = -1;
 768   int lib_offset = -1;
 769 #ifdef STATIC_BUILD
 770   char* p = strrchr(buf, '/');
 771   *p = '\0';
 772   strcat(p, "/lib/");
 773   lib_offset = jvm_offset = strlen(buf);
 774 #else
 775   {
 776     // Match "libjvm" instead of "jvm" on *nix platforms. Creates better matches.
 777     // Match "[lib]jvm[^/]*" in jvm_path.
 778     const char* base = buf;
 779     const char* p = strrchr(buf, *os::file_separator());
 780     if (p != NULL) lib_offset = p - base + 1; // this points to the first char after separator
 781 #ifdef _WIN32
 782     p = strstr(p ? p : base, "jvm");
 783     if (p != NULL) jvm_offset = p - base;     // this points to 'j' in jvm.
 784 #else
 785     p = strstr(p ? p : base, "libjvm");
 786     if (p != NULL) jvm_offset = p - base + 3; // this points to 'j' in libjvm.
 787 #endif
 788   }
 789 #endif
 790 
 791   // Find the disassembler shared library.
 792   // Search for several paths derived from libjvm, in this order:
 793   // 1. <home>/jre/lib/<arch>/<vm>/libhsdis-<arch>.so  (for compatibility)
 794   // 2. <home>/jre/lib/<arch>/<vm>/hsdis-<arch>.so
 795   // 3. <home>/jre/lib/<arch>/hsdis-<arch>.so
 796   // 4. hsdis-<arch>.so  (using LD_LIBRARY_PATH)
 797   if (jvm_offset >= 0) {
 798     // 1. <home>/jre/lib/<arch>/<vm>/libhsdis-<arch>.so
 799     strcpy(&buf[jvm_offset], hsdis_library_name);
 800     strcat(&buf[jvm_offset], os::dll_file_extension());
 801     if (Verbose) st->print_cr("Trying to load: %s", buf);
 802     _library = os::dll_load(buf, ebuf, sizeof ebuf);
 803     if (_library == NULL && lib_offset >= 0) {
 804       // 2. <home>/jre/lib/<arch>/<vm>/hsdis-<arch>.so
 805       strcpy(&buf[lib_offset], hsdis_library_name);
 806       strcat(&buf[lib_offset], os::dll_file_extension());
 807       if (Verbose) st->print_cr("Trying to load: %s", buf);
 808       _library = os::dll_load(buf, ebuf, sizeof ebuf);
 809     }
 810     if (_library == NULL && lib_offset > 0) {
 811       // 3. <home>/jre/lib/<arch>/hsdis-<arch>.so
 812       buf[lib_offset - 1] = '\0';
 813       const char* p = strrchr(buf, *os::file_separator());
 814       if (p != NULL) {
 815         lib_offset = p - buf + 1;
 816         strcpy(&buf[lib_offset], hsdis_library_name);
 817         strcat(&buf[lib_offset], os::dll_file_extension());
 818         if (Verbose) st->print_cr("Trying to load: %s", buf);
 819         _library = os::dll_load(buf, ebuf, sizeof ebuf);
 820       }
 821     }
 822   }
 823   if (_library == NULL) {
 824     // 4. hsdis-<arch>.so  (using LD_LIBRARY_PATH)
 825     strcpy(&buf[0], hsdis_library_name);
 826     strcat(&buf[0], os::dll_file_extension());
 827     if (Verbose) st->print_cr("Trying to load: %s via LD_LIBRARY_PATH or equivalent", buf);
 828     _library = os::dll_load(buf, ebuf, sizeof ebuf);
 829   }
 830 
 831   // load the decoder function to use (new or old version).
 832   if (_library != NULL) {
 833     _decode_instructions_virtual = CAST_TO_FN_PTR(Disassembler::decode_func_virtual,
 834                                           os::dll_lookup(_library, decode_instructions_virtual_name));
 835   }
 836   if (_decode_instructions_virtual == NULL && _library != NULL) {
 837     // could not spot in new version, try old version
 838     _decode_instructions = CAST_TO_FN_PTR(Disassembler::decode_func,
 839                                           os::dll_lookup(_library, decode_instructions_name));
 840     use_new_version = false;
 841   } else {
 842     use_new_version = true;
 843   }
 844   _tried_to_load_library = true;
 845   _library_usable        = _decode_instructions_virtual != NULL || _decode_instructions != NULL;
 846 
 847   // Create a dummy environment to initialize PrintAssemblyOptions.
 848   // The PrintAssemblyOptions must be known for abstract disassemblies as well.
 849   decode_env dummy((unsigned char*)(&buf[0]), (unsigned char*)(&buf[1]), st);
 850 
 851   // Report problems during dll_load or dll_lookup, if any.
 852   if (st != NULL) {
 853     // Success.
 854     if (_library_usable) {
 855       st->print_cr("Loaded disassembler from %s", buf);
 856     } else {
 857       st->print_cr("Could not load %s; %s; %s",
 858                    buf,
 859                    ((_library != NULL)
 860                     ? "entry point is missing"
 861                     : ((WizardMode || PrintMiscellaneous)
 862                        ? (const char*)ebuf
 863                        : "library not loadable")),
 864                    "PrintAssembly defaults to abstract disassembly.");
 865     }
 866   }
 867 #endif
 868   return _library_usable;
 869 }
 870 
 871 
 872 // Directly disassemble code buffer.
 873 void Disassembler::decode(CodeBuffer* cb, address start, address end, outputStream* st) {
 874 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 875   //---<  Test memory before decoding  >---
 876   if (!(cb->contains(start) && cb->contains(end))) {
 877     //---<  Allow output suppression, but prevent writing to a NULL stream. Could happen with +PrintStubCode.  >---
 878     if (st != NULL) {
 879       st->print("Memory range [" PTR_FORMAT ".." PTR_FORMAT "] not contained in CodeBuffer", p2i(start), p2i(end));
 880     }
 881     return;
 882   }
 883   if (!os::is_readable_range(start, end)) {
 884     //---<  Allow output suppression, but prevent writing to a NULL stream. Could happen with +PrintStubCode.  >---
 885     if (st != NULL) {
 886       st->print("Memory range [" PTR_FORMAT ".." PTR_FORMAT "] not readable", p2i(start), p2i(end));
 887     }
 888     return;
 889   }
 890 
 891   decode_env env(cb, st);
 892   env.output()->print_cr("--------------------------------------------------------------------------------");
 893   env.output()->print("Decoding CodeBuffer (" PTR_FORMAT ")", p2i(cb));
 894   if (cb->name() != NULL) {
 895     env.output()->print(", name: %s,", cb->name());
 896   }
 897   env.output()->print_cr(" at  [" PTR_FORMAT ", " PTR_FORMAT "]  " JLONG_FORMAT " bytes", p2i(start), p2i(end), ((jlong)(end - start)));
 898 
 899   if (is_abstract()) {
 900     AbstractDisassembler::decode_abstract(start, end, env.output(), Assembler::instr_maxlen());
 901   } else {
 902     env.decode_instructions(start, end);
 903   }
 904   env.output()->print_cr("--------------------------------------------------------------------------------");
 905 #endif
 906 }
 907 
 908 // Directly disassemble code blob.
 909 void Disassembler::decode(CodeBlob* cb, outputStream* st, CodeStrings c) {
 910 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 911   if (cb->is_nmethod()) {
 912     // If we  have an nmethod at hand,
 913     // call the specialized decoder directly.
 914     decode((nmethod*)cb, st, c);
 915     return;
 916   }
 917 
 918   decode_env env(cb, st);
 919   env.output()->print_cr("--------------------------------------------------------------------------------");
 920   if (cb->is_aot()) {
 921     env.output()->print("A ");
 922     if (cb->is_compiled()) {
 923       CompiledMethod* cm = (CompiledMethod*)cb;
 924       env.output()->print("%d ",cm->compile_id());
 925       cm->method()->method_holder()->name()->print_symbol_on(env.output());
 926       env.output()->print(".");
 927       cm->method()->name()->print_symbol_on(env.output());
 928       cm->method()->signature()->print_symbol_on(env.output());
 929     } else {
 930       env.output()->print_cr("%s", cb->name());
 931     }
 932   } else {
 933     env.output()->print("Decoding CodeBlob");
 934     if (cb->name() != NULL) {
 935       env.output()->print(", name: %s,", cb->name());
 936     }
 937   }
 938   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())));
 939 
 940   if (is_abstract()) {
 941     AbstractDisassembler::decode_abstract(cb->code_begin(), cb->code_end(), env.output(), Assembler::instr_maxlen());
 942   } else {
 943     env.decode_instructions(cb->code_begin(), cb->code_end());
 944   }
 945   env.output()->print_cr("--------------------------------------------------------------------------------");
 946 #endif
 947 }
 948 
 949 // Decode a nmethod.
 950 // This includes printing the constant pool and all code segments.
 951 // The nmethod data structures (oop maps, relocations and the like) are not printed.
 952 void Disassembler::decode(nmethod* nm, outputStream* st, CodeStrings c) {
 953 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 954   ttyLocker ttyl;
 955 
 956   decode_env env(nm, st);
 957   env.output()->print_cr("--------------------------------------------------------------------------------");
 958   nm->print_constant_pool(env.output());
 959   env.output()->print_cr("--------------------------------------------------------------------------------");
 960   env.output()->cr();
 961   if (is_abstract()) {
 962     AbstractDisassembler::decode_abstract(nm->code_begin(), nm->code_end(), env.output(), Assembler::instr_maxlen());
 963   } else {
 964     env.decode_instructions(nm->code_begin(), nm->code_end());
 965   }
 966   env.output()->print_cr("--------------------------------------------------------------------------------");
 967 #endif
 968 }
 969 
 970 // Decode a range, given as [start address, end address)
 971 void Disassembler::decode(address start, address end, outputStream* st, CodeStrings c /*, ptrdiff_t offset */) {
 972 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 973   //---<  Test memory before decoding  >---
 974   if (!os::is_readable_range(start, end)) {
 975     //---<  Allow output suppression, but prevent writing to a NULL stream. Could happen with +PrintStubCode.  >---
 976     if (st != NULL) {
 977       st->print("Memory range [" PTR_FORMAT ".." PTR_FORMAT "] not readable", p2i(start), p2i(end));
 978     }
 979     return;
 980   }
 981 
 982   if (is_abstract()) {
 983     AbstractDisassembler::decode_abstract(start, end, st, Assembler::instr_maxlen());
 984     return;
 985   }
 986 
 987 // Don't do that fancy stuff. If we just have two addresses, live with it
 988 // and treat the memory contents as "amorphic" piece of code.
 989 #if 0
 990   CodeBlob* cb = CodeCache::find_blob_unsafe(start);
 991   if (cb != NULL) {
 992     // If we  have an CodeBlob at hand,
 993     // call the specialized decoder directly.
 994     decode(cb, st, c);
 995   } else
 996 #endif
 997   {
 998     // This seems to be just a chunk of memory.
 999     decode_env env(start, end, st);
1000     env.output()->print_cr("--------------------------------------------------------------------------------");
1001     env.decode_instructions(start, end);
1002     env.output()->print_cr("--------------------------------------------------------------------------------");
1003   }
1004 #endif
1005 }
1006 
1007 // To prevent excessive code expansion in the interpreter generator, we
1008 // do not inline this function into Disassembler::hook().
1009 void Disassembler::_hook(const char* file, int line, MacroAssembler* masm) {
1010   decode_env::hook(file, line, masm->code_section()->end());
1011 }