]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Commands/CommandObjectDisassemble.cpp
Merge OpenSSL 1.0.2l.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Commands / CommandObjectDisassemble.cpp
1 //===-- CommandObjectDisassemble.cpp ----------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 // C Includes
11 // C++ Includes
12 // Other libraries and framework includes
13 // Project includes
14 #include "CommandObjectDisassemble.h"
15 #include "lldb/Core/AddressRange.h"
16 #include "lldb/Core/Disassembler.h"
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/SourceManager.h"
19 #include "lldb/Host/StringConvert.h"
20 #include "lldb/Interpreter/CommandCompletions.h"
21 #include "lldb/Interpreter/CommandInterpreter.h"
22 #include "lldb/Interpreter/CommandReturnObject.h"
23 #include "lldb/Interpreter/Options.h"
24 #include "lldb/Symbol/Function.h"
25 #include "lldb/Symbol/Symbol.h"
26 #include "lldb/Target/Process.h"
27 #include "lldb/Target/SectionLoadList.h"
28 #include "lldb/Target/StackFrame.h"
29 #include "lldb/Target/Target.h"
30
31 #define DEFAULT_DISASM_BYTE_SIZE 32
32 #define DEFAULT_DISASM_NUM_INS 4
33
34 using namespace lldb;
35 using namespace lldb_private;
36
37 static OptionDefinition g_disassemble_options[] = {
38     // clang-format off
39   { LLDB_OPT_SET_ALL, false, "bytes",         'b', OptionParser::eNoArgument,       nullptr, nullptr, 0,                                     eArgTypeNone,                "Show opcode bytes when disassembling." },
40   { LLDB_OPT_SET_ALL, false, "context",       'C', OptionParser::eRequiredArgument, nullptr, nullptr, 0,                                     eArgTypeNumLines,            "Number of context lines of source to show." },
41   { LLDB_OPT_SET_ALL, false, "mixed",         'm', OptionParser::eNoArgument,       nullptr, nullptr, 0,                                     eArgTypeNone,                "Enable mixed source and assembly display." },
42   { LLDB_OPT_SET_ALL, false, "raw",           'r', OptionParser::eNoArgument,       nullptr, nullptr, 0,                                     eArgTypeNone,                "Print raw disassembly with no symbol information." },
43   { LLDB_OPT_SET_ALL, false, "plugin",        'P', OptionParser::eRequiredArgument, nullptr, nullptr, 0,                                     eArgTypePlugin,              "Name of the disassembler plugin you want to use." },
44   { LLDB_OPT_SET_ALL, false, "flavor",        'F', OptionParser::eRequiredArgument, nullptr, nullptr, 0,                                     eArgTypeDisassemblyFlavor,   "Name of the disassembly flavor you want to use.  "
45   "Currently the only valid options are default, and for Intel "
46   "architectures, att and intel." },
47   { LLDB_OPT_SET_ALL, false, "arch",          'A', OptionParser::eRequiredArgument, nullptr, nullptr, 0,                                     eArgTypeArchitecture,        "Specify the architecture to use from cross disassembly." },
48   { LLDB_OPT_SET_1 |
49   LLDB_OPT_SET_2,   true,  "start-address", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0,                                     eArgTypeAddressOrExpression, "Address at which to start disassembling." },
50   { LLDB_OPT_SET_1,   false, "end-address",   'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0,                                     eArgTypeAddressOrExpression, "Address at which to end disassembling." },
51   { LLDB_OPT_SET_2 |
52   LLDB_OPT_SET_3 |
53   LLDB_OPT_SET_4 |
54   LLDB_OPT_SET_5,   false, "count",         'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0,                                     eArgTypeNumLines,            "Number of instructions to display." },
55   { LLDB_OPT_SET_3,   false, "name",          'n', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eSymbolCompletion, eArgTypeFunctionName,        "Disassemble entire contents of the given function name." },
56   { LLDB_OPT_SET_4,   false, "frame",         'f', OptionParser::eNoArgument,       nullptr, nullptr, 0,                                     eArgTypeNone,                "Disassemble from the start of the current frame's function." },
57   { LLDB_OPT_SET_5,   false, "pc",            'p', OptionParser::eNoArgument,       nullptr, nullptr, 0,                                     eArgTypeNone,                "Disassemble around the current pc." },
58   { LLDB_OPT_SET_6,   false, "line",          'l', OptionParser::eNoArgument,       nullptr, nullptr, 0,                                     eArgTypeNone,                "Disassemble the current frame's current source line instructions if there is debug line "
59   "table information, else disassemble around the pc." },
60   { LLDB_OPT_SET_7,   false, "address",       'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0,                                     eArgTypeAddressOrExpression, "Disassemble function containing this address." },
61     // clang-format on
62 };
63
64 CommandObjectDisassemble::CommandOptions::CommandOptions()
65     : Options(), num_lines_context(0), num_instructions(0), func_name(),
66       current_function(false), start_addr(), end_addr(), at_pc(false),
67       frame_line(false), plugin_name(), flavor_string(), arch(),
68       some_location_specified(false), symbol_containing_addr() {
69   OptionParsingStarting(nullptr);
70 }
71
72 CommandObjectDisassemble::CommandOptions::~CommandOptions() = default;
73
74 Error CommandObjectDisassemble::CommandOptions::SetOptionValue(
75     uint32_t option_idx, llvm::StringRef option_arg,
76     ExecutionContext *execution_context) {
77   Error error;
78
79   const int short_option = m_getopt_table[option_idx].val;
80
81   switch (short_option) {
82   case 'm':
83     show_mixed = true;
84     break;
85
86   case 'C':
87     if (option_arg.getAsInteger(0, num_lines_context))
88       error.SetErrorStringWithFormat("invalid num context lines string: \"%s\"",
89                                      option_arg.str().c_str());
90     break;
91
92   case 'c':
93     if (option_arg.getAsInteger(0, num_instructions))
94       error.SetErrorStringWithFormat(
95           "invalid num of instructions string: \"%s\"",
96           option_arg.str().c_str());
97     break;
98
99   case 'b':
100     show_bytes = true;
101     break;
102
103   case 's': {
104     start_addr = Args::StringToAddress(execution_context, option_arg,
105                                        LLDB_INVALID_ADDRESS, &error);
106     if (start_addr != LLDB_INVALID_ADDRESS)
107       some_location_specified = true;
108   } break;
109   case 'e': {
110     end_addr = Args::StringToAddress(execution_context, option_arg,
111                                      LLDB_INVALID_ADDRESS, &error);
112     if (end_addr != LLDB_INVALID_ADDRESS)
113       some_location_specified = true;
114   } break;
115
116   case 'n':
117     func_name.assign(option_arg);
118     some_location_specified = true;
119     break;
120
121   case 'p':
122     at_pc = true;
123     some_location_specified = true;
124     break;
125
126   case 'l':
127     frame_line = true;
128     // Disassemble the current source line kind of implies showing mixed
129     // source code context.
130     show_mixed = true;
131     some_location_specified = true;
132     break;
133
134   case 'P':
135     plugin_name.assign(option_arg);
136     break;
137
138   case 'F': {
139     TargetSP target_sp =
140         execution_context ? execution_context->GetTargetSP() : TargetSP();
141     if (target_sp && (target_sp->GetArchitecture().GetTriple().getArch() ==
142                           llvm::Triple::x86 ||
143                       target_sp->GetArchitecture().GetTriple().getArch() ==
144                           llvm::Triple::x86_64)) {
145       flavor_string.assign(option_arg);
146     } else
147       error.SetErrorStringWithFormat("Disassembler flavors are currently only "
148                                      "supported for x86 and x86_64 targets.");
149     break;
150   }
151
152   case 'r':
153     raw = true;
154     break;
155
156   case 'f':
157     current_function = true;
158     some_location_specified = true;
159     break;
160
161   case 'A':
162     if (execution_context) {
163       auto target_sp =
164           execution_context ? execution_context->GetTargetSP() : TargetSP();
165       auto platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP();
166       if (!arch.SetTriple(option_arg, platform_sp.get()))
167         arch.SetTriple(option_arg);
168     }
169     break;
170
171   case 'a': {
172     symbol_containing_addr = Args::StringToAddress(
173         execution_context, option_arg, LLDB_INVALID_ADDRESS, &error);
174     if (symbol_containing_addr != LLDB_INVALID_ADDRESS) {
175       some_location_specified = true;
176     }
177   } break;
178
179   default:
180     error.SetErrorStringWithFormat("unrecognized short option '%c'",
181                                    short_option);
182     break;
183   }
184
185   return error;
186 }
187
188 void CommandObjectDisassemble::CommandOptions::OptionParsingStarting(
189     ExecutionContext *execution_context) {
190   show_mixed = false;
191   show_bytes = false;
192   num_lines_context = 0;
193   num_instructions = 0;
194   func_name.clear();
195   current_function = false;
196   at_pc = false;
197   frame_line = false;
198   start_addr = LLDB_INVALID_ADDRESS;
199   end_addr = LLDB_INVALID_ADDRESS;
200   symbol_containing_addr = LLDB_INVALID_ADDRESS;
201   raw = false;
202   plugin_name.clear();
203
204   Target *target =
205       execution_context ? execution_context->GetTargetPtr() : nullptr;
206
207   // This is a hack till we get the ability to specify features based on
208   // architecture.  For now GetDisassemblyFlavor
209   // is really only valid for x86 (and for the llvm assembler plugin, but I'm
210   // papering over that since that is the
211   // only disassembler plugin we have...
212   if (target) {
213     if (target->GetArchitecture().GetTriple().getArch() == llvm::Triple::x86 ||
214         target->GetArchitecture().GetTriple().getArch() ==
215             llvm::Triple::x86_64) {
216       flavor_string.assign(target->GetDisassemblyFlavor());
217     } else
218       flavor_string.assign("default");
219
220   } else
221     flavor_string.assign("default");
222
223   arch.Clear();
224   some_location_specified = false;
225 }
226
227 Error CommandObjectDisassemble::CommandOptions::OptionParsingFinished(
228     ExecutionContext *execution_context) {
229   if (!some_location_specified)
230     current_function = true;
231   return Error();
232 }
233
234 llvm::ArrayRef<OptionDefinition>
235 CommandObjectDisassemble::CommandOptions::GetDefinitions() {
236   return llvm::makeArrayRef(g_disassemble_options);
237 }
238
239 //-------------------------------------------------------------------------
240 // CommandObjectDisassemble
241 //-------------------------------------------------------------------------
242
243 CommandObjectDisassemble::CommandObjectDisassemble(
244     CommandInterpreter &interpreter)
245     : CommandObjectParsed(
246           interpreter, "disassemble",
247           "Disassemble specified instructions in the current target.  "
248           "Defaults to the current function for the current thread and "
249           "stack frame.",
250           "disassemble [<cmd-options>]"),
251       m_options() {}
252
253 CommandObjectDisassemble::~CommandObjectDisassemble() = default;
254
255 bool CommandObjectDisassemble::DoExecute(Args &command,
256                                          CommandReturnObject &result) {
257   Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
258   if (target == nullptr) {
259     result.AppendError("invalid target, create a debug target using the "
260                        "'target create' command");
261     result.SetStatus(eReturnStatusFailed);
262     return false;
263   }
264   if (!m_options.arch.IsValid())
265     m_options.arch = target->GetArchitecture();
266
267   if (!m_options.arch.IsValid()) {
268     result.AppendError(
269         "use the --arch option or set the target architecture to disassemble");
270     result.SetStatus(eReturnStatusFailed);
271     return false;
272   }
273
274   const char *plugin_name = m_options.GetPluginName();
275   const char *flavor_string = m_options.GetFlavorString();
276
277   DisassemblerSP disassembler =
278       Disassembler::FindPlugin(m_options.arch, flavor_string, plugin_name);
279
280   if (!disassembler) {
281     if (plugin_name) {
282       result.AppendErrorWithFormat(
283           "Unable to find Disassembler plug-in named '%s' that supports the "
284           "'%s' architecture.\n",
285           plugin_name, m_options.arch.GetArchitectureName());
286     } else
287       result.AppendErrorWithFormat(
288           "Unable to find Disassembler plug-in for the '%s' architecture.\n",
289           m_options.arch.GetArchitectureName());
290     result.SetStatus(eReturnStatusFailed);
291     return false;
292   } else if (flavor_string != nullptr &&
293              !disassembler->FlavorValidForArchSpec(m_options.arch,
294                                                    flavor_string))
295     result.AppendWarningWithFormat(
296         "invalid disassembler flavor \"%s\", using default.\n", flavor_string);
297
298   result.SetStatus(eReturnStatusSuccessFinishResult);
299
300   if (!command.empty()) {
301     result.AppendErrorWithFormat(
302         "\"disassemble\" arguments are specified as options.\n");
303     const int terminal_width =
304         GetCommandInterpreter().GetDebugger().GetTerminalWidth();
305     GetOptions()->GenerateOptionUsage(result.GetErrorStream(), this,
306                                       terminal_width);
307     result.SetStatus(eReturnStatusFailed);
308     return false;
309   }
310
311   if (m_options.show_mixed && m_options.num_lines_context == 0)
312     m_options.num_lines_context = 2;
313
314   // Always show the PC in the disassembly
315   uint32_t options = Disassembler::eOptionMarkPCAddress;
316
317   // Mark the source line for the current PC only if we are doing mixed source
318   // and assembly
319   if (m_options.show_mixed)
320     options |= Disassembler::eOptionMarkPCSourceLine;
321
322   if (m_options.show_bytes)
323     options |= Disassembler::eOptionShowBytes;
324
325   if (m_options.raw)
326     options |= Disassembler::eOptionRawOuput;
327
328   if (!m_options.func_name.empty()) {
329     ConstString name(m_options.func_name.c_str());
330
331     if (Disassembler::Disassemble(
332             m_interpreter.GetDebugger(), m_options.arch, plugin_name,
333             flavor_string, m_exe_ctx, name,
334             nullptr, // Module *
335             m_options.num_instructions, m_options.show_mixed,
336             m_options.show_mixed ? m_options.num_lines_context : 0, options,
337             result.GetOutputStream())) {
338       result.SetStatus(eReturnStatusSuccessFinishResult);
339     } else {
340       result.AppendErrorWithFormat("Unable to find symbol with name '%s'.\n",
341                                    name.GetCString());
342       result.SetStatus(eReturnStatusFailed);
343     }
344   } else {
345     std::vector<AddressRange> ranges;
346     AddressRange range;
347     StackFrame *frame = m_exe_ctx.GetFramePtr();
348     if (m_options.frame_line) {
349       if (frame == nullptr) {
350         result.AppendError("Cannot disassemble around the current line without "
351                            "a selected frame.\n");
352         result.SetStatus(eReturnStatusFailed);
353         return false;
354       }
355       LineEntry pc_line_entry(
356           frame->GetSymbolContext(eSymbolContextLineEntry).line_entry);
357       if (pc_line_entry.IsValid()) {
358         range = pc_line_entry.range;
359       } else {
360         m_options.at_pc =
361             true; // No line entry, so just disassemble around the current pc
362         m_options.show_mixed = false;
363       }
364     } else if (m_options.current_function) {
365       if (frame == nullptr) {
366         result.AppendError("Cannot disassemble around the current function "
367                            "without a selected frame.\n");
368         result.SetStatus(eReturnStatusFailed);
369         return false;
370       }
371       Symbol *symbol = frame->GetSymbolContext(eSymbolContextSymbol).symbol;
372       if (symbol) {
373         range.GetBaseAddress() = symbol->GetAddress();
374         range.SetByteSize(symbol->GetByteSize());
375       }
376     }
377
378     // Did the "m_options.frame_line" find a valid range already? If so
379     // skip the rest...
380     if (range.GetByteSize() == 0) {
381       if (m_options.at_pc) {
382         if (frame == nullptr) {
383           result.AppendError("Cannot disassemble around the current PC without "
384                              "a selected frame.\n");
385           result.SetStatus(eReturnStatusFailed);
386           return false;
387         }
388         range.GetBaseAddress() = frame->GetFrameCodeAddress();
389         if (m_options.num_instructions == 0) {
390           // Disassembling at the PC always disassembles some number of
391           // instructions (not the whole function).
392           m_options.num_instructions = DEFAULT_DISASM_NUM_INS;
393         }
394         ranges.push_back(range);
395       } else {
396         range.GetBaseAddress().SetOffset(m_options.start_addr);
397         if (range.GetBaseAddress().IsValid()) {
398           if (m_options.end_addr != LLDB_INVALID_ADDRESS) {
399             if (m_options.end_addr <= m_options.start_addr) {
400               result.AppendErrorWithFormat(
401                   "End address before start address.\n");
402               result.SetStatus(eReturnStatusFailed);
403               return false;
404             }
405             range.SetByteSize(m_options.end_addr - m_options.start_addr);
406           }
407           ranges.push_back(range);
408         } else {
409           if (m_options.symbol_containing_addr != LLDB_INVALID_ADDRESS &&
410               target) {
411             if (!target->GetSectionLoadList().IsEmpty()) {
412               bool failed = false;
413               Address symbol_containing_address;
414               if (target->GetSectionLoadList().ResolveLoadAddress(
415                       m_options.symbol_containing_addr,
416                       symbol_containing_address)) {
417                 ModuleSP module_sp(symbol_containing_address.GetModule());
418                 SymbolContext sc;
419                 bool resolve_tail_call_address = true; // PC can be one past the
420                                                        // address range of the
421                                                        // function.
422                 module_sp->ResolveSymbolContextForAddress(
423                     symbol_containing_address, eSymbolContextEverything, sc,
424                     resolve_tail_call_address);
425                 if (sc.function || sc.symbol) {
426                   sc.GetAddressRange(eSymbolContextFunction |
427                                          eSymbolContextSymbol,
428                                      0, false, range);
429                 } else {
430                   failed = true;
431                 }
432               } else {
433                 failed = true;
434               }
435               if (failed) {
436                 result.AppendErrorWithFormat(
437                     "Could not find function bounds for address 0x%" PRIx64
438                     "\n",
439                     m_options.symbol_containing_addr);
440                 result.SetStatus(eReturnStatusFailed);
441                 return false;
442               }
443               ranges.push_back(range);
444             } else {
445               for (lldb::ModuleSP module_sp : target->GetImages().Modules()) {
446                 lldb::addr_t file_addr = m_options.symbol_containing_addr;
447                 Address file_address;
448                 if (module_sp->ResolveFileAddress(file_addr, file_address)) {
449                   SymbolContext sc;
450                   bool resolve_tail_call_address = true; // PC can be one past
451                                                          // the address range of
452                                                          // the function.
453                   module_sp->ResolveSymbolContextForAddress(
454                       file_address, eSymbolContextEverything, sc,
455                       resolve_tail_call_address);
456                   if (sc.function || sc.symbol) {
457                     sc.GetAddressRange(eSymbolContextFunction |
458                                            eSymbolContextSymbol,
459                                        0, false, range);
460                     ranges.push_back(range);
461                   }
462                 }
463               }
464             }
465           }
466         }
467       }
468     } else
469       ranges.push_back(range);
470
471     if (m_options.num_instructions != 0) {
472       if (ranges.empty()) {
473         // The default action is to disassemble the current frame function.
474         if (frame) {
475           SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction |
476                                                    eSymbolContextSymbol));
477           if (sc.function)
478             range.GetBaseAddress() =
479                 sc.function->GetAddressRange().GetBaseAddress();
480           else if (sc.symbol && sc.symbol->ValueIsAddress())
481             range.GetBaseAddress() = sc.symbol->GetAddress();
482           else
483             range.GetBaseAddress() = frame->GetFrameCodeAddress();
484         }
485
486         if (!range.GetBaseAddress().IsValid()) {
487           result.AppendError("invalid frame");
488           result.SetStatus(eReturnStatusFailed);
489           return false;
490         }
491       }
492
493       bool print_sc_header = ranges.size() > 1;
494       for (AddressRange cur_range : ranges) {
495         if (Disassembler::Disassemble(
496                 m_interpreter.GetDebugger(), m_options.arch, plugin_name,
497                 flavor_string, m_exe_ctx, cur_range.GetBaseAddress(),
498                 m_options.num_instructions, m_options.show_mixed,
499                 m_options.show_mixed ? m_options.num_lines_context : 0, options,
500                 result.GetOutputStream())) {
501           result.SetStatus(eReturnStatusSuccessFinishResult);
502         } else {
503           if (m_options.start_addr != LLDB_INVALID_ADDRESS)
504             result.AppendErrorWithFormat(
505                 "Failed to disassemble memory at 0x%8.8" PRIx64 ".\n",
506                 m_options.start_addr);
507           else if (m_options.symbol_containing_addr != LLDB_INVALID_ADDRESS)
508             result.AppendErrorWithFormat(
509                 "Failed to disassemble memory in function at 0x%8.8" PRIx64
510                 ".\n",
511                 m_options.symbol_containing_addr);
512           result.SetStatus(eReturnStatusFailed);
513         }
514       }
515       if (print_sc_header)
516         result.AppendMessage("\n");
517     } else {
518       if (ranges.empty()) {
519         // The default action is to disassemble the current frame function.
520         if (frame) {
521           SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction |
522                                                    eSymbolContextSymbol));
523           if (sc.function)
524             range = sc.function->GetAddressRange();
525           else if (sc.symbol && sc.symbol->ValueIsAddress()) {
526             range.GetBaseAddress() = sc.symbol->GetAddress();
527             range.SetByteSize(sc.symbol->GetByteSize());
528           } else
529             range.GetBaseAddress() = frame->GetFrameCodeAddress();
530         } else {
531           result.AppendError("invalid frame");
532           result.SetStatus(eReturnStatusFailed);
533           return false;
534         }
535         ranges.push_back(range);
536       }
537
538       bool print_sc_header = ranges.size() > 1;
539       for (AddressRange cur_range : ranges) {
540         if (cur_range.GetByteSize() == 0)
541           cur_range.SetByteSize(DEFAULT_DISASM_BYTE_SIZE);
542
543         if (Disassembler::Disassemble(
544                 m_interpreter.GetDebugger(), m_options.arch, plugin_name,
545                 flavor_string, m_exe_ctx, cur_range, m_options.num_instructions,
546                 m_options.show_mixed,
547                 m_options.show_mixed ? m_options.num_lines_context : 0, options,
548                 result.GetOutputStream())) {
549           result.SetStatus(eReturnStatusSuccessFinishResult);
550         } else {
551           result.AppendErrorWithFormat(
552               "Failed to disassemble memory at 0x%8.8" PRIx64 ".\n",
553               m_options.start_addr);
554           result.SetStatus(eReturnStatusFailed);
555         }
556         if (print_sc_header)
557           result.AppendMessage("\n");
558       }
559     }
560   }
561
562   return result.Succeeded();
563 }