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"
17 // Other libraries and framework includes
19 #include "lldb/Core/DataBufferHeap.h"
20 #include "lldb/Core/DataExtractor.h"
21 #include "lldb/Core/Debugger.h"
22 #include "lldb/Core/EmulateInstruction.h"
23 #include "lldb/Core/Error.h"
24 #include "lldb/Core/Module.h"
25 #include "lldb/Core/PluginManager.h"
26 #include "lldb/Core/RegularExpression.h"
27 #include "lldb/Core/Timer.h"
28 #include "lldb/Host/FileSystem.h"
29 #include "lldb/Interpreter/OptionValue.h"
30 #include "lldb/Interpreter/OptionValueArray.h"
31 #include "lldb/Interpreter/OptionValueDictionary.h"
32 #include "lldb/Interpreter/OptionValueString.h"
33 #include "lldb/Interpreter/OptionValueUInt64.h"
34 #include "lldb/Symbol/Function.h"
35 #include "lldb/Symbol/ObjectFile.h"
36 #include "lldb/Target/ExecutionContext.h"
37 #include "lldb/Target/Process.h"
38 #include "lldb/Target/SectionLoadList.h"
39 #include "lldb/Target/StackFrame.h"
40 #include "lldb/Target/Target.h"
41 #include "lldb/lldb-private.h"
43 #define DEFAULT_DISASM_BYTE_SIZE 32
46 using namespace lldb_private;
49 Disassembler::FindPlugin (const ArchSpec &arch, const char *flavor, const char *plugin_name)
51 Timer scoped_timer (__PRETTY_FUNCTION__,
52 "Disassembler::FindPlugin (arch = %s, plugin_name = %s)",
53 arch.GetArchitectureName(),
56 DisassemblerCreateInstance create_callback = nullptr;
60 ConstString const_plugin_name (plugin_name);
61 create_callback = PluginManager::GetDisassemblerCreateCallbackForPluginName (const_plugin_name);
64 DisassemblerSP disassembler_sp(create_callback(arch, flavor));
67 return disassembler_sp;
72 for (uint32_t idx = 0; (create_callback = PluginManager::GetDisassemblerCreateCallbackAtIndex(idx)) != nullptr; ++idx)
74 DisassemblerSP disassembler_sp(create_callback(arch, flavor));
77 return disassembler_sp;
80 return DisassemblerSP();
84 Disassembler::FindPluginForTarget(const TargetSP target_sp, const ArchSpec &arch, const char *flavor, const char *plugin_name)
86 if (target_sp && flavor == nullptr)
88 // FIXME - we don't have the mechanism in place to do per-architecture settings. But since we know that for now
89 // we only support flavors on x86 & x86_64,
90 if (arch.GetTriple().getArch() == llvm::Triple::x86
91 || arch.GetTriple().getArch() == llvm::Triple::x86_64)
92 flavor = target_sp->GetDisassemblyFlavor();
94 return FindPlugin(arch, flavor, plugin_name);
98 ResolveAddress (const ExecutionContext &exe_ctx,
100 Address &resolved_addr)
102 if (!addr.IsSectionOffset())
104 // If we weren't passed in a section offset address range,
105 // try and resolve it to something
106 Target *target = exe_ctx.GetTargetPtr();
109 if (target->GetSectionLoadList().IsEmpty())
111 target->GetImages().ResolveFileAddress (addr.GetOffset(), resolved_addr);
115 target->GetSectionLoadList().ResolveLoadAddress (addr.GetOffset(), resolved_addr);
117 // We weren't able to resolve the address, just treat it as a
119 if (resolved_addr.IsValid())
123 resolved_addr = addr;
127 Disassembler::Disassemble(Debugger &debugger,
128 const ArchSpec &arch,
129 const char *plugin_name,
131 const ExecutionContext &exe_ctx,
132 SymbolContextList &sc_list,
133 uint32_t num_instructions,
134 uint32_t num_mixed_context_lines,
138 size_t success_count = 0;
139 const size_t count = sc_list.GetSize();
142 const uint32_t scope = eSymbolContextBlock | eSymbolContextFunction | eSymbolContextSymbol;
143 const bool use_inline_block_range = true;
144 for (size_t i = 0; i < count; ++i)
146 if (!sc_list.GetContextAtIndex(i, sc))
148 for (uint32_t range_idx = 0; sc.GetAddressRange(scope, range_idx, use_inline_block_range, range); ++range_idx)
150 if (Disassemble (debugger,
157 num_mixed_context_lines,
166 return success_count;
170 Disassembler::Disassemble(Debugger &debugger,
171 const ArchSpec &arch,
172 const char *plugin_name,
174 const ExecutionContext &exe_ctx,
175 const ConstString &name,
177 uint32_t num_instructions,
178 uint32_t num_mixed_context_lines,
182 SymbolContextList sc_list;
185 const bool include_symbols = true;
186 const bool include_inlines = true;
189 module->FindFunctions(name,
191 eFunctionNameTypeAuto,
197 else if (exe_ctx.GetTargetPtr())
199 exe_ctx.GetTargetPtr()->GetImages().FindFunctions (name,
200 eFunctionNameTypeAuto,
208 if (sc_list.GetSize ())
210 return Disassemble (debugger,
217 num_mixed_context_lines,
225 Disassembler::DisassembleRange(const ArchSpec &arch,
226 const char *plugin_name,
228 const ExecutionContext &exe_ctx,
229 const AddressRange &range,
230 bool prefer_file_cache)
232 lldb::DisassemblerSP disasm_sp;
233 if (range.GetByteSize() > 0 && range.GetBaseAddress().IsValid())
235 disasm_sp = Disassembler::FindPluginForTarget(exe_ctx.GetTargetSP(), arch, flavor, plugin_name);
239 size_t bytes_disassembled = disasm_sp->ParseInstructions(&exe_ctx, range, nullptr, prefer_file_cache);
240 if (bytes_disassembled == 0)
248 Disassembler::DisassembleBytes (const ArchSpec &arch,
249 const char *plugin_name,
251 const Address &start,
254 uint32_t num_instructions,
257 lldb::DisassemblerSP disasm_sp;
261 disasm_sp = Disassembler::FindPlugin(arch, flavor, plugin_name);
265 DataExtractor data(src, src_len, arch.GetByteOrder(), arch.GetAddressByteSize());
267 (void)disasm_sp->DecodeInstructions (start,
280 Disassembler::Disassemble(Debugger &debugger,
281 const ArchSpec &arch,
282 const char *plugin_name,
284 const ExecutionContext &exe_ctx,
285 const AddressRange &disasm_range,
286 uint32_t num_instructions,
287 uint32_t num_mixed_context_lines,
291 if (disasm_range.GetByteSize())
293 lldb::DisassemblerSP disasm_sp (Disassembler::FindPluginForTarget(exe_ctx.GetTargetSP(), arch, flavor, plugin_name));
298 ResolveAddress (exe_ctx, disasm_range.GetBaseAddress(), range.GetBaseAddress());
299 range.SetByteSize (disasm_range.GetByteSize());
300 const bool prefer_file_cache = false;
301 size_t bytes_disassembled = disasm_sp->ParseInstructions (&exe_ctx, range, &strm, prefer_file_cache);
302 if (bytes_disassembled == 0)
305 return PrintInstructions(disasm_sp.get(), debugger, arch, exe_ctx, num_instructions,
306 num_mixed_context_lines, options, strm);
313 Disassembler::Disassemble(Debugger &debugger,
314 const ArchSpec &arch,
315 const char *plugin_name,
317 const ExecutionContext &exe_ctx,
318 const Address &start_address,
319 uint32_t num_instructions,
320 uint32_t num_mixed_context_lines,
324 if (num_instructions > 0)
326 lldb::DisassemblerSP disasm_sp (Disassembler::FindPluginForTarget(exe_ctx.GetTargetSP(),
333 ResolveAddress (exe_ctx, start_address, addr);
334 const bool prefer_file_cache = false;
335 size_t bytes_disassembled = disasm_sp->ParseInstructions (&exe_ctx,
339 if (bytes_disassembled == 0)
341 return PrintInstructions(disasm_sp.get(), debugger, arch, exe_ctx, num_instructions,
342 num_mixed_context_lines, options, strm);
349 Disassembler::PrintInstructions(Disassembler *disasm_ptr, Debugger &debugger, const ArchSpec &arch,
350 const ExecutionContext &exe_ctx, uint32_t num_instructions,
351 uint32_t num_mixed_context_lines, uint32_t options, Stream &strm)
353 // We got some things disassembled...
354 size_t num_instructions_found = disasm_ptr->GetInstructionList().GetSize();
356 if (num_instructions > 0 && num_instructions < num_instructions_found)
357 num_instructions_found = num_instructions;
359 const uint32_t max_opcode_byte_size = disasm_ptr->GetInstructionList().GetMaxOpcocdeByteSize ();
362 SymbolContext prev_sc;
363 AddressRange sc_range;
364 const Address *pc_addr_ptr = nullptr;
365 StackFrame *frame = exe_ctx.GetFramePtr();
367 TargetSP target_sp (exe_ctx.GetTargetSP());
368 SourceManager &source_manager = target_sp ? target_sp->GetSourceManager() : debugger.GetSourceManager();
372 pc_addr_ptr = &frame->GetFrameCodeAddress();
374 const uint32_t scope = eSymbolContextLineEntry | eSymbolContextFunction | eSymbolContextSymbol;
375 const bool use_inline_block_range = false;
377 const FormatEntity::Entry *disassembly_format = nullptr;
378 FormatEntity::Entry format;
379 if (exe_ctx.HasTargetScope())
381 disassembly_format = exe_ctx.GetTargetRef().GetDebugger().GetDisassemblyFormat ();
385 FormatEntity::Parse("${addr}: ", format);
386 disassembly_format = &format;
389 // First pass: step through the list of instructions,
390 // find how long the initial addresses strings are, insert padding
391 // in the second pass so the opcodes all line up nicely.
392 size_t address_text_size = 0;
393 for (size_t i = 0; i < num_instructions_found; ++i)
395 Instruction *inst = disasm_ptr->GetInstructionList().GetInstructionAtIndex (i).get();
398 const Address &addr = inst->GetAddress();
399 ModuleSP module_sp (addr.GetModule());
402 const uint32_t resolve_mask = eSymbolContextFunction | eSymbolContextSymbol;
403 uint32_t resolved_mask = module_sp->ResolveSymbolContextForAddress(addr, resolve_mask, sc);
406 StreamString strmstr;
407 Debugger::FormatDisassemblerAddress(disassembly_format, &sc, nullptr, &exe_ctx, &addr, strmstr);
408 size_t cur_line = strmstr.GetSizeOfLastLine();
409 if (cur_line > address_text_size)
410 address_text_size = cur_line;
417 for (size_t i = 0; i < num_instructions_found; ++i)
419 Instruction *inst = disasm_ptr->GetInstructionList().GetInstructionAtIndex (i).get();
422 const Address &addr = inst->GetAddress();
423 const bool inst_is_at_pc = pc_addr_ptr && addr == *pc_addr_ptr;
427 ModuleSP module_sp (addr.GetModule());
430 uint32_t resolved_mask = module_sp->ResolveSymbolContextForAddress(addr, eSymbolContextEverything, sc);
433 if (num_mixed_context_lines)
435 if (!sc_range.ContainsFileAddress (addr))
437 sc.GetAddressRange (scope, 0, use_inline_block_range, sc_range);
444 sc.DumpStopContext(&strm, exe_ctx.GetProcessPtr(), addr, false, true, false, false, true);
447 if (sc.comp_unit && sc.line_entry.IsValid())
449 source_manager.DisplaySourceLinesWithLineNumbers (sc.line_entry.file,
451 num_mixed_context_lines,
452 num_mixed_context_lines,
453 ((inst_is_at_pc && (options & eOptionMarkPCSourceLine)) ? "->" : ""),
466 const bool show_bytes = (options & eOptionShowBytes) != 0;
467 inst->Dump(&strm, max_opcode_byte_size, true, show_bytes, &exe_ctx, &sc, &prev_sc, nullptr, address_text_size);
480 Disassembler::Disassemble(Debugger &debugger,
481 const ArchSpec &arch,
482 const char *plugin_name,
484 const ExecutionContext &exe_ctx,
485 uint32_t num_instructions,
486 uint32_t num_mixed_context_lines,
491 StackFrame *frame = exe_ctx.GetFramePtr();
494 SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol));
497 range = sc.function->GetAddressRange();
499 else if (sc.symbol && sc.symbol->ValueIsAddress())
501 range.GetBaseAddress() = sc.symbol->GetAddressRef();
502 range.SetByteSize (sc.symbol->GetByteSize());
506 range.GetBaseAddress() = frame->GetFrameCodeAddress();
509 if (range.GetBaseAddress().IsValid() && range.GetByteSize() == 0)
510 range.SetByteSize (DEFAULT_DISASM_BYTE_SIZE);
513 return Disassemble (debugger,
520 num_mixed_context_lines,
525 Instruction::Instruction(const Address &address, AddressClass addr_class) :
527 m_address_class (addr_class),
529 m_calculated_strings(false)
533 Instruction::~Instruction() = default;
536 Instruction::GetAddressClass ()
538 if (m_address_class == eAddressClassInvalid)
539 m_address_class = m_address.GetAddressClass();
540 return m_address_class;
544 Instruction::Dump (lldb_private::Stream *s,
545 uint32_t max_opcode_byte_size,
548 const ExecutionContext* exe_ctx,
549 const SymbolContext *sym_ctx,
550 const SymbolContext *prev_sym_ctx,
551 const FormatEntity::Entry *disassembly_addr_format,
552 size_t max_address_text_size)
554 size_t opcode_column_width = 7;
555 const size_t operand_column_width = 25;
557 CalculateMnemonicOperandsAndCommentIfNeeded (exe_ctx);
563 Debugger::FormatDisassemblerAddress (disassembly_addr_format, sym_ctx, prev_sym_ctx, exe_ctx, &m_address, ss);
564 ss.FillLastLineToColumn (max_address_text_size, ' ');
569 if (m_opcode.GetType() == Opcode::eTypeBytes)
571 // x86_64 and i386 are the only ones that use bytes right now so
572 // pad out the byte dump to be able to always show 15 bytes (3 chars each)
574 if (max_opcode_byte_size > 0)
575 m_opcode.Dump (&ss, max_opcode_byte_size * 3 + 1);
577 m_opcode.Dump (&ss, 15 * 3 + 1);
581 // Else, we have ARM or MIPS which can show up to a uint32_t
582 // 0x00000000 (10 spaces) plus two for padding...
583 if (max_opcode_byte_size > 0)
584 m_opcode.Dump (&ss, max_opcode_byte_size * 3 + 1);
586 m_opcode.Dump (&ss, 12);
590 const size_t opcode_pos = ss.GetSizeOfLastLine();
592 // The default opcode size of 7 characters is plenty for most architectures
593 // but some like arm can pull out the occasional vqrshrun.s16. We won't get
594 // consistent column spacing in these cases, unfortunately.
595 if (m_opcode_name.length() >= opcode_column_width)
597 opcode_column_width = m_opcode_name.length() + 1;
600 ss.PutCString (m_opcode_name.c_str());
601 ss.FillLastLineToColumn (opcode_pos + opcode_column_width, ' ');
602 ss.PutCString (m_mnemonics.c_str());
604 if (!m_comment.empty())
606 ss.FillLastLineToColumn (opcode_pos + opcode_column_width + operand_column_width, ' ');
607 ss.PutCString (" ; ");
608 ss.PutCString (m_comment.c_str());
610 s->Write (ss.GetData(), ss.GetSize());
614 Instruction::DumpEmulation (const ArchSpec &arch)
616 std::unique_ptr<EmulateInstruction> insn_emulator_ap(EmulateInstruction::FindPlugin(arch, eInstructionTypeAny, nullptr));
617 if (insn_emulator_ap)
619 insn_emulator_ap->SetInstruction(GetOpcode(), GetAddress(), nullptr);
620 return insn_emulator_ap->EvaluateInstruction (0);
627 Instruction::HasDelaySlot ()
634 Instruction::ReadArray (FILE *in_file, Stream *out_stream, OptionValue::Type data_type)
639 OptionValueSP option_value_sp (new OptionValueArray (1u << data_type));
644 if (!fgets (buffer, 1023, in_file))
646 out_stream->Printf ("Instruction::ReadArray: Error reading file (fgets).\n");
647 option_value_sp.reset ();
648 return option_value_sp;
651 std::string line (buffer);
653 size_t len = line.size();
654 if (line[len-1] == '\n')
660 if ((line.size() == 1) && line[0] == ']')
669 static RegularExpression g_reg_exp ("^[ \t]*([^ \t]+)[ \t]*$");
670 RegularExpression::Match regex_match(1);
671 bool reg_exp_success = g_reg_exp.Execute (line.c_str(), ®ex_match);
673 regex_match.GetMatchAtIndex (line.c_str(), 1, value);
677 OptionValueSP data_value_sp;
680 case OptionValue::eTypeUInt64:
681 data_value_sp.reset (new OptionValueUInt64 (0, 0));
682 data_value_sp->SetValueFromString (value);
684 // Other types can be added later as needed.
686 data_value_sp.reset (new OptionValueString (value.c_str(), ""));
690 option_value_sp->GetAsArray()->InsertValue (idx, data_value_sp);
695 return option_value_sp;
699 Instruction::ReadDictionary (FILE *in_file, Stream *out_stream)
704 OptionValueSP option_value_sp (new OptionValueDictionary());
705 static ConstString encoding_key ("data_encoding");
706 OptionValue::Type data_type = OptionValue::eTypeInvalid;
711 // Read the next line in the file
712 if (!fgets (buffer, 1023, in_file))
714 out_stream->Printf ("Instruction::ReadDictionary: Error reading file (fgets).\n");
715 option_value_sp.reset ();
716 return option_value_sp;
719 // Check to see if the line contains the end-of-dictionary marker ("}")
720 std::string line (buffer);
722 size_t len = line.size();
723 if (line[len-1] == '\n')
729 if ((line.size() == 1) && (line[0] == '}'))
735 // Try to find a key-value pair in the current line and add it to the dictionary.
738 static RegularExpression g_reg_exp ("^[ \t]*([a-zA-Z_][a-zA-Z0-9_]*)[ \t]*=[ \t]*(.*)[ \t]*$");
739 RegularExpression::Match regex_match(2);
741 bool reg_exp_success = g_reg_exp.Execute (line.c_str(), ®ex_match);
746 regex_match.GetMatchAtIndex (line.c_str(), 1, key);
747 regex_match.GetMatchAtIndex (line.c_str(), 2, value);
751 out_stream->Printf ("Instruction::ReadDictionary: Failure executing regular expression.\n");
752 option_value_sp.reset();
753 return option_value_sp;
756 ConstString const_key (key.c_str());
757 // Check value to see if it's the start of an array or dictionary.
759 lldb::OptionValueSP value_sp;
760 assert (value.empty() == false);
761 assert (key.empty() == false);
765 assert (value.size() == 1);
766 // value is a dictionary
767 value_sp = ReadDictionary (in_file, out_stream);
770 option_value_sp.reset ();
771 return option_value_sp;
774 else if (value[0] == '[')
776 assert (value.size() == 1);
778 value_sp = ReadArray (in_file, out_stream, data_type);
781 option_value_sp.reset ();
782 return option_value_sp;
784 // We've used the data_type to read an array; re-set the type to Invalid
785 data_type = OptionValue::eTypeInvalid;
787 else if ((value[0] == '0') && (value[1] == 'x'))
789 value_sp.reset (new OptionValueUInt64 (0, 0));
790 value_sp->SetValueFromString (value);
794 size_t len = value.size();
795 if ((value[0] == '"') && (value[len-1] == '"'))
796 value = value.substr (1, len-2);
797 value_sp.reset (new OptionValueString (value.c_str(), ""));
800 if (const_key == encoding_key)
802 // A 'data_encoding=..." is NOT a normal key-value pair; it is meta-data indicating the
803 // data type of an upcoming array (usually the next bit of data to be read in).
804 if (strcmp (value.c_str(), "uint32_t") == 0)
805 data_type = OptionValue::eTypeUInt64;
808 option_value_sp->GetAsDictionary()->SetValueForKey (const_key, value_sp, false);
812 return option_value_sp;
816 Instruction::TestEmulation (Stream *out_stream, const char *file_name)
823 out_stream->Printf ("Instruction::TestEmulation: Missing file_name.");
826 FILE *test_file = FileSystem::Fopen(file_name, "r");
829 out_stream->Printf ("Instruction::TestEmulation: Attempt to open test file failed.");
834 if (!fgets (buffer, 255, test_file))
836 out_stream->Printf ("Instruction::TestEmulation: Error reading first line of test file.\n");
841 if (strncmp (buffer, "InstructionEmulationState={", 27) != 0)
843 out_stream->Printf ("Instructin::TestEmulation: Test file does not contain emulation state dictionary\n");
848 // Read all the test information from the test file into an OptionValueDictionary.
850 OptionValueSP data_dictionary_sp (ReadDictionary (test_file, out_stream));
851 if (!data_dictionary_sp)
853 out_stream->Printf ("Instruction::TestEmulation: Error reading Dictionary Object.\n");
860 OptionValueDictionary *data_dictionary = data_dictionary_sp->GetAsDictionary();
861 static ConstString description_key ("assembly_string");
862 static ConstString triple_key ("triple");
864 OptionValueSP value_sp = data_dictionary->GetValueForKey (description_key);
868 out_stream->Printf ("Instruction::TestEmulation: Test file does not contain description string.\n");
872 SetDescription (value_sp->GetStringValue());
874 value_sp = data_dictionary->GetValueForKey (triple_key);
877 out_stream->Printf ("Instruction::TestEmulation: Test file does not contain triple.\n");
882 arch.SetTriple (llvm::Triple (value_sp->GetStringValue()));
884 bool success = false;
885 std::unique_ptr<EmulateInstruction> insn_emulator_ap(EmulateInstruction::FindPlugin(arch, eInstructionTypeAny, nullptr));
886 if (insn_emulator_ap)
887 success = insn_emulator_ap->TestEmulation (out_stream, arch, data_dictionary);
890 out_stream->Printf ("Emulation test succeeded.");
892 out_stream->Printf ("Emulation test failed.");
898 Instruction::Emulate (const ArchSpec &arch,
899 uint32_t evaluate_options,
901 EmulateInstruction::ReadMemoryCallback read_mem_callback,
902 EmulateInstruction::WriteMemoryCallback write_mem_callback,
903 EmulateInstruction::ReadRegisterCallback read_reg_callback,
904 EmulateInstruction::WriteRegisterCallback write_reg_callback)
906 std::unique_ptr<EmulateInstruction> insn_emulator_ap(EmulateInstruction::FindPlugin(arch, eInstructionTypeAny, nullptr));
907 if (insn_emulator_ap)
909 insn_emulator_ap->SetBaton(baton);
910 insn_emulator_ap->SetCallbacks(read_mem_callback, write_mem_callback, read_reg_callback, write_reg_callback);
911 insn_emulator_ap->SetInstruction(GetOpcode(), GetAddress(), nullptr);
912 return insn_emulator_ap->EvaluateInstruction(evaluate_options);
919 Instruction::GetData (DataExtractor &data)
921 return m_opcode.GetData(data);
924 InstructionList::InstructionList() :
929 InstructionList::~InstructionList() = default;
932 InstructionList::GetSize() const
934 return m_instructions.size();
938 InstructionList::GetMaxOpcocdeByteSize () const
940 uint32_t max_inst_size = 0;
941 collection::const_iterator pos, end;
942 for (pos = m_instructions.begin(), end = m_instructions.end();
946 uint32_t inst_size = (*pos)->GetOpcode().GetByteSize();
947 if (max_inst_size < inst_size)
948 max_inst_size = inst_size;
950 return max_inst_size;
954 InstructionList::GetInstructionAtIndex (size_t idx) const
956 InstructionSP inst_sp;
957 if (idx < m_instructions.size())
958 inst_sp = m_instructions[idx];
963 InstructionList::Dump (Stream *s,
966 const ExecutionContext* exe_ctx)
968 const uint32_t max_opcode_byte_size = GetMaxOpcocdeByteSize();
969 collection::const_iterator pos, begin, end;
971 const FormatEntity::Entry *disassembly_format = nullptr;
972 FormatEntity::Entry format;
973 if (exe_ctx && exe_ctx->HasTargetScope())
975 disassembly_format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat ();
979 FormatEntity::Parse("${addr}: ", format);
980 disassembly_format = &format;
983 for (begin = m_instructions.begin(), end = m_instructions.end(), pos = begin;
989 (*pos)->Dump(s, max_opcode_byte_size, show_address, show_bytes, exe_ctx, nullptr, nullptr, disassembly_format, 0);
994 InstructionList::Clear()
996 m_instructions.clear();
1000 InstructionList::Append (lldb::InstructionSP &inst_sp)
1003 m_instructions.push_back(inst_sp);
1007 InstructionList::GetIndexOfNextBranchInstruction(uint32_t start, Target &target) const
1009 size_t num_instructions = m_instructions.size();
1011 uint32_t next_branch = UINT32_MAX;
1013 for (i = start; i < num_instructions; i++)
1015 if (m_instructions[i]->DoesBranch())
1022 // Hexagon needs the first instruction of the packet with the branch.
1023 // Go backwards until we find an instruction marked end-of-packet, or
1024 // until we hit start.
1025 if (target.GetArchitecture().GetTriple().getArch() == llvm::Triple::hexagon)
1027 // If we didn't find a branch, find the last packet start.
1028 if (next_branch == UINT32_MAX)
1030 i = num_instructions - 1;
1038 uint32_t inst_bytes;
1039 bool prefer_file_cache = false; // Read from process if process is running
1040 lldb::addr_t load_addr = LLDB_INVALID_ADDRESS;
1041 target.ReadMemory(m_instructions[i]->GetAddress(),
1047 // If we have an error reading memory, return start
1048 if (!error.Success())
1050 // check if this is the last instruction in a packet
1051 // bits 15:14 will be 11b or 00b for a duplex
1052 if (((inst_bytes & 0xC000) == 0xC000) ||
1053 ((inst_bytes & 0xC000) == 0x0000))
1055 // instruction after this should be the start of next packet
1056 next_branch = i + 1;
1061 if (next_branch == UINT32_MAX)
1063 // We couldn't find the previous packet, so return start
1064 next_branch = start;
1071 InstructionList::GetIndexOfInstructionAtAddress (const Address &address)
1073 size_t num_instructions = m_instructions.size();
1074 uint32_t index = UINT32_MAX;
1075 for (size_t i = 0; i < num_instructions; i++)
1077 if (m_instructions[i]->GetAddress() == address)
1087 InstructionList::GetIndexOfInstructionAtLoadAddress (lldb::addr_t load_addr, Target &target)
1090 address.SetLoadAddress(load_addr, &target);
1091 return GetIndexOfInstructionAtAddress(address);
1095 Disassembler::ParseInstructions (const ExecutionContext *exe_ctx,
1096 const AddressRange &range,
1097 Stream *error_strm_ptr,
1098 bool prefer_file_cache)
1102 Target *target = exe_ctx->GetTargetPtr();
1103 const addr_t byte_size = range.GetByteSize();
1104 if (target == nullptr || byte_size == 0 || !range.GetBaseAddress().IsValid())
1107 DataBufferHeap *heap_buffer = new DataBufferHeap (byte_size, '\0');
1108 DataBufferSP data_sp(heap_buffer);
1111 lldb::addr_t load_addr = LLDB_INVALID_ADDRESS;
1112 const size_t bytes_read = target->ReadMemory (range.GetBaseAddress(),
1114 heap_buffer->GetBytes(),
1115 heap_buffer->GetByteSize(),
1121 if (bytes_read != heap_buffer->GetByteSize())
1122 heap_buffer->SetByteSize (bytes_read);
1123 DataExtractor data (data_sp,
1124 m_arch.GetByteOrder(),
1125 m_arch.GetAddressByteSize());
1126 const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS;
1127 return DecodeInstructions(range.GetBaseAddress(), data, 0, UINT32_MAX, false,
1130 else if (error_strm_ptr)
1132 const char *error_cstr = error.AsCString();
1135 error_strm_ptr->Printf("error: %s\n", error_cstr);
1139 else if (error_strm_ptr)
1141 error_strm_ptr->PutCString("error: invalid execution context\n");
1147 Disassembler::ParseInstructions (const ExecutionContext *exe_ctx,
1148 const Address &start,
1149 uint32_t num_instructions,
1150 bool prefer_file_cache)
1152 m_instruction_list.Clear();
1154 if (exe_ctx == nullptr || num_instructions == 0 || !start.IsValid())
1157 Target *target = exe_ctx->GetTargetPtr();
1158 // Calculate the max buffer size we will need in order to disassemble
1159 const addr_t byte_size = num_instructions * m_arch.GetMaximumOpcodeByteSize();
1161 if (target == nullptr || byte_size == 0)
1164 DataBufferHeap *heap_buffer = new DataBufferHeap (byte_size, '\0');
1165 DataBufferSP data_sp (heap_buffer);
1168 lldb::addr_t load_addr = LLDB_INVALID_ADDRESS;
1169 const size_t bytes_read = target->ReadMemory (start,
1171 heap_buffer->GetBytes(),
1176 const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS;
1178 if (bytes_read == 0)
1180 DataExtractor data (data_sp,
1181 m_arch.GetByteOrder(),
1182 m_arch.GetAddressByteSize());
1184 const bool append_instructions = true;
1185 DecodeInstructions (start,
1189 append_instructions,
1192 return m_instruction_list.GetSize();
1195 //----------------------------------------------------------------------
1196 // Disassembler copy constructor
1197 //----------------------------------------------------------------------
1198 Disassembler::Disassembler(const ArchSpec& arch, const char *flavor) :
1200 m_instruction_list(),
1201 m_base_addr(LLDB_INVALID_ADDRESS),
1204 if (flavor == nullptr)
1205 m_flavor.assign("default");
1207 m_flavor.assign(flavor);
1209 // If this is an arm variant that can only include thumb (T16, T32)
1210 // instructions, force the arch triple to be "thumbv.." instead of
1212 if (arch.IsAlwaysThumbInstructions())
1214 std::string thumb_arch_name (arch.GetTriple().getArchName().str());
1215 // Replace "arm" with "thumb" so we get all thumb variants correct
1216 if (thumb_arch_name.size() > 3)
1218 thumb_arch_name.erase(0, 3);
1219 thumb_arch_name.insert(0, "thumb");
1221 m_arch.SetTriple (thumb_arch_name.c_str());
1225 Disassembler::~Disassembler() = default;
1228 Disassembler::GetInstructionList ()
1230 return m_instruction_list;
1233 const InstructionList &
1234 Disassembler::GetInstructionList () const
1236 return m_instruction_list;
1239 //----------------------------------------------------------------------
1240 // Class PseudoInstruction
1241 //----------------------------------------------------------------------
1243 PseudoInstruction::PseudoInstruction () :
1244 Instruction (Address(), eAddressClassUnknown),
1249 PseudoInstruction::~PseudoInstruction() = default;
1252 PseudoInstruction::DoesBranch ()
1254 // This is NOT a valid question for a pseudo instruction.
1259 PseudoInstruction::HasDelaySlot ()
1261 // This is NOT a valid question for a pseudo instruction.
1266 PseudoInstruction::Decode (const lldb_private::Disassembler &disassembler,
1267 const lldb_private::DataExtractor &data,
1268 lldb::offset_t data_offset)
1270 return m_opcode.GetByteSize();
1274 PseudoInstruction::SetOpcode (size_t opcode_size, void *opcode_data)
1279 switch (opcode_size)
1283 uint8_t value8 = *((uint8_t *) opcode_data);
1284 m_opcode.SetOpcode8 (value8, eByteOrderInvalid);
1289 uint16_t value16 = *((uint16_t *) opcode_data);
1290 m_opcode.SetOpcode16 (value16, eByteOrderInvalid);
1295 uint32_t value32 = *((uint32_t *) opcode_data);
1296 m_opcode.SetOpcode32 (value32, eByteOrderInvalid);
1301 uint64_t value64 = *((uint64_t *) opcode_data);
1302 m_opcode.SetOpcode64 (value64, eByteOrderInvalid);
1311 PseudoInstruction::SetDescription (const char *description)
1313 if (description && strlen (description) > 0)
1314 m_description = description;