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 //===----------------------------------------------------------------------===//
13 #include "DisassemblerLLVMC.h"
15 // Other libraries and framework includes
16 #include "llvm-c/Disassembler.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
21 #include "llvm/MC/MCDisassembler/MCExternalSymbolizer.h"
22 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstPrinter.h"
25 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCRegisterInfo.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ScopedPrinter.h"
30 #include "llvm/Support/TargetRegistry.h"
31 #include "llvm/Support/TargetSelect.h"
33 #include "lldb/Core/Address.h"
34 #include "lldb/Core/Module.h"
35 #include "lldb/Symbol/SymbolContext.h"
36 #include "lldb/Target/ExecutionContext.h"
37 #include "lldb/Target/Process.h"
38 #include "lldb/Target/RegisterContext.h"
39 #include "lldb/Target/SectionLoadList.h"
40 #include "lldb/Target/StackFrame.h"
41 #include "lldb/Target/Target.h"
42 #include "lldb/Utility/DataExtractor.h"
43 #include "lldb/Utility/Log.h"
44 #include "lldb/Utility/RegularExpression.h"
45 #include "lldb/Utility/Stream.h"
48 using namespace lldb_private;
50 class DisassemblerLLVMC::MCDisasmInstance {
52 static std::unique_ptr<MCDisasmInstance>
53 Create(const char *triple, const char *cpu, const char *features_str,
54 unsigned flavor, DisassemblerLLVMC &owner);
56 ~MCDisasmInstance() = default;
58 uint64_t GetMCInst(const uint8_t *opcode_data, size_t opcode_data_len,
59 lldb::addr_t pc, llvm::MCInst &mc_inst) const;
60 void PrintMCInst(llvm::MCInst &mc_inst, std::string &inst_string,
61 std::string &comments_string);
62 void SetStyle(bool use_hex_immed, HexImmediateStyle hex_style);
63 bool CanBranch(llvm::MCInst &mc_inst) const;
64 bool HasDelaySlot(llvm::MCInst &mc_inst) const;
65 bool IsCall(llvm::MCInst &mc_inst) const;
68 MCDisasmInstance(std::unique_ptr<llvm::MCInstrInfo> &&instr_info_up,
69 std::unique_ptr<llvm::MCRegisterInfo> &®_info_up,
70 std::unique_ptr<llvm::MCSubtargetInfo> &&subtarget_info_up,
71 std::unique_ptr<llvm::MCAsmInfo> &&asm_info_up,
72 std::unique_ptr<llvm::MCContext> &&context_up,
73 std::unique_ptr<llvm::MCDisassembler> &&disasm_up,
74 std::unique_ptr<llvm::MCInstPrinter> &&instr_printer_up);
76 std::unique_ptr<llvm::MCInstrInfo> m_instr_info_up;
77 std::unique_ptr<llvm::MCRegisterInfo> m_reg_info_up;
78 std::unique_ptr<llvm::MCSubtargetInfo> m_subtarget_info_up;
79 std::unique_ptr<llvm::MCAsmInfo> m_asm_info_up;
80 std::unique_ptr<llvm::MCContext> m_context_up;
81 std::unique_ptr<llvm::MCDisassembler> m_disasm_up;
82 std::unique_ptr<llvm::MCInstPrinter> m_instr_printer_up;
85 class InstructionLLVMC : public lldb_private::Instruction {
87 InstructionLLVMC(DisassemblerLLVMC &disasm,
88 const lldb_private::Address &address,
89 AddressClass addr_class)
90 : Instruction(address, addr_class),
91 m_disasm_wp(std::static_pointer_cast<DisassemblerLLVMC>(
92 disasm.shared_from_this())),
93 m_does_branch(eLazyBoolCalculate), m_has_delay_slot(eLazyBoolCalculate),
94 m_is_call(eLazyBoolCalculate), m_is_valid(false),
95 m_using_file_addr(false) {}
97 ~InstructionLLVMC() override = default;
99 bool DoesBranch() override {
100 if (m_does_branch == eLazyBoolCalculate) {
101 std::shared_ptr<DisassemblerLLVMC> disasm_sp(GetDisassembler());
103 disasm_sp->Lock(this, NULL);
105 if (m_opcode.GetData(data)) {
106 bool is_alternate_isa;
107 lldb::addr_t pc = m_address.GetFileAddress();
109 DisassemblerLLVMC::MCDisasmInstance *mc_disasm_ptr =
110 GetDisasmToUse(is_alternate_isa);
111 const uint8_t *opcode_data = data.GetDataStart();
112 const size_t opcode_data_len = data.GetByteSize();
114 const size_t inst_size =
115 mc_disasm_ptr->GetMCInst(opcode_data, opcode_data_len, pc, inst);
116 // Be conservative, if we didn't understand the instruction, say it
119 m_does_branch = eLazyBoolYes;
121 const bool can_branch = mc_disasm_ptr->CanBranch(inst);
123 m_does_branch = eLazyBoolYes;
125 m_does_branch = eLazyBoolNo;
131 return m_does_branch == eLazyBoolYes;
134 bool HasDelaySlot() override {
135 if (m_has_delay_slot == eLazyBoolCalculate) {
136 std::shared_ptr<DisassemblerLLVMC> disasm_sp(GetDisassembler());
138 disasm_sp->Lock(this, NULL);
140 if (m_opcode.GetData(data)) {
141 bool is_alternate_isa;
142 lldb::addr_t pc = m_address.GetFileAddress();
144 DisassemblerLLVMC::MCDisasmInstance *mc_disasm_ptr =
145 GetDisasmToUse(is_alternate_isa);
146 const uint8_t *opcode_data = data.GetDataStart();
147 const size_t opcode_data_len = data.GetByteSize();
149 const size_t inst_size =
150 mc_disasm_ptr->GetMCInst(opcode_data, opcode_data_len, pc, inst);
151 // if we didn't understand the instruction, say it doesn't have a
154 m_has_delay_slot = eLazyBoolNo;
156 const bool has_delay_slot = mc_disasm_ptr->HasDelaySlot(inst);
158 m_has_delay_slot = eLazyBoolYes;
160 m_has_delay_slot = eLazyBoolNo;
166 return m_has_delay_slot == eLazyBoolYes;
169 DisassemblerLLVMC::MCDisasmInstance *GetDisasmToUse(bool &is_alternate_isa) {
170 is_alternate_isa = false;
171 std::shared_ptr<DisassemblerLLVMC> disasm_sp(GetDisassembler());
173 if (disasm_sp->m_alternate_disasm_up) {
174 const AddressClass address_class = GetAddressClass();
176 if (address_class == AddressClass::eCodeAlternateISA) {
177 is_alternate_isa = true;
178 return disasm_sp->m_alternate_disasm_up.get();
181 return disasm_sp->m_disasm_up.get();
186 size_t Decode(const lldb_private::Disassembler &disassembler,
187 const lldb_private::DataExtractor &data,
188 lldb::offset_t data_offset) override {
189 // All we have to do is read the opcode which can be easy for some
192 std::shared_ptr<DisassemblerLLVMC> disasm_sp(GetDisassembler());
194 const ArchSpec &arch = disasm_sp->GetArchitecture();
195 const lldb::ByteOrder byte_order = data.GetByteOrder();
197 const uint32_t min_op_byte_size = arch.GetMinimumOpcodeByteSize();
198 const uint32_t max_op_byte_size = arch.GetMaximumOpcodeByteSize();
199 if (min_op_byte_size == max_op_byte_size) {
200 // Fixed size instructions, just read that amount of data.
201 if (!data.ValidOffsetForDataOfSize(data_offset, min_op_byte_size))
204 switch (min_op_byte_size) {
206 m_opcode.SetOpcode8(data.GetU8(&data_offset), byte_order);
211 m_opcode.SetOpcode16(data.GetU16(&data_offset), byte_order);
216 m_opcode.SetOpcode32(data.GetU32(&data_offset), byte_order);
221 m_opcode.SetOpcode64(data.GetU64(&data_offset), byte_order);
226 m_opcode.SetOpcodeBytes(data.PeekData(data_offset, min_op_byte_size),
233 bool is_alternate_isa = false;
234 DisassemblerLLVMC::MCDisasmInstance *mc_disasm_ptr =
235 GetDisasmToUse(is_alternate_isa);
237 const llvm::Triple::ArchType machine = arch.GetMachine();
238 if (machine == llvm::Triple::arm || machine == llvm::Triple::thumb) {
239 if (machine == llvm::Triple::thumb || is_alternate_isa) {
240 uint32_t thumb_opcode = data.GetU16(&data_offset);
241 if ((thumb_opcode & 0xe000) != 0xe000 ||
242 ((thumb_opcode & 0x1800u) == 0)) {
243 m_opcode.SetOpcode16(thumb_opcode, byte_order);
247 thumb_opcode |= data.GetU16(&data_offset);
248 m_opcode.SetOpcode16_2(thumb_opcode, byte_order);
252 m_opcode.SetOpcode32(data.GetU32(&data_offset), byte_order);
256 // The opcode isn't evenly sized, so we need to actually use the llvm
257 // disassembler to parse it and get the size.
258 uint8_t *opcode_data =
259 const_cast<uint8_t *>(data.PeekData(data_offset, 1));
260 const size_t opcode_data_len = data.BytesLeft(data_offset);
261 const addr_t pc = m_address.GetFileAddress();
264 disasm_sp->Lock(this, NULL);
265 const size_t inst_size =
266 mc_disasm_ptr->GetMCInst(opcode_data, opcode_data_len, pc, inst);
271 m_opcode.SetOpcodeBytes(opcode_data, inst_size);
276 return m_opcode.GetByteSize();
281 void AppendComment(std::string &description) {
282 if (m_comment.empty())
283 m_comment.swap(description);
285 m_comment.append(", ");
286 m_comment.append(description);
290 void CalculateMnemonicOperandsAndComment(
291 const lldb_private::ExecutionContext *exe_ctx) override {
293 const AddressClass address_class = GetAddressClass();
295 if (m_opcode.GetData(data)) {
296 std::string out_string;
297 std::string comment_string;
299 std::shared_ptr<DisassemblerLLVMC> disasm_sp(GetDisassembler());
301 DisassemblerLLVMC::MCDisasmInstance *mc_disasm_ptr;
303 if (address_class == AddressClass::eCodeAlternateISA)
304 mc_disasm_ptr = disasm_sp->m_alternate_disasm_up.get();
306 mc_disasm_ptr = disasm_sp->m_disasm_up.get();
308 lldb::addr_t pc = m_address.GetFileAddress();
309 m_using_file_addr = true;
311 const bool data_from_file = disasm_sp->m_data_from_file;
312 bool use_hex_immediates = true;
313 Disassembler::HexImmediateStyle hex_style = Disassembler::eHexStyleC;
316 Target *target = exe_ctx->GetTargetPtr();
318 use_hex_immediates = target->GetUseHexImmediates();
319 hex_style = target->GetHexImmediateStyle();
321 if (!data_from_file) {
322 const lldb::addr_t load_addr = m_address.GetLoadAddress(target);
323 if (load_addr != LLDB_INVALID_ADDRESS) {
325 m_using_file_addr = false;
331 disasm_sp->Lock(this, exe_ctx);
333 const uint8_t *opcode_data = data.GetDataStart();
334 const size_t opcode_data_len = data.GetByteSize();
337 mc_disasm_ptr->GetMCInst(opcode_data, opcode_data_len, pc, inst);
340 mc_disasm_ptr->SetStyle(use_hex_immediates, hex_style);
341 mc_disasm_ptr->PrintMCInst(inst, out_string, comment_string);
343 if (!comment_string.empty()) {
344 AppendComment(comment_string);
350 if (inst_size == 0) {
351 m_comment.assign("unknown opcode");
352 inst_size = m_opcode.GetByteSize();
353 StreamString mnemonic_strm;
354 lldb::offset_t offset = 0;
355 lldb::ByteOrder byte_order = data.GetByteOrder();
358 const uint8_t uval8 = data.GetU8(&offset);
359 m_opcode.SetOpcode8(uval8, byte_order);
360 m_opcode_name.assign(".byte");
361 mnemonic_strm.Printf("0x%2.2x", uval8);
364 const uint16_t uval16 = data.GetU16(&offset);
365 m_opcode.SetOpcode16(uval16, byte_order);
366 m_opcode_name.assign(".short");
367 mnemonic_strm.Printf("0x%4.4x", uval16);
370 const uint32_t uval32 = data.GetU32(&offset);
371 m_opcode.SetOpcode32(uval32, byte_order);
372 m_opcode_name.assign(".long");
373 mnemonic_strm.Printf("0x%8.8x", uval32);
376 const uint64_t uval64 = data.GetU64(&offset);
377 m_opcode.SetOpcode64(uval64, byte_order);
378 m_opcode_name.assign(".quad");
379 mnemonic_strm.Printf("0x%16.16" PRIx64, uval64);
385 const uint8_t *bytes = data.PeekData(offset, inst_size);
388 m_opcode_name.assign(".byte");
389 m_opcode.SetOpcodeBytes(bytes, inst_size);
390 mnemonic_strm.Printf("0x%2.2x", bytes[0]);
391 for (uint32_t i = 1; i < inst_size; ++i)
392 mnemonic_strm.Printf(" 0x%2.2x", bytes[i]);
396 m_mnemonics = mnemonic_strm.GetString();
399 if (m_does_branch == eLazyBoolCalculate) {
400 const bool can_branch = mc_disasm_ptr->CanBranch(inst);
402 m_does_branch = eLazyBoolYes;
404 m_does_branch = eLazyBoolNo;
408 static RegularExpression s_regex(
409 llvm::StringRef("[ \t]*([^ ^\t]+)[ \t]*([^ ^\t].*)?"));
411 RegularExpression::Match matches(3);
413 if (s_regex.Execute(out_string, &matches)) {
414 matches.GetMatchAtIndex(out_string.c_str(), 1, m_opcode_name);
415 matches.GetMatchAtIndex(out_string.c_str(), 2, m_mnemonics);
421 bool IsValid() const { return m_is_valid; }
423 bool UsingFileAddress() const { return m_using_file_addr; }
424 size_t GetByteSize() const { return m_opcode.GetByteSize(); }
426 std::shared_ptr<DisassemblerLLVMC> GetDisassembler() {
427 return m_disasm_wp.lock();
430 static llvm::StringRef::const_iterator
431 ConsumeWhitespace(llvm::StringRef::const_iterator osi,
432 llvm::StringRef::const_iterator ose) {
447 static std::pair<bool, llvm::StringRef::const_iterator>
448 ConsumeChar(llvm::StringRef::const_iterator osi, const char c,
449 llvm::StringRef::const_iterator ose) {
452 osi = ConsumeWhitespace(osi, ose);
453 if (osi != ose && *osi == c) {
458 return std::make_pair(found, osi);
461 static std::pair<Operand, llvm::StringRef::const_iterator>
462 ParseRegisterName(llvm::StringRef::const_iterator osi,
463 llvm::StringRef::const_iterator ose) {
465 ret.m_type = Operand::Type::Register;
468 osi = ConsumeWhitespace(osi, ose);
471 if (*osi >= '0' && *osi <= '9') {
473 return std::make_pair(Operand(), osi);
477 } else if (*osi >= 'a' && *osi <= 'z') {
483 return std::make_pair(Operand(), osi);
485 ret.m_register = ConstString(str);
486 return std::make_pair(ret, osi);
490 return std::make_pair(Operand(), osi);
498 ret.m_register = ConstString(str);
499 return std::make_pair(ret, osi);
502 static std::pair<Operand, llvm::StringRef::const_iterator>
503 ParseImmediate(llvm::StringRef::const_iterator osi,
504 llvm::StringRef::const_iterator ose) {
506 ret.m_type = Operand::Type::Immediate;
510 osi = ConsumeWhitespace(osi, ose);
513 if (*osi >= '0' && *osi <= '9') {
515 } else if (*osi >= 'a' && *osi <= 'f') {
519 return std::make_pair(Operand(), osi);
525 return std::make_pair(Operand(), osi);
527 ret.m_immediate = strtoull(str.c_str(), nullptr, 0);
528 return std::make_pair(ret, osi);
531 if (!str.compare("0")) {
535 return std::make_pair(Operand(), osi);
541 return std::make_pair(Operand(), osi);
546 ret.m_negative = true;
548 return std::make_pair(Operand(), osi);
555 ret.m_immediate = strtoull(str.c_str(), nullptr, 0);
556 return std::make_pair(ret, osi);
560 static std::pair<Operand, llvm::StringRef::const_iterator>
561 ParseIntelIndexedAccess(llvm::StringRef::const_iterator osi,
562 llvm::StringRef::const_iterator ose) {
563 std::pair<Operand, llvm::StringRef::const_iterator> offset_and_iterator =
564 ParseImmediate(osi, ose);
565 if (offset_and_iterator.first.IsValid()) {
566 osi = offset_and_iterator.second;
570 std::tie(found, osi) = ConsumeChar(osi, '(', ose);
572 return std::make_pair(Operand(), osi);
575 std::pair<Operand, llvm::StringRef::const_iterator> base_and_iterator =
576 ParseRegisterName(osi, ose);
577 if (base_and_iterator.first.IsValid()) {
578 osi = base_and_iterator.second;
580 return std::make_pair(Operand(), osi);
583 std::tie(found, osi) = ConsumeChar(osi, ',', ose);
585 return std::make_pair(Operand(), osi);
588 std::pair<Operand, llvm::StringRef::const_iterator> index_and_iterator =
589 ParseRegisterName(osi, ose);
590 if (index_and_iterator.first.IsValid()) {
591 osi = index_and_iterator.second;
593 return std::make_pair(Operand(), osi);
596 std::tie(found, osi) = ConsumeChar(osi, ',', ose);
598 return std::make_pair(Operand(), osi);
601 std::pair<Operand, llvm::StringRef::const_iterator>
602 multiplier_and_iterator = ParseImmediate(osi, ose);
603 if (index_and_iterator.first.IsValid()) {
604 osi = index_and_iterator.second;
606 return std::make_pair(Operand(), osi);
609 std::tie(found, osi) = ConsumeChar(osi, ')', ose);
611 return std::make_pair(Operand(), osi);
615 product.m_type = Operand::Type::Product;
616 product.m_children.push_back(index_and_iterator.first);
617 product.m_children.push_back(multiplier_and_iterator.first);
620 index.m_type = Operand::Type::Sum;
621 index.m_children.push_back(base_and_iterator.first);
622 index.m_children.push_back(product);
624 if (offset_and_iterator.first.IsValid()) {
626 offset.m_type = Operand::Type::Sum;
627 offset.m_children.push_back(offset_and_iterator.first);
628 offset.m_children.push_back(index);
631 deref.m_type = Operand::Type::Dereference;
632 deref.m_children.push_back(offset);
633 return std::make_pair(deref, osi);
636 deref.m_type = Operand::Type::Dereference;
637 deref.m_children.push_back(index);
638 return std::make_pair(deref, osi);
643 static std::pair<Operand, llvm::StringRef::const_iterator>
644 ParseIntelDerefAccess(llvm::StringRef::const_iterator osi,
645 llvm::StringRef::const_iterator ose) {
646 std::pair<Operand, llvm::StringRef::const_iterator> offset_and_iterator =
647 ParseImmediate(osi, ose);
648 if (offset_and_iterator.first.IsValid()) {
649 osi = offset_and_iterator.second;
653 std::tie(found, osi) = ConsumeChar(osi, '(', ose);
655 return std::make_pair(Operand(), osi);
658 std::pair<Operand, llvm::StringRef::const_iterator> base_and_iterator =
659 ParseRegisterName(osi, ose);
660 if (base_and_iterator.first.IsValid()) {
661 osi = base_and_iterator.second;
663 return std::make_pair(Operand(), osi);
666 std::tie(found, osi) = ConsumeChar(osi, ')', ose);
668 return std::make_pair(Operand(), osi);
671 if (offset_and_iterator.first.IsValid()) {
673 offset.m_type = Operand::Type::Sum;
674 offset.m_children.push_back(offset_and_iterator.first);
675 offset.m_children.push_back(base_and_iterator.first);
678 deref.m_type = Operand::Type::Dereference;
679 deref.m_children.push_back(offset);
680 return std::make_pair(deref, osi);
683 deref.m_type = Operand::Type::Dereference;
684 deref.m_children.push_back(base_and_iterator.first);
685 return std::make_pair(deref, osi);
690 static std::pair<Operand, llvm::StringRef::const_iterator>
691 ParseARMOffsetAccess(llvm::StringRef::const_iterator osi,
692 llvm::StringRef::const_iterator ose) {
694 std::tie(found, osi) = ConsumeChar(osi, '[', ose);
696 return std::make_pair(Operand(), osi);
699 std::pair<Operand, llvm::StringRef::const_iterator> base_and_iterator =
700 ParseRegisterName(osi, ose);
701 if (base_and_iterator.first.IsValid()) {
702 osi = base_and_iterator.second;
704 return std::make_pair(Operand(), osi);
707 std::tie(found, osi) = ConsumeChar(osi, ',', ose);
709 return std::make_pair(Operand(), osi);
712 std::pair<Operand, llvm::StringRef::const_iterator> offset_and_iterator =
713 ParseImmediate(osi, ose);
714 if (offset_and_iterator.first.IsValid()) {
715 osi = offset_and_iterator.second;
718 std::tie(found, osi) = ConsumeChar(osi, ']', ose);
720 return std::make_pair(Operand(), osi);
724 offset.m_type = Operand::Type::Sum;
725 offset.m_children.push_back(offset_and_iterator.first);
726 offset.m_children.push_back(base_and_iterator.first);
729 deref.m_type = Operand::Type::Dereference;
730 deref.m_children.push_back(offset);
731 return std::make_pair(deref, osi);
735 static std::pair<Operand, llvm::StringRef::const_iterator>
736 ParseARMDerefAccess(llvm::StringRef::const_iterator osi,
737 llvm::StringRef::const_iterator ose) {
739 std::tie(found, osi) = ConsumeChar(osi, '[', ose);
741 return std::make_pair(Operand(), osi);
744 std::pair<Operand, llvm::StringRef::const_iterator> base_and_iterator =
745 ParseRegisterName(osi, ose);
746 if (base_and_iterator.first.IsValid()) {
747 osi = base_and_iterator.second;
749 return std::make_pair(Operand(), osi);
752 std::tie(found, osi) = ConsumeChar(osi, ']', ose);
754 return std::make_pair(Operand(), osi);
758 deref.m_type = Operand::Type::Dereference;
759 deref.m_children.push_back(base_and_iterator.first);
760 return std::make_pair(deref, osi);
763 static void DumpOperand(const Operand &op, Stream &s) {
765 case Operand::Type::Dereference:
767 DumpOperand(op.m_children[0], s);
769 case Operand::Type::Immediate:
773 s.PutCString(llvm::to_string(op.m_immediate));
775 case Operand::Type::Invalid:
776 s.PutCString("Invalid");
778 case Operand::Type::Product:
780 DumpOperand(op.m_children[0], s);
782 DumpOperand(op.m_children[1], s);
785 case Operand::Type::Register:
786 s.PutCString(op.m_register.AsCString());
788 case Operand::Type::Sum:
790 DumpOperand(op.m_children[0], s);
792 DumpOperand(op.m_children[1], s);
799 llvm::SmallVectorImpl<Instruction::Operand> &operands) override {
800 const char *operands_string = GetOperands(nullptr);
802 if (!operands_string) {
806 llvm::StringRef operands_ref(operands_string);
808 llvm::StringRef::const_iterator osi = operands_ref.begin();
809 llvm::StringRef::const_iterator ose = operands_ref.end();
813 llvm::StringRef::const_iterator iter;
815 if ((std::tie(operand, iter) = ParseIntelIndexedAccess(osi, ose),
816 operand.IsValid()) ||
817 (std::tie(operand, iter) = ParseIntelDerefAccess(osi, ose),
818 operand.IsValid()) ||
819 (std::tie(operand, iter) = ParseARMOffsetAccess(osi, ose),
820 operand.IsValid()) ||
821 (std::tie(operand, iter) = ParseARMDerefAccess(osi, ose),
822 operand.IsValid()) ||
823 (std::tie(operand, iter) = ParseRegisterName(osi, ose),
824 operand.IsValid()) ||
825 (std::tie(operand, iter) = ParseImmediate(osi, ose),
826 operand.IsValid())) {
828 operands.push_back(operand);
833 std::pair<bool, llvm::StringRef::const_iterator> found_and_iter =
834 ConsumeChar(osi, ',', ose);
835 if (found_and_iter.first) {
836 osi = found_and_iter.second;
839 osi = ConsumeWhitespace(osi, ose);
842 DisassemblerSP disasm_sp = m_disasm_wp.lock();
844 if (disasm_sp && operands.size() > 1) {
845 // TODO tie this into the MC Disassembler's notion of clobbers.
846 switch (disasm_sp->GetArchitecture().GetMachine()) {
849 case llvm::Triple::x86:
850 case llvm::Triple::x86_64:
851 operands[operands.size() - 1].m_clobbered = true;
853 case llvm::Triple::arm:
854 operands[0].m_clobbered = true;
860 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)) {
863 ss.Printf("[%s] expands to %zu operands:\n", operands_string,
865 for (const Operand &operand : operands) {
867 DumpOperand(operand, ss);
871 log->PutString(ss.GetString());
877 bool IsCall() override {
878 if (m_is_call == eLazyBoolCalculate) {
879 std::shared_ptr<DisassemblerLLVMC> disasm_sp(GetDisassembler());
881 disasm_sp->Lock(this, NULL);
883 if (m_opcode.GetData(data)) {
884 bool is_alternate_isa;
885 lldb::addr_t pc = m_address.GetFileAddress();
887 DisassemblerLLVMC::MCDisasmInstance *mc_disasm_ptr =
888 GetDisasmToUse(is_alternate_isa);
889 const uint8_t *opcode_data = data.GetDataStart();
890 const size_t opcode_data_len = data.GetByteSize();
892 const size_t inst_size =
893 mc_disasm_ptr->GetMCInst(opcode_data, opcode_data_len, pc, inst);
894 if (inst_size == 0) {
895 m_is_call = eLazyBoolNo;
897 if (mc_disasm_ptr->IsCall(inst))
898 m_is_call = eLazyBoolYes;
900 m_is_call = eLazyBoolNo;
906 return m_is_call == eLazyBoolYes;
910 std::weak_ptr<DisassemblerLLVMC> m_disasm_wp;
911 LazyBool m_does_branch;
912 LazyBool m_has_delay_slot;
915 bool m_using_file_addr;
918 std::unique_ptr<DisassemblerLLVMC::MCDisasmInstance>
919 DisassemblerLLVMC::MCDisasmInstance::Create(const char *triple, const char *cpu,
920 const char *features_str,
922 DisassemblerLLVMC &owner) {
923 using Instance = std::unique_ptr<DisassemblerLLVMC::MCDisasmInstance>;
926 const llvm::Target *curr_target =
927 llvm::TargetRegistry::lookupTarget(triple, Status);
931 std::unique_ptr<llvm::MCInstrInfo> instr_info_up(
932 curr_target->createMCInstrInfo());
936 std::unique_ptr<llvm::MCRegisterInfo> reg_info_up(
937 curr_target->createMCRegInfo(triple));
941 std::unique_ptr<llvm::MCSubtargetInfo> subtarget_info_up(
942 curr_target->createMCSubtargetInfo(triple, cpu, features_str));
943 if (!subtarget_info_up)
946 std::unique_ptr<llvm::MCAsmInfo> asm_info_up(
947 curr_target->createMCAsmInfo(*reg_info_up, triple));
951 std::unique_ptr<llvm::MCContext> context_up(
952 new llvm::MCContext(asm_info_up.get(), reg_info_up.get(), 0));
956 std::unique_ptr<llvm::MCDisassembler> disasm_up(
957 curr_target->createMCDisassembler(*subtarget_info_up, *context_up));
961 std::unique_ptr<llvm::MCRelocationInfo> rel_info_up(
962 curr_target->createMCRelocationInfo(triple, *context_up));
966 std::unique_ptr<llvm::MCSymbolizer> symbolizer_up(
967 curr_target->createMCSymbolizer(
968 triple, nullptr, DisassemblerLLVMC::SymbolLookupCallback, &owner,
969 context_up.get(), std::move(rel_info_up)));
970 disasm_up->setSymbolizer(std::move(symbolizer_up));
972 unsigned asm_printer_variant =
973 flavor == ~0U ? asm_info_up->getAssemblerDialect() : flavor;
975 std::unique_ptr<llvm::MCInstPrinter> instr_printer_up(
976 curr_target->createMCInstPrinter(llvm::Triple{triple},
977 asm_printer_variant, *asm_info_up,
978 *instr_info_up, *reg_info_up));
979 if (!instr_printer_up)
983 new MCDisasmInstance(std::move(instr_info_up), std::move(reg_info_up),
984 std::move(subtarget_info_up), std::move(asm_info_up),
985 std::move(context_up), std::move(disasm_up),
986 std::move(instr_printer_up)));
989 DisassemblerLLVMC::MCDisasmInstance::MCDisasmInstance(
990 std::unique_ptr<llvm::MCInstrInfo> &&instr_info_up,
991 std::unique_ptr<llvm::MCRegisterInfo> &®_info_up,
992 std::unique_ptr<llvm::MCSubtargetInfo> &&subtarget_info_up,
993 std::unique_ptr<llvm::MCAsmInfo> &&asm_info_up,
994 std::unique_ptr<llvm::MCContext> &&context_up,
995 std::unique_ptr<llvm::MCDisassembler> &&disasm_up,
996 std::unique_ptr<llvm::MCInstPrinter> &&instr_printer_up)
997 : m_instr_info_up(std::move(instr_info_up)),
998 m_reg_info_up(std::move(reg_info_up)),
999 m_subtarget_info_up(std::move(subtarget_info_up)),
1000 m_asm_info_up(std::move(asm_info_up)),
1001 m_context_up(std::move(context_up)), m_disasm_up(std::move(disasm_up)),
1002 m_instr_printer_up(std::move(instr_printer_up)) {
1003 assert(m_instr_info_up && m_reg_info_up && m_subtarget_info_up &&
1004 m_asm_info_up && m_context_up && m_disasm_up && m_instr_printer_up);
1007 uint64_t DisassemblerLLVMC::MCDisasmInstance::GetMCInst(
1008 const uint8_t *opcode_data, size_t opcode_data_len, lldb::addr_t pc,
1009 llvm::MCInst &mc_inst) const {
1010 llvm::ArrayRef<uint8_t> data(opcode_data, opcode_data_len);
1011 llvm::MCDisassembler::DecodeStatus status;
1013 uint64_t new_inst_size;
1014 status = m_disasm_up->getInstruction(mc_inst, new_inst_size, data, pc,
1015 llvm::nulls(), llvm::nulls());
1016 if (status == llvm::MCDisassembler::Success)
1017 return new_inst_size;
1022 void DisassemblerLLVMC::MCDisasmInstance::PrintMCInst(
1023 llvm::MCInst &mc_inst, std::string &inst_string,
1024 std::string &comments_string) {
1025 llvm::raw_string_ostream inst_stream(inst_string);
1026 llvm::raw_string_ostream comments_stream(comments_string);
1028 m_instr_printer_up->setCommentStream(comments_stream);
1029 m_instr_printer_up->printInst(&mc_inst, inst_stream, llvm::StringRef(),
1030 *m_subtarget_info_up);
1031 m_instr_printer_up->setCommentStream(llvm::nulls());
1032 comments_stream.flush();
1034 static std::string g_newlines("\r\n");
1036 for (size_t newline_pos = 0;
1037 (newline_pos = comments_string.find_first_of(g_newlines, newline_pos)) !=
1038 comments_string.npos;
1040 comments_string.replace(comments_string.begin() + newline_pos,
1041 comments_string.begin() + newline_pos + 1, 1, ' ');
1045 void DisassemblerLLVMC::MCDisasmInstance::SetStyle(
1046 bool use_hex_immed, HexImmediateStyle hex_style) {
1047 m_instr_printer_up->setPrintImmHex(use_hex_immed);
1048 switch (hex_style) {
1050 m_instr_printer_up->setPrintHexStyle(llvm::HexStyle::C);
1053 m_instr_printer_up->setPrintHexStyle(llvm::HexStyle::Asm);
1058 bool DisassemblerLLVMC::MCDisasmInstance::CanBranch(
1059 llvm::MCInst &mc_inst) const {
1060 return m_instr_info_up->get(mc_inst.getOpcode())
1061 .mayAffectControlFlow(mc_inst, *m_reg_info_up);
1064 bool DisassemblerLLVMC::MCDisasmInstance::HasDelaySlot(
1065 llvm::MCInst &mc_inst) const {
1066 return m_instr_info_up->get(mc_inst.getOpcode()).hasDelaySlot();
1069 bool DisassemblerLLVMC::MCDisasmInstance::IsCall(llvm::MCInst &mc_inst) const {
1070 return m_instr_info_up->get(mc_inst.getOpcode()).isCall();
1073 DisassemblerLLVMC::DisassemblerLLVMC(const ArchSpec &arch,
1074 const char *flavor_string)
1075 : Disassembler(arch, flavor_string), m_exe_ctx(NULL), m_inst(NULL),
1076 m_data_from_file(false) {
1077 if (!FlavorValidForArchSpec(arch, m_flavor.c_str())) {
1078 m_flavor.assign("default");
1081 unsigned flavor = ~0U;
1082 llvm::Triple triple = arch.GetTriple();
1084 // So far the only supported flavor is "intel" on x86. The base class will
1085 // set this correctly coming in.
1086 if (triple.getArch() == llvm::Triple::x86 ||
1087 triple.getArch() == llvm::Triple::x86_64) {
1088 if (m_flavor == "intel") {
1090 } else if (m_flavor == "att") {
1095 ArchSpec thumb_arch(arch);
1096 if (triple.getArch() == llvm::Triple::arm) {
1097 std::string thumb_arch_name(thumb_arch.GetTriple().getArchName().str());
1098 // Replace "arm" with "thumb" so we get all thumb variants correct
1099 if (thumb_arch_name.size() > 3) {
1100 thumb_arch_name.erase(0, 3);
1101 thumb_arch_name.insert(0, "thumb");
1103 thumb_arch_name = "thumbv8.2a";
1105 thumb_arch.GetTriple().setArchName(llvm::StringRef(thumb_arch_name));
1108 // If no sub architecture specified then use the most recent arm architecture
1109 // so the disassembler will return all instruction. Without it we will see a
1110 // lot of unknow opcode in case the code uses instructions which are not
1111 // available in the oldest arm version (used when no sub architecture is
1113 if (triple.getArch() == llvm::Triple::arm &&
1114 triple.getSubArch() == llvm::Triple::NoSubArch)
1115 triple.setArchName("armv8.2a");
1117 const char *triple_str = triple.getTriple().c_str();
1119 // ARM Cortex M0-M7 devices only execute thumb instructions
1120 if (arch.IsAlwaysThumbInstructions()) {
1121 triple_str = thumb_arch.GetTriple().getTriple().c_str();
1124 const char *cpu = "";
1126 switch (arch.GetCore()) {
1127 case ArchSpec::eCore_mips32:
1128 case ArchSpec::eCore_mips32el:
1131 case ArchSpec::eCore_mips32r2:
1132 case ArchSpec::eCore_mips32r2el:
1135 case ArchSpec::eCore_mips32r3:
1136 case ArchSpec::eCore_mips32r3el:
1139 case ArchSpec::eCore_mips32r5:
1140 case ArchSpec::eCore_mips32r5el:
1143 case ArchSpec::eCore_mips32r6:
1144 case ArchSpec::eCore_mips32r6el:
1147 case ArchSpec::eCore_mips64:
1148 case ArchSpec::eCore_mips64el:
1151 case ArchSpec::eCore_mips64r2:
1152 case ArchSpec::eCore_mips64r2el:
1155 case ArchSpec::eCore_mips64r3:
1156 case ArchSpec::eCore_mips64r3el:
1159 case ArchSpec::eCore_mips64r5:
1160 case ArchSpec::eCore_mips64r5el:
1163 case ArchSpec::eCore_mips64r6:
1164 case ArchSpec::eCore_mips64r6el:
1172 std::string features_str = "";
1173 if (triple.getArch() == llvm::Triple::mips ||
1174 triple.getArch() == llvm::Triple::mipsel ||
1175 triple.getArch() == llvm::Triple::mips64 ||
1176 triple.getArch() == llvm::Triple::mips64el) {
1177 uint32_t arch_flags = arch.GetFlags();
1178 if (arch_flags & ArchSpec::eMIPSAse_msa)
1179 features_str += "+msa,";
1180 if (arch_flags & ArchSpec::eMIPSAse_dsp)
1181 features_str += "+dsp,";
1182 if (arch_flags & ArchSpec::eMIPSAse_dspr2)
1183 features_str += "+dspr2,";
1186 // If any AArch64 variant, enable the ARMv8.2 ISA extensions so we can
1187 // disassemble newer instructions.
1188 if (triple.getArch() == llvm::Triple::aarch64)
1189 features_str += "+v8.2a";
1191 // We use m_disasm_ap.get() to tell whether we are valid or not, so if this
1192 // isn't good for some reason, we won't be valid and FindPlugin will fail and
1193 // we won't get used.
1194 m_disasm_up = MCDisasmInstance::Create(triple_str, cpu, features_str.c_str(),
1197 llvm::Triple::ArchType llvm_arch = triple.getArch();
1199 // For arm CPUs that can execute arm or thumb instructions, also create a
1200 // thumb instruction disassembler.
1201 if (llvm_arch == llvm::Triple::arm) {
1202 std::string thumb_triple(thumb_arch.GetTriple().getTriple());
1203 m_alternate_disasm_up =
1204 MCDisasmInstance::Create(thumb_triple.c_str(), "", "", flavor, *this);
1205 if (!m_alternate_disasm_up)
1206 m_disasm_up.reset();
1208 } else if (llvm_arch == llvm::Triple::mips ||
1209 llvm_arch == llvm::Triple::mipsel ||
1210 llvm_arch == llvm::Triple::mips64 ||
1211 llvm_arch == llvm::Triple::mips64el) {
1212 /* Create alternate disassembler for MIPS16 and microMIPS */
1213 uint32_t arch_flags = arch.GetFlags();
1214 if (arch_flags & ArchSpec::eMIPSAse_mips16)
1215 features_str += "+mips16,";
1216 else if (arch_flags & ArchSpec::eMIPSAse_micromips)
1217 features_str += "+micromips,";
1219 m_alternate_disasm_up = MCDisasmInstance::Create(
1220 triple_str, cpu, features_str.c_str(), flavor, *this);
1221 if (!m_alternate_disasm_up)
1222 m_disasm_up.reset();
1226 DisassemblerLLVMC::~DisassemblerLLVMC() = default;
1228 Disassembler *DisassemblerLLVMC::CreateInstance(const ArchSpec &arch,
1229 const char *flavor) {
1230 if (arch.GetTriple().getArch() != llvm::Triple::UnknownArch) {
1231 std::unique_ptr<DisassemblerLLVMC> disasm_ap(
1232 new DisassemblerLLVMC(arch, flavor));
1234 if (disasm_ap.get() && disasm_ap->IsValid())
1235 return disasm_ap.release();
1240 size_t DisassemblerLLVMC::DecodeInstructions(const Address &base_addr,
1241 const DataExtractor &data,
1242 lldb::offset_t data_offset,
1243 size_t num_instructions,
1244 bool append, bool data_from_file) {
1246 m_instruction_list.Clear();
1251 m_data_from_file = data_from_file;
1252 uint32_t data_cursor = data_offset;
1253 const size_t data_byte_size = data.GetByteSize();
1254 uint32_t instructions_parsed = 0;
1255 Address inst_addr(base_addr);
1257 while (data_cursor < data_byte_size &&
1258 instructions_parsed < num_instructions) {
1260 AddressClass address_class = AddressClass::eCode;
1262 if (m_alternate_disasm_up)
1263 address_class = inst_addr.GetAddressClass();
1265 InstructionSP inst_sp(
1266 new InstructionLLVMC(*this, inst_addr, address_class));
1271 uint32_t inst_size = inst_sp->Decode(*this, data, data_cursor);
1276 m_instruction_list.Append(inst_sp);
1277 data_cursor += inst_size;
1278 inst_addr.Slide(inst_size);
1279 instructions_parsed++;
1282 return data_cursor - data_offset;
1285 void DisassemblerLLVMC::Initialize() {
1286 PluginManager::RegisterPlugin(GetPluginNameStatic(),
1287 "Disassembler that uses LLVM MC to disassemble "
1288 "i386, x86_64, ARM, and ARM64.",
1291 llvm::InitializeAllTargetInfos();
1292 llvm::InitializeAllTargetMCs();
1293 llvm::InitializeAllAsmParsers();
1294 llvm::InitializeAllDisassemblers();
1297 void DisassemblerLLVMC::Terminate() {
1298 PluginManager::UnregisterPlugin(CreateInstance);
1301 ConstString DisassemblerLLVMC::GetPluginNameStatic() {
1302 static ConstString g_name("llvm-mc");
1306 int DisassemblerLLVMC::OpInfoCallback(void *disassembler, uint64_t pc,
1307 uint64_t offset, uint64_t size,
1308 int tag_type, void *tag_bug) {
1309 return static_cast<DisassemblerLLVMC *>(disassembler)
1310 ->OpInfo(pc, offset, size, tag_type, tag_bug);
1313 const char *DisassemblerLLVMC::SymbolLookupCallback(void *disassembler,
1315 uint64_t *type, uint64_t pc,
1316 const char **name) {
1317 return static_cast<DisassemblerLLVMC *>(disassembler)
1318 ->SymbolLookup(value, type, pc, name);
1321 bool DisassemblerLLVMC::FlavorValidForArchSpec(
1322 const lldb_private::ArchSpec &arch, const char *flavor) {
1323 llvm::Triple triple = arch.GetTriple();
1324 if (flavor == NULL || strcmp(flavor, "default") == 0)
1327 if (triple.getArch() == llvm::Triple::x86 ||
1328 triple.getArch() == llvm::Triple::x86_64) {
1329 if (strcmp(flavor, "intel") == 0 || strcmp(flavor, "att") == 0)
1337 bool DisassemblerLLVMC::IsValid() const { return m_disasm_up.operator bool(); }
1339 int DisassemblerLLVMC::OpInfo(uint64_t PC, uint64_t Offset, uint64_t Size,
1340 int tag_type, void *tag_bug) {
1345 memset(tag_bug, 0, sizeof(::LLVMOpInfo1));
1351 const char *DisassemblerLLVMC::SymbolLookup(uint64_t value, uint64_t *type_ptr,
1352 uint64_t pc, const char **name) {
1354 if (m_exe_ctx && m_inst) {
1355 // std::string remove_this_prior_to_checkin;
1356 Target *target = m_exe_ctx ? m_exe_ctx->GetTargetPtr() : NULL;
1357 Address value_so_addr;
1359 if (m_inst->UsingFileAddress()) {
1360 ModuleSP module_sp(m_inst->GetAddress().GetModule());
1362 module_sp->ResolveFileAddress(value, value_so_addr);
1363 module_sp->ResolveFileAddress(pc, pc_so_addr);
1365 } else if (target && !target->GetSectionLoadList().IsEmpty()) {
1366 target->GetSectionLoadList().ResolveLoadAddress(value, value_so_addr);
1367 target->GetSectionLoadList().ResolveLoadAddress(pc, pc_so_addr);
1370 SymbolContext sym_ctx;
1371 const uint32_t resolve_scope =
1372 eSymbolContextFunction | eSymbolContextSymbol;
1373 if (pc_so_addr.IsValid() && pc_so_addr.GetModule()) {
1374 pc_so_addr.GetModule()->ResolveSymbolContextForAddress(
1375 pc_so_addr, resolve_scope, sym_ctx);
1378 if (value_so_addr.IsValid() && value_so_addr.GetSection()) {
1381 bool format_omitting_current_func_name = false;
1382 if (sym_ctx.symbol || sym_ctx.function) {
1384 if (sym_ctx.GetAddressRange(resolve_scope, 0, false, range) &&
1385 range.GetBaseAddress().IsValid() &&
1386 range.ContainsLoadAddress(value_so_addr, target)) {
1387 format_omitting_current_func_name = true;
1391 // If the "value" address (the target address we're symbolicating) is
1392 // inside the same SymbolContext as the current instruction pc
1393 // (pc_so_addr), don't print the full function name - just print it
1394 // with DumpStyleNoFunctionName style, e.g. "<+36>".
1395 if (format_omitting_current_func_name) {
1396 value_so_addr.Dump(&ss, target, Address::DumpStyleNoFunctionName,
1397 Address::DumpStyleSectionNameOffset);
1401 Address::DumpStyleResolvedDescriptionNoFunctionArguments,
1402 Address::DumpStyleSectionNameOffset);
1405 if (!ss.GetString().empty()) {
1406 // If Address::Dump returned a multi-line description, most commonly
1407 // seen when we have multiple levels of inlined functions at an
1408 // address, only show the first line.
1409 std::string str = ss.GetString();
1410 size_t first_eol_char = str.find_first_of("\r\n");
1411 if (first_eol_char != std::string::npos) {
1412 str.erase(first_eol_char);
1414 m_inst->AppendComment(str);
1420 *type_ptr = LLVMDisassembler_ReferenceType_InOut_None;
1425 //------------------------------------------------------------------
1426 // PluginInterface protocol
1427 //------------------------------------------------------------------
1428 ConstString DisassemblerLLVMC::GetPluginName() { return GetPluginNameStatic(); }
1430 uint32_t DisassemblerLLVMC::GetPluginVersion() { return 1; }