Path: blob/master/src/hotspot/share/compiler/disassembler.cpp
40930 views
/*1* Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "asm/assembler.inline.hpp"26#include "asm/macroAssembler.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 "memory/universe.hpp"36#include "oops/oop.inline.hpp"37#include "runtime/handles.inline.hpp"38#include "runtime/os.hpp"39#include "runtime/stubCodeGenerator.hpp"40#include "runtime/stubRoutines.hpp"41#include "utilities/resourceHash.hpp"4243void* Disassembler::_library = NULL;44bool Disassembler::_tried_to_load_library = false;45bool Disassembler::_library_usable = false;4647// This routine is in the shared library:48Disassembler::decode_func_virtual Disassembler::_decode_instructions_virtual = NULL;4950static const char hsdis_library_name[] = "hsdis-" HOTSPOT_LIB_ARCH;51static const char decode_instructions_virtual_name[] = "decode_instructions_virtual";52#define COMMENT_COLUMN 52 LP64_ONLY(+8) /*could be an option*/53#define BYTES_COMMENT ";..." /* funky byte display comment */5455class decode_env {56private:57outputStream* _output; // where the disassembly is directed to58CodeBlob* _codeBlob; // != NULL only when decoding a CodeBlob59nmethod* _nm; // != NULL only when decoding a nmethod6061address _start; // != NULL when decoding a range of unknown type62address _end; // != NULL when decoding a range of unknown type6364char _option_buf[512];65char _print_raw;66address _cur_insn; // address of instruction currently being decoded67int _bytes_per_line; // arch-specific formatting option68int _pre_decode_alignment;69int _post_decode_alignment;70bool _print_file_name;71bool _print_help;72bool _helpPrinted;73static bool _optionsParsed;74NOT_PRODUCT(const CodeStrings* _strings;)7576enum {77tabspacing = 878};7980// Check if the event matches the expected tag81// The tag must be a substring of the event, and82// the tag must be a token in the event, i.e. separated by delimiters83static bool match(const char* event, const char* tag) {84size_t eventlen = strlen(event);85size_t taglen = strlen(tag);86if (eventlen < taglen) // size mismatch87return false;88if (strncmp(event, tag, taglen) != 0) // string mismatch89return false;90char delim = event[taglen];91return delim == '\0' || delim == ' ' || delim == '/' || delim == '=';92}9394// Merge new option string with previously recorded options95void collect_options(const char* p) {96if (p == NULL || p[0] == '\0') return;97size_t opt_so_far = strlen(_option_buf);98if (opt_so_far + 1 + strlen(p) + 1 > sizeof(_option_buf)) return;99char* fillp = &_option_buf[opt_so_far];100if (opt_so_far > 0) *fillp++ = ',';101strcat(fillp, p);102// replace white space by commas:103char* q = fillp;104while ((q = strpbrk(q, " \t\n")) != NULL)105*q++ = ',';106}107108void process_options(outputStream* ost);109110void print_insn_labels();111void print_insn_prefix();112void print_address(address value);113114// Properly initializes _start/_end. Overwritten too often if115// printing of instructions is called for each instruction.116void set_start(address s) { _start = s; }117void set_end (address e) { _end = e; }118void set_nm (nmethod* nm) { _nm = nm; }119void set_output(outputStream* st) { _output = st; }120121#if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)122// The disassembler library (sometimes) uses tabs to nicely align the instruction operands.123// Depending on the mnemonic length and the column position where the124// mnemonic is printed, alignment may turn out to be not so nice.125// To improve, we assume 8-character tab spacing and left-align the mnemonic on a tab position.126// Instruction comments are aligned 4 tab positions to the right of the mnemonic.127void calculate_alignment() {128_pre_decode_alignment = ((output()->position()+tabspacing-1)/tabspacing)*tabspacing;129_post_decode_alignment = _pre_decode_alignment + 4*tabspacing;130}131132void start_insn(address pc) {133_cur_insn = pc;134output()->bol();135print_insn_labels();136print_insn_prefix();137}138139void end_insn(address pc) {140address pc0 = cur_insn();141outputStream* st = output();142143if (AbstractDisassembler::show_comment()) {144if ((_nm != NULL) && _nm->has_code_comment(pc0, pc)) {145_nm->print_code_comment_on146(st,147_post_decode_alignment ? _post_decode_alignment : COMMENT_COLUMN,148pc0, pc);149// this calls reloc_string_for which calls oop::print_value_on150}151print_hook_comments(pc0, _nm != NULL);152}153Disassembler::annotate(pc0, output());154// follow each complete insn by a nice newline155st->bol();156}157#endif158159struct SourceFileInfo {160struct Link : public CHeapObj<mtCode> {161const char* file;162int line;163Link* next;164Link(const char* f, int l) : file(f), line(l), next(NULL) {}165};166Link *head, *tail;167168static unsigned hash(const address& a) {169return primitive_hash<address>(a);170}171static bool equals(const address& a0, const address& a1) {172return primitive_equals<address>(a0, a1);173}174void append(const char* file, int line) {175if (tail != NULL && tail->file == file && tail->line == line) {176// Don't print duplicated lines at the same address. This could happen with C177// macros that end up having multiple "__" tokens on the same __LINE__.178return;179}180Link *link = new Link(file, line);181if (head == NULL) {182head = tail = link;183} else {184tail->next = link;185tail = link;186}187}188SourceFileInfo(const char* file, int line) : head(NULL), tail(NULL) {189append(file, line);190}191};192193typedef ResourceHashtable<194address, SourceFileInfo,195SourceFileInfo::hash,196SourceFileInfo::equals,19715889, // prime number198ResourceObj::C_HEAP> SourceFileInfoTable;199200static SourceFileInfoTable* _src_table;201static const char* _cached_src;202static GrowableArray<const char*>* _cached_src_lines;203204static SourceFileInfoTable& src_table() {205if (_src_table == NULL) {206_src_table = new (ResourceObj::C_HEAP, mtCode)SourceFileInfoTable();207}208return *_src_table;209}210211public:212decode_env(CodeBlob* code, outputStream* output);213decode_env(nmethod* code, outputStream* output);214// Constructor for a 'decode_env' to decode an arbitrary215// piece of memory, hopefully containing code.216decode_env(address start, address end, outputStream* output, const CodeStrings* strings = NULL);217218// Add 'original_start' argument which is the the original address219// the instructions were located at (if this is not equal to 'start').220address decode_instructions(address start, address end, address original_start = NULL);221222address handle_event(const char* event, address arg);223224outputStream* output() { return _output; }225address cur_insn() { return _cur_insn; }226const char* options() { return _option_buf; }227static void hook(const char* file, int line, address pc);228void print_hook_comments(address pc, bool newline);229};230231bool decode_env::_optionsParsed = false;232233decode_env::SourceFileInfoTable* decode_env::_src_table = NULL;234const char* decode_env::_cached_src = NULL;235GrowableArray<const char*>* decode_env::_cached_src_lines = NULL;236237void decode_env::hook(const char* file, int line, address pc) {238// For simplication, we never free from this table. It's really not239// necessary as we add to the table only when PrintInterpreter is true,240// which means we are debugging the VM and a little bit of extra241// memory usage doesn't matter.242SourceFileInfo* found = src_table().get(pc);243if (found != NULL) {244found->append(file, line);245} else {246SourceFileInfo sfi(file, line);247src_table().put(pc, sfi); // sfi is copied by value248}249}250251void decode_env::print_hook_comments(address pc, bool newline) {252SourceFileInfo* found = src_table().get(pc);253outputStream* st = output();254if (found != NULL) {255for (SourceFileInfo::Link *link = found->head; link; link = link->next) {256const char* file = link->file;257int line = link->line;258if (_cached_src == NULL || strcmp(_cached_src, file) != 0) {259FILE* fp;260261// _cached_src_lines is a single cache of the lines of a source file, and we refill this cache262// every time we need to print a line from a different source file. It's not the fastest,263// but seems bearable.264if (_cached_src_lines != NULL) {265for (int i=0; i<_cached_src_lines->length(); i++) {266os::free((void*)_cached_src_lines->at(i));267}268_cached_src_lines->clear();269} else {270_cached_src_lines = new (ResourceObj::C_HEAP, mtCode)GrowableArray<const char*>(0, mtCode);271}272273if ((fp = fopen(file, "r")) == NULL) {274_cached_src = NULL;275return;276}277_cached_src = file;278279char line[500]; // don't write lines that are too long in your source files!280while (fgets(line, sizeof(line), fp) != NULL) {281size_t len = strlen(line);282if (len > 0 && line[len-1] == '\n') {283line[len-1] = '\0';284}285_cached_src_lines->append(os::strdup(line));286}287fclose(fp);288_print_file_name = true;289}290291if (_print_file_name) {292// We print the file name whenever we switch to a new file, or when293// Disassembler::decode is called to disassemble a new block of code.294_print_file_name = false;295if (newline) {296st->cr();297}298st->move_to(COMMENT_COLUMN);299st->print(";;@FILE: %s", file);300newline = true;301}302303int index = line - 1; // 1-based line number -> 0-based index.304if (index >= _cached_src_lines->length()) {305// This could happen if source file is mismatched.306} else {307const char* source_line = _cached_src_lines->at(index);308if (newline) {309st->cr();310}311st->move_to(COMMENT_COLUMN);312st->print(";;%5d: %s", line, source_line);313newline = true;314}315}316}317}318319decode_env::decode_env(CodeBlob* code, outputStream* output) :320_output(output ? output : tty),321_codeBlob(code),322_nm(_codeBlob != NULL && _codeBlob->is_nmethod() ? (nmethod*) code : NULL),323_start(NULL),324_end(NULL),325_option_buf(),326_print_raw(0),327_cur_insn(NULL),328_bytes_per_line(0),329_pre_decode_alignment(0),330_post_decode_alignment(0),331_print_file_name(false),332_print_help(false),333_helpPrinted(false)334NOT_PRODUCT(COMMA _strings(NULL)) {335336memset(_option_buf, 0, sizeof(_option_buf));337process_options(_output);338339}340341decode_env::decode_env(nmethod* code, outputStream* output) :342_output(output ? output : tty),343_codeBlob(NULL),344_nm(code),345_start(_nm->code_begin()),346_end(_nm->code_end()),347_option_buf(),348_print_raw(0),349_cur_insn(NULL),350_bytes_per_line(0),351_pre_decode_alignment(0),352_post_decode_alignment(0),353_print_file_name(false),354_print_help(false),355_helpPrinted(false)356NOT_PRODUCT(COMMA _strings(NULL)) {357358memset(_option_buf, 0, sizeof(_option_buf));359process_options(_output);360}361362// Constructor for a 'decode_env' to decode a memory range [start, end)363// of unknown origin, assuming it contains code.364decode_env::decode_env(address start, address end, outputStream* output, const CodeStrings* c) :365_output(output ? output : tty),366_codeBlob(NULL),367_nm(NULL),368_start(start),369_end(end),370_option_buf(),371_print_raw(0),372_cur_insn(NULL),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)379NOT_PRODUCT(COMMA _strings(c)) {380381assert(start < end, "Range must have a positive size, [" PTR_FORMAT ".." PTR_FORMAT ").", p2i(start), p2i(end));382memset(_option_buf, 0, sizeof(_option_buf));383process_options(_output);384}385386void decode_env::process_options(outputStream* ost) {387// by default, output pc but not bytes:388_print_help = false;389_bytes_per_line = Disassembler::pd_instruction_alignment();390_print_file_name = true;391392// parse the global option string393// We need to fill the options buffer for each newly created394// decode_env instance. The hsdis_* library looks for options395// in that buffer.396collect_options(Disassembler::pd_cpu_opts());397collect_options(PrintAssemblyOptions);398399if (strstr(options(), "print-raw")) {400_print_raw = (strstr(options(), "xml") ? 2 : 1);401}402403if (_optionsParsed) return; // parse only once404405if (strstr(options(), "help")) {406_print_help = true;407}408if (strstr(options(), "align-instr")) {409AbstractDisassembler::toggle_align_instr();410}411if (strstr(options(), "show-pc")) {412AbstractDisassembler::toggle_show_pc();413}414if (strstr(options(), "show-offset")) {415AbstractDisassembler::toggle_show_offset();416}417if (strstr(options(), "show-bytes")) {418AbstractDisassembler::toggle_show_bytes();419}420if (strstr(options(), "show-data-hex")) {421AbstractDisassembler::toggle_show_data_hex();422}423if (strstr(options(), "show-data-int")) {424AbstractDisassembler::toggle_show_data_int();425}426if (strstr(options(), "show-data-float")) {427AbstractDisassembler::toggle_show_data_float();428}429if (strstr(options(), "show-structs")) {430AbstractDisassembler::toggle_show_structs();431}432if (strstr(options(), "show-comment")) {433AbstractDisassembler::toggle_show_comment();434}435if (strstr(options(), "show-block-comment")) {436AbstractDisassembler::toggle_show_block_comment();437}438_optionsParsed = true;439440if (_print_help && ! _helpPrinted) {441_helpPrinted = true;442ost->print_cr("PrintAssemblyOptions help:");443ost->print_cr(" print-raw test plugin by requesting raw output");444ost->print_cr(" print-raw-xml test plugin by requesting raw xml");445ost->cr();446ost->print_cr(" show-pc toggle printing current pc, currently %s", AbstractDisassembler::show_pc() ? "ON" : "OFF");447ost->print_cr(" show-offset toggle printing current offset, currently %s", AbstractDisassembler::show_offset() ? "ON" : "OFF");448ost->print_cr(" show-bytes toggle printing instruction bytes, currently %s", AbstractDisassembler::show_bytes() ? "ON" : "OFF");449ost->print_cr(" show-data-hex toggle formatting data as hex, currently %s", AbstractDisassembler::show_data_hex() ? "ON" : "OFF");450ost->print_cr(" show-data-int toggle formatting data as int, currently %s", AbstractDisassembler::show_data_int() ? "ON" : "OFF");451ost->print_cr(" show-data-float toggle formatting data as float, currently %s", AbstractDisassembler::show_data_float() ? "ON" : "OFF");452ost->print_cr(" show-structs toggle compiler data structures, currently %s", AbstractDisassembler::show_structs() ? "ON" : "OFF");453ost->print_cr(" show-comment toggle instruction comments, currently %s", AbstractDisassembler::show_comment() ? "ON" : "OFF");454ost->print_cr(" show-block-comment toggle block comments, currently %s", AbstractDisassembler::show_block_comment() ? "ON" : "OFF");455ost->print_cr(" align-instr toggle instruction alignment, currently %s", AbstractDisassembler::align_instr() ? "ON" : "OFF");456ost->print_cr("combined options: %s", options());457}458}459460// Disassembly Event Handler.461// This method receives events from the disassembler library hsdis462// via event_to_env for each decoding step (installed by463// Disassembler::decode_instructions(), replacing the default464// callback method). This enables dumping additional info465// and custom line formatting.466// In a future extension, calling a custom decode method will be467// supported. We can use such a method to decode instructions the468// binutils decoder does not handle to our liking (suboptimal469// formatting, incomplete information, ...).470// Returns:471// - NULL for all standard invocations. The function result is not472// examined (as of now, 20190409) by the hsdis decoder loop.473// - next for 'insn0' invocations.474// next == arg: the custom decoder didn't do anything.475// next > arg: the custom decoder did decode the instruction.476// next points to the next undecoded instruction477// (continuation point for decoder loop).478//479// "Normal" sequence of events:480// insns - start of instruction stream decoding481// mach - display architecture482// format - display bytes-per-line483// for each instruction:484// insn - start of instruction decoding485// insn0 - custom decoder invocation (if any)486// addr - print address value487// /insn - end of instruction decoding488// /insns - premature end of instruction stream due to no progress489//490address decode_env::handle_event(const char* event, address arg) {491492#if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)493494//---< Event: end decoding loop (error, no progress) >---495if (decode_env::match(event, "/insns")) {496// Nothing to be done here.497return NULL;498}499500//---< Event: start decoding loop >---501if (decode_env::match(event, "insns")) {502// Nothing to be done here.503return NULL;504}505506//---< Event: finish decoding an instruction >---507if (decode_env::match(event, "/insn")) {508output()->fill_to(_post_decode_alignment);509end_insn(arg);510return NULL;511}512513//---< Event: start decoding an instruction >---514if (decode_env::match(event, "insn")) {515start_insn(arg);516} else if (match(event, "/insn")) {517end_insn(arg);518} else if (match(event, "addr")) {519if (arg != NULL) {520print_address(arg);521return arg;522}523calculate_alignment();524output()->fill_to(_pre_decode_alignment);525return NULL;526}527528//---< Event: call custom decoder (platform specific) >---529if (decode_env::match(event, "insn0")) {530return Disassembler::decode_instruction0(arg, output(), arg);531}532533//---< Event: Print address >---534if (decode_env::match(event, "addr")) {535print_address(arg);536return arg;537}538539//---< Event: mach (inform about machine architecture) >---540// This event is problematic because it messes up the output.541// The event is fired after the instruction address has already542// been printed. The decoded instruction (event "insn") is543// printed afterwards. That doesn't look nice.544if (decode_env::match(event, "mach")) {545guarantee(arg != NULL, "event_to_env - arg must not be NULL for event 'mach'");546static char buffer[64] = { 0, };547// Output suppressed because it messes up disassembly.548// Only print this when the mach changes.549if (false && (strcmp(buffer, (const char*)arg) != 0 ||550strlen((const char*)arg) > sizeof(buffer) - 1)) {551// Only print this when the mach changes552strncpy(buffer, (const char*)arg, sizeof(buffer) - 1);553buffer[sizeof(buffer) - 1] = '\0';554output()->print_cr("[Disassembling for mach='%s']", (const char*)arg);555}556return NULL;557}558559//---< Event: format bytes-per-line >---560if (decode_env::match(event, "format bytes-per-line")) {561_bytes_per_line = (int) (intptr_t) arg;562return NULL;563}564#endif565return NULL;566}567568static void* event_to_env(void* env_pv, const char* event, void* arg) {569decode_env* env = (decode_env*) env_pv;570return env->handle_event(event, (address) arg);571}572573// called by the disassembler to print out jump targets and data addresses574void decode_env::print_address(address adr) {575outputStream* st = output();576577if (adr == NULL) {578st->print("NULL");579return;580}581582int small_num = (int)(intptr_t)adr;583if ((intptr_t)adr == (intptr_t)small_num584&& -1 <= small_num && small_num <= 9) {585st->print("%d", small_num);586return;587}588589if (Universe::is_fully_initialized()) {590if (StubRoutines::contains(adr)) {591StubCodeDesc* desc = StubCodeDesc::desc_for(adr);592if (desc == NULL) {593desc = StubCodeDesc::desc_for(adr + frame::pc_return_offset);594}595if (desc != NULL) {596st->print("Stub::%s", desc->name());597if (desc->begin() != adr) {598st->print(INTX_FORMAT_W(+) " " PTR_FORMAT, adr - desc->begin(), p2i(adr));599} else if (WizardMode) {600st->print(" " PTR_FORMAT, p2i(adr));601}602return;603}604st->print("Stub::<unknown> " PTR_FORMAT, p2i(adr));605return;606}607608BarrierSet* bs = BarrierSet::barrier_set();609if (bs->is_a(BarrierSet::CardTableBarrierSet) &&610adr == ci_card_table_address_as<address>()) {611st->print("word_map_base");612if (WizardMode) st->print(" " INTPTR_FORMAT, p2i(adr));613return;614}615}616617if (_nm == NULL) {618// Don't do this for native methods, as the function name will be printed in619// nmethod::reloc_string_for().620// Allocate the buffer on the stack instead of as RESOURCE array.621// In case we do DecodeErrorFile, Thread will not be initialized,622// causing a "assert(current != __null) failed" failure.623const int buflen = 1024;624char buf[buflen];625int offset;626if (os::dll_address_to_function_name(adr, buf, buflen, &offset)) {627st->print(PTR_FORMAT " = %s", p2i(adr), buf);628if (offset != 0) {629st->print("+%d", offset);630}631return;632}633}634635// Fall through to a simple (hexadecimal) numeral.636st->print(PTR_FORMAT, p2i(adr));637}638639void decode_env::print_insn_labels() {640if (AbstractDisassembler::show_block_comment()) {641address p = cur_insn();642outputStream* st = output();643644//---< Block comments for nmethod >---645// Outputs a bol() before and a cr() after, but only if a comment is printed.646// Prints nmethod_section_label as well.647if (_nm != NULL) {648_nm->print_block_comment(st, p);649}650if (_codeBlob != NULL) {651_codeBlob->print_block_comment(st, p);652}653#ifndef PRODUCT654if (_strings != NULL) {655_strings->print_block_comment(st, (intptr_t)(p - _start));656}657#endif658}659}660661void decode_env::print_insn_prefix() {662address p = cur_insn();663outputStream* st = output();664AbstractDisassembler::print_location(p, _start, _end, st, false, false);665AbstractDisassembler::print_instruction(p, Assembler::instr_len(p), Assembler::instr_maxlen(), st, true, false);666}667668ATTRIBUTE_PRINTF(2, 3)669static int printf_to_env(void* env_pv, const char* format, ...) {670decode_env* env = (decode_env*) env_pv;671outputStream* st = env->output();672size_t flen = strlen(format);673const char* raw = NULL;674if (flen == 0) return 0;675if (flen == 1 && format[0] == '\n') { st->bol(); return 1; }676if (flen < 2 ||677strchr(format, '%') == NULL) {678raw = format;679} else if (format[0] == '%' && format[1] == '%' &&680strchr(format+2, '%') == NULL) {681// happens a lot on machines with names like %foo682flen--;683raw = format+1;684}685if (raw != NULL) {686st->print_raw(raw, (int) flen);687return (int) flen;688}689va_list ap;690va_start(ap, format);691julong cnt0 = st->count();692st->vprint(format, ap);693julong cnt1 = st->count();694va_end(ap);695return (int)(cnt1 - cnt0);696}697698// The 'original_start' argument holds the the original address where699// the instructions were located in the originating system. If zero (NULL)700// is passed in, there is no original address.701address decode_env::decode_instructions(address start, address end, address original_start /* = 0*/) {702// CodeComment in Stubs.703// Properly initialize _start/_end. Overwritten too often if704// printing of instructions is called for each instruction.705assert((_start == NULL) || (start == NULL) || (_start == start), "don't overwrite CTOR values");706assert((_end == NULL) || (end == NULL) || (_end == end ), "don't overwrite CTOR values");707if (start != NULL) set_start(start);708if (end != NULL) set_end(end);709if (original_start == NULL) {710original_start = start;711}712713//---< Check (and correct) alignment >---714// Don't check alignment of end, it is not aligned.715if (((uint64_t)start & ((uint64_t)Disassembler::pd_instruction_alignment() - 1)) != 0) {716output()->print_cr("Decode range start:" PTR_FORMAT ": ... (unaligned)", p2i(start));717start = (address)((uint64_t)start & ~((uint64_t)Disassembler::pd_instruction_alignment() - 1));718}719720// Trying to decode instructions doesn't make sense if we721// couldn't load the disassembler library.722if (Disassembler::is_abstract()) {723return NULL;724}725726// decode a series of instructions and return the end of the last instruction727728if (_print_raw) {729// Print whatever the library wants to print, w/o fancy callbacks.730// This is mainly for debugging the library itself.731FILE* out = stdout;732FILE* xmlout = (_print_raw > 1 ? out : NULL);733return734(address)735(*Disassembler::_decode_instructions_virtual)((uintptr_t)start, (uintptr_t)end,736start, end - start,737NULL, (void*) xmlout,738NULL, (void*) out,739options(), 0/*nice new line*/);740}741742return743(address)744(*Disassembler::_decode_instructions_virtual)((uintptr_t)start, (uintptr_t)end,745start, end - start,746&event_to_env, (void*) this,747&printf_to_env, (void*) this,748options(), 0/*nice new line*/);749}750751// ----------------------------------------------------------------------------752// Disassembler753// Used as a static wrapper for decode_env.754// Each method will create a decode_env before decoding.755// You can call the decode_env methods directly if you already have one.756757758bool Disassembler::load_library(outputStream* st) {759// Do not try to load multiple times. Failed once -> fails always.760// To force retry in debugger: assign _tried_to_load_library=0761if (_tried_to_load_library) {762return _library_usable;763}764765#if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)766// Print to given stream, if any.767// Print to tty if Verbose is on and no stream given.768st = ((st == NULL) && Verbose) ? tty : st;769770// Compute fully qualified library name.771char ebuf[1024];772char buf[JVM_MAXPATHLEN];773os::jvm_path(buf, sizeof(buf));774int jvm_offset = -1;775int lib_offset = -1;776#ifdef STATIC_BUILD777char* p = strrchr(buf, '/');778*p = '\0';779strcat(p, "/lib/");780lib_offset = jvm_offset = strlen(buf);781#else782{783// Match "libjvm" instead of "jvm" on *nix platforms. Creates better matches.784// Match "[lib]jvm[^/]*" in jvm_path.785const char* base = buf;786const char* p = strrchr(buf, *os::file_separator());787if (p != NULL) lib_offset = p - base + 1; // this points to the first char after separator788#ifdef _WIN32789p = strstr(p ? p : base, "jvm");790if (p != NULL) jvm_offset = p - base; // this points to 'j' in jvm.791#else792p = strstr(p ? p : base, "libjvm");793if (p != NULL) jvm_offset = p - base + 3; // this points to 'j' in libjvm.794#endif795}796#endif797798// Find the disassembler shared library.799// Search for several paths derived from libjvm, in this order:800// 1. <home>/lib/<vm>/libhsdis-<arch>.so (for compatibility)801// 2. <home>/lib/<vm>/hsdis-<arch>.so802// 3. <home>/lib/hsdis-<arch>.so803// 4. hsdis-<arch>.so (using LD_LIBRARY_PATH)804if (jvm_offset >= 0) {805// 1. <home>/lib/<vm>/libhsdis-<arch>.so806if (jvm_offset + strlen(hsdis_library_name) + strlen(os::dll_file_extension()) < JVM_MAXPATHLEN) {807strcpy(&buf[jvm_offset], hsdis_library_name);808strcat(&buf[jvm_offset], os::dll_file_extension());809if (Verbose) st->print_cr("Trying to load: %s", buf);810_library = os::dll_load(buf, ebuf, sizeof ebuf);811} else {812if (Verbose) st->print_cr("Try to load hsdis library failed: the length of path is beyond the OS limit");813}814if (_library == NULL && lib_offset >= 0) {815// 2. <home>/lib/<vm>/hsdis-<arch>.so816if (lib_offset + strlen(hsdis_library_name) + strlen(os::dll_file_extension()) < JVM_MAXPATHLEN) {817strcpy(&buf[lib_offset], hsdis_library_name);818strcat(&buf[lib_offset], os::dll_file_extension());819if (Verbose) st->print_cr("Trying to load: %s", buf);820_library = os::dll_load(buf, ebuf, sizeof ebuf);821} else {822if (Verbose) st->print_cr("Try to load hsdis library failed: the length of path is beyond the OS limit");823}824}825if (_library == NULL && lib_offset > 0) {826// 3. <home>/lib/hsdis-<arch>.so827buf[lib_offset - 1] = '\0';828const char* p = strrchr(buf, *os::file_separator());829if (p != NULL) {830lib_offset = p - buf + 1;831if (lib_offset + strlen(hsdis_library_name) + strlen(os::dll_file_extension()) < JVM_MAXPATHLEN) {832strcpy(&buf[lib_offset], hsdis_library_name);833strcat(&buf[lib_offset], os::dll_file_extension());834if (Verbose) st->print_cr("Trying to load: %s", buf);835_library = os::dll_load(buf, ebuf, sizeof ebuf);836} else {837if (Verbose) st->print_cr("Try to load hsdis library failed: the length of path is beyond the OS limit");838}839}840}841}842if (_library == NULL) {843// 4. hsdis-<arch>.so (using LD_LIBRARY_PATH)844strcpy(&buf[0], hsdis_library_name);845strcat(&buf[0], os::dll_file_extension());846if (Verbose) st->print_cr("Trying to load: %s via LD_LIBRARY_PATH or equivalent", buf);847_library = os::dll_load(buf, ebuf, sizeof ebuf);848}849850// load the decoder function to use.851if (_library != NULL) {852_decode_instructions_virtual = CAST_TO_FN_PTR(Disassembler::decode_func_virtual,853os::dll_lookup(_library, decode_instructions_virtual_name));854}855_tried_to_load_library = true;856_library_usable = _decode_instructions_virtual != NULL;857858// Create a dummy environment to initialize PrintAssemblyOptions.859// The PrintAssemblyOptions must be known for abstract disassemblies as well.860decode_env dummy((unsigned char*)(&buf[0]), (unsigned char*)(&buf[1]), st);861862// Report problems during dll_load or dll_lookup, if any.863if (st != NULL) {864// Success.865if (_library_usable) {866st->print_cr("Loaded disassembler from %s", buf);867} else {868st->print_cr("Could not load %s; %s; %s",869buf,870((_library != NULL)871? "entry point is missing"872: ((WizardMode || PrintMiscellaneous)873? (const char*)ebuf874: "library not loadable")),875"PrintAssembly defaults to abstract disassembly.");876}877}878#endif879return _library_usable;880}881882883// Directly disassemble code blob.884void Disassembler::decode(CodeBlob* cb, outputStream* st) {885#if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)886if (cb->is_nmethod()) {887// If we have an nmethod at hand,888// call the specialized decoder directly.889decode((nmethod*)cb, st);890return;891}892893decode_env env(cb, st);894env.output()->print_cr("--------------------------------------------------------------------------------");895env.output()->print("Decoding CodeBlob");896if (cb->name() != NULL) {897env.output()->print(", name: %s,", cb->name());898}899env.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())));900901if (is_abstract()) {902AbstractDisassembler::decode_abstract(cb->code_begin(), cb->code_end(), env.output(), Assembler::instr_maxlen());903} else {904env.decode_instructions(cb->code_begin(), cb->code_end());905}906env.output()->print_cr("--------------------------------------------------------------------------------");907#endif908}909910// Decode a nmethod.911// This includes printing the constant pool and all code segments.912// The nmethod data structures (oop maps, relocations and the like) are not printed.913void Disassembler::decode(nmethod* nm, outputStream* st) {914#if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)915ttyLocker ttyl;916917decode_env env(nm, st);918env.output()->print_cr("--------------------------------------------------------------------------------");919nm->print_constant_pool(env.output());920env.output()->print_cr("--------------------------------------------------------------------------------");921env.output()->cr();922if (is_abstract()) {923AbstractDisassembler::decode_abstract(nm->code_begin(), nm->code_end(), env.output(), Assembler::instr_maxlen());924} else {925env.decode_instructions(nm->code_begin(), nm->code_end());926}927env.output()->print_cr("--------------------------------------------------------------------------------");928#endif929}930931// Decode a range, given as [start address, end address)932void Disassembler::decode(address start, address end, outputStream* st, const CodeStrings* c) {933#if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)934//---< Test memory before decoding >---935if (!os::is_readable_range(start, end)) {936//---< Allow output suppression, but prevent writing to a NULL stream. Could happen with +PrintStubCode. >---937if (st != NULL) {938st->print("Memory range [" PTR_FORMAT ".." PTR_FORMAT "] not readable", p2i(start), p2i(end));939}940return;941}942943if (is_abstract()) {944AbstractDisassembler::decode_abstract(start, end, st, Assembler::instr_maxlen());945return;946}947948// Don't do that fancy stuff. If we just have two addresses, live with it949// and treat the memory contents as "amorphic" piece of code.950#if 0951CodeBlob* cb = CodeCache::find_blob_unsafe(start);952if (cb != NULL) {953// If we have an CodeBlob at hand,954// call the specialized decoder directly.955decode(cb, st, c);956} else957#endif958{959// This seems to be just a chunk of memory.960decode_env env(start, end, st, c);961env.output()->print_cr("--------------------------------------------------------------------------------");962env.decode_instructions(start, end);963env.output()->print_cr("--------------------------------------------------------------------------------");964}965#endif966}967968// To prevent excessive code expansion in the interpreter generator, we969// do not inline this function into Disassembler::hook().970void Disassembler::_hook(const char* file, int line, MacroAssembler* masm) {971decode_env::hook(file, line, masm->code_section()->end());972}973974975