Path: blob/main/contrib/llvm-project/lldb/source/Commands/CommandObjectDisassemble.cpp
39587 views
//===-- CommandObjectDisassemble.cpp --------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "CommandObjectDisassemble.h"9#include "lldb/Core/AddressRange.h"10#include "lldb/Core/Disassembler.h"11#include "lldb/Core/Module.h"12#include "lldb/Host/OptionParser.h"13#include "lldb/Interpreter/CommandInterpreter.h"14#include "lldb/Interpreter/CommandOptionArgumentTable.h"15#include "lldb/Interpreter/CommandReturnObject.h"16#include "lldb/Interpreter/OptionArgParser.h"17#include "lldb/Interpreter/Options.h"18#include "lldb/Symbol/Function.h"19#include "lldb/Symbol/Symbol.h"20#include "lldb/Target/SectionLoadList.h"21#include "lldb/Target/StackFrame.h"22#include "lldb/Target/Target.h"2324static constexpr unsigned default_disasm_byte_size = 32;25static constexpr unsigned default_disasm_num_ins = 4;2627using namespace lldb;28using namespace lldb_private;2930#define LLDB_OPTIONS_disassemble31#include "CommandOptions.inc"3233CommandObjectDisassemble::CommandOptions::CommandOptions() {34OptionParsingStarting(nullptr);35}3637CommandObjectDisassemble::CommandOptions::~CommandOptions() = default;3839Status CommandObjectDisassemble::CommandOptions::SetOptionValue(40uint32_t option_idx, llvm::StringRef option_arg,41ExecutionContext *execution_context) {42Status error;4344const int short_option = m_getopt_table[option_idx].val;4546switch (short_option) {47case 'm':48show_mixed = true;49break;5051case 'C':52if (option_arg.getAsInteger(0, num_lines_context))53error.SetErrorStringWithFormat("invalid num context lines string: \"%s\"",54option_arg.str().c_str());55break;5657case 'c':58if (option_arg.getAsInteger(0, num_instructions))59error.SetErrorStringWithFormat(60"invalid num of instructions string: \"%s\"",61option_arg.str().c_str());62break;6364case 'b':65show_bytes = true;66break;6768case 'k':69show_control_flow_kind = true;70break;7172case 's': {73start_addr = OptionArgParser::ToAddress(execution_context, option_arg,74LLDB_INVALID_ADDRESS, &error);75if (start_addr != LLDB_INVALID_ADDRESS)76some_location_specified = true;77} break;78case 'e': {79end_addr = OptionArgParser::ToAddress(execution_context, option_arg,80LLDB_INVALID_ADDRESS, &error);81if (end_addr != LLDB_INVALID_ADDRESS)82some_location_specified = true;83} break;8485case 'n':86func_name.assign(std::string(option_arg));87some_location_specified = true;88break;8990case 'p':91at_pc = true;92some_location_specified = true;93break;9495case 'l':96frame_line = true;97// Disassemble the current source line kind of implies showing mixed source98// code context.99show_mixed = true;100some_location_specified = true;101break;102103case 'P':104plugin_name.assign(std::string(option_arg));105break;106107case 'F': {108TargetSP target_sp =109execution_context ? execution_context->GetTargetSP() : TargetSP();110if (target_sp && (target_sp->GetArchitecture().GetTriple().getArch() ==111llvm::Triple::x86 ||112target_sp->GetArchitecture().GetTriple().getArch() ==113llvm::Triple::x86_64)) {114flavor_string.assign(std::string(option_arg));115} else116error.SetErrorStringWithFormat("Disassembler flavors are currently only "117"supported for x86 and x86_64 targets.");118break;119}120121case 'r':122raw = true;123break;124125case 'f':126current_function = true;127some_location_specified = true;128break;129130case 'A':131if (execution_context) {132const auto &target_sp = execution_context->GetTargetSP();133auto platform_ptr = target_sp ? target_sp->GetPlatform().get() : nullptr;134arch = Platform::GetAugmentedArchSpec(platform_ptr, option_arg);135}136break;137138case 'a': {139symbol_containing_addr = OptionArgParser::ToAddress(140execution_context, option_arg, LLDB_INVALID_ADDRESS, &error);141if (symbol_containing_addr != LLDB_INVALID_ADDRESS) {142some_location_specified = true;143}144} break;145146case '\x01':147force = true;148break;149150default:151llvm_unreachable("Unimplemented option");152}153154return error;155}156157void CommandObjectDisassemble::CommandOptions::OptionParsingStarting(158ExecutionContext *execution_context) {159show_mixed = false;160show_bytes = false;161show_control_flow_kind = false;162num_lines_context = 0;163num_instructions = 0;164func_name.clear();165current_function = false;166at_pc = false;167frame_line = false;168start_addr = LLDB_INVALID_ADDRESS;169end_addr = LLDB_INVALID_ADDRESS;170symbol_containing_addr = LLDB_INVALID_ADDRESS;171raw = false;172plugin_name.clear();173174Target *target =175execution_context ? execution_context->GetTargetPtr() : nullptr;176177// This is a hack till we get the ability to specify features based on178// architecture. For now GetDisassemblyFlavor is really only valid for x86179// (and for the llvm assembler plugin, but I'm papering over that since that180// is the only disassembler plugin we have...181if (target) {182if (target->GetArchitecture().GetTriple().getArch() == llvm::Triple::x86 ||183target->GetArchitecture().GetTriple().getArch() ==184llvm::Triple::x86_64) {185flavor_string.assign(target->GetDisassemblyFlavor());186} else187flavor_string.assign("default");188189} else190flavor_string.assign("default");191192arch.Clear();193some_location_specified = false;194force = false;195}196197Status CommandObjectDisassemble::CommandOptions::OptionParsingFinished(198ExecutionContext *execution_context) {199if (!some_location_specified)200current_function = true;201return Status();202}203204llvm::ArrayRef<OptionDefinition>205CommandObjectDisassemble::CommandOptions::GetDefinitions() {206return llvm::ArrayRef(g_disassemble_options);207}208209// CommandObjectDisassemble210211CommandObjectDisassemble::CommandObjectDisassemble(212CommandInterpreter &interpreter)213: CommandObjectParsed(214interpreter, "disassemble",215"Disassemble specified instructions in the current target. "216"Defaults to the current function for the current thread and "217"stack frame.",218"disassemble [<cmd-options>]", eCommandRequiresTarget) {}219220CommandObjectDisassemble::~CommandObjectDisassemble() = default;221222llvm::Error CommandObjectDisassemble::CheckRangeSize(const AddressRange &range,223llvm::StringRef what) {224if (m_options.num_instructions > 0 || m_options.force ||225range.GetByteSize() < GetDebugger().GetStopDisassemblyMaxSize())226return llvm::Error::success();227StreamString msg;228msg << "Not disassembling " << what << " because it is very large ";229range.Dump(&msg, &GetSelectedTarget(), Address::DumpStyleLoadAddress,230Address::DumpStyleFileAddress);231msg << ". To disassemble specify an instruction count limit, start/stop "232"addresses or use the --force option.";233return llvm::createStringError(llvm::inconvertibleErrorCode(),234msg.GetString());235}236237llvm::Expected<std::vector<AddressRange>>238CommandObjectDisassemble::GetContainingAddressRanges() {239std::vector<AddressRange> ranges;240const auto &get_range = [&](Address addr) {241ModuleSP module_sp(addr.GetModule());242SymbolContext sc;243bool resolve_tail_call_address = true;244addr.GetModule()->ResolveSymbolContextForAddress(245addr, eSymbolContextEverything, sc, resolve_tail_call_address);246if (sc.function || sc.symbol) {247AddressRange range;248sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0,249false, range);250ranges.push_back(range);251}252};253254Target &target = GetSelectedTarget();255if (!target.GetSectionLoadList().IsEmpty()) {256Address symbol_containing_address;257if (target.GetSectionLoadList().ResolveLoadAddress(258m_options.symbol_containing_addr, symbol_containing_address)) {259get_range(symbol_containing_address);260}261} else {262for (lldb::ModuleSP module_sp : target.GetImages().Modules()) {263Address file_address;264if (module_sp->ResolveFileAddress(m_options.symbol_containing_addr,265file_address)) {266get_range(file_address);267}268}269}270271if (ranges.empty()) {272return llvm::createStringError(273llvm::inconvertibleErrorCode(),274"Could not find function bounds for address 0x%" PRIx64,275m_options.symbol_containing_addr);276}277278if (llvm::Error err = CheckRangeSize(ranges[0], "the function"))279return std::move(err);280return ranges;281}282283llvm::Expected<std::vector<AddressRange>>284CommandObjectDisassemble::GetCurrentFunctionRanges() {285Process *process = m_exe_ctx.GetProcessPtr();286StackFrame *frame = m_exe_ctx.GetFramePtr();287if (!frame) {288if (process) {289return llvm::createStringError(290llvm::inconvertibleErrorCode(),291"Cannot disassemble around the current "292"function without the process being stopped.\n");293} else {294return llvm::createStringError(llvm::inconvertibleErrorCode(),295"Cannot disassemble around the current "296"function without a selected frame: "297"no currently running process.\n");298}299}300SymbolContext sc(301frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol));302AddressRange range;303if (sc.function)304range = sc.function->GetAddressRange();305else if (sc.symbol && sc.symbol->ValueIsAddress()) {306range = {sc.symbol->GetAddress(), sc.symbol->GetByteSize()};307} else308range = {frame->GetFrameCodeAddress(), default_disasm_byte_size};309310if (llvm::Error err = CheckRangeSize(range, "the current function"))311return std::move(err);312return std::vector<AddressRange>{range};313}314315llvm::Expected<std::vector<AddressRange>>316CommandObjectDisassemble::GetCurrentLineRanges() {317Process *process = m_exe_ctx.GetProcessPtr();318StackFrame *frame = m_exe_ctx.GetFramePtr();319if (!frame) {320if (process) {321return llvm::createStringError(322llvm::inconvertibleErrorCode(),323"Cannot disassemble around the current "324"function without the process being stopped.\n");325} else {326return llvm::createStringError(llvm::inconvertibleErrorCode(),327"Cannot disassemble around the current "328"line without a selected frame: "329"no currently running process.\n");330}331}332333LineEntry pc_line_entry(334frame->GetSymbolContext(eSymbolContextLineEntry).line_entry);335if (pc_line_entry.IsValid())336return std::vector<AddressRange>{pc_line_entry.range};337338// No line entry, so just disassemble around the current pc339m_options.show_mixed = false;340return GetPCRanges();341}342343llvm::Expected<std::vector<AddressRange>>344CommandObjectDisassemble::GetNameRanges(CommandReturnObject &result) {345ConstString name(m_options.func_name.c_str());346347ModuleFunctionSearchOptions function_options;348function_options.include_symbols = true;349function_options.include_inlines = true;350351// Find functions matching the given name.352SymbolContextList sc_list;353GetSelectedTarget().GetImages().FindFunctions(name, eFunctionNameTypeAuto,354function_options, sc_list);355356std::vector<AddressRange> ranges;357llvm::Error range_errs = llvm::Error::success();358AddressRange range;359const uint32_t scope =360eSymbolContextBlock | eSymbolContextFunction | eSymbolContextSymbol;361const bool use_inline_block_range = true;362for (SymbolContext sc : sc_list.SymbolContexts()) {363for (uint32_t range_idx = 0;364sc.GetAddressRange(scope, range_idx, use_inline_block_range, range);365++range_idx) {366if (llvm::Error err = CheckRangeSize(range, "a range"))367range_errs = joinErrors(std::move(range_errs), std::move(err));368else369ranges.push_back(range);370}371}372if (ranges.empty()) {373if (range_errs)374return std::move(range_errs);375return llvm::createStringError(llvm::inconvertibleErrorCode(),376"Unable to find symbol with name '%s'.\n",377name.GetCString());378}379if (range_errs)380result.AppendWarning(toString(std::move(range_errs)));381return ranges;382}383384llvm::Expected<std::vector<AddressRange>>385CommandObjectDisassemble::GetPCRanges() {386Process *process = m_exe_ctx.GetProcessPtr();387StackFrame *frame = m_exe_ctx.GetFramePtr();388if (!frame) {389if (process) {390return llvm::createStringError(391llvm::inconvertibleErrorCode(),392"Cannot disassemble around the current "393"function without the process being stopped.\n");394} else {395return llvm::createStringError(llvm::inconvertibleErrorCode(),396"Cannot disassemble around the current "397"PC without a selected frame: "398"no currently running process.\n");399}400}401402if (m_options.num_instructions == 0) {403// Disassembling at the PC always disassembles some number of404// instructions (not the whole function).405m_options.num_instructions = default_disasm_num_ins;406}407return std::vector<AddressRange>{{frame->GetFrameCodeAddress(), 0}};408}409410llvm::Expected<std::vector<AddressRange>>411CommandObjectDisassemble::GetStartEndAddressRanges() {412addr_t size = 0;413if (m_options.end_addr != LLDB_INVALID_ADDRESS) {414if (m_options.end_addr <= m_options.start_addr) {415return llvm::createStringError(llvm::inconvertibleErrorCode(),416"End address before start address.");417}418size = m_options.end_addr - m_options.start_addr;419}420return std::vector<AddressRange>{{Address(m_options.start_addr), size}};421}422423llvm::Expected<std::vector<AddressRange>>424CommandObjectDisassemble::GetRangesForSelectedMode(425CommandReturnObject &result) {426if (m_options.symbol_containing_addr != LLDB_INVALID_ADDRESS)427return CommandObjectDisassemble::GetContainingAddressRanges();428if (m_options.current_function)429return CommandObjectDisassemble::GetCurrentFunctionRanges();430if (m_options.frame_line)431return CommandObjectDisassemble::GetCurrentLineRanges();432if (!m_options.func_name.empty())433return CommandObjectDisassemble::GetNameRanges(result);434if (m_options.start_addr != LLDB_INVALID_ADDRESS)435return CommandObjectDisassemble::GetStartEndAddressRanges();436return CommandObjectDisassemble::GetPCRanges();437}438439void CommandObjectDisassemble::DoExecute(Args &command,440CommandReturnObject &result) {441Target *target = &GetSelectedTarget();442443if (!m_options.arch.IsValid())444m_options.arch = target->GetArchitecture();445446if (!m_options.arch.IsValid()) {447result.AppendError(448"use the --arch option or set the target architecture to disassemble");449return;450}451452const char *plugin_name = m_options.GetPluginName();453const char *flavor_string = m_options.GetFlavorString();454455DisassemblerSP disassembler =456Disassembler::FindPlugin(m_options.arch, flavor_string, plugin_name);457458if (!disassembler) {459if (plugin_name) {460result.AppendErrorWithFormat(461"Unable to find Disassembler plug-in named '%s' that supports the "462"'%s' architecture.\n",463plugin_name, m_options.arch.GetArchitectureName());464} else465result.AppendErrorWithFormat(466"Unable to find Disassembler plug-in for the '%s' architecture.\n",467m_options.arch.GetArchitectureName());468return;469} else if (flavor_string != nullptr && !disassembler->FlavorValidForArchSpec(470m_options.arch, flavor_string))471result.AppendWarningWithFormat(472"invalid disassembler flavor \"%s\", using default.\n", flavor_string);473474result.SetStatus(eReturnStatusSuccessFinishResult);475476if (!command.empty()) {477result.AppendErrorWithFormat(478"\"disassemble\" arguments are specified as options.\n");479const int terminal_width =480GetCommandInterpreter().GetDebugger().GetTerminalWidth();481GetOptions()->GenerateOptionUsage(result.GetErrorStream(), *this,482terminal_width);483return;484}485486if (m_options.show_mixed && m_options.num_lines_context == 0)487m_options.num_lines_context = 2;488489// Always show the PC in the disassembly490uint32_t options = Disassembler::eOptionMarkPCAddress;491492// Mark the source line for the current PC only if we are doing mixed source493// and assembly494if (m_options.show_mixed)495options |= Disassembler::eOptionMarkPCSourceLine;496497if (m_options.show_bytes)498options |= Disassembler::eOptionShowBytes;499500if (m_options.show_control_flow_kind)501options |= Disassembler::eOptionShowControlFlowKind;502503if (m_options.raw)504options |= Disassembler::eOptionRawOuput;505506llvm::Expected<std::vector<AddressRange>> ranges =507GetRangesForSelectedMode(result);508if (!ranges) {509result.AppendError(toString(ranges.takeError()));510return;511}512513bool print_sc_header = ranges->size() > 1;514for (AddressRange cur_range : *ranges) {515Disassembler::Limit limit;516if (m_options.num_instructions == 0) {517limit = {Disassembler::Limit::Bytes, cur_range.GetByteSize()};518if (limit.value == 0)519limit.value = default_disasm_byte_size;520} else {521limit = {Disassembler::Limit::Instructions, m_options.num_instructions};522}523if (Disassembler::Disassemble(524GetDebugger(), m_options.arch, plugin_name, flavor_string,525m_exe_ctx, cur_range.GetBaseAddress(), limit, m_options.show_mixed,526m_options.show_mixed ? m_options.num_lines_context : 0, options,527result.GetOutputStream())) {528result.SetStatus(eReturnStatusSuccessFinishResult);529} else {530if (m_options.symbol_containing_addr != LLDB_INVALID_ADDRESS) {531result.AppendErrorWithFormat(532"Failed to disassemble memory in function at 0x%8.8" PRIx64 ".\n",533m_options.symbol_containing_addr);534} else {535result.AppendErrorWithFormat(536"Failed to disassemble memory at 0x%8.8" PRIx64 ".\n",537cur_range.GetBaseAddress().GetLoadAddress(target));538}539}540if (print_sc_header)541result.GetOutputStream() << "\n";542}543}544545546