LLDB mainline
CommandObjectDisassemble.cpp
Go to the documentation of this file.
1//===-- CommandObjectDisassemble.cpp --------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
12#include "lldb/Core/Module.h"
20#include "lldb/Symbol/Symbol.h"
23#include "lldb/Target/Target.h"
24
25static constexpr unsigned default_disasm_byte_size = 32;
26static constexpr unsigned default_disasm_num_ins = 4;
27
28using namespace lldb;
29using namespace lldb_private;
30
31#define LLDB_OPTIONS_disassemble
32#include "CommandOptions.inc"
33
35 OptionParsingStarting(nullptr);
36}
37
39
41 uint32_t option_idx, llvm::StringRef option_arg,
42 ExecutionContext *execution_context) {
44
45 const int short_option = m_getopt_table[option_idx].val;
46
47 switch (short_option) {
48 case 'm':
49 show_mixed = true;
50 break;
51
52 case 'C':
53 if (option_arg.getAsInteger(0, num_lines_context))
54 error.SetErrorStringWithFormat("invalid num context lines string: \"%s\"",
55 option_arg.str().c_str());
56 break;
57
58 case 'c':
59 if (option_arg.getAsInteger(0, num_instructions))
60 error.SetErrorStringWithFormat(
61 "invalid num of instructions string: \"%s\"",
62 option_arg.str().c_str());
63 break;
64
65 case 'b':
66 show_bytes = true;
67 break;
68
69 case 'k':
70 show_control_flow_kind = true;
71 break;
72
73 case 's': {
74 start_addr = OptionArgParser::ToAddress(execution_context, option_arg,
76 if (start_addr != LLDB_INVALID_ADDRESS)
77 some_location_specified = true;
78 } break;
79 case 'e': {
80 end_addr = OptionArgParser::ToAddress(execution_context, option_arg,
82 if (end_addr != LLDB_INVALID_ADDRESS)
83 some_location_specified = true;
84 } break;
85
86 case 'n':
87 func_name.assign(std::string(option_arg));
88 some_location_specified = true;
89 break;
90
91 case 'p':
92 at_pc = true;
93 some_location_specified = true;
94 break;
95
96 case 'l':
97 frame_line = true;
98 // Disassemble the current source line kind of implies showing mixed source
99 // code context.
100 show_mixed = true;
101 some_location_specified = true;
102 break;
103
104 case 'P':
105 plugin_name.assign(std::string(option_arg));
106 break;
107
108 case 'F': {
109 TargetSP target_sp =
110 execution_context ? execution_context->GetTargetSP() : TargetSP();
111 if (target_sp && (target_sp->GetArchitecture().GetTriple().getArch() ==
112 llvm::Triple::x86 ||
113 target_sp->GetArchitecture().GetTriple().getArch() ==
114 llvm::Triple::x86_64)) {
115 flavor_string.assign(std::string(option_arg));
116 } else
117 error.SetErrorStringWithFormat("Disassembler flavors are currently only "
118 "supported for x86 and x86_64 targets.");
119 break;
120 }
121
122 case 'r':
123 raw = true;
124 break;
125
126 case 'f':
127 current_function = true;
128 some_location_specified = true;
129 break;
130
131 case 'A':
132 if (execution_context) {
133 const auto &target_sp = execution_context->GetTargetSP();
134 auto platform_ptr = target_sp ? target_sp->GetPlatform().get() : nullptr;
135 arch = Platform::GetAugmentedArchSpec(platform_ptr, option_arg);
136 }
137 break;
138
139 case 'a': {
140 symbol_containing_addr = OptionArgParser::ToAddress(
141 execution_context, option_arg, LLDB_INVALID_ADDRESS, &error);
142 if (symbol_containing_addr != LLDB_INVALID_ADDRESS) {
143 some_location_specified = true;
144 }
145 } break;
146
147 case '\x01':
148 force = true;
149 break;
150
151 default:
152 llvm_unreachable("Unimplemented option");
153 }
154
155 return error;
156}
157
159 ExecutionContext *execution_context) {
160 show_mixed = false;
161 show_bytes = false;
162 show_control_flow_kind = false;
163 num_lines_context = 0;
164 num_instructions = 0;
165 func_name.clear();
166 current_function = false;
167 at_pc = false;
168 frame_line = false;
169 start_addr = LLDB_INVALID_ADDRESS;
170 end_addr = LLDB_INVALID_ADDRESS;
171 symbol_containing_addr = LLDB_INVALID_ADDRESS;
172 raw = false;
173 plugin_name.clear();
174
175 Target *target =
176 execution_context ? execution_context->GetTargetPtr() : nullptr;
177
178 // This is a hack till we get the ability to specify features based on
179 // architecture. For now GetDisassemblyFlavor is really only valid for x86
180 // (and for the llvm assembler plugin, but I'm papering over that since that
181 // is the only disassembler plugin we have...
182 if (target) {
183 if (target->GetArchitecture().GetTriple().getArch() == llvm::Triple::x86 ||
184 target->GetArchitecture().GetTriple().getArch() ==
185 llvm::Triple::x86_64) {
186 flavor_string.assign(target->GetDisassemblyFlavor());
187 } else
188 flavor_string.assign("default");
189
190 } else
191 flavor_string.assign("default");
192
193 arch.Clear();
194 some_location_specified = false;
195 force = false;
196}
197
199 ExecutionContext *execution_context) {
200 if (!some_location_specified)
201 current_function = true;
202 return Status();
203}
204
205llvm::ArrayRef<OptionDefinition>
207 return llvm::ArrayRef(g_disassemble_options);
208}
209
210// CommandObjectDisassemble
211
213 CommandInterpreter &interpreter)
215 interpreter, "disassemble",
216 "Disassemble specified instructions in the current target. "
217 "Defaults to the current function for the current thread and "
218 "stack frame.",
219 "disassemble [<cmd-options>]", eCommandRequiresTarget) {}
220
222
224 llvm::StringRef what) {
226 range.GetByteSize() < GetDebugger().GetStopDisassemblyMaxSize())
227 return llvm::Error::success();
228 StreamString msg;
229 msg << "Not disassembling " << what << " because it is very large ";
232 msg << ". To disassemble specify an instruction count limit, start/stop "
233 "addresses or use the --force option.";
234 return llvm::createStringError(llvm::inconvertibleErrorCode(),
235 msg.GetString());
236}
237
238llvm::Expected<std::vector<AddressRange>>
240 std::vector<AddressRange> ranges;
241 const auto &get_range = [&](Address addr) {
242 ModuleSP module_sp(addr.GetModule());
243 SymbolContext sc;
244 bool resolve_tail_call_address = true;
245 addr.GetModule()->ResolveSymbolContextForAddress(
246 addr, eSymbolContextEverything, sc, resolve_tail_call_address);
247 if (sc.function || sc.symbol) {
248 AddressRange range;
249 sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0,
250 false, range);
251 ranges.push_back(range);
252 }
253 };
254
255 Target &target = GetTarget();
256 if (!target.GetSectionLoadList().IsEmpty()) {
257 Address symbol_containing_address;
259 m_options.symbol_containing_addr, symbol_containing_address)) {
260 get_range(symbol_containing_address);
261 }
262 } else {
263 for (lldb::ModuleSP module_sp : target.GetImages().Modules()) {
264 Address file_address;
265 if (module_sp->ResolveFileAddress(m_options.symbol_containing_addr,
266 file_address)) {
267 get_range(file_address);
268 }
269 }
270 }
271
272 if (ranges.empty()) {
273 return llvm::createStringError(
274 llvm::inconvertibleErrorCode(),
275 "Could not find function bounds for address 0x%" PRIx64,
277 }
278
279 if (llvm::Error err = CheckRangeSize(ranges[0], "the function"))
280 return std::move(err);
281 return ranges;
282}
283
284llvm::Expected<std::vector<AddressRange>>
286 Process *process = m_exe_ctx.GetProcessPtr();
288 if (!frame) {
289 if (process) {
290 return llvm::createStringError(
291 llvm::inconvertibleErrorCode(),
292 "Cannot disassemble around the current "
293 "function without the process being stopped.\n");
294 } else {
295 return llvm::createStringError(llvm::inconvertibleErrorCode(),
296 "Cannot disassemble around the current "
297 "function without a selected frame: "
298 "no currently running process.\n");
299 }
300 }
301 SymbolContext sc(
302 frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol));
303 AddressRange range;
304 if (sc.function)
305 range = sc.function->GetAddressRange();
306 else if (sc.symbol && sc.symbol->ValueIsAddress()) {
307 range = {sc.symbol->GetAddress(), sc.symbol->GetByteSize()};
308 } else
310
311 if (llvm::Error err = CheckRangeSize(range, "the current function"))
312 return std::move(err);
313 return std::vector<AddressRange>{range};
314}
315
316llvm::Expected<std::vector<AddressRange>>
318 Process *process = m_exe_ctx.GetProcessPtr();
320 if (!frame) {
321 if (process) {
322 return llvm::createStringError(
323 llvm::inconvertibleErrorCode(),
324 "Cannot disassemble around the current "
325 "function without the process being stopped.\n");
326 } else {
327 return llvm::createStringError(llvm::inconvertibleErrorCode(),
328 "Cannot disassemble around the current "
329 "line without a selected frame: "
330 "no currently running process.\n");
331 }
332 }
333
334 LineEntry pc_line_entry(
335 frame->GetSymbolContext(eSymbolContextLineEntry).line_entry);
336 if (pc_line_entry.IsValid())
337 return std::vector<AddressRange>{pc_line_entry.range};
338
339 // No line entry, so just disassemble around the current pc
340 m_options.show_mixed = false;
341 return GetPCRanges();
342}
343
344llvm::Expected<std::vector<AddressRange>>
346 ConstString name(m_options.func_name.c_str());
347
348 ModuleFunctionSearchOptions function_options;
349 function_options.include_symbols = true;
350 function_options.include_inlines = true;
351
352 // Find functions matching the given name.
353 SymbolContextList sc_list;
354 GetTarget().GetImages().FindFunctions(name, eFunctionNameTypeAuto,
355 function_options, sc_list);
356
357 std::vector<AddressRange> ranges;
358 llvm::Error range_errs = llvm::Error::success();
359 AddressRange range;
360 const uint32_t scope =
361 eSymbolContextBlock | eSymbolContextFunction | eSymbolContextSymbol;
362 const bool use_inline_block_range = true;
363 for (SymbolContext sc : sc_list.SymbolContexts()) {
364 for (uint32_t range_idx = 0;
365 sc.GetAddressRange(scope, range_idx, use_inline_block_range, range);
366 ++range_idx) {
367 if (llvm::Error err = CheckRangeSize(range, "a range"))
368 range_errs = joinErrors(std::move(range_errs), std::move(err));
369 else
370 ranges.push_back(range);
371 }
372 }
373 if (ranges.empty()) {
374 if (range_errs)
375 return std::move(range_errs);
376 return llvm::createStringError(llvm::inconvertibleErrorCode(),
377 "Unable to find symbol with name '%s'.\n",
378 name.GetCString());
379 }
380 if (range_errs)
381 result.AppendWarning(toString(std::move(range_errs)));
382 return ranges;
383}
384
385llvm::Expected<std::vector<AddressRange>>
387 Process *process = m_exe_ctx.GetProcessPtr();
389 if (!frame) {
390 if (process) {
391 return llvm::createStringError(
392 llvm::inconvertibleErrorCode(),
393 "Cannot disassemble around the current "
394 "function without the process being stopped.\n");
395 } else {
396 return llvm::createStringError(llvm::inconvertibleErrorCode(),
397 "Cannot disassemble around the current "
398 "PC without a selected frame: "
399 "no currently running process.\n");
400 }
401 }
402
403 if (m_options.num_instructions == 0) {
404 // Disassembling at the PC always disassembles some number of
405 // instructions (not the whole function).
407 }
408 return std::vector<AddressRange>{{frame->GetFrameCodeAddress(), 0}};
409}
410
411llvm::Expected<std::vector<AddressRange>>
413 addr_t size = 0;
416 return llvm::createStringError(llvm::inconvertibleErrorCode(),
417 "End address before start address.");
418 }
420 }
421 return std::vector<AddressRange>{{Address(m_options.start_addr), size}};
422}
423
424llvm::Expected<std::vector<AddressRange>>
426 CommandReturnObject &result) {
433 if (!m_options.func_name.empty())
438}
439
441 CommandReturnObject &result) {
442 Target &target = GetTarget();
443
444 if (!m_options.arch.IsValid())
445 m_options.arch = target.GetArchitecture();
446
447 if (!m_options.arch.IsValid()) {
448 result.AppendError(
449 "use the --arch option or set the target architecture to disassemble");
450 return;
451 }
452
453 const char *plugin_name = m_options.GetPluginName();
454 const char *flavor_string = m_options.GetFlavorString();
455
456 DisassemblerSP disassembler =
457 Disassembler::FindPlugin(m_options.arch, flavor_string, plugin_name);
458
459 if (!disassembler) {
460 if (plugin_name) {
462 "Unable to find Disassembler plug-in named '%s' that supports the "
463 "'%s' architecture.\n",
464 plugin_name, m_options.arch.GetArchitectureName());
465 } else
467 "Unable to find Disassembler plug-in for the '%s' architecture.\n",
469 return;
470 } else if (flavor_string != nullptr && !disassembler->FlavorValidForArchSpec(
471 m_options.arch, flavor_string))
473 "invalid disassembler flavor \"%s\", using default.\n", flavor_string);
474
476
477 if (!command.empty()) {
479 "\"disassemble\" arguments are specified as options.\n");
480 const int terminal_width =
483 terminal_width);
484 return;
485 }
486
489
490 // Always show the PC in the disassembly
491 uint32_t options = Disassembler::eOptionMarkPCAddress;
492
493 // Mark the source line for the current PC only if we are doing mixed source
494 // and assembly
497
500
503
504 if (m_options.raw)
506
507 llvm::Expected<std::vector<AddressRange>> ranges =
509 if (!ranges) {
510 result.AppendError(toString(ranges.takeError()));
511 return;
512 }
513
514 bool print_sc_header = ranges->size() > 1;
515 for (AddressRange cur_range : *ranges) {
517 if (m_options.num_instructions == 0) {
518 limit = {Disassembler::Limit::Bytes, cur_range.GetByteSize()};
519 if (limit.value == 0)
521 } else {
523 }
525 GetDebugger(), m_options.arch, plugin_name, flavor_string,
526 m_exe_ctx, cur_range.GetBaseAddress(), limit, m_options.show_mixed,
528 result.GetOutputStream())) {
530 } else {
533 "Failed to disassemble memory in function at 0x%8.8" PRIx64 ".\n",
535 } else {
537 "Failed to disassemble memory at 0x%8.8" PRIx64 ".\n",
538 cur_range.GetBaseAddress().GetLoadAddress(&target));
539 }
540 }
541 if (print_sc_header)
542 result.GetOutputStream() << "\n";
543 }
544}
static constexpr unsigned default_disasm_num_ins
static constexpr unsigned default_disasm_byte_size
static llvm::raw_ostream & error(Stream &strm)
A section + offset based address range class.
Definition: AddressRange.h:25
bool Dump(Stream *s, Target *target, Address::DumpStyle style, Address::DumpStyle fallback_style=Address::DumpStyleInvalid) const
Dump a description of this object to a Stream.
lldb::addr_t GetByteSize() const
Get accessor for the byte size of this range.
Definition: AddressRange.h:223
A section + offset based address class.
Definition: Address.h:62
@ DumpStyleFileAddress
Display as the file address (if any).
Definition: Address.h:87
@ DumpStyleLoadAddress
Display as the load address (if resolved).
Definition: Address.h:99
bool IsValid() const
Tests if this ArchSpec is valid.
Definition: ArchSpec.h:348
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition: ArchSpec.h:450
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition: ArchSpec.cpp:552
A command line argument class.
Definition: Args.h:33
bool empty() const
Definition: Args.h:118
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void OptionParsingStarting(ExecutionContext *execution_context) override
Status OptionParsingFinished(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
llvm::Expected< std::vector< AddressRange > > GetCurrentFunctionRanges()
void DoExecute(Args &command, CommandReturnObject &result) override
llvm::Expected< std::vector< AddressRange > > GetStartEndAddressRanges()
llvm::Error CheckRangeSize(const AddressRange &range, llvm::StringRef what)
CommandObjectDisassemble(CommandInterpreter &interpreter)
llvm::Expected< std::vector< AddressRange > > GetNameRanges(CommandReturnObject &result)
llvm::Expected< std::vector< AddressRange > > GetPCRanges()
llvm::Expected< std::vector< AddressRange > > GetCurrentLineRanges()
llvm::Expected< std::vector< AddressRange > > GetContainingAddressRanges()
llvm::Expected< std::vector< AddressRange > > GetRangesForSelectedMode(CommandReturnObject &result)
ExecutionContext m_exe_ctx
CommandInterpreter & GetCommandInterpreter()
void void AppendError(llvm::StringRef in_string)
void AppendWarningWithFormat(const char *format,...) __attribute__((format(printf
void SetStatus(lldb::ReturnStatus status)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
void void AppendWarning(llvm::StringRef in_string)
A uniqued constant string class.
Definition: ConstString.h:40
const char * GetCString() const
Get the string value as a C string.
Definition: ConstString.h:216
uint64_t GetTerminalWidth() const
Definition: Debugger.cpp:367
static lldb::DisassemblerSP FindPlugin(const ArchSpec &arch, const char *flavor, const char *plugin_name)
static bool Disassemble(Debugger &debugger, const ArchSpec &arch, const char *plugin_name, const char *flavor, const ExecutionContext &exe_ctx, const Address &start, Limit limit, bool mixed_source_and_assembly, uint32_t num_mixed_context_lines, uint32_t options, Stream &strm)
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
const lldb::TargetSP & GetTargetSP() const
Get accessor to get the target shared pointer.
StackFrame * GetFramePtr() const
Returns a pointer to the frame object.
Target * GetTargetPtr() const
Returns a pointer to the target object.
Process * GetProcessPtr() const
Returns a pointer to the process object.
const AddressRange & GetAddressRange()
Definition: Function.h:447
void FindFunctions(ConstString name, lldb::FunctionNameType name_type_mask, const ModuleFunctionSearchOptions &options, SymbolContextList &sc_list) const
ModuleIterable Modules() const
Definition: ModuleList.h:527
void GenerateOptionUsage(Stream &strm, CommandObject &cmd, uint32_t screen_width)
Definition: Options.cpp:395
static ArchSpec GetAugmentedArchSpec(Platform *platform, llvm::StringRef triple)
Augments the triple either with information from platform or the host system (if platform is null).
Definition: Platform.cpp:227
A plug-in interface definition class for debugging a process.
Definition: Process.h:341
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, bool allow_section_end=false) const
This base class provides an interface to stack frames.
Definition: StackFrame.h:43
const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
Definition: StackFrame.cpp:300
const Address & GetFrameCodeAddress()
Get an Address for the current pc value in this StackFrame.
Definition: StackFrame.cpp:190
An error handling class.
Definition: Status.h:44
llvm::StringRef GetString() const
Defines a list of symbol context objects.
SymbolContextIterable SymbolContexts()
Defines a symbol context baton that can be handed other debug core functions.
Definition: SymbolContext.h:34
Function * function
The Function for a given query.
bool GetAddressRange(uint32_t scope, uint32_t range_idx, bool use_inline_block_range, AddressRange &range) const
Get the address range contained within a symbol context.
Symbol * symbol
The Symbol for a given query.
LineEntry line_entry
The LineEntry for a given query.
bool ValueIsAddress() const
Definition: Symbol.cpp:165
lldb::addr_t GetByteSize() const
Definition: Symbol.cpp:468
Address GetAddress() const
Definition: Symbol.h:88
const char * GetDisassemblyFlavor() const
Definition: Target.cpp:4338
SectionLoadList & GetSectionLoadList()
Definition: Target.h:1143
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition: Target.h:986
const ArchSpec & GetArchitecture() const
Definition: Target.h:1028
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:82
A class that represents a running process on the host machine.
const char * toString(AppleArm64ExceptionClass EC)
Definition: SBAddress.h:15
std::shared_ptr< lldb_private::Disassembler > DisassemblerSP
Definition: lldb-forward.h:339
@ eReturnStatusSuccessFinishResult
uint64_t addr_t
Definition: lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
Definition: lldb-forward.h:444
std::shared_ptr< lldb_private::Module > ModuleSP
Definition: lldb-forward.h:371
A line table entry class.
Definition: LineEntry.h:21
bool IsValid() const
Check if a line entry object is valid.
Definition: LineEntry.cpp:35
AddressRange range
The section offset address range for this line entry.
Definition: LineEntry.h:137
Options used by Module::FindFunctions.
Definition: Module.h:65
bool include_inlines
Include inlined functions.
Definition: Module.h:69
bool include_symbols
Include the symbol table.
Definition: Module.h:67
static lldb::addr_t ToAddress(const ExecutionContext *exe_ctx, llvm::StringRef s, lldb::addr_t fail_value, Status *error_ptr)
Try to parse an address.