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