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