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   _output(output ? output : tty),
 320   _codeBuffer(code),
 321   _codeBlob(NULL),
 322   _nm(NULL),
 323   _strings(),
 324   _start(NULL),
 325   _end(NULL),
 326   _option_buf(),
 327   _print_raw(0),
 328   _cur_insn(NULL),
 329   _bytes_per_line(0),
 330   _pre_decode_alignment(0),
 331   _post_decode_alignment(0),
 332   _print_file_name(false),
 333   _print_help(false),
 334   _helpPrinted(false) {
 335 
 336   memset(_option_buf, 0, sizeof(_option_buf));
 337   process_options(_output);
 338 }
 339 
 340 decode_env::decode_env(CodeBlob* code, outputStream* output, CodeStrings c) :
 341   _output(output ? output : tty),
 342   _codeBuffer(NULL),
 343   _codeBlob(code),
 344   _nm(_codeBlob != NULL && _codeBlob->is_nmethod() ? (nmethod*) code : NULL),
 345   _strings(),
 346   _start(NULL),
 347   _end(NULL),
 348   _option_buf(),
 349   _print_raw(0),
 350   _cur_insn(NULL),
 351   _bytes_per_line(0),
 352   _pre_decode_alignment(0),
 353   _post_decode_alignment(0),
 354   _print_file_name(false),
 355   _print_help(false),
 356   _helpPrinted(false) {
 357 
 358   memset(_option_buf, 0, sizeof(_option_buf));
 359   _strings.copy(c);
 360   process_options(_output);
 361 }
 362 
 363 decode_env::decode_env(nmethod* code, outputStream* output, CodeStrings c) :
 364   _output(output ? output : tty),
 365   _codeBuffer(NULL),
 366   _codeBlob(NULL),
 367   _nm(code),
 368   _strings(),
 369   _start(_nm->code_begin()),
 370   _end(_nm->code_end()),
 371   _option_buf(),
 372   _print_raw(0),
 373   _cur_insn(NULL),
 374   _bytes_per_line(0),
 375   _pre_decode_alignment(0),
 376   _post_decode_alignment(0),
 377   _print_file_name(false),
 378   _print_help(false),
 379   _helpPrinted(false) {
 380 
 381   memset(_option_buf, 0, sizeof(_option_buf));
 382   _strings.copy(c);
 383   process_options(_output);
 384 }
 385 
 386 // Constructor for a 'decode_env' to decode a memory range [start, end)
 387 // of unknown origin, assuming it contains code.
 388 decode_env::decode_env(address start, address end, outputStream* output) :
 389   _output(output ? output : tty),
 390   _codeBuffer(NULL),
 391   _codeBlob(NULL),
 392   _nm(NULL),
 393   _strings(),
 394   _start(start),
 395   _end(end),
 396   _option_buf(),
 397   _print_raw(0),
 398   _cur_insn(NULL),
 399   _bytes_per_line(0),
 400   _pre_decode_alignment(0),
 401   _post_decode_alignment(0),
 402   _print_file_name(false),
 403   _print_help(false),
 404   _helpPrinted(false) {
 405 
 406   assert(start < end, "Range must have a positive size, [" PTR_FORMAT ".." PTR_FORMAT ").", p2i(start), p2i(end));
 407   memset(_option_buf, 0, sizeof(_option_buf));
 408   process_options(_output);
 409 }
 410 
 411 void decode_env::process_options(outputStream* ost) {
 412   // by default, output pc but not bytes:
 413   _print_help      = false;
 414   _bytes_per_line  = Disassembler::pd_instruction_alignment();
 415   _print_file_name = true;
 416 
 417   // parse the global option string
 418   if ((options() == NULL) || (strlen(options()) == 0)) {
 419     // We need to fill the options buffer for each newly created
 420     // decode_env instance. The hsdis_* library looks for options
 421     // in that buffer.
 422     collect_options(Disassembler::pd_cpu_opts());
 423     collect_options(PrintAssemblyOptions);
 424   }
 425 
 426   if (_optionsParsed) return;  // parse only once
 427 
 428   if (strstr(options(), "print-raw")) {
 429     _print_raw = (strstr(options(), "xml") ? 2 : 1);
 430   }
 431 
 432   if (strstr(options(), "help")) {
 433     _print_help = true;
 434   }
 435   if (strstr(options(), "align-instr")) {
 436     AbstractDisassembler::toggle_align_instr();
 437   }
 438   if (strstr(options(), "show-pc")) {
 439     AbstractDisassembler::toggle_show_pc();
 440   }
 441   if (strstr(options(), "show-offset")) {
 442     AbstractDisassembler::toggle_show_offset();
 443   }
 444   if (strstr(options(), "show-bytes")) {
 445     AbstractDisassembler::toggle_show_bytes();
 446   }
 447   if (strstr(options(), "show-data-hex")) {
 448     AbstractDisassembler::toggle_show_data_hex();
 449   }
 450   if (strstr(options(), "show-data-int")) {
 451     AbstractDisassembler::toggle_show_data_int();
 452   }
 453   if (strstr(options(), "show-data-float")) {
 454     AbstractDisassembler::toggle_show_data_float();
 455   }
 456   if (strstr(options(), "show-structs")) {
 457     AbstractDisassembler::toggle_show_structs();
 458   }
 459   if (strstr(options(), "show-comment")) {
 460     AbstractDisassembler::toggle_show_comment();
 461   }
 462   if (strstr(options(), "show-block-comment")) {
 463     AbstractDisassembler::toggle_show_block_comment();
 464   }
 465   _optionsParsed = true;
 466 
 467   if (_print_help && ! _helpPrinted) {
 468     _helpPrinted = true;
 469     ost->print_cr("PrintAssemblyOptions help:");
 470     ost->print_cr("  print-raw       test plugin by requesting raw output");
 471     ost->print_cr("  print-raw-xml   test plugin by requesting raw xml");
 472     ost->cr();
 473     ost->print_cr("  show-pc            toggle printing current pc,        currently %s", AbstractDisassembler::show_pc()            ? "ON" : "OFF");
 474     ost->print_cr("  show-offset        toggle printing current offset,    currently %s", AbstractDisassembler::show_offset()        ? "ON" : "OFF");
 475     ost->print_cr("  show-bytes         toggle printing instruction bytes, currently %s", AbstractDisassembler::show_bytes()         ? "ON" : "OFF");
 476     ost->print_cr("  show-data-hex      toggle formatting data as hex,     currently %s", AbstractDisassembler::show_data_hex()      ? "ON" : "OFF");
 477     ost->print_cr("  show-data-int      toggle formatting data as int,     currently %s", AbstractDisassembler::show_data_int()      ? "ON" : "OFF");
 478     ost->print_cr("  show-data-float    toggle formatting data as float,   currently %s", AbstractDisassembler::show_data_float()    ? "ON" : "OFF");
 479     ost->print_cr("  show-structs       toggle compiler data structures,   currently %s", AbstractDisassembler::show_structs()       ? "ON" : "OFF");
 480     ost->print_cr("  show-comment       toggle instruction comments,       currently %s", AbstractDisassembler::show_comment()       ? "ON" : "OFF");
 481     ost->print_cr("  show-block-comment toggle block comments,             currently %s", AbstractDisassembler::show_block_comment() ? "ON" : "OFF");
 482     ost->print_cr("  align-instr        toggle instruction alignment,      currently %s", AbstractDisassembler::align_instr()        ? "ON" : "OFF");
 483     ost->print_cr("combined options: %s", options());
 484   }
 485 }
 486 
 487 // Disassembly Event Handler.
 488 // This method receives events from the disassembler library hsdis
 489 // via event_to_env for each decoding step (installed by
 490 // Disassembler::decode_instructions(), replacing the default
 491 // callback method). This enables dumping additional info
 492 // and custom line formatting.
 493 // In a future extension, calling a custom decode method will be
 494 // supported. We can use such a method to decode instructions the
 495 // binutils decoder does not handle to our liking (suboptimal
 496 // formatting, incomplete information, ...).
 497 // Returns:
 498 // - NULL for all standard invocations. The function result is not
 499 //        examined (as of now, 20190409) by the hsdis decoder loop.
 500 // - next for 'insn0' invocations.
 501 //        next == arg: the custom decoder didn't do anything.
 502 //        next >  arg: the custom decoder did decode the instruction.
 503 //                     next points to the next undecoded instruction
 504 //                     (continuation point for decoder loop).
 505 //
 506 // "Normal" sequence of events:
 507 //  insns   - start of instruction stream decoding
 508 //  mach    - display architecture
 509 //  format  - display bytes-per-line
 510 //  for each instruction:
 511 //    insn    - start of instruction decoding
 512 //    insn0   - custom decoder invocation (if any)
 513 //    addr    - print address value
 514 //    /insn   - end of instruction decoding
 515 //  /insns  - premature end of instruction stream due to no progress
 516 //
 517 address decode_env::handle_event(const char* event, address arg) {
 518 
 519 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 520 
 521   //---<  Event: end decoding loop (error, no progress)  >---
 522   if (decode_env::match(event, "/insns")) {
 523     // Nothing to be done here.
 524     return NULL;
 525   }
 526 
 527   //---<  Event: start decoding loop  >---
 528   if (decode_env::match(event, "insns")) {
 529     // Nothing to be done here.
 530     return NULL;
 531   }
 532 
 533   //---<  Event: finish decoding an instruction  >---
 534   if (decode_env::match(event, "/insn")) {
 535     output()->fill_to(_post_decode_alignment);
 536     end_insn(arg);
 537     return NULL;
 538   }
 539 
 540   //---<  Event: start decoding an instruction  >---
 541   if (decode_env::match(event, "insn")) {
 542     start_insn(arg);
 543   } else if (match(event, "/insn")) {
 544     end_insn(arg);
 545   } else if (match(event, "addr")) {
 546     if (arg != NULL) {
 547       print_address(arg);
 548       return arg;
 549     }
 550     calculate_alignment();
 551     output()->fill_to(_pre_decode_alignment);
 552     return NULL;
 553   }
 554 
 555   //---<  Event: call custom decoder (platform specific)  >---
 556   if (decode_env::match(event, "insn0")) {
 557     return Disassembler::decode_instruction0(arg, output(), arg);
 558   }
 559 
 560   //---<  Event: Print address  >---
 561   if (decode_env::match(event, "addr")) {
 562     print_address(arg);
 563     return arg;
 564   }
 565 
 566   //---<  Event: mach (inform about machine architecture)  >---
 567   // This event is problematic because it messes up the output.
 568   // The event is fired after the instruction address has already
 569   // been printed. The decoded instruction (event "insn") is
 570   // printed afterwards. That doesn't look nice.
 571   if (decode_env::match(event, "mach")) {
 572     guarantee(arg != NULL, "event_to_env - arg must not be NULL for event 'mach'");
 573     static char buffer[64] = { 0, };
 574     // Output suppressed because it messes up disassembly.
 575     // Only print this when the mach changes.
 576     if (false && (strcmp(buffer, (const char*)arg) != 0 ||
 577                   strlen((const char*)arg) > sizeof(buffer) - 1)) {
 578       // Only print this when the mach changes
 579       strncpy(buffer, (const char*)arg, sizeof(buffer) - 1);
 580       buffer[sizeof(buffer) - 1] = '\0';
 581       output()->print_cr("[Disassembling for mach='%s']", (const char*)arg);
 582     }
 583     return NULL;
 584   }
 585 
 586   //---<  Event: format bytes-per-line  >---
 587   if (decode_env::match(event, "format bytes-per-line")) {
 588     _bytes_per_line = (int) (intptr_t) arg;
 589     return NULL;
 590   }
 591 #endif
 592   return NULL;
 593 }
 594 
 595 static void* event_to_env(void* env_pv, const char* event, void* arg) {
 596   decode_env* env = (decode_env*) env_pv;
 597   return env->handle_event(event, (address) arg);
 598 }
 599 
 600 // called by the disassembler to print out jump targets and data addresses
 601 void decode_env::print_address(address adr) {
 602   outputStream* st = output();
 603 
 604   if (adr == NULL) {
 605     st->print("NULL");
 606     return;
 607   }
 608 
 609   int small_num = (int)(intptr_t)adr;
 610   if ((intptr_t)adr == (intptr_t)small_num
 611       && -1 <= small_num && small_num <= 9) {
 612     st->print("%d", small_num);
 613     return;
 614   }
 615 
 616   if (Universe::is_fully_initialized()) {
 617     if (StubRoutines::contains(adr)) {
 618       StubCodeDesc* desc = StubCodeDesc::desc_for(adr);
 619       if (desc == NULL) {
 620         desc = StubCodeDesc::desc_for(adr + frame::pc_return_offset);
 621       }
 622       if (desc != NULL) {
 623         st->print("Stub::%s", desc->name());
 624         if (desc->begin() != adr) {
 625           st->print(INTX_FORMAT_W(+) " " PTR_FORMAT, adr - desc->begin(), p2i(adr));
 626         } else if (WizardMode) {
 627           st->print(" " PTR_FORMAT, p2i(adr));
 628         }
 629         return;
 630       }
 631       st->print("Stub::<unknown> " PTR_FORMAT, p2i(adr));
 632       return;
 633     }
 634 
 635     BarrierSet* bs = BarrierSet::barrier_set();
 636     if (bs->is_a(BarrierSet::CardTableBarrierSet) &&
 637         adr == ci_card_table_address_as<address>()) {
 638       st->print("word_map_base");
 639       if (WizardMode) st->print(" " INTPTR_FORMAT, p2i(adr));
 640       return;
 641     }
 642   }
 643 
 644   if (_nm == NULL) {
 645     // Don't do this for native methods, as the function name will be printed in
 646     // nmethod::reloc_string_for().
 647     // Allocate the buffer on the stack instead of as RESOURCE array.
 648     // In case we do DecodeErrorFile, Thread will not be initialized,
 649     // causing a "assert(current != __null) failed" failure.
 650     const int buflen = 1024;
 651     char buf[buflen];
 652     int offset;
 653     if (os::dll_address_to_function_name(adr, buf, buflen, &offset)) {
 654       st->print(PTR_FORMAT " = %s",  p2i(adr), buf);
 655       if (offset != 0) {
 656         st->print("+%d", offset);
 657       }
 658       return;
 659     }
 660   }
 661 
 662   // Fall through to a simple (hexadecimal) numeral.
 663   st->print(PTR_FORMAT, p2i(adr));
 664 }
 665 
 666 void decode_env::print_insn_labels() {
 667   if (AbstractDisassembler::show_block_comment()) {
 668     address       p  = cur_insn();
 669     outputStream* st = output();
 670 
 671     //---<  Block comments for nmethod  >---
 672     // Outputs a bol() before and a cr() after, but only if a comment is printed.
 673     // Prints nmethod_section_label as well.
 674     if (_nm != NULL) {
 675       _nm->print_block_comment(st, p);
 676     }
 677     if (_codeBlob != NULL) {
 678       _codeBlob->print_block_comment(st, p);
 679     }
 680     if (_codeBuffer != NULL) {
 681       _codeBuffer->print_block_comment(st, p);
 682     }
 683     _strings.print_block_comment(st, (intptr_t)(p - _start));
 684   }
 685 }
 686 
 687 void decode_env::print_insn_prefix() {
 688   address       p  = cur_insn();
 689   outputStream* st = output();
 690   AbstractDisassembler::print_location(p, _start, _end, st, false, false);
 691   AbstractDisassembler::print_instruction(p, Assembler::instr_len(p), Assembler::instr_maxlen(), st, true, false);
 692 }
 693 
 694 ATTRIBUTE_PRINTF(2, 3)
 695 static int printf_to_env(void* env_pv, const char* format, ...) {
 696   decode_env* env = (decode_env*) env_pv;
 697   outputStream* st = env->output();
 698   size_t flen = strlen(format);
 699   const char* raw = NULL;
 700   if (flen == 0)  return 0;
 701   if (flen == 1 && format[0] == '\n') { st->bol(); return 1; }
 702   if (flen < 2 ||
 703       strchr(format, '%') == NULL) {
 704     raw = format;
 705   } else if (format[0] == '%' && format[1] == '%' &&
 706              strchr(format+2, '%') == NULL) {
 707     // happens a lot on machines with names like %foo
 708     flen--;
 709     raw = format+1;
 710   }
 711   if (raw != NULL) {
 712     st->print_raw(raw, (int) flen);
 713     return (int) flen;
 714   }
 715   va_list ap;
 716   va_start(ap, format);
 717   julong cnt0 = st->count();
 718   st->vprint(format, ap);
 719   julong cnt1 = st->count();
 720   va_end(ap);
 721   return (int)(cnt1 - cnt0);
 722 }
 723 
 724 // The 'original_start' argument holds the the original address where
 725 // the instructions were located in the originating system. If zero (NULL)
 726 // is passed in, there is no original address.
 727 address decode_env::decode_instructions(address start, address end, address original_start /* = 0*/) {
 728   // CodeComment in Stubs.
 729   // Properly initialize _start/_end. Overwritten too often if
 730   // printing of instructions is called for each instruction.
 731   assert((_start == NULL) || (start == NULL) || (_start == start), "don't overwrite CTOR values");
 732   assert((_end   == NULL) || (end   == NULL) || (_end   == end  ), "don't overwrite CTOR values");
 733   if (start != NULL) set_start(start);
 734   if (end   != NULL) set_end(end);
 735   if (original_start == NULL) {
 736     original_start = start;
 737   }
 738 
 739   //---<  Check (and correct) alignment  >---
 740   // Don't check alignment of end, it is not aligned.
 741   if (((uint64_t)start & ((uint64_t)Disassembler::pd_instruction_alignment() - 1)) != 0) {
 742     output()->print_cr("Decode range start:" PTR_FORMAT ": ... (unaligned)", p2i(start));
 743     start = (address)((uint64_t)start & ~((uint64_t)Disassembler::pd_instruction_alignment() - 1));
 744   }
 745 
 746   // Trying to decode instructions doesn't make sense if we
 747   // couldn't load the disassembler library.
 748   if (Disassembler::is_abstract()) {
 749     return NULL;
 750   }
 751 
 752   // decode a series of instructions and return the end of the last instruction
 753 
 754   if (_print_raw) {
 755     // Print whatever the library wants to print, w/o fancy callbacks.
 756     // This is mainly for debugging the library itself.
 757     FILE* out = stdout;
 758     FILE* xmlout = (_print_raw > 1 ? out : NULL);
 759     return use_new_version ?
 760       (address)
 761       (*Disassembler::_decode_instructions_virtual)((uintptr_t)start, (uintptr_t)end,
 762                                                     start, end - start,
 763                                                     NULL, (void*) xmlout,
 764                                                     NULL, (void*) out,
 765                                                     options(), 0/*nice new line*/)
 766       :
 767       (address)
 768       (*Disassembler::_decode_instructions)(start, end,
 769                                             NULL, (void*) xmlout,
 770                                             NULL, (void*) out,
 771                                             options());
 772   }
 773 
 774   return use_new_version ?
 775     (address)
 776     (*Disassembler::_decode_instructions_virtual)((uintptr_t)start, (uintptr_t)end,
 777                                                   start, end - start,
 778                                                   &event_to_env,  (void*) this,
 779                                                   &printf_to_env, (void*) this,
 780                                                   options(), 0/*nice new line*/)
 781     :
 782     (address)
 783     (*Disassembler::_decode_instructions)(start, end,
 784                                           &event_to_env,  (void*) this,
 785                                           &printf_to_env, (void*) this,
 786                                           options());
 787 }
 788 
 789 // ----------------------------------------------------------------------------
 790 // Disassembler
 791 // Used as a static wrapper for decode_env.
 792 // Each method will create a decode_env before decoding.
 793 // You can call the decode_env methods directly if you already have one.
 794 
 795 
 796 bool Disassembler::load_library(outputStream* st) {
 797   // Do not try to load multiple times. Failed once -> fails always.
 798   // To force retry in debugger: assign _tried_to_load_library=0
 799   if (_tried_to_load_library) {
 800     return _library_usable;
 801   }
 802 
 803 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 804   // Print to given stream, if any.
 805   // Print to tty if Verbose is on and no stream given.
 806   st = ((st == NULL) && Verbose) ? tty : st;
 807 
 808   // Compute fully qualified library name.
 809   char ebuf[1024];
 810   char buf[JVM_MAXPATHLEN];
 811   os::jvm_path(buf, sizeof(buf));
 812   int jvm_offset = -1;
 813   int lib_offset = -1;
 814 #ifdef STATIC_BUILD
 815   char* p = strrchr(buf, '/');
 816   *p = '\0';
 817   strcat(p, "/lib/");
 818   lib_offset = jvm_offset = strlen(buf);
 819 #else
 820   {
 821     // Match "libjvm" instead of "jvm" on *nix platforms. Creates better matches.
 822     // Match "[lib]jvm[^/]*" in jvm_path.
 823     const char* base = buf;
 824     const char* p = strrchr(buf, *os::file_separator());
 825     if (p != NULL) lib_offset = p - base + 1; // this points to the first char after separator
 826 #ifdef _WIN32
 827     p = strstr(p ? p : base, "jvm");
 828     if (p != NULL) jvm_offset = p - base;     // this points to 'j' in jvm.
 829 #else
 830     p = strstr(p ? p : base, "libjvm");
 831     if (p != NULL) jvm_offset = p - base + 3; // this points to 'j' in libjvm.
 832 #endif
 833   }
 834 #endif
 835 
 836   // Find the disassembler shared library.
 837   // Search for several paths derived from libjvm, in this order:
 838   // 1. <home>/jre/lib/<arch>/<vm>/libhsdis-<arch>.so  (for compatibility)
 839   // 2. <home>/jre/lib/<arch>/<vm>/hsdis-<arch>.so
 840   // 3. <home>/jre/lib/<arch>/hsdis-<arch>.so
 841   // 4. hsdis-<arch>.so  (using LD_LIBRARY_PATH)
 842   if (jvm_offset >= 0) {
 843     // 1. <home>/jre/lib/<arch>/<vm>/libhsdis-<arch>.so
 844     strcpy(&buf[jvm_offset], hsdis_library_name);
 845     strcat(&buf[jvm_offset], os::dll_file_extension());
 846     if (Verbose) st->print_cr("Trying to load: %s", buf);
 847     _library = os::dll_load(buf, ebuf, sizeof ebuf);
 848     if (_library == NULL && lib_offset >= 0) {
 849       // 2. <home>/jre/lib/<arch>/<vm>/hsdis-<arch>.so
 850       strcpy(&buf[lib_offset], hsdis_library_name);
 851       strcat(&buf[lib_offset], os::dll_file_extension());
 852       if (Verbose) st->print_cr("Trying to load: %s", buf);
 853       _library = os::dll_load(buf, ebuf, sizeof ebuf);
 854     }
 855     if (_library == NULL && lib_offset > 0) {
 856       // 3. <home>/jre/lib/<arch>/hsdis-<arch>.so
 857       buf[lib_offset - 1] = '\0';
 858       const char* p = strrchr(buf, *os::file_separator());
 859       if (p != NULL) {
 860         lib_offset = p - buf + 1;
 861         strcpy(&buf[lib_offset], hsdis_library_name);
 862         strcat(&buf[lib_offset], os::dll_file_extension());
 863         if (Verbose) st->print_cr("Trying to load: %s", buf);
 864         _library = os::dll_load(buf, ebuf, sizeof ebuf);
 865       }
 866     }
 867   }
 868   if (_library == NULL) {
 869     // 4. hsdis-<arch>.so  (using LD_LIBRARY_PATH)
 870     strcpy(&buf[0], hsdis_library_name);
 871     strcat(&buf[0], os::dll_file_extension());
 872     if (Verbose) st->print_cr("Trying to load: %s via LD_LIBRARY_PATH or equivalent", buf);
 873     _library = os::dll_load(buf, ebuf, sizeof ebuf);
 874   }
 875 
 876   // load the decoder function to use (new or old version).
 877   if (_library != NULL) {
 878     _decode_instructions_virtual = CAST_TO_FN_PTR(Disassembler::decode_func_virtual,
 879                                           os::dll_lookup(_library, decode_instructions_virtual_name));
 880   }
 881   if (_decode_instructions_virtual == NULL && _library != NULL) {
 882     // could not spot in new version, try old version
 883     _decode_instructions = CAST_TO_FN_PTR(Disassembler::decode_func,
 884                                           os::dll_lookup(_library, decode_instructions_name));
 885     use_new_version = false;
 886   } else {
 887     use_new_version = true;
 888   }
 889   _tried_to_load_library = true;
 890   _library_usable        = _decode_instructions_virtual != NULL || _decode_instructions != NULL;
 891 
 892   // Create a dummy environment to initialize PrintAssemblyOptions.
 893   // The PrintAssemblyOptions must be known for abstract disassemblies as well.
 894   decode_env dummy((unsigned char*)(&buf[0]), (unsigned char*)(&buf[1]), st);
 895 
 896   // Report problems during dll_load or dll_lookup, if any.
 897   if (st != NULL) {
 898     // Success.
 899     if (_library_usable) {
 900       st->print_cr("Loaded disassembler from %s", buf);
 901     } else {
 902       st->print_cr("Could not load %s; %s; %s",
 903                    buf,
 904                    ((_library != NULL)
 905                     ? "entry point is missing"
 906                     : ((WizardMode || PrintMiscellaneous)
 907                        ? (const char*)ebuf
 908                        : "library not loadable")),
 909                    "PrintAssembly defaults to abstract disassembly.");
 910     }
 911   }
 912 #endif
 913   return _library_usable;
 914 }
 915 
 916 
 917 // Directly disassemble code buffer.
 918 void Disassembler::decode(CodeBuffer* cb, address start, address end, outputStream* st) {
 919 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 920   //---<  Test memory before decoding  >---
 921   if (!(cb->contains(start) && cb->contains(end))) {
 922     //---<  Allow output suppression, but prevent writing to a NULL stream. Could happen with +PrintStubCode.  >---
 923     if (st != NULL) {
 924       st->print("Memory range [" PTR_FORMAT ".." PTR_FORMAT "] not contained in CodeBuffer", p2i(start), p2i(end));
 925     }
 926     return;
 927   }
 928   if (!os::is_readable_range(start, end)) {
 929     //---<  Allow output suppression, but prevent writing to a NULL stream. Could happen with +PrintStubCode.  >---
 930     if (st != NULL) {
 931       st->print("Memory range [" PTR_FORMAT ".." PTR_FORMAT "] not readable", p2i(start), p2i(end));
 932     }
 933     return;
 934   }
 935 
 936   decode_env env(cb, st);
 937   env.output()->print_cr("--------------------------------------------------------------------------------");
 938   env.output()->print("Decoding CodeBuffer (" PTR_FORMAT ")", p2i(cb));
 939   if (cb->name() != NULL) {
 940     env.output()->print(", name: %s,", cb->name());
 941   }
 942   env.output()->print_cr(" at  [" PTR_FORMAT ", " PTR_FORMAT "]  " JLONG_FORMAT " bytes", p2i(start), p2i(end), ((jlong)(end - start)));
 943 
 944   if (is_abstract()) {
 945     AbstractDisassembler::decode_abstract(start, end, env.output(), Assembler::instr_maxlen());
 946   } else {
 947     env.decode_instructions(start, end);
 948   }
 949   env.output()->print_cr("--------------------------------------------------------------------------------");
 950 #endif
 951 }
 952 
 953 // Directly disassemble code blob.
 954 void Disassembler::decode(CodeBlob* cb, outputStream* st, CodeStrings c) {
 955 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 956   if (cb->is_nmethod()) {
 957     // If we  have an nmethod at hand,
 958     // call the specialized decoder directly.
 959     decode((nmethod*)cb, st, c);
 960     return;
 961   }
 962 
 963   decode_env env(cb, st);
 964   env.output()->print_cr("--------------------------------------------------------------------------------");
 965   if (cb->is_aot()) {
 966     env.output()->print("A ");
 967     if (cb->is_compiled()) {
 968       CompiledMethod* cm = (CompiledMethod*)cb;
 969       env.output()->print("%d ",cm->compile_id());
 970       cm->method()->method_holder()->name()->print_symbol_on(env.output());
 971       env.output()->print(".");
 972       cm->method()->name()->print_symbol_on(env.output());
 973       cm->method()->signature()->print_symbol_on(env.output());
 974     } else {
 975       env.output()->print_cr("%s", cb->name());
 976     }
 977   } else {
 978     env.output()->print("Decoding CodeBlob");
 979     if (cb->name() != NULL) {
 980       env.output()->print(", name: %s,", cb->name());
 981     }
 982   }
 983   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())));
 984 
 985   if (is_abstract()) {
 986     AbstractDisassembler::decode_abstract(cb->code_begin(), cb->code_end(), env.output(), Assembler::instr_maxlen());
 987   } else {
 988     env.decode_instructions(cb->code_begin(), cb->code_end());
 989   }
 990   env.output()->print_cr("--------------------------------------------------------------------------------");
 991 #endif
 992 }
 993 
 994 // Decode a nmethod.
 995 // This includes printing the constant pool and all code segments.
 996 // The nmethod data structures (oop maps, relocations and the like) are not printed.
 997 void Disassembler::decode(nmethod* nm, outputStream* st, CodeStrings c) {
 998 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 999   ttyLocker ttyl;
1000 
1001   decode_env env(nm, st);
1002   env.output()->print_cr("--------------------------------------------------------------------------------");
1003   nm->print_constant_pool(env.output());
1004   env.output()->print_cr("--------------------------------------------------------------------------------");
1005   env.output()->cr();
1006   if (is_abstract()) {
1007     AbstractDisassembler::decode_abstract(nm->code_begin(), nm->code_end(), env.output(), Assembler::instr_maxlen());
1008   } else {
1009     env.decode_instructions(nm->code_begin(), nm->code_end());
1010   }
1011   env.output()->print_cr("--------------------------------------------------------------------------------");
1012 #endif
1013 }
1014 
1015 // Decode a range, given as [start address, end address)
1016 void Disassembler::decode(address start, address end, outputStream* st, CodeStrings c /*, ptrdiff_t offset */) {
1017 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
1018   //---<  Test memory before decoding  >---
1019   if (!os::is_readable_range(start, end)) {
1020     //---<  Allow output suppression, but prevent writing to a NULL stream. Could happen with +PrintStubCode.  >---
1021     if (st != NULL) {
1022       st->print("Memory range [" PTR_FORMAT ".." PTR_FORMAT "] not readable", p2i(start), p2i(end));
1023     }
1024     return;
1025   }
1026 
1027   if (is_abstract()) {
1028     AbstractDisassembler::decode_abstract(start, end, st, Assembler::instr_maxlen());
1029     return;
1030   }
1031 
1032 // Don't do that fancy stuff. If we just have two addresses, live with it
1033 // and treat the memory contents as "amorphic" piece of code.
1034 #if 0
1035   CodeBlob* cb = CodeCache::find_blob_unsafe(start);
1036   if (cb != NULL) {
1037     // If we  have an CodeBlob at hand,
1038     // call the specialized decoder directly.
1039     decode(cb, st, c);
1040   } else
1041 #endif
1042   {
1043     // This seems to be just a chunk of memory.
1044     decode_env env(start, end, st);
1045     env.output()->print_cr("--------------------------------------------------------------------------------");
1046     env.decode_instructions(start, end);
1047     env.output()->print_cr("--------------------------------------------------------------------------------");
1048   }
1049 #endif
1050 }
1051 
1052 // To prevent excessive code expansion in the interpreter generator, we
1053 // do not inline this function into Disassembler::hook().
1054 void Disassembler::_hook(const char* file, int line, MacroAssembler* masm) {
1055   decode_env::hook(file, line, masm->code_section()->end());
1056 }