1 //===-- Disassembler.cpp ----------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Core/Disassembler.h"
12 #include "lldb/Core/AddressRange.h"
13 #include "lldb/Core/Debugger.h"
14 #include "lldb/Core/EmulateInstruction.h"
15 #include "lldb/Core/Mangled.h"
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/ModuleList.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Core/SourceManager.h"
20 #include "lldb/Host/FileSystem.h"
21 #include "lldb/Interpreter/OptionValue.h"
22 #include "lldb/Interpreter/OptionValueArray.h"
23 #include "lldb/Interpreter/OptionValueDictionary.h"
24 #include "lldb/Interpreter/OptionValueRegex.h"
25 #include "lldb/Interpreter/OptionValueString.h"
26 #include "lldb/Interpreter/OptionValueUInt64.h"
27 #include "lldb/Symbol/Function.h"
28 #include "lldb/Symbol/Symbol.h"
29 #include "lldb/Symbol/SymbolContext.h"
30 #include "lldb/Target/ExecutionContext.h"
31 #include "lldb/Target/SectionLoadList.h"
32 #include "lldb/Target/StackFrame.h"
33 #include "lldb/Target/Target.h"
34 #include "lldb/Target/Thread.h"
35 #include "lldb/Utility/DataBufferHeap.h"
36 #include "lldb/Utility/DataExtractor.h"
37 #include "lldb/Utility/RegularExpression.h"
38 #include "lldb/Utility/Status.h"
39 #include "lldb/Utility/Stream.h"
40 #include "lldb/Utility/StreamString.h"
41 #include "lldb/Utility/Timer.h"
42 #include "lldb/lldb-private-enumerations.h"
43 #include "lldb/lldb-private-interfaces.h"
44 #include "lldb/lldb-private-types.h"
45 #include "llvm/ADT/Triple.h"
46 #include "llvm/Support/Compiler.h"
54 #define DEFAULT_DISASM_BYTE_SIZE 32
57 using namespace lldb_private;
59 DisassemblerSP Disassembler::FindPlugin(const ArchSpec &arch,
61 const char *plugin_name) {
62 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
63 Timer scoped_timer(func_cat,
64 "Disassembler::FindPlugin (arch = %s, plugin_name = %s)",
65 arch.GetArchitectureName(), plugin_name);
67 DisassemblerCreateInstance create_callback = nullptr;
70 ConstString const_plugin_name(plugin_name);
71 create_callback = PluginManager::GetDisassemblerCreateCallbackForPluginName(
73 if (create_callback) {
74 DisassemblerSP disassembler_sp(create_callback(arch, flavor));
77 return disassembler_sp;
80 for (uint32_t idx = 0;
81 (create_callback = PluginManager::GetDisassemblerCreateCallbackAtIndex(
84 DisassemblerSP disassembler_sp(create_callback(arch, flavor));
87 return disassembler_sp;
90 return DisassemblerSP();
93 DisassemblerSP Disassembler::FindPluginForTarget(const TargetSP target_sp,
96 const char *plugin_name) {
97 if (target_sp && flavor == nullptr) {
98 // FIXME - we don't have the mechanism in place to do per-architecture
99 // settings. But since we know that for now we only support flavors on x86
101 if (arch.GetTriple().getArch() == llvm::Triple::x86 ||
102 arch.GetTriple().getArch() == llvm::Triple::x86_64)
103 flavor = target_sp->GetDisassemblyFlavor();
105 return FindPlugin(arch, flavor, plugin_name);
108 static void ResolveAddress(const ExecutionContext &exe_ctx, const Address &addr,
109 Address &resolved_addr) {
110 if (!addr.IsSectionOffset()) {
111 // If we weren't passed in a section offset address range, try and resolve
113 Target *target = exe_ctx.GetTargetPtr();
116 target->GetSectionLoadList().IsEmpty() ?
117 target->GetImages().ResolveFileAddress(addr.GetOffset(),
119 target->GetSectionLoadList().ResolveLoadAddress(addr.GetOffset(),
122 // We weren't able to resolve the address, just treat it as a raw address
123 if (is_resolved && resolved_addr.IsValid())
127 resolved_addr = addr;
130 size_t Disassembler::Disassemble(Debugger &debugger, const ArchSpec &arch,
131 const char *plugin_name, const char *flavor,
132 const ExecutionContext &exe_ctx,
133 SymbolContextList &sc_list,
134 uint32_t num_instructions,
135 bool mixed_source_and_assembly,
136 uint32_t num_mixed_context_lines,
137 uint32_t options, Stream &strm) {
138 size_t success_count = 0;
139 const size_t count = sc_list.GetSize();
142 const uint32_t scope =
143 eSymbolContextBlock | eSymbolContextFunction | eSymbolContextSymbol;
144 const bool use_inline_block_range = true;
145 for (size_t i = 0; i < count; ++i) {
146 if (!sc_list.GetContextAtIndex(i, sc))
148 for (uint32_t range_idx = 0;
149 sc.GetAddressRange(scope, range_idx, use_inline_block_range, range);
151 if (Disassemble(debugger, arch, plugin_name, flavor, exe_ctx, range,
152 num_instructions, mixed_source_and_assembly,
153 num_mixed_context_lines, options, strm)) {
159 return success_count;
162 bool Disassembler::Disassemble(Debugger &debugger, const ArchSpec &arch,
163 const char *plugin_name, const char *flavor,
164 const ExecutionContext &exe_ctx,
165 const ConstString &name, Module *module,
166 uint32_t num_instructions,
167 bool mixed_source_and_assembly,
168 uint32_t num_mixed_context_lines,
169 uint32_t options, Stream &strm) {
170 SymbolContextList sc_list;
172 const bool include_symbols = true;
173 const bool include_inlines = true;
175 module->FindFunctions(name, nullptr, eFunctionNameTypeAuto,
176 include_symbols, include_inlines, true, sc_list);
177 } else if (exe_ctx.GetTargetPtr()) {
178 exe_ctx.GetTargetPtr()->GetImages().FindFunctions(
179 name, eFunctionNameTypeAuto, include_symbols, include_inlines, false,
184 if (sc_list.GetSize()) {
185 return Disassemble(debugger, arch, plugin_name, flavor, exe_ctx, sc_list,
186 num_instructions, mixed_source_and_assembly,
187 num_mixed_context_lines, options, strm);
192 lldb::DisassemblerSP Disassembler::DisassembleRange(
193 const ArchSpec &arch, const char *plugin_name, const char *flavor,
194 const ExecutionContext &exe_ctx, const AddressRange &range,
195 bool prefer_file_cache) {
196 lldb::DisassemblerSP disasm_sp;
197 if (range.GetByteSize() > 0 && range.GetBaseAddress().IsValid()) {
198 disasm_sp = Disassembler::FindPluginForTarget(exe_ctx.GetTargetSP(), arch,
199 flavor, plugin_name);
202 size_t bytes_disassembled = disasm_sp->ParseInstructions(
203 &exe_ctx, range, nullptr, prefer_file_cache);
204 if (bytes_disassembled == 0)
212 Disassembler::DisassembleBytes(const ArchSpec &arch, const char *plugin_name,
213 const char *flavor, const Address &start,
214 const void *src, size_t src_len,
215 uint32_t num_instructions, bool data_from_file) {
216 lldb::DisassemblerSP disasm_sp;
219 disasm_sp = Disassembler::FindPlugin(arch, flavor, plugin_name);
222 DataExtractor data(src, src_len, arch.GetByteOrder(),
223 arch.GetAddressByteSize());
225 (void)disasm_sp->DecodeInstructions(start, data, 0, num_instructions,
226 false, data_from_file);
233 bool Disassembler::Disassemble(Debugger &debugger, const ArchSpec &arch,
234 const char *plugin_name, const char *flavor,
235 const ExecutionContext &exe_ctx,
236 const AddressRange &disasm_range,
237 uint32_t num_instructions,
238 bool mixed_source_and_assembly,
239 uint32_t num_mixed_context_lines,
240 uint32_t options, Stream &strm) {
241 if (disasm_range.GetByteSize()) {
242 lldb::DisassemblerSP disasm_sp(Disassembler::FindPluginForTarget(
243 exe_ctx.GetTargetSP(), arch, flavor, plugin_name));
247 ResolveAddress(exe_ctx, disasm_range.GetBaseAddress(),
248 range.GetBaseAddress());
249 range.SetByteSize(disasm_range.GetByteSize());
250 const bool prefer_file_cache = false;
251 size_t bytes_disassembled = disasm_sp->ParseInstructions(
252 &exe_ctx, range, &strm, prefer_file_cache);
253 if (bytes_disassembled == 0)
256 return PrintInstructions(disasm_sp.get(), debugger, arch, exe_ctx,
257 num_instructions, mixed_source_and_assembly,
258 num_mixed_context_lines, options, strm);
264 bool Disassembler::Disassemble(Debugger &debugger, const ArchSpec &arch,
265 const char *plugin_name, const char *flavor,
266 const ExecutionContext &exe_ctx,
267 const Address &start_address,
268 uint32_t num_instructions,
269 bool mixed_source_and_assembly,
270 uint32_t num_mixed_context_lines,
271 uint32_t options, Stream &strm) {
272 if (num_instructions > 0) {
273 lldb::DisassemblerSP disasm_sp(Disassembler::FindPluginForTarget(
274 exe_ctx.GetTargetSP(), arch, flavor, plugin_name));
277 ResolveAddress(exe_ctx, start_address, addr);
278 const bool prefer_file_cache = false;
279 size_t bytes_disassembled = disasm_sp->ParseInstructions(
280 &exe_ctx, addr, num_instructions, prefer_file_cache);
281 if (bytes_disassembled == 0)
283 return PrintInstructions(disasm_sp.get(), debugger, arch, exe_ctx,
284 num_instructions, mixed_source_and_assembly,
285 num_mixed_context_lines, options, strm);
291 Disassembler::SourceLine
292 Disassembler::GetFunctionDeclLineEntry(const SymbolContext &sc) {
293 SourceLine decl_line;
294 if (sc.function && sc.line_entry.IsValid()) {
295 LineEntry prologue_end_line = sc.line_entry;
296 FileSpec func_decl_file;
297 uint32_t func_decl_line;
298 sc.function->GetStartLineSourceInfo(func_decl_file, func_decl_line);
299 if (func_decl_file == prologue_end_line.file ||
300 func_decl_file == prologue_end_line.original_file) {
301 decl_line.file = func_decl_file;
302 decl_line.line = func_decl_line;
303 // TODO do we care about column on these entries? If so, we need to
304 // plumb that through GetStartLineSourceInfo.
305 decl_line.column = 0;
311 void Disassembler::AddLineToSourceLineTables(
313 std::map<FileSpec, std::set<uint32_t>> &source_lines_seen) {
314 if (line.IsValid()) {
315 auto source_lines_seen_pos = source_lines_seen.find(line.file);
316 if (source_lines_seen_pos == source_lines_seen.end()) {
317 std::set<uint32_t> lines;
318 lines.insert(line.line);
319 source_lines_seen.emplace(line.file, lines);
321 source_lines_seen_pos->second.insert(line.line);
326 bool Disassembler::ElideMixedSourceAndDisassemblyLine(
327 const ExecutionContext &exe_ctx, const SymbolContext &sc,
330 // TODO: should we also check target.process.thread.step-avoid-libraries ?
332 const RegularExpression *avoid_regex = nullptr;
334 // Skip any line #0 entries - they are implementation details
338 ThreadSP thread_sp = exe_ctx.GetThreadSP();
340 avoid_regex = thread_sp->GetSymbolsToAvoidRegexp();
342 TargetSP target_sp = exe_ctx.GetTargetSP();
345 OptionValueSP value_sp = target_sp->GetDebugger().GetPropertyValue(
346 &exe_ctx, "target.process.thread.step-avoid-regexp", false, error);
347 if (value_sp && value_sp->GetType() == OptionValue::eTypeRegex) {
348 OptionValueRegex *re = value_sp->GetAsRegex();
350 avoid_regex = re->GetCurrentValue();
355 if (avoid_regex && sc.symbol != nullptr) {
356 const char *function_name =
357 sc.GetFunctionName(Mangled::ePreferDemangledWithoutArguments)
360 RegularExpression::Match regex_match(1);
361 if (avoid_regex->Execute(function_name, ®ex_match)) {
362 // skip this source line
367 // don't skip this source line
371 bool Disassembler::PrintInstructions(Disassembler *disasm_ptr,
372 Debugger &debugger, const ArchSpec &arch,
373 const ExecutionContext &exe_ctx,
374 uint32_t num_instructions,
375 bool mixed_source_and_assembly,
376 uint32_t num_mixed_context_lines,
377 uint32_t options, Stream &strm) {
378 // We got some things disassembled...
379 size_t num_instructions_found = disasm_ptr->GetInstructionList().GetSize();
381 if (num_instructions > 0 && num_instructions < num_instructions_found)
382 num_instructions_found = num_instructions;
384 const uint32_t max_opcode_byte_size =
385 disasm_ptr->GetInstructionList().GetMaxOpcocdeByteSize();
387 SymbolContext prev_sc;
388 AddressRange current_source_line_range;
389 const Address *pc_addr_ptr = nullptr;
390 StackFrame *frame = exe_ctx.GetFramePtr();
392 TargetSP target_sp(exe_ctx.GetTargetSP());
393 SourceManager &source_manager =
394 target_sp ? target_sp->GetSourceManager() : debugger.GetSourceManager();
397 pc_addr_ptr = &frame->GetFrameCodeAddress();
399 const uint32_t scope =
400 eSymbolContextLineEntry | eSymbolContextFunction | eSymbolContextSymbol;
401 const bool use_inline_block_range = false;
403 const FormatEntity::Entry *disassembly_format = nullptr;
404 FormatEntity::Entry format;
405 if (exe_ctx.HasTargetScope()) {
407 exe_ctx.GetTargetRef().GetDebugger().GetDisassemblyFormat();
409 FormatEntity::Parse("${addr}: ", format);
410 disassembly_format = &format;
413 // First pass: step through the list of instructions, find how long the
414 // initial addresses strings are, insert padding in the second pass so the
415 // opcodes all line up nicely.
417 // Also build up the source line mapping if this is mixed source & assembly
418 // mode. Calculate the source line for each assembly instruction (eliding
419 // inlined functions which the user wants to skip).
421 std::map<FileSpec, std::set<uint32_t>> source_lines_seen;
422 Symbol *previous_symbol = nullptr;
424 size_t address_text_size = 0;
425 for (size_t i = 0; i < num_instructions_found; ++i) {
427 disasm_ptr->GetInstructionList().GetInstructionAtIndex(i).get();
429 const Address &addr = inst->GetAddress();
430 ModuleSP module_sp(addr.GetModule());
432 const SymbolContextItem resolve_mask = eSymbolContextFunction |
433 eSymbolContextSymbol |
434 eSymbolContextLineEntry;
435 uint32_t resolved_mask =
436 module_sp->ResolveSymbolContextForAddress(addr, resolve_mask, sc);
438 StreamString strmstr;
439 Debugger::FormatDisassemblerAddress(disassembly_format, &sc, nullptr,
440 &exe_ctx, &addr, strmstr);
441 size_t cur_line = strmstr.GetSizeOfLastLine();
442 if (cur_line > address_text_size)
443 address_text_size = cur_line;
445 // Add entries to our "source_lines_seen" map+set which list which
446 // sources lines occur in this disassembly session. We will print
447 // lines of context around a source line, but we don't want to print
448 // a source line that has a line table entry of its own - we'll leave
449 // that source line to be printed when it actually occurs in the
452 if (mixed_source_and_assembly && sc.line_entry.IsValid()) {
453 if (sc.symbol != previous_symbol) {
454 SourceLine decl_line = GetFunctionDeclLineEntry(sc);
455 if (!ElideMixedSourceAndDisassemblyLine(exe_ctx, sc, decl_line))
456 AddLineToSourceLineTables(decl_line, source_lines_seen);
458 if (sc.line_entry.IsValid()) {
459 SourceLine this_line;
460 this_line.file = sc.line_entry.file;
461 this_line.line = sc.line_entry.line;
462 this_line.column = sc.line_entry.column;
463 if (!ElideMixedSourceAndDisassemblyLine(exe_ctx, sc, this_line))
464 AddLineToSourceLineTables(this_line, source_lines_seen);
473 previous_symbol = nullptr;
474 SourceLine previous_line;
475 for (size_t i = 0; i < num_instructions_found; ++i) {
477 disasm_ptr->GetInstructionList().GetInstructionAtIndex(i).get();
480 const Address &addr = inst->GetAddress();
481 const bool inst_is_at_pc = pc_addr_ptr && addr == *pc_addr_ptr;
482 SourceLinesToDisplay source_lines_to_display;
486 ModuleSP module_sp(addr.GetModule());
488 uint32_t resolved_mask = module_sp->ResolveSymbolContextForAddress(
489 addr, eSymbolContextEverything, sc);
491 if (mixed_source_and_assembly) {
493 // If we've started a new function (non-inlined), print all of the
494 // source lines from the function declaration until the first line
495 // table entry - typically the opening curly brace of the function.
496 if (previous_symbol != sc.symbol) {
497 // The default disassembly format puts an extra blank line
498 // between functions - so when we're displaying the source
499 // context for a function, we don't want to add a blank line
500 // after the source context or we'll end up with two of them.
501 if (previous_symbol != nullptr)
502 source_lines_to_display.print_source_context_end_eol = false;
504 previous_symbol = sc.symbol;
505 if (sc.function && sc.line_entry.IsValid()) {
506 LineEntry prologue_end_line = sc.line_entry;
507 if (!ElideMixedSourceAndDisassemblyLine(exe_ctx, sc,
508 prologue_end_line)) {
509 FileSpec func_decl_file;
510 uint32_t func_decl_line;
511 sc.function->GetStartLineSourceInfo(func_decl_file,
513 if (func_decl_file == prologue_end_line.file ||
514 func_decl_file == prologue_end_line.original_file) {
515 // Add all the lines between the function declaration and
516 // the first non-prologue source line to the list of lines
518 for (uint32_t lineno = func_decl_line;
519 lineno <= prologue_end_line.line; lineno++) {
520 SourceLine this_line;
521 this_line.file = func_decl_file;
522 this_line.line = lineno;
523 source_lines_to_display.lines.push_back(this_line);
525 // Mark the last line as the "current" one. Usually this
526 // is the open curly brace.
527 if (source_lines_to_display.lines.size() > 0)
528 source_lines_to_display.current_source_line =
529 source_lines_to_display.lines.size() - 1;
533 sc.GetAddressRange(scope, 0, use_inline_block_range,
534 current_source_line_range);
537 // If we've left a previous source line's address range, print a
539 if (!current_source_line_range.ContainsFileAddress(addr)) {
540 sc.GetAddressRange(scope, 0, use_inline_block_range,
541 current_source_line_range);
543 if (sc != prev_sc && sc.comp_unit && sc.line_entry.IsValid()) {
544 SourceLine this_line;
545 this_line.file = sc.line_entry.file;
546 this_line.line = sc.line_entry.line;
548 if (!ElideMixedSourceAndDisassemblyLine(exe_ctx, sc,
550 // Only print this source line if it is different from the
551 // last source line we printed. There may have been inlined
552 // functions between these lines that we elided, resulting in
553 // the same line being printed twice in a row for a
554 // contiguous block of assembly instructions.
555 if (this_line != previous_line) {
557 std::vector<uint32_t> previous_lines;
559 i < num_mixed_context_lines &&
560 (this_line.line - num_mixed_context_lines) > 0;
563 this_line.line - num_mixed_context_lines + i;
564 auto pos = source_lines_seen.find(this_line.file);
565 if (pos != source_lines_seen.end()) {
566 if (pos->second.count(line) == 1) {
567 previous_lines.clear();
569 previous_lines.push_back(line);
573 for (size_t i = 0; i < previous_lines.size(); i++) {
574 SourceLine previous_line;
575 previous_line.file = this_line.file;
576 previous_line.line = previous_lines[i];
577 auto pos = source_lines_seen.find(previous_line.file);
578 if (pos != source_lines_seen.end()) {
579 pos->second.insert(previous_line.line);
581 source_lines_to_display.lines.push_back(previous_line);
584 source_lines_to_display.lines.push_back(this_line);
585 source_lines_to_display.current_source_line =
586 source_lines_to_display.lines.size() - 1;
588 for (uint32_t i = 0; i < num_mixed_context_lines; i++) {
589 SourceLine next_line;
590 next_line.file = this_line.file;
591 next_line.line = this_line.line + i + 1;
592 auto pos = source_lines_seen.find(next_line.file);
593 if (pos != source_lines_seen.end()) {
594 if (pos->second.count(next_line.line) == 1)
596 pos->second.insert(next_line.line);
598 source_lines_to_display.lines.push_back(next_line);
601 previous_line = this_line;
611 if (source_lines_to_display.lines.size() > 0) {
613 for (size_t idx = 0; idx < source_lines_to_display.lines.size();
615 SourceLine ln = source_lines_to_display.lines[idx];
616 const char *line_highlight = "";
617 if (inst_is_at_pc && (options & eOptionMarkPCSourceLine)) {
618 line_highlight = "->";
619 } else if (idx == source_lines_to_display.current_source_line) {
620 line_highlight = "**";
622 source_manager.DisplaySourceLinesWithLineNumbers(
623 ln.file, ln.line, ln.column, 0, 0, line_highlight, &strm);
625 if (source_lines_to_display.print_source_context_end_eol)
629 const bool show_bytes = (options & eOptionShowBytes) != 0;
630 inst->Dump(&strm, max_opcode_byte_size, true, show_bytes, &exe_ctx, &sc,
631 &prev_sc, nullptr, address_text_size);
641 bool Disassembler::Disassemble(Debugger &debugger, const ArchSpec &arch,
642 const char *plugin_name, const char *flavor,
643 const ExecutionContext &exe_ctx,
644 uint32_t num_instructions,
645 bool mixed_source_and_assembly,
646 uint32_t num_mixed_context_lines,
647 uint32_t options, Stream &strm) {
649 StackFrame *frame = exe_ctx.GetFramePtr();
652 frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol));
654 range = sc.function->GetAddressRange();
655 } else if (sc.symbol && sc.symbol->ValueIsAddress()) {
656 range.GetBaseAddress() = sc.symbol->GetAddressRef();
657 range.SetByteSize(sc.symbol->GetByteSize());
659 range.GetBaseAddress() = frame->GetFrameCodeAddress();
662 if (range.GetBaseAddress().IsValid() && range.GetByteSize() == 0)
663 range.SetByteSize(DEFAULT_DISASM_BYTE_SIZE);
666 return Disassemble(debugger, arch, plugin_name, flavor, exe_ctx, range,
667 num_instructions, mixed_source_and_assembly,
668 num_mixed_context_lines, options, strm);
671 Instruction::Instruction(const Address &address, AddressClass addr_class)
672 : m_address(address), m_address_class(addr_class), m_opcode(),
673 m_calculated_strings(false) {}
675 Instruction::~Instruction() = default;
677 AddressClass Instruction::GetAddressClass() {
678 if (m_address_class == AddressClass::eInvalid)
679 m_address_class = m_address.GetAddressClass();
680 return m_address_class;
683 void Instruction::Dump(lldb_private::Stream *s, uint32_t max_opcode_byte_size,
684 bool show_address, bool show_bytes,
685 const ExecutionContext *exe_ctx,
686 const SymbolContext *sym_ctx,
687 const SymbolContext *prev_sym_ctx,
688 const FormatEntity::Entry *disassembly_addr_format,
689 size_t max_address_text_size) {
690 size_t opcode_column_width = 7;
691 const size_t operand_column_width = 25;
693 CalculateMnemonicOperandsAndCommentIfNeeded(exe_ctx);
698 Debugger::FormatDisassemblerAddress(disassembly_addr_format, sym_ctx,
699 prev_sym_ctx, exe_ctx, &m_address, ss);
700 ss.FillLastLineToColumn(max_address_text_size, ' ');
704 if (m_opcode.GetType() == Opcode::eTypeBytes) {
705 // x86_64 and i386 are the only ones that use bytes right now so pad out
706 // the byte dump to be able to always show 15 bytes (3 chars each) plus a
708 if (max_opcode_byte_size > 0)
709 m_opcode.Dump(&ss, max_opcode_byte_size * 3 + 1);
711 m_opcode.Dump(&ss, 15 * 3 + 1);
713 // Else, we have ARM or MIPS which can show up to a uint32_t 0x00000000
714 // (10 spaces) plus two for padding...
715 if (max_opcode_byte_size > 0)
716 m_opcode.Dump(&ss, max_opcode_byte_size * 3 + 1);
718 m_opcode.Dump(&ss, 12);
722 const size_t opcode_pos = ss.GetSizeOfLastLine();
724 // The default opcode size of 7 characters is plenty for most architectures
725 // but some like arm can pull out the occasional vqrshrun.s16. We won't get
726 // consistent column spacing in these cases, unfortunately.
727 if (m_opcode_name.length() >= opcode_column_width) {
728 opcode_column_width = m_opcode_name.length() + 1;
731 ss.PutCString(m_opcode_name);
732 ss.FillLastLineToColumn(opcode_pos + opcode_column_width, ' ');
733 ss.PutCString(m_mnemonics);
735 if (!m_comment.empty()) {
736 ss.FillLastLineToColumn(
737 opcode_pos + opcode_column_width + operand_column_width, ' ');
738 ss.PutCString(" ; ");
739 ss.PutCString(m_comment);
741 s->PutCString(ss.GetString());
744 bool Instruction::DumpEmulation(const ArchSpec &arch) {
745 std::unique_ptr<EmulateInstruction> insn_emulator_ap(
746 EmulateInstruction::FindPlugin(arch, eInstructionTypeAny, nullptr));
747 if (insn_emulator_ap) {
748 insn_emulator_ap->SetInstruction(GetOpcode(), GetAddress(), nullptr);
749 return insn_emulator_ap->EvaluateInstruction(0);
755 bool Instruction::CanSetBreakpoint () {
756 return !HasDelaySlot();
759 bool Instruction::HasDelaySlot() {
764 OptionValueSP Instruction::ReadArray(FILE *in_file, Stream *out_stream,
765 OptionValue::Type data_type) {
769 auto option_value_sp = std::make_shared<OptionValueArray>(1u << data_type);
773 if (!fgets(buffer, 1023, in_file)) {
775 "Instruction::ReadArray: Error reading file (fgets).\n");
776 option_value_sp.reset();
777 return option_value_sp;
780 std::string line(buffer);
782 size_t len = line.size();
783 if (line[len - 1] == '\n') {
784 line[len - 1] = '\0';
785 line.resize(len - 1);
788 if ((line.size() == 1) && line[0] == ']') {
795 static RegularExpression g_reg_exp(
796 llvm::StringRef("^[ \t]*([^ \t]+)[ \t]*$"));
797 RegularExpression::Match regex_match(1);
798 bool reg_exp_success = g_reg_exp.Execute(line, ®ex_match);
800 regex_match.GetMatchAtIndex(line.c_str(), 1, value);
804 OptionValueSP data_value_sp;
806 case OptionValue::eTypeUInt64:
807 data_value_sp = std::make_shared<OptionValueUInt64>(0, 0);
808 data_value_sp->SetValueFromString(value);
810 // Other types can be added later as needed.
812 data_value_sp = std::make_shared<OptionValueString>(value.c_str(), "");
816 option_value_sp->GetAsArray()->InsertValue(idx, data_value_sp);
821 return option_value_sp;
824 OptionValueSP Instruction::ReadDictionary(FILE *in_file, Stream *out_stream) {
828 auto option_value_sp = std::make_shared<OptionValueDictionary>();
829 static ConstString encoding_key("data_encoding");
830 OptionValue::Type data_type = OptionValue::eTypeInvalid;
833 // Read the next line in the file
834 if (!fgets(buffer, 1023, in_file)) {
836 "Instruction::ReadDictionary: Error reading file (fgets).\n");
837 option_value_sp.reset();
838 return option_value_sp;
841 // Check to see if the line contains the end-of-dictionary marker ("}")
842 std::string line(buffer);
844 size_t len = line.size();
845 if (line[len - 1] == '\n') {
846 line[len - 1] = '\0';
847 line.resize(len - 1);
850 if ((line.size() == 1) && (line[0] == '}')) {
855 // Try to find a key-value pair in the current line and add it to the
858 static RegularExpression g_reg_exp(llvm::StringRef(
859 "^[ \t]*([a-zA-Z_][a-zA-Z0-9_]*)[ \t]*=[ \t]*(.*)[ \t]*$"));
860 RegularExpression::Match regex_match(2);
862 bool reg_exp_success = g_reg_exp.Execute(line, ®ex_match);
865 if (reg_exp_success) {
866 regex_match.GetMatchAtIndex(line.c_str(), 1, key);
867 regex_match.GetMatchAtIndex(line.c_str(), 2, value);
869 out_stream->Printf("Instruction::ReadDictionary: Failure executing "
870 "regular expression.\n");
871 option_value_sp.reset();
872 return option_value_sp;
875 ConstString const_key(key.c_str());
876 // Check value to see if it's the start of an array or dictionary.
878 lldb::OptionValueSP value_sp;
879 assert(value.empty() == false);
880 assert(key.empty() == false);
882 if (value[0] == '{') {
883 assert(value.size() == 1);
884 // value is a dictionary
885 value_sp = ReadDictionary(in_file, out_stream);
887 option_value_sp.reset();
888 return option_value_sp;
890 } else if (value[0] == '[') {
891 assert(value.size() == 1);
893 value_sp = ReadArray(in_file, out_stream, data_type);
895 option_value_sp.reset();
896 return option_value_sp;
898 // We've used the data_type to read an array; re-set the type to
900 data_type = OptionValue::eTypeInvalid;
901 } else if ((value[0] == '0') && (value[1] == 'x')) {
902 value_sp = std::make_shared<OptionValueUInt64>(0, 0);
903 value_sp->SetValueFromString(value);
905 size_t len = value.size();
906 if ((value[0] == '"') && (value[len - 1] == '"'))
907 value = value.substr(1, len - 2);
908 value_sp = std::make_shared<OptionValueString>(value.c_str(), "");
911 if (const_key == encoding_key) {
912 // A 'data_encoding=..." is NOT a normal key-value pair; it is meta-data
914 // data type of an upcoming array (usually the next bit of data to be
916 if (strcmp(value.c_str(), "uint32_t") == 0)
917 data_type = OptionValue::eTypeUInt64;
919 option_value_sp->GetAsDictionary()->SetValueForKey(const_key, value_sp,
924 return option_value_sp;
927 bool Instruction::TestEmulation(Stream *out_stream, const char *file_name) {
932 out_stream->Printf("Instruction::TestEmulation: Missing file_name.");
935 FILE *test_file = FileSystem::Instance().Fopen(file_name, "r");
938 "Instruction::TestEmulation: Attempt to open test file failed.");
943 if (!fgets(buffer, 255, test_file)) {
945 "Instruction::TestEmulation: Error reading first line of test file.\n");
950 if (strncmp(buffer, "InstructionEmulationState={", 27) != 0) {
951 out_stream->Printf("Instructin::TestEmulation: Test file does not contain "
952 "emulation state dictionary\n");
957 // Read all the test information from the test file into an
958 // OptionValueDictionary.
960 OptionValueSP data_dictionary_sp(ReadDictionary(test_file, out_stream));
961 if (!data_dictionary_sp) {
963 "Instruction::TestEmulation: Error reading Dictionary Object.\n");
970 OptionValueDictionary *data_dictionary =
971 data_dictionary_sp->GetAsDictionary();
972 static ConstString description_key("assembly_string");
973 static ConstString triple_key("triple");
975 OptionValueSP value_sp = data_dictionary->GetValueForKey(description_key);
978 out_stream->Printf("Instruction::TestEmulation: Test file does not "
979 "contain description string.\n");
983 SetDescription(value_sp->GetStringValue());
985 value_sp = data_dictionary->GetValueForKey(triple_key);
988 "Instruction::TestEmulation: Test file does not contain triple.\n");
993 arch.SetTriple(llvm::Triple(value_sp->GetStringValue()));
995 bool success = false;
996 std::unique_ptr<EmulateInstruction> insn_emulator_ap(
997 EmulateInstruction::FindPlugin(arch, eInstructionTypeAny, nullptr));
998 if (insn_emulator_ap)
1000 insn_emulator_ap->TestEmulation(out_stream, arch, data_dictionary);
1003 out_stream->Printf("Emulation test succeeded.");
1005 out_stream->Printf("Emulation test failed.");
1010 bool Instruction::Emulate(
1011 const ArchSpec &arch, uint32_t evaluate_options, void *baton,
1012 EmulateInstruction::ReadMemoryCallback read_mem_callback,
1013 EmulateInstruction::WriteMemoryCallback write_mem_callback,
1014 EmulateInstruction::ReadRegisterCallback read_reg_callback,
1015 EmulateInstruction::WriteRegisterCallback write_reg_callback) {
1016 std::unique_ptr<EmulateInstruction> insn_emulator_ap(
1017 EmulateInstruction::FindPlugin(arch, eInstructionTypeAny, nullptr));
1018 if (insn_emulator_ap) {
1019 insn_emulator_ap->SetBaton(baton);
1020 insn_emulator_ap->SetCallbacks(read_mem_callback, write_mem_callback,
1021 read_reg_callback, write_reg_callback);
1022 insn_emulator_ap->SetInstruction(GetOpcode(), GetAddress(), nullptr);
1023 return insn_emulator_ap->EvaluateInstruction(evaluate_options);
1029 uint32_t Instruction::GetData(DataExtractor &data) {
1030 return m_opcode.GetData(data);
1033 InstructionList::InstructionList() : m_instructions() {}
1035 InstructionList::~InstructionList() = default;
1037 size_t InstructionList::GetSize() const { return m_instructions.size(); }
1039 uint32_t InstructionList::GetMaxOpcocdeByteSize() const {
1040 uint32_t max_inst_size = 0;
1041 collection::const_iterator pos, end;
1042 for (pos = m_instructions.begin(), end = m_instructions.end(); pos != end;
1044 uint32_t inst_size = (*pos)->GetOpcode().GetByteSize();
1045 if (max_inst_size < inst_size)
1046 max_inst_size = inst_size;
1048 return max_inst_size;
1051 InstructionSP InstructionList::GetInstructionAtIndex(size_t idx) const {
1052 InstructionSP inst_sp;
1053 if (idx < m_instructions.size())
1054 inst_sp = m_instructions[idx];
1058 void InstructionList::Dump(Stream *s, bool show_address, bool show_bytes,
1059 const ExecutionContext *exe_ctx) {
1060 const uint32_t max_opcode_byte_size = GetMaxOpcocdeByteSize();
1061 collection::const_iterator pos, begin, end;
1063 const FormatEntity::Entry *disassembly_format = nullptr;
1064 FormatEntity::Entry format;
1065 if (exe_ctx && exe_ctx->HasTargetScope()) {
1066 disassembly_format =
1067 exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1069 FormatEntity::Parse("${addr}: ", format);
1070 disassembly_format = &format;
1073 for (begin = m_instructions.begin(), end = m_instructions.end(), pos = begin;
1074 pos != end; ++pos) {
1077 (*pos)->Dump(s, max_opcode_byte_size, show_address, show_bytes, exe_ctx,
1078 nullptr, nullptr, disassembly_format, 0);
1082 void InstructionList::Clear() { m_instructions.clear(); }
1084 void InstructionList::Append(lldb::InstructionSP &inst_sp) {
1086 m_instructions.push_back(inst_sp);
1090 InstructionList::GetIndexOfNextBranchInstruction(uint32_t start,
1091 Target &target) const {
1092 size_t num_instructions = m_instructions.size();
1094 uint32_t next_branch = UINT32_MAX;
1096 for (i = start; i < num_instructions; i++) {
1097 if (m_instructions[i]->DoesBranch()) {
1103 // Hexagon needs the first instruction of the packet with the branch. Go
1104 // backwards until we find an instruction marked end-of-packet, or until we
1106 if (target.GetArchitecture().GetTriple().getArch() == llvm::Triple::hexagon) {
1107 // If we didn't find a branch, find the last packet start.
1108 if (next_branch == UINT32_MAX) {
1109 i = num_instructions - 1;
1116 uint32_t inst_bytes;
1117 bool prefer_file_cache = false; // Read from process if process is running
1118 lldb::addr_t load_addr = LLDB_INVALID_ADDRESS;
1119 target.ReadMemory(m_instructions[i]->GetAddress(), prefer_file_cache,
1120 &inst_bytes, sizeof(inst_bytes), error, &load_addr);
1121 // If we have an error reading memory, return start
1122 if (!error.Success())
1124 // check if this is the last instruction in a packet bits 15:14 will be
1125 // 11b or 00b for a duplex
1126 if (((inst_bytes & 0xC000) == 0xC000) ||
1127 ((inst_bytes & 0xC000) == 0x0000)) {
1128 // instruction after this should be the start of next packet
1129 next_branch = i + 1;
1134 if (next_branch == UINT32_MAX) {
1135 // We couldn't find the previous packet, so return start
1136 next_branch = start;
1143 InstructionList::GetIndexOfInstructionAtAddress(const Address &address) {
1144 size_t num_instructions = m_instructions.size();
1145 uint32_t index = UINT32_MAX;
1146 for (size_t i = 0; i < num_instructions; i++) {
1147 if (m_instructions[i]->GetAddress() == address) {
1156 InstructionList::GetIndexOfInstructionAtLoadAddress(lldb::addr_t load_addr,
1159 address.SetLoadAddress(load_addr, &target);
1160 return GetIndexOfInstructionAtAddress(address);
1163 size_t Disassembler::ParseInstructions(const ExecutionContext *exe_ctx,
1164 const AddressRange &range,
1165 Stream *error_strm_ptr,
1166 bool prefer_file_cache) {
1168 Target *target = exe_ctx->GetTargetPtr();
1169 const addr_t byte_size = range.GetByteSize();
1170 if (target == nullptr || byte_size == 0 ||
1171 !range.GetBaseAddress().IsValid())
1174 auto data_sp = std::make_shared<DataBufferHeap>(byte_size, '\0');
1177 lldb::addr_t load_addr = LLDB_INVALID_ADDRESS;
1178 const size_t bytes_read = target->ReadMemory(
1179 range.GetBaseAddress(), prefer_file_cache, data_sp->GetBytes(),
1180 data_sp->GetByteSize(), error, &load_addr);
1182 if (bytes_read > 0) {
1183 if (bytes_read != data_sp->GetByteSize())
1184 data_sp->SetByteSize(bytes_read);
1185 DataExtractor data(data_sp, m_arch.GetByteOrder(),
1186 m_arch.GetAddressByteSize());
1187 const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS;
1188 return DecodeInstructions(range.GetBaseAddress(), data, 0, UINT32_MAX,
1189 false, data_from_file);
1190 } else if (error_strm_ptr) {
1191 const char *error_cstr = error.AsCString();
1193 error_strm_ptr->Printf("error: %s\n", error_cstr);
1196 } else if (error_strm_ptr) {
1197 error_strm_ptr->PutCString("error: invalid execution context\n");
1202 size_t Disassembler::ParseInstructions(const ExecutionContext *exe_ctx,
1203 const Address &start,
1204 uint32_t num_instructions,
1205 bool prefer_file_cache) {
1206 m_instruction_list.Clear();
1208 if (exe_ctx == nullptr || num_instructions == 0 || !start.IsValid())
1211 Target *target = exe_ctx->GetTargetPtr();
1212 // Calculate the max buffer size we will need in order to disassemble
1213 const addr_t byte_size = num_instructions * m_arch.GetMaximumOpcodeByteSize();
1215 if (target == nullptr || byte_size == 0)
1218 DataBufferHeap *heap_buffer = new DataBufferHeap(byte_size, '\0');
1219 DataBufferSP data_sp(heap_buffer);
1222 lldb::addr_t load_addr = LLDB_INVALID_ADDRESS;
1223 const size_t bytes_read =
1224 target->ReadMemory(start, prefer_file_cache, heap_buffer->GetBytes(),
1225 byte_size, error, &load_addr);
1227 const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS;
1229 if (bytes_read == 0)
1231 DataExtractor data(data_sp, m_arch.GetByteOrder(),
1232 m_arch.GetAddressByteSize());
1234 const bool append_instructions = true;
1235 DecodeInstructions(start, data, 0, num_instructions, append_instructions,
1238 return m_instruction_list.GetSize();
1241 //----------------------------------------------------------------------
1242 // Disassembler copy constructor
1243 //----------------------------------------------------------------------
1244 Disassembler::Disassembler(const ArchSpec &arch, const char *flavor)
1245 : m_arch(arch), m_instruction_list(), m_base_addr(LLDB_INVALID_ADDRESS),
1247 if (flavor == nullptr)
1248 m_flavor.assign("default");
1250 m_flavor.assign(flavor);
1252 // If this is an arm variant that can only include thumb (T16, T32)
1253 // instructions, force the arch triple to be "thumbv.." instead of "armv..."
1254 if (arch.IsAlwaysThumbInstructions()) {
1255 std::string thumb_arch_name(arch.GetTriple().getArchName().str());
1256 // Replace "arm" with "thumb" so we get all thumb variants correct
1257 if (thumb_arch_name.size() > 3) {
1258 thumb_arch_name.erase(0, 3);
1259 thumb_arch_name.insert(0, "thumb");
1261 m_arch.SetTriple(thumb_arch_name.c_str());
1265 Disassembler::~Disassembler() = default;
1267 InstructionList &Disassembler::GetInstructionList() {
1268 return m_instruction_list;
1271 const InstructionList &Disassembler::GetInstructionList() const {
1272 return m_instruction_list;
1275 //----------------------------------------------------------------------
1276 // Class PseudoInstruction
1277 //----------------------------------------------------------------------
1279 PseudoInstruction::PseudoInstruction()
1280 : Instruction(Address(), AddressClass::eUnknown), m_description() {}
1282 PseudoInstruction::~PseudoInstruction() = default;
1284 bool PseudoInstruction::DoesBranch() {
1285 // This is NOT a valid question for a pseudo instruction.
1289 bool PseudoInstruction::HasDelaySlot() {
1290 // This is NOT a valid question for a pseudo instruction.
1294 size_t PseudoInstruction::Decode(const lldb_private::Disassembler &disassembler,
1295 const lldb_private::DataExtractor &data,
1296 lldb::offset_t data_offset) {
1297 return m_opcode.GetByteSize();
1300 void PseudoInstruction::SetOpcode(size_t opcode_size, void *opcode_data) {
1304 switch (opcode_size) {
1306 uint8_t value8 = *((uint8_t *)opcode_data);
1307 m_opcode.SetOpcode8(value8, eByteOrderInvalid);
1311 uint16_t value16 = *((uint16_t *)opcode_data);
1312 m_opcode.SetOpcode16(value16, eByteOrderInvalid);
1316 uint32_t value32 = *((uint32_t *)opcode_data);
1317 m_opcode.SetOpcode32(value32, eByteOrderInvalid);
1321 uint64_t value64 = *((uint64_t *)opcode_data);
1322 m_opcode.SetOpcode64(value64, eByteOrderInvalid);
1330 void PseudoInstruction::SetDescription(llvm::StringRef description) {
1331 m_description = description;
1334 Instruction::Operand Instruction::Operand::BuildRegister(ConstString &r) {
1336 ret.m_type = Type::Register;
1341 Instruction::Operand Instruction::Operand::BuildImmediate(lldb::addr_t imm,
1344 ret.m_type = Type::Immediate;
1345 ret.m_immediate = imm;
1346 ret.m_negative = neg;
1350 Instruction::Operand Instruction::Operand::BuildImmediate(int64_t imm) {
1352 ret.m_type = Type::Immediate;
1354 ret.m_immediate = -imm;
1355 ret.m_negative = true;
1357 ret.m_immediate = imm;
1358 ret.m_negative = false;
1363 Instruction::Operand
1364 Instruction::Operand::BuildDereference(const Operand &ref) {
1366 ret.m_type = Type::Dereference;
1367 ret.m_children = {ref};
1371 Instruction::Operand Instruction::Operand::BuildSum(const Operand &lhs,
1372 const Operand &rhs) {
1374 ret.m_type = Type::Sum;
1375 ret.m_children = {lhs, rhs};
1379 Instruction::Operand Instruction::Operand::BuildProduct(const Operand &lhs,
1380 const Operand &rhs) {
1382 ret.m_type = Type::Product;
1383 ret.m_children = {lhs, rhs};
1387 std::function<bool(const Instruction::Operand &)>
1388 lldb_private::OperandMatchers::MatchBinaryOp(
1389 std::function<bool(const Instruction::Operand &)> base,
1390 std::function<bool(const Instruction::Operand &)> left,
1391 std::function<bool(const Instruction::Operand &)> right) {
1392 return [base, left, right](const Instruction::Operand &op) -> bool {
1393 return (base(op) && op.m_children.size() == 2 &&
1394 ((left(op.m_children[0]) && right(op.m_children[1])) ||
1395 (left(op.m_children[1]) && right(op.m_children[0]))));
1399 std::function<bool(const Instruction::Operand &)>
1400 lldb_private::OperandMatchers::MatchUnaryOp(
1401 std::function<bool(const Instruction::Operand &)> base,
1402 std::function<bool(const Instruction::Operand &)> child) {
1403 return [base, child](const Instruction::Operand &op) -> bool {
1404 return (base(op) && op.m_children.size() == 1 && child(op.m_children[0]));
1408 std::function<bool(const Instruction::Operand &)>
1409 lldb_private::OperandMatchers::MatchRegOp(const RegisterInfo &info) {
1410 return [&info](const Instruction::Operand &op) {
1411 return (op.m_type == Instruction::Operand::Type::Register &&
1412 (op.m_register == ConstString(info.name) ||
1413 op.m_register == ConstString(info.alt_name)));
1417 std::function<bool(const Instruction::Operand &)>
1418 lldb_private::OperandMatchers::FetchRegOp(ConstString ®) {
1419 return [®](const Instruction::Operand &op) {
1420 if (op.m_type != Instruction::Operand::Type::Register) {
1423 reg = op.m_register;
1428 std::function<bool(const Instruction::Operand &)>
1429 lldb_private::OperandMatchers::MatchImmOp(int64_t imm) {
1430 return [imm](const Instruction::Operand &op) {
1431 return (op.m_type == Instruction::Operand::Type::Immediate &&
1432 ((op.m_negative && op.m_immediate == (uint64_t)-imm) ||
1433 (!op.m_negative && op.m_immediate == (uint64_t)imm)));
1437 std::function<bool(const Instruction::Operand &)>
1438 lldb_private::OperandMatchers::FetchImmOp(int64_t &imm) {
1439 return [&imm](const Instruction::Operand &op) {
1440 if (op.m_type != Instruction::Operand::Type::Immediate) {
1443 if (op.m_negative) {
1444 imm = -((int64_t)op.m_immediate);
1446 imm = ((int64_t)op.m_immediate);
1452 std::function<bool(const Instruction::Operand &)>
1453 lldb_private::OperandMatchers::MatchOpType(Instruction::Operand::Type type) {
1454 return [type](const Instruction::Operand &op) { return op.m_type == type; };