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#include "llvm/Support/ErrorExtras.h"
25#include <iterator>
26
27static constexpr unsigned default_disasm_byte_size = 32;
28static constexpr unsigned default_disasm_num_ins = 4;
29
30using namespace lldb;
31using namespace lldb_private;
32
33#define LLDB_OPTIONS_disassemble
34#include "CommandOptions.inc"
35
39
41
43 uint32_t option_idx, llvm::StringRef option_arg,
44 ExecutionContext *execution_context) {
46
47 const int short_option = m_getopt_table[option_idx].val;
48
49 switch (short_option) {
50 case 'm':
51 show_mixed = true;
52 break;
53
54 case 'C':
55 if (option_arg.getAsInteger(0, num_lines_context))
57 "invalid num context lines string: \"%s\"", option_arg.str().c_str());
58 break;
59
60 case 'c':
61 if (option_arg.getAsInteger(0, num_instructions))
63 "invalid num of instructions string: \"%s\"",
64 option_arg.str().c_str());
65 break;
66
67 case 'b':
68 show_bytes = true;
69 break;
70
71 case 'k':
73 break;
74
75 case 's': {
76 start_addr = OptionArgParser::ToAddress(execution_context, option_arg,
80 } break;
81 case 'e': {
82 end_addr = OptionArgParser::ToAddress(execution_context, option_arg,
86 } break;
87
88 case 'n':
89 func_name.assign(std::string(option_arg));
91 break;
92
93 case 'p':
94 at_pc = true;
96 break;
97
98 case 'l':
99 frame_line = true;
100 // Disassemble the current source line kind of implies showing mixed source
101 // code context.
102 show_mixed = true;
104 break;
105
106 case 'P':
107 plugin_name.assign(std::string(option_arg));
108 break;
109
110 case 'F': {
111 TargetSP target_sp =
112 execution_context ? execution_context->GetTargetSP() : TargetSP();
113 if (target_sp && (target_sp->GetArchitecture().GetTriple().getArch() ==
114 llvm::Triple::x86 ||
115 target_sp->GetArchitecture().GetTriple().getArch() ==
116 llvm::Triple::x86_64)) {
117 flavor_string.assign(std::string(option_arg));
118 } else
120 "Disassembler flavors are currently only "
121 "supported for x86 and x86_64 targets.");
122 break;
123 }
124
125 case 'X':
126 cpu_string = std::string(option_arg);
127 break;
128
129 case 'Y':
130 features_string = std::string(option_arg);
131 break;
132
133 case 'r':
134 raw = true;
135 break;
136
137 case 'f':
138 current_function = true;
140 break;
141
142 case 'A':
143 if (execution_context) {
144 const auto &target_sp = execution_context->GetTargetSP();
145 auto platform_ptr = target_sp ? target_sp->GetPlatform().get() : nullptr;
146 arch = Platform::GetAugmentedArchSpec(platform_ptr, option_arg);
147 }
148 break;
149
150 case 'a': {
152 execution_context, option_arg, LLDB_INVALID_ADDRESS, &error);
155 }
156 } break;
157
158 case 'v':
160 break;
161
162 case '\x01':
163 force = true;
164 break;
165
166 default:
167 llvm_unreachable("Unimplemented option");
168 }
169
170 return error;
171}
172
174 ExecutionContext *execution_context) {
175 show_mixed = false;
176 show_bytes = false;
180 func_name.clear();
181 current_function = false;
182 at_pc = false;
183 frame_line = false;
187 raw = false;
189 plugin_name.clear();
190
191 Target *target =
192 execution_context ? execution_context->GetTargetPtr() : nullptr;
193
194 if (target) {
195 // This is a hack till we get the ability to specify features based on
196 // architecture. For now GetDisassemblyFlavor is really only valid for x86
197 // (and for the llvm assembler plugin, but I'm papering over that since that
198 // is the only disassembler plugin we have...
199 if (target->GetArchitecture().GetTriple().getArch() == llvm::Triple::x86 ||
200 target->GetArchitecture().GetTriple().getArch() ==
201 llvm::Triple::x86_64) {
202 flavor_string.assign(target->GetDisassemblyFlavor());
203 } else {
204 flavor_string.assign("default");
205 }
206 if (const char *cpu = target->GetDisassemblyCPU())
207 cpu_string.assign(cpu);
208 if (const char *features = target->GetDisassemblyFeatures())
209 features_string.assign(features);
210 } else {
211 flavor_string.assign("default");
212 cpu_string.assign("default");
213 features_string.assign("default");
214 }
215
216 arch.Clear();
218 force = false;
219}
220
227
228llvm::ArrayRef<OptionDefinition>
230 return llvm::ArrayRef(g_disassemble_options);
231}
232
233// CommandObjectDisassemble
234
236 CommandInterpreter &interpreter)
238 interpreter, "disassemble",
239 "Disassemble specified instructions in the current target. "
240 "Defaults to the current function for the current thread and "
241 "stack frame.",
242 "disassemble [<cmd-options>]", eCommandRequiresTarget) {}
243
245
246llvm::Expected<std::vector<AddressRange>>
247CommandObjectDisassemble::CheckRangeSize(std::vector<AddressRange> ranges,
248 llvm::StringRef what) {
249 addr_t total_range_size = 0;
250 for (const AddressRange &r : ranges)
251 total_range_size += r.GetByteSize();
252
253 if (m_options.num_instructions > 0 || m_options.force ||
254 total_range_size < GetDebugger().GetStopDisassemblyMaxSize())
255 return ranges;
256
257 StreamString msg;
258 msg << "not disassembling " << what << " because it is very large ";
259 for (const AddressRange &r : ranges)
262 msg << ". To disassemble specify an instruction count limit, start/stop "
263 "addresses or use the --force option";
264 return llvm::createStringError(msg.GetString());
265}
266
267llvm::Expected<std::vector<AddressRange>>
269 std::vector<AddressRange> ranges;
270 const auto &get_ranges = [&](Address addr) {
271 ModuleSP module_sp(addr.GetModule());
272 SymbolContext sc;
273 bool resolve_tail_call_address = true;
274 addr.GetModule()->ResolveSymbolContextForAddress(
275 addr, eSymbolContextEverything, sc, resolve_tail_call_address);
276 if (sc.function || sc.symbol) {
277 AddressRange range;
278 for (uint32_t idx = 0;
279 sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol,
280 idx, false, range);
281 ++idx)
282 ranges.push_back(range);
283 }
284 };
285
286 Target *target = GetTarget();
287 assert(target && "target guaranteed by eCommandRequiresTarget");
288 if (target->HasLoadedSections()) {
289 Address symbol_containing_address;
290 if (target->ResolveLoadAddress(m_options.symbol_containing_addr,
291 symbol_containing_address)) {
292 get_ranges(symbol_containing_address);
293 }
294 } else {
295 for (lldb::ModuleSP module_sp : target->GetImages().Modules()) {
296 Address file_address;
297 if (module_sp->ResolveFileAddress(m_options.symbol_containing_addr,
298 file_address)) {
299 get_ranges(file_address);
300 }
301 }
302 }
303
304 if (ranges.empty()) {
305 return llvm::createStringError(
306 llvm::inconvertibleErrorCode(),
307 "Could not find function bounds for address 0x%" PRIx64,
308 m_options.symbol_containing_addr);
309 }
310
311 return CheckRangeSize(std::move(ranges), "the function");
312}
313
314llvm::Expected<std::vector<AddressRange>>
316 Process *process = m_exe_ctx.GetProcessPtr();
317 StackFrame *frame = m_exe_ctx.GetFramePtr();
318 if (!frame) {
319 if (process) {
320 return llvm::createStringError(
321 "Cannot disassemble around the current function without the process "
322 "being stopped.\n");
323 }
324 return llvm::createStringError(
325 "Cannot disassemble around the current function without a selected "
326 "frame: no currently running process.\n");
327 }
328 SymbolContext sc =
329 frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol);
330 std::vector<AddressRange> ranges;
331 if (sc.function)
332 ranges = sc.function->GetAddressRanges();
333 else if (sc.symbol && sc.symbol->ValueIsAddress())
334 ranges.emplace_back(sc.symbol->GetAddress(), sc.symbol->GetByteSize());
335 else
336 ranges.emplace_back(frame->GetFrameCodeAddress(), default_disasm_byte_size);
337
338 return CheckRangeSize(std::move(ranges), "the current function");
339}
340
341llvm::Expected<std::vector<AddressRange>>
343 Process *process = m_exe_ctx.GetProcessPtr();
344 StackFrame *frame = m_exe_ctx.GetFramePtr();
345 if (!frame) {
346 if (process) {
347 return llvm::createStringError(
348 llvm::inconvertibleErrorCode(),
349 "Cannot disassemble around the current "
350 "function without the process being stopped.\n");
351 } else {
352 return llvm::createStringError(llvm::inconvertibleErrorCode(),
353 "Cannot disassemble around the current "
354 "line without a selected frame: "
355 "no currently running process.\n");
356 }
357 }
358
359 LineEntry pc_line_entry(
360 frame->GetSymbolContext(eSymbolContextLineEntry).line_entry);
361 if (pc_line_entry.IsValid())
362 return std::vector<AddressRange>{pc_line_entry.range};
363
364 // No line entry, so just disassemble around the current pc
365 m_options.show_mixed = false;
366 return GetPCRanges();
367}
368
369llvm::Expected<std::vector<AddressRange>>
371 llvm::StringRef name = m_options.func_name;
372
373 ModuleFunctionSearchOptions function_options;
374 function_options.include_symbols = true;
375 function_options.include_inlines = true;
376
377 // Find functions matching the given name.
378 SymbolContextList sc_list;
379 GetTarget()->GetImages().FindFunctions(name, eFunctionNameTypeAuto,
380 function_options, sc_list);
381
382 std::vector<AddressRange> ranges;
383 llvm::Error range_errs = llvm::Error::success();
384 const uint32_t scope =
385 eSymbolContextBlock | eSymbolContextFunction | eSymbolContextSymbol;
386 const bool use_inline_block_range = true;
387 for (SymbolContext sc : sc_list.SymbolContexts()) {
388 std::vector<AddressRange> fn_ranges;
389 AddressRange range;
390 for (uint32_t range_idx = 0;
391 sc.GetAddressRange(scope, range_idx, use_inline_block_range, range);
392 ++range_idx)
393 fn_ranges.push_back(std::move(range));
394
395 if (llvm::Expected<std::vector<AddressRange>> checked_ranges =
396 CheckRangeSize(std::move(fn_ranges), "a function"))
397 llvm::move(*checked_ranges, std::back_inserter(ranges));
398 else
399 range_errs =
400 joinErrors(std::move(range_errs), checked_ranges.takeError());
401 }
402 if (ranges.empty()) {
403 if (range_errs)
404 return std::move(range_errs);
405 return llvm::createStringErrorV("Unable to find symbol with name '{0}'.\n",
406 name);
407 }
408 if (range_errs)
409 result.AppendWarning(toString(std::move(range_errs)));
410 return ranges;
411}
412
413llvm::Expected<std::vector<AddressRange>>
415 Process *process = m_exe_ctx.GetProcessPtr();
416 StackFrame *frame = m_exe_ctx.GetFramePtr();
417 if (!frame) {
418 if (process) {
419 return llvm::createStringError(
420 llvm::inconvertibleErrorCode(),
421 "Cannot disassemble around the current "
422 "function without the process being stopped.\n");
423 } else {
424 return llvm::createStringError(llvm::inconvertibleErrorCode(),
425 "Cannot disassemble around the current "
426 "PC without a selected frame: "
427 "no currently running process.\n");
428 }
429 }
430
431 if (m_options.num_instructions == 0) {
432 // Disassembling at the PC always disassembles some number of
433 // instructions (not the whole function).
434 m_options.num_instructions = default_disasm_num_ins;
435 }
436 return std::vector<AddressRange>{{frame->GetFrameCodeAddress(), 0}};
437}
438
439llvm::Expected<std::vector<AddressRange>>
441 addr_t size = 0;
442 if (m_options.end_addr != LLDB_INVALID_ADDRESS) {
443 if (m_options.end_addr <= m_options.start_addr) {
444 return llvm::createStringError(llvm::inconvertibleErrorCode(),
445 "End address before start address.");
446 }
447 size = m_options.end_addr - m_options.start_addr;
448 }
449 return std::vector<AddressRange>{{Address(m_options.start_addr), size}};
450}
451
452llvm::Expected<std::vector<AddressRange>>
467
469 CommandReturnObject &result) {
470 Target *target = GetTarget();
471 assert(target && "target guaranteed by eCommandRequiresTarget");
472 if (!m_options.arch.IsValid())
473 m_options.arch = target->GetArchitecture();
474
475 if (!m_options.arch.IsValid()) {
476 result.AppendError(
477 "use the --arch option or set the target architecture to disassemble");
478 return;
479 }
480
481 const char *plugin_name = m_options.GetPluginName();
482 const char *flavor_string = m_options.GetFlavorString();
483 const char *cpu_string = m_options.GetCPUString();
484 const char *features_string = m_options.GetFeaturesString();
485
487 m_options.arch, flavor_string, cpu_string, features_string, plugin_name);
488
489 if (!disassembler) {
490 if (plugin_name) {
492 "Unable to find Disassembler plug-in named '%s' that supports the "
493 "'%s' architecture",
494 plugin_name, m_options.arch.GetArchitectureName());
495 } else
497 "Unable to find Disassembler plug-in for the '%s' architecture",
498 m_options.arch.GetArchitectureName());
499 return;
500 } else if (flavor_string != nullptr && !disassembler->FlavorValidForArchSpec(
501 m_options.arch, flavor_string))
503 "invalid disassembler flavor \"{0}\", using default", flavor_string);
504
506
507 if (!command.empty()) {
509 "\"disassemble\" arguments are specified as options");
510 const int terminal_width =
512 const bool use_color = GetCommandInterpreter().GetDebugger().GetUseColor();
514 terminal_width, use_color);
515 return;
516 }
517
518 if (m_options.show_mixed && m_options.num_lines_context == 0)
519 m_options.num_lines_context = 2;
520
521 // Always show the PC in the disassembly
522 uint32_t options = Disassembler::eOptionMarkPCAddress;
523
524 // Mark the source line for the current PC only if we are doing mixed source
525 // and assembly
526 if (m_options.show_mixed)
528
529 if (m_options.show_bytes)
531
532 if (m_options.show_control_flow_kind)
534
535 if (m_options.raw)
537
538 if (m_options.enable_variable_annotations)
540
541 llvm::Expected<std::vector<AddressRange>> ranges =
543 if (!ranges) {
544 result.AppendError(toString(ranges.takeError()));
545 return;
546 }
547
548 bool print_sc_header = ranges->size() > 1;
549 for (AddressRange cur_range : *ranges) {
551 if (m_options.num_instructions == 0) {
552 limit = {Disassembler::Limit::Bytes, cur_range.GetByteSize()};
553 if (limit.value == 0)
555 } else {
556 limit = {Disassembler::Limit::Instructions, m_options.num_instructions};
557 }
559 GetDebugger(), m_options.arch, plugin_name, flavor_string,
560 cpu_string, features_string, m_exe_ctx, cur_range.GetBaseAddress(),
561 limit, m_options.show_mixed,
562 m_options.show_mixed ? m_options.num_lines_context : 0, options,
563 result.GetOutputStream())) {
565 } else {
566 if (m_options.symbol_containing_addr != LLDB_INVALID_ADDRESS) {
568 "Failed to disassemble memory in function at 0x%8.8" PRIx64,
569 m_options.symbol_containing_addr);
570 } else {
572 "Failed to disassemble memory at 0x%8.8" PRIx64,
573 cur_range.GetBaseAddress().GetLoadAddress(target));
574 }
575 }
576 if (print_sc_header)
577 result.GetOutputStream() << "\n";
578 }
579}
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.
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
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:465
A command line argument class.
Definition Args.h:33
bool empty() const
Definition Args.h:122
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()
CommandObjectDisassemble(CommandInterpreter &interpreter)
llvm::Expected< std::vector< AddressRange > > GetNameRanges(CommandReturnObject &result)
llvm::Expected< std::vector< AddressRange > > GetPCRanges()
llvm::Expected< std::vector< AddressRange > > CheckRangeSize(std::vector< AddressRange > ranges, llvm::StringRef what)
llvm::Expected< std::vector< AddressRange > > GetCurrentLineRanges()
llvm::Expected< std::vector< AddressRange > > GetContainingAddressRanges()
llvm::Expected< std::vector< AddressRange > > GetRangesForSelectedMode(CommandReturnObject &result)
CommandObjectParsed(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandInterpreter & GetCommandInterpreter()
Target * GetTarget()
Get the target this command should operate on.
void AppendError(llvm::StringRef in_string)
void AppendWarningWithFormatv(const char *format, Args &&...args)
void SetStatus(lldb::ReturnStatus status)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
void AppendWarning(llvm::StringRef in_string)
uint64_t GetTerminalWidth() const
Definition Debugger.cpp:481
bool GetUseColor() const
Definition Debugger.cpp:544
static lldb::DisassemblerSP FindPlugin(const ArchSpec &arch, const char *flavor, const char *cpu, const char *features, const char *plugin_name)
static bool Disassemble(Debugger &debugger, const ArchSpec &arch, const char *plugin_name, const char *flavor, const char *cpu, const char *features, 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.
Target * GetTargetPtr() const
Returns a pointer to the target object.
AddressRanges GetAddressRanges()
Definition Function.h:434
void FindFunctions(llvm::StringRef name, lldb::FunctionNameType name_type_mask, const ModuleFunctionSearchOptions &options, SymbolContextList &sc_list) const
ModuleIterable Modules() const
Definition ModuleList.h:586
void GenerateOptionUsage(Stream &strm, CommandObject &cmd, uint32_t screen_width, bool use_color)
Definition Options.cpp:351
std::vector< Option > m_getopt_table
Definition Options.h:198
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:332
A plug-in interface definition class for debugging a process.
Definition Process.h:370
This base class provides an interface to stack frames.
Definition StackFrame.h:44
virtual const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
virtual const Address & GetFrameCodeAddress()
Get an Address for the current pc value in this StackFrame.
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
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.
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:192
lldb::addr_t GetByteSize() const
Definition Symbol.cpp:470
Address GetAddress() const
Definition Symbol.h:98
const char * GetDisassemblyFeatures() const
Definition Target.cpp:5534
const char * GetDisassemblyFlavor() const
Definition Target.cpp:5514
const char * GetDisassemblyCPU() const
Definition Target.cpp:5527
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow, bool allow_section_end=false)
Definition Target.cpp:3638
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1295
const ArchSpec & GetArchitecture() const
Definition Target.h:1337
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
std::string toString(FormatterBytecode::OpCodes op)
std::shared_ptr< lldb_private::Disassembler > DisassemblerSP
@ eReturnStatusSuccessFinishResult
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::Module > ModuleSP
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:68
bool include_inlines
Include inlined functions.
Definition Module.h:72
bool include_symbols
Include the symbol table.
Definition Module.h:70
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.