1 //===-- DisassemblerLLVMC.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 "DisassemblerLLVMC.h"
12 #include "llvm-c/Disassembler.h"
13 #include "llvm/MC/MCAsmInfo.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCDisassembler.h"
16 #include "llvm/MC/MCInst.h"
17 #include "llvm/MC/MCInstPrinter.h"
18 #include "llvm/MC/MCInstrInfo.h"
19 #include "llvm/MC/MCRegisterInfo.h"
20 #include "llvm/MC/MCSubtargetInfo.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MemoryObject.h"
23 #include "llvm/Support/TargetRegistry.h"
24 #include "llvm/Support/TargetSelect.h"
25 #include "llvm/ADT/SmallString.h"
28 #include "lldb/Core/Address.h"
29 #include "lldb/Core/DataExtractor.h"
30 #include "lldb/Core/Module.h"
31 #include "lldb/Core/Stream.h"
32 #include "lldb/Symbol/SymbolContext.h"
33 #include "lldb/Target/ExecutionContext.h"
34 #include "lldb/Target/Process.h"
35 #include "lldb/Target/RegisterContext.h"
36 #include "lldb/Target/Target.h"
37 #include "lldb/Target/StackFrame.h"
42 using namespace lldb_private;
44 class InstructionLLVMC : public lldb_private::Instruction
47 InstructionLLVMC (DisassemblerLLVMC &disasm,
48 const lldb_private::Address &address,
49 AddressClass addr_class) :
50 Instruction (address, addr_class),
51 m_disasm_sp (disasm.shared_from_this()),
52 m_does_branch (eLazyBoolCalculate),
54 m_using_file_addr (false)
66 if (m_does_branch == eLazyBoolCalculate)
68 GetDisassemblerLLVMC().Lock(this, NULL);
70 if (m_opcode.GetData(data))
72 bool is_alternate_isa;
73 lldb::addr_t pc = m_address.GetFileAddress();
75 DisassemblerLLVMC::LLVMCDisassembler *mc_disasm_ptr = GetDisasmToUse (is_alternate_isa);
76 const uint8_t *opcode_data = data.GetDataStart();
77 const size_t opcode_data_len = data.GetByteSize();
79 const size_t inst_size = mc_disasm_ptr->GetMCInst (opcode_data,
83 // Be conservative, if we didn't understand the instruction, say it might branch...
85 m_does_branch = eLazyBoolYes;
88 const bool can_branch = mc_disasm_ptr->CanBranch(inst);
90 m_does_branch = eLazyBoolYes;
92 m_does_branch = eLazyBoolNo;
95 GetDisassemblerLLVMC().Unlock();
97 return m_does_branch == eLazyBoolYes;
100 DisassemblerLLVMC::LLVMCDisassembler *
101 GetDisasmToUse (bool &is_alternate_isa)
103 is_alternate_isa = false;
104 DisassemblerLLVMC &llvm_disasm = GetDisassemblerLLVMC();
105 if (llvm_disasm.m_alternate_disasm_ap.get() != NULL)
107 const AddressClass address_class = GetAddressClass ();
109 if (address_class == eAddressClassCodeAlternateISA)
111 is_alternate_isa = true;
112 return llvm_disasm.m_alternate_disasm_ap.get();
115 return llvm_disasm.m_disasm_ap.get();
119 Decode (const lldb_private::Disassembler &disassembler,
120 const lldb_private::DataExtractor &data,
121 lldb::offset_t data_offset)
123 // All we have to do is read the opcode which can be easy for some
126 DisassemblerLLVMC &llvm_disasm = GetDisassemblerLLVMC();
127 const ArchSpec &arch = llvm_disasm.GetArchitecture();
129 const uint32_t min_op_byte_size = arch.GetMinimumOpcodeByteSize();
130 const uint32_t max_op_byte_size = arch.GetMaximumOpcodeByteSize();
131 if (min_op_byte_size == max_op_byte_size)
133 // Fixed size instructions, just read that amount of data.
134 if (!data.ValidOffsetForDataOfSize(data_offset, min_op_byte_size))
137 switch (min_op_byte_size)
140 m_opcode.SetOpcode8 (data.GetU8 (&data_offset));
145 m_opcode.SetOpcode16 (data.GetU16 (&data_offset));
150 m_opcode.SetOpcode32 (data.GetU32 (&data_offset));
155 m_opcode.SetOpcode64 (data.GetU64 (&data_offset));
160 m_opcode.SetOpcodeBytes(data.PeekData(data_offset, min_op_byte_size), min_op_byte_size);
167 bool is_alternate_isa = false;
168 DisassemblerLLVMC::LLVMCDisassembler *mc_disasm_ptr = GetDisasmToUse (is_alternate_isa);
170 const llvm::Triple::ArchType machine = arch.GetMachine();
171 if (machine == llvm::Triple::arm || machine == llvm::Triple::thumb)
173 if (machine == llvm::Triple::thumb || is_alternate_isa)
175 uint32_t thumb_opcode = data.GetU16(&data_offset);
176 if ((thumb_opcode & 0xe000) != 0xe000 || ((thumb_opcode & 0x1800u) == 0))
178 m_opcode.SetOpcode16 (thumb_opcode);
184 thumb_opcode |= data.GetU16(&data_offset);
185 m_opcode.SetOpcode16_2 (thumb_opcode);
191 m_opcode.SetOpcode32 (data.GetU32(&data_offset));
197 // The opcode isn't evenly sized, so we need to actually use the llvm
198 // disassembler to parse it and get the size.
199 uint8_t *opcode_data = const_cast<uint8_t *>(data.PeekData (data_offset, 1));
200 const size_t opcode_data_len = data.BytesLeft(data_offset);
201 const addr_t pc = m_address.GetFileAddress();
204 llvm_disasm.Lock(this, NULL);
205 const size_t inst_size = mc_disasm_ptr->GetMCInst(opcode_data,
209 llvm_disasm.Unlock();
214 m_opcode.SetOpcodeBytes(opcode_data, inst_size);
219 return m_opcode.GetByteSize();
223 AppendComment (std::string &description)
225 if (m_comment.empty())
226 m_comment.swap (description);
229 m_comment.append(", ");
230 m_comment.append(description);
235 CalculateMnemonicOperandsAndComment (const lldb_private::ExecutionContext *exe_ctx)
238 const AddressClass address_class = GetAddressClass ();
240 if (m_opcode.GetData(data))
242 char out_string[512];
244 DisassemblerLLVMC &llvm_disasm = GetDisassemblerLLVMC();
246 DisassemblerLLVMC::LLVMCDisassembler *mc_disasm_ptr;
248 if (address_class == eAddressClassCodeAlternateISA)
249 mc_disasm_ptr = llvm_disasm.m_alternate_disasm_ap.get();
251 mc_disasm_ptr = llvm_disasm.m_disasm_ap.get();
253 lldb::addr_t pc = m_address.GetFileAddress();
254 m_using_file_addr = true;
256 const bool data_from_file = GetDisassemblerLLVMC().m_data_from_file;
257 bool use_hex_immediates = true;
258 Disassembler::HexImmediateStyle hex_style = Disassembler::eHexStyleC;
262 Target *target = exe_ctx->GetTargetPtr();
265 use_hex_immediates = target->GetUseHexImmediates();
266 hex_style = target->GetHexImmediateStyle();
270 const lldb::addr_t load_addr = m_address.GetLoadAddress(target);
271 if (load_addr != LLDB_INVALID_ADDRESS)
274 m_using_file_addr = false;
280 llvm_disasm.Lock(this, exe_ctx);
282 const uint8_t *opcode_data = data.GetDataStart();
283 const size_t opcode_data_len = data.GetByteSize();
285 size_t inst_size = mc_disasm_ptr->GetMCInst (opcode_data,
292 mc_disasm_ptr->SetStyle(use_hex_immediates, hex_style);
293 mc_disasm_ptr->PrintMCInst(inst, out_string, sizeof(out_string));
296 llvm_disasm.Unlock();
300 m_comment.assign ("unknown opcode");
301 inst_size = m_opcode.GetByteSize();
302 StreamString mnemonic_strm;
303 lldb::offset_t offset = 0;
308 const uint8_t uval8 = data.GetU8 (&offset);
309 m_opcode.SetOpcode8 (uval8);
310 m_opcode_name.assign (".byte");
311 mnemonic_strm.Printf("0x%2.2x", uval8);
316 const uint16_t uval16 = data.GetU16(&offset);
317 m_opcode.SetOpcode16(uval16);
318 m_opcode_name.assign (".short");
319 mnemonic_strm.Printf("0x%4.4x", uval16);
324 const uint32_t uval32 = data.GetU32(&offset);
325 m_opcode.SetOpcode32(uval32);
326 m_opcode_name.assign (".long");
327 mnemonic_strm.Printf("0x%8.8x", uval32);
332 const uint64_t uval64 = data.GetU64(&offset);
333 m_opcode.SetOpcode64(uval64);
334 m_opcode_name.assign (".quad");
335 mnemonic_strm.Printf("0x%16.16" PRIx64, uval64);
343 const uint8_t *bytes = data.PeekData(offset, inst_size);
346 m_opcode_name.assign (".byte");
347 m_opcode.SetOpcodeBytes(bytes, inst_size);
348 mnemonic_strm.Printf("0x%2.2x", bytes[0]);
349 for (uint32_t i=1; i<inst_size; ++i)
350 mnemonic_strm.Printf(" 0x%2.2x", bytes[i]);
354 m_mnemonics.swap(mnemonic_strm.GetString());
359 if (m_does_branch == eLazyBoolCalculate)
361 const bool can_branch = mc_disasm_ptr->CanBranch(inst);
363 m_does_branch = eLazyBoolYes;
365 m_does_branch = eLazyBoolNo;
370 if (!s_regex_compiled)
372 ::regcomp(&s_regex, "[ \t]*([^ ^\t]+)[ \t]*([^ ^\t].*)?", REG_EXTENDED);
373 s_regex_compiled = true;
376 ::regmatch_t matches[3];
378 if (!::regexec(&s_regex, out_string, sizeof(matches) / sizeof(::regmatch_t), matches, 0))
380 if (matches[1].rm_so != -1)
381 m_opcode_name.assign(out_string + matches[1].rm_so, matches[1].rm_eo - matches[1].rm_so);
382 if (matches[2].rm_so != -1)
383 m_mnemonics.assign(out_string + matches[2].rm_so, matches[2].rm_eo - matches[2].rm_so);
395 UsingFileAddress() const
397 return m_using_file_addr;
402 return m_opcode.GetByteSize();
406 GetDisassemblerLLVMC ()
408 return *(DisassemblerLLVMC *)m_disasm_sp.get();
412 DisassemblerSP m_disasm_sp; // for ownership
413 LazyBool m_does_branch;
415 bool m_using_file_addr;
417 static bool s_regex_compiled;
418 static ::regex_t s_regex;
421 bool InstructionLLVMC::s_regex_compiled = false;
422 ::regex_t InstructionLLVMC::s_regex;
424 DisassemblerLLVMC::LLVMCDisassembler::LLVMCDisassembler (const char *triple, unsigned flavor, DisassemblerLLVMC &owner):
428 const llvm::Target *curr_target = llvm::TargetRegistry::lookupTarget(triple, Error);
435 m_instr_info_ap.reset(curr_target->createMCInstrInfo());
436 m_reg_info_ap.reset (curr_target->createMCRegInfo(triple));
438 std::string features_str;
440 m_subtarget_info_ap.reset(curr_target->createMCSubtargetInfo(triple, "",
443 m_asm_info_ap.reset(curr_target->createMCAsmInfo(triple));
445 if (m_instr_info_ap.get() == NULL || m_reg_info_ap.get() == NULL || m_subtarget_info_ap.get() == NULL || m_asm_info_ap.get() == NULL)
451 m_context_ap.reset(new llvm::MCContext(*m_asm_info_ap.get(), *(m_reg_info_ap.get()), 0));
453 m_disasm_ap.reset(curr_target->createMCDisassembler(*m_subtarget_info_ap.get()));
454 if (m_disasm_ap.get())
456 m_disasm_ap->setupForSymbolicDisassembly(NULL,
457 DisassemblerLLVMC::SymbolLookupCallback,
461 unsigned asm_printer_variant;
463 asm_printer_variant = m_asm_info_ap->getAssemblerDialect();
466 asm_printer_variant = flavor;
469 m_instr_printer_ap.reset(curr_target->createMCInstPrinter(asm_printer_variant,
470 *m_asm_info_ap.get(),
471 *m_instr_info_ap.get(),
472 *m_reg_info_ap.get(),
473 *m_subtarget_info_ap.get()));
474 if (m_instr_printer_ap.get() == NULL)
484 DisassemblerLLVMC::LLVMCDisassembler::~LLVMCDisassembler()
489 // This is the memory object we use in GetInstruction.
490 class LLDBDisasmMemoryObject : public llvm::MemoryObject {
491 const uint8_t *m_bytes;
495 LLDBDisasmMemoryObject(const uint8_t *bytes, uint64_t size, uint64_t basePC) :
496 m_bytes(bytes), m_size(size), m_base_PC(basePC) {}
498 uint64_t getBase() const { return m_base_PC; }
499 uint64_t getExtent() const { return m_size; }
501 int readByte(uint64_t addr, uint8_t *byte) const {
502 if (addr - m_base_PC >= m_size)
504 *byte = m_bytes[addr - m_base_PC];
508 } // End Anonymous Namespace
511 DisassemblerLLVMC::LLVMCDisassembler::GetMCInst (const uint8_t *opcode_data,
512 size_t opcode_data_len,
514 llvm::MCInst &mc_inst)
516 LLDBDisasmMemoryObject memory_object (opcode_data, opcode_data_len, pc);
517 llvm::MCDisassembler::DecodeStatus status;
519 uint64_t new_inst_size;
520 status = m_disasm_ap->getInstruction(mc_inst,
526 if (status == llvm::MCDisassembler::Success)
527 return new_inst_size;
533 DisassemblerLLVMC::LLVMCDisassembler::PrintMCInst (llvm::MCInst &mc_inst,
537 llvm::StringRef unused_annotations;
538 llvm::SmallString<64> inst_string;
539 llvm::raw_svector_ostream inst_stream(inst_string);
540 m_instr_printer_ap->printInst (&mc_inst, inst_stream, unused_annotations);
542 const size_t output_size = std::min(dst_len - 1, inst_string.size());
543 std::memcpy(dst, inst_string.data(), output_size);
544 dst[output_size] = '\0';
550 DisassemblerLLVMC::LLVMCDisassembler::SetStyle (bool use_hex_immed, HexImmediateStyle hex_style)
552 m_instr_printer_ap->setPrintImmHex(use_hex_immed);
555 case eHexStyleC: m_instr_printer_ap->setPrintImmHex(llvm::HexStyle::C); break;
556 case eHexStyleAsm: m_instr_printer_ap->setPrintImmHex(llvm::HexStyle::Asm); break;
561 DisassemblerLLVMC::LLVMCDisassembler::CanBranch (llvm::MCInst &mc_inst)
563 return m_instr_info_ap->get(mc_inst.getOpcode()).mayAffectControlFlow(mc_inst, *m_reg_info_ap.get());
567 DisassemblerLLVMC::FlavorValidForArchSpec (const lldb_private::ArchSpec &arch, const char *flavor)
569 llvm::Triple triple = arch.GetTriple();
570 if (flavor == NULL || strcmp (flavor, "default") == 0)
573 if (triple.getArch() == llvm::Triple::x86 || triple.getArch() == llvm::Triple::x86_64)
575 if (strcmp (flavor, "intel") == 0 || strcmp (flavor, "att") == 0)
586 DisassemblerLLVMC::CreateInstance (const ArchSpec &arch, const char *flavor)
588 if (arch.GetTriple().getArch() != llvm::Triple::UnknownArch)
590 std::unique_ptr<DisassemblerLLVMC> disasm_ap (new DisassemblerLLVMC(arch, flavor));
592 if (disasm_ap.get() && disasm_ap->IsValid())
593 return disasm_ap.release();
598 DisassemblerLLVMC::DisassemblerLLVMC (const ArchSpec &arch, const char *flavor_string) :
599 Disassembler(arch, flavor_string),
602 m_data_from_file (false)
604 if (!FlavorValidForArchSpec (arch, m_flavor.c_str()))
606 m_flavor.assign("default");
609 const char *triple = arch.GetTriple().getTriple().c_str();
610 unsigned flavor = ~0U;
612 // So far the only supported flavor is "intel" on x86. The base class will set this
613 // correctly coming in.
614 if (arch.GetTriple().getArch() == llvm::Triple::x86
615 || arch.GetTriple().getArch() == llvm::Triple::x86_64)
617 if (m_flavor == "intel")
621 else if (m_flavor == "att")
627 ArchSpec thumb_arch(arch);
628 if (arch.GetTriple().getArch() == llvm::Triple::arm)
630 std::string thumb_arch_name (thumb_arch.GetTriple().getArchName().str());
631 // Replace "arm" with "thumb" so we get all thumb variants correct
632 if (thumb_arch_name.size() > 3)
634 thumb_arch_name.erase(0,3);
635 thumb_arch_name.insert(0, "thumb");
639 thumb_arch_name = "thumbv7";
641 thumb_arch.GetTriple().setArchName(llvm::StringRef(thumb_arch_name.c_str()));
644 // Cortex-M3 devices (e.g. armv7m) can only execute thumb (T2) instructions,
645 // so hardcode the primary disassembler to thumb mode.
646 if (arch.GetTriple().getArch() == llvm::Triple::arm
647 && (arch.GetCore() == ArchSpec::Core::eCore_arm_armv7m || arch.GetCore() == ArchSpec::Core::eCore_arm_armv7em))
649 triple = thumb_arch.GetTriple().getTriple().c_str();
652 m_disasm_ap.reset (new LLVMCDisassembler(triple, flavor, *this));
653 if (!m_disasm_ap->IsValid())
655 // We use m_disasm_ap.get() to tell whether we are valid or not, so if this isn't good for some reason,
656 // we reset it, and then we won't be valid and FindPlugin will fail and we won't get used.
660 // For arm CPUs that can execute arm or thumb instructions, also create a thumb instruction disassembler.
661 if (arch.GetTriple().getArch() == llvm::Triple::arm)
663 std::string thumb_triple(thumb_arch.GetTriple().getTriple());
664 m_alternate_disasm_ap.reset(new LLVMCDisassembler(thumb_triple.c_str(), flavor, *this));
665 if (!m_alternate_disasm_ap->IsValid())
668 m_alternate_disasm_ap.reset();
673 DisassemblerLLVMC::~DisassemblerLLVMC()
678 DisassemblerLLVMC::DecodeInstructions (const Address &base_addr,
679 const DataExtractor& data,
680 lldb::offset_t data_offset,
681 size_t num_instructions,
686 m_instruction_list.Clear();
691 m_data_from_file = data_from_file;
692 uint32_t data_cursor = data_offset;
693 const size_t data_byte_size = data.GetByteSize();
694 uint32_t instructions_parsed = 0;
695 Address inst_addr(base_addr);
697 while (data_cursor < data_byte_size && instructions_parsed < num_instructions)
700 AddressClass address_class = eAddressClassCode;
702 if (m_alternate_disasm_ap.get() != NULL)
703 address_class = inst_addr.GetAddressClass ();
705 InstructionSP inst_sp(new InstructionLLVMC(*this,
712 uint32_t inst_size = inst_sp->Decode(*this, data, data_cursor);
717 m_instruction_list.Append(inst_sp);
718 data_cursor += inst_size;
719 inst_addr.Slide(inst_size);
720 instructions_parsed++;
723 return data_cursor - data_offset;
727 DisassemblerLLVMC::Initialize()
729 PluginManager::RegisterPlugin (GetPluginNameStatic(),
730 "Disassembler that uses LLVM MC to disassemble i386, x86_64 and ARM.",
733 llvm::InitializeAllTargetInfos();
734 llvm::InitializeAllTargetMCs();
735 llvm::InitializeAllAsmParsers();
736 llvm::InitializeAllDisassemblers();
740 DisassemblerLLVMC::Terminate()
742 PluginManager::UnregisterPlugin (CreateInstance);
747 DisassemblerLLVMC::GetPluginNameStatic()
749 static ConstString g_name("llvm-mc");
753 int DisassemblerLLVMC::OpInfoCallback (void *disassembler,
760 return static_cast<DisassemblerLLVMC*>(disassembler)->OpInfo (pc,
767 const char *DisassemblerLLVMC::SymbolLookupCallback (void *disassembler,
773 return static_cast<DisassemblerLLVMC*>(disassembler)->SymbolLookup(value,
779 int DisassemblerLLVMC::OpInfo (uint64_t PC,
790 bzero (tag_bug, sizeof(::LLVMOpInfo1));
796 const char *DisassemblerLLVMC::SymbolLookup (uint64_t value,
803 if (m_exe_ctx && m_inst)
805 //std::string remove_this_prior_to_checkin;
806 Target *target = m_exe_ctx ? m_exe_ctx->GetTargetPtr() : NULL;
807 Address value_so_addr;
808 if (m_inst->UsingFileAddress())
810 ModuleSP module_sp(m_inst->GetAddress().GetModule());
812 module_sp->ResolveFileAddress(value, value_so_addr);
814 else if (target && !target->GetSectionLoadList().IsEmpty())
816 target->GetSectionLoadList().ResolveLoadAddress(value, value_so_addr);
819 if (value_so_addr.IsValid() && value_so_addr.GetSection())
823 value_so_addr.Dump (&ss,
825 Address::DumpStyleResolvedDescriptionNoModule,
826 Address::DumpStyleSectionNameOffset);
828 if (!ss.GetString().empty())
830 m_inst->AppendComment(ss.GetString());
836 *type_ptr = LLVMDisassembler_ReferenceType_InOut_None;
841 //------------------------------------------------------------------
842 // PluginInterface protocol
843 //------------------------------------------------------------------
845 DisassemblerLLVMC::GetPluginName()
847 return GetPluginNameStatic();
851 DisassemblerLLVMC::GetPluginVersion()