1 //===-- DisassemblerLLVMC.cpp -----------------------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "DisassemblerLLVMC.h"
11
12 #include "llvm-c/Disassembler.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/MC/MCAsmInfo.h"
15 #include "llvm/MC/MCContext.h"
16 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
17 #include "llvm/MC/MCDisassembler/MCExternalSymbolizer.h"
18 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
19 #include "llvm/MC/MCInst.h"
20 #include "llvm/MC/MCInstPrinter.h"
21 #include "llvm/MC/MCInstrInfo.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/ScopedPrinter.h"
26 #include "llvm/Support/TargetRegistry.h"
27 #include "llvm/Support/TargetSelect.h"
28
29 #include "lldb/Core/Address.h"
30 #include "lldb/Core/Module.h"
31 #include "lldb/Symbol/SymbolContext.h"
32 #include "lldb/Target/ExecutionContext.h"
33 #include "lldb/Target/Process.h"
34 #include "lldb/Target/RegisterContext.h"
35 #include "lldb/Target/SectionLoadList.h"
36 #include "lldb/Target/StackFrame.h"
37 #include "lldb/Target/Target.h"
38 #include "lldb/Utility/DataExtractor.h"
39 #include "lldb/Utility/Log.h"
40 #include "lldb/Utility/RegularExpression.h"
41 #include "lldb/Utility/Stream.h"
42
43 using namespace lldb;
44 using namespace lldb_private;
45
46 class DisassemblerLLVMC::MCDisasmInstance {
47 public:
48 static std::unique_ptr<MCDisasmInstance>
49 Create(const char *triple, const char *cpu, const char *features_str,
50 unsigned flavor, DisassemblerLLVMC &owner);
51
52 ~MCDisasmInstance() = default;
53
54 uint64_t GetMCInst(const uint8_t *opcode_data, size_t opcode_data_len,
55 lldb::addr_t pc, llvm::MCInst &mc_inst) const;
56 void PrintMCInst(llvm::MCInst &mc_inst, std::string &inst_string,
57 std::string &comments_string);
58 void SetStyle(bool use_hex_immed, HexImmediateStyle hex_style);
59 bool CanBranch(llvm::MCInst &mc_inst) const;
60 bool HasDelaySlot(llvm::MCInst &mc_inst) const;
61 bool IsCall(llvm::MCInst &mc_inst) const;
62
63 private:
64 MCDisasmInstance(std::unique_ptr<llvm::MCInstrInfo> &&instr_info_up,
65 std::unique_ptr<llvm::MCRegisterInfo> &®_info_up,
66 std::unique_ptr<llvm::MCSubtargetInfo> &&subtarget_info_up,
67 std::unique_ptr<llvm::MCAsmInfo> &&asm_info_up,
68 std::unique_ptr<llvm::MCContext> &&context_up,
69 std::unique_ptr<llvm::MCDisassembler> &&disasm_up,
70 std::unique_ptr<llvm::MCInstPrinter> &&instr_printer_up);
71
72 std::unique_ptr<llvm::MCInstrInfo> m_instr_info_up;
73 std::unique_ptr<llvm::MCRegisterInfo> m_reg_info_up;
74 std::unique_ptr<llvm::MCSubtargetInfo> m_subtarget_info_up;
75 std::unique_ptr<llvm::MCAsmInfo> m_asm_info_up;
76 std::unique_ptr<llvm::MCContext> m_context_up;
77 std::unique_ptr<llvm::MCDisassembler> m_disasm_up;
78 std::unique_ptr<llvm::MCInstPrinter> m_instr_printer_up;
79 };
80
81 class InstructionLLVMC : public lldb_private::Instruction {
82 public:
InstructionLLVMC(DisassemblerLLVMC & disasm,const lldb_private::Address & address,AddressClass addr_class)83 InstructionLLVMC(DisassemblerLLVMC &disasm,
84 const lldb_private::Address &address,
85 AddressClass addr_class)
86 : Instruction(address, addr_class),
87 m_disasm_wp(std::static_pointer_cast<DisassemblerLLVMC>(
88 disasm.shared_from_this())),
89 m_does_branch(eLazyBoolCalculate), m_has_delay_slot(eLazyBoolCalculate),
90 m_is_call(eLazyBoolCalculate), m_is_valid(false),
91 m_using_file_addr(false) {}
92
93 ~InstructionLLVMC() override = default;
94
DoesBranch()95 bool DoesBranch() override {
96 if (m_does_branch == eLazyBoolCalculate) {
97 DisassemblerScope disasm(*this);
98 if (disasm) {
99 DataExtractor data;
100 if (m_opcode.GetData(data)) {
101 bool is_alternate_isa;
102 lldb::addr_t pc = m_address.GetFileAddress();
103
104 DisassemblerLLVMC::MCDisasmInstance *mc_disasm_ptr =
105 GetDisasmToUse(is_alternate_isa, disasm);
106 const uint8_t *opcode_data = data.GetDataStart();
107 const size_t opcode_data_len = data.GetByteSize();
108 llvm::MCInst inst;
109 const size_t inst_size =
110 mc_disasm_ptr->GetMCInst(opcode_data, opcode_data_len, pc, inst);
111 // Be conservative, if we didn't understand the instruction, say it
112 // might branch...
113 if (inst_size == 0)
114 m_does_branch = eLazyBoolYes;
115 else {
116 const bool can_branch = mc_disasm_ptr->CanBranch(inst);
117 if (can_branch)
118 m_does_branch = eLazyBoolYes;
119 else
120 m_does_branch = eLazyBoolNo;
121 }
122 }
123 }
124 }
125 return m_does_branch == eLazyBoolYes;
126 }
127
HasDelaySlot()128 bool HasDelaySlot() override {
129 if (m_has_delay_slot == eLazyBoolCalculate) {
130 DisassemblerScope disasm(*this);
131 if (disasm) {
132 DataExtractor data;
133 if (m_opcode.GetData(data)) {
134 bool is_alternate_isa;
135 lldb::addr_t pc = m_address.GetFileAddress();
136
137 DisassemblerLLVMC::MCDisasmInstance *mc_disasm_ptr =
138 GetDisasmToUse(is_alternate_isa, disasm);
139 const uint8_t *opcode_data = data.GetDataStart();
140 const size_t opcode_data_len = data.GetByteSize();
141 llvm::MCInst inst;
142 const size_t inst_size =
143 mc_disasm_ptr->GetMCInst(opcode_data, opcode_data_len, pc, inst);
144 // if we didn't understand the instruction, say it doesn't have a
145 // delay slot...
146 if (inst_size == 0)
147 m_has_delay_slot = eLazyBoolNo;
148 else {
149 const bool has_delay_slot = mc_disasm_ptr->HasDelaySlot(inst);
150 if (has_delay_slot)
151 m_has_delay_slot = eLazyBoolYes;
152 else
153 m_has_delay_slot = eLazyBoolNo;
154 }
155 }
156 }
157 }
158 return m_has_delay_slot == eLazyBoolYes;
159 }
160
GetDisasmToUse(bool & is_alternate_isa)161 DisassemblerLLVMC::MCDisasmInstance *GetDisasmToUse(bool &is_alternate_isa) {
162 DisassemblerScope disasm(*this);
163 return GetDisasmToUse(is_alternate_isa, disasm);
164 }
165
Decode(const lldb_private::Disassembler & disassembler,const lldb_private::DataExtractor & data,lldb::offset_t data_offset)166 size_t Decode(const lldb_private::Disassembler &disassembler,
167 const lldb_private::DataExtractor &data,
168 lldb::offset_t data_offset) override {
169 // All we have to do is read the opcode which can be easy for some
170 // architectures
171 bool got_op = false;
172 DisassemblerScope disasm(*this);
173 if (disasm) {
174 const ArchSpec &arch = disasm->GetArchitecture();
175 const lldb::ByteOrder byte_order = data.GetByteOrder();
176
177 const uint32_t min_op_byte_size = arch.GetMinimumOpcodeByteSize();
178 const uint32_t max_op_byte_size = arch.GetMaximumOpcodeByteSize();
179 if (min_op_byte_size == max_op_byte_size) {
180 // Fixed size instructions, just read that amount of data.
181 if (!data.ValidOffsetForDataOfSize(data_offset, min_op_byte_size))
182 return false;
183
184 switch (min_op_byte_size) {
185 case 1:
186 m_opcode.SetOpcode8(data.GetU8(&data_offset), byte_order);
187 got_op = true;
188 break;
189
190 case 2:
191 m_opcode.SetOpcode16(data.GetU16(&data_offset), byte_order);
192 got_op = true;
193 break;
194
195 case 4:
196 m_opcode.SetOpcode32(data.GetU32(&data_offset), byte_order);
197 got_op = true;
198 break;
199
200 case 8:
201 m_opcode.SetOpcode64(data.GetU64(&data_offset), byte_order);
202 got_op = true;
203 break;
204
205 default:
206 m_opcode.SetOpcodeBytes(data.PeekData(data_offset, min_op_byte_size),
207 min_op_byte_size);
208 got_op = true;
209 break;
210 }
211 }
212 if (!got_op) {
213 bool is_alternate_isa = false;
214 DisassemblerLLVMC::MCDisasmInstance *mc_disasm_ptr =
215 GetDisasmToUse(is_alternate_isa, disasm);
216
217 const llvm::Triple::ArchType machine = arch.GetMachine();
218 if (machine == llvm::Triple::arm || machine == llvm::Triple::thumb) {
219 if (machine == llvm::Triple::thumb || is_alternate_isa) {
220 uint32_t thumb_opcode = data.GetU16(&data_offset);
221 if ((thumb_opcode & 0xe000) != 0xe000 ||
222 ((thumb_opcode & 0x1800u) == 0)) {
223 m_opcode.SetOpcode16(thumb_opcode, byte_order);
224 m_is_valid = true;
225 } else {
226 thumb_opcode <<= 16;
227 thumb_opcode |= data.GetU16(&data_offset);
228 m_opcode.SetOpcode16_2(thumb_opcode, byte_order);
229 m_is_valid = true;
230 }
231 } else {
232 m_opcode.SetOpcode32(data.GetU32(&data_offset), byte_order);
233 m_is_valid = true;
234 }
235 } else {
236 // The opcode isn't evenly sized, so we need to actually use the llvm
237 // disassembler to parse it and get the size.
238 uint8_t *opcode_data =
239 const_cast<uint8_t *>(data.PeekData(data_offset, 1));
240 const size_t opcode_data_len = data.BytesLeft(data_offset);
241 const addr_t pc = m_address.GetFileAddress();
242 llvm::MCInst inst;
243
244 const size_t inst_size =
245 mc_disasm_ptr->GetMCInst(opcode_data, opcode_data_len, pc, inst);
246 if (inst_size == 0)
247 m_opcode.Clear();
248 else {
249 m_opcode.SetOpcodeBytes(opcode_data, inst_size);
250 m_is_valid = true;
251 }
252 }
253 }
254 return m_opcode.GetByteSize();
255 }
256 return 0;
257 }
258
AppendComment(std::string & description)259 void AppendComment(std::string &description) {
260 if (m_comment.empty())
261 m_comment.swap(description);
262 else {
263 m_comment.append(", ");
264 m_comment.append(description);
265 }
266 }
267
CalculateMnemonicOperandsAndComment(const lldb_private::ExecutionContext * exe_ctx)268 void CalculateMnemonicOperandsAndComment(
269 const lldb_private::ExecutionContext *exe_ctx) override {
270 DataExtractor data;
271 const AddressClass address_class = GetAddressClass();
272
273 if (m_opcode.GetData(data)) {
274 std::string out_string;
275 std::string comment_string;
276
277 DisassemblerScope disasm(*this, exe_ctx);
278 if (disasm) {
279 DisassemblerLLVMC::MCDisasmInstance *mc_disasm_ptr;
280
281 if (address_class == AddressClass::eCodeAlternateISA)
282 mc_disasm_ptr = disasm->m_alternate_disasm_up.get();
283 else
284 mc_disasm_ptr = disasm->m_disasm_up.get();
285
286 lldb::addr_t pc = m_address.GetFileAddress();
287 m_using_file_addr = true;
288
289 const bool data_from_file = disasm->m_data_from_file;
290 bool use_hex_immediates = true;
291 Disassembler::HexImmediateStyle hex_style = Disassembler::eHexStyleC;
292
293 if (exe_ctx) {
294 Target *target = exe_ctx->GetTargetPtr();
295 if (target) {
296 use_hex_immediates = target->GetUseHexImmediates();
297 hex_style = target->GetHexImmediateStyle();
298
299 if (!data_from_file) {
300 const lldb::addr_t load_addr = m_address.GetLoadAddress(target);
301 if (load_addr != LLDB_INVALID_ADDRESS) {
302 pc = load_addr;
303 m_using_file_addr = false;
304 }
305 }
306 }
307 }
308
309 const uint8_t *opcode_data = data.GetDataStart();
310 const size_t opcode_data_len = data.GetByteSize();
311 llvm::MCInst inst;
312 size_t inst_size =
313 mc_disasm_ptr->GetMCInst(opcode_data, opcode_data_len, pc, inst);
314
315 if (inst_size > 0) {
316 mc_disasm_ptr->SetStyle(use_hex_immediates, hex_style);
317 mc_disasm_ptr->PrintMCInst(inst, out_string, comment_string);
318
319 if (!comment_string.empty()) {
320 AppendComment(comment_string);
321 }
322 }
323
324 if (inst_size == 0) {
325 m_comment.assign("unknown opcode");
326 inst_size = m_opcode.GetByteSize();
327 StreamString mnemonic_strm;
328 lldb::offset_t offset = 0;
329 lldb::ByteOrder byte_order = data.GetByteOrder();
330 switch (inst_size) {
331 case 1: {
332 const uint8_t uval8 = data.GetU8(&offset);
333 m_opcode.SetOpcode8(uval8, byte_order);
334 m_opcode_name.assign(".byte");
335 mnemonic_strm.Printf("0x%2.2x", uval8);
336 } break;
337 case 2: {
338 const uint16_t uval16 = data.GetU16(&offset);
339 m_opcode.SetOpcode16(uval16, byte_order);
340 m_opcode_name.assign(".short");
341 mnemonic_strm.Printf("0x%4.4x", uval16);
342 } break;
343 case 4: {
344 const uint32_t uval32 = data.GetU32(&offset);
345 m_opcode.SetOpcode32(uval32, byte_order);
346 m_opcode_name.assign(".long");
347 mnemonic_strm.Printf("0x%8.8x", uval32);
348 } break;
349 case 8: {
350 const uint64_t uval64 = data.GetU64(&offset);
351 m_opcode.SetOpcode64(uval64, byte_order);
352 m_opcode_name.assign(".quad");
353 mnemonic_strm.Printf("0x%16.16" PRIx64, uval64);
354 } break;
355 default:
356 if (inst_size == 0)
357 return;
358 else {
359 const uint8_t *bytes = data.PeekData(offset, inst_size);
360 if (bytes == NULL)
361 return;
362 m_opcode_name.assign(".byte");
363 m_opcode.SetOpcodeBytes(bytes, inst_size);
364 mnemonic_strm.Printf("0x%2.2x", bytes[0]);
365 for (uint32_t i = 1; i < inst_size; ++i)
366 mnemonic_strm.Printf(" 0x%2.2x", bytes[i]);
367 }
368 break;
369 }
370 m_mnemonics = mnemonic_strm.GetString();
371 return;
372 } else {
373 if (m_does_branch == eLazyBoolCalculate) {
374 const bool can_branch = mc_disasm_ptr->CanBranch(inst);
375 if (can_branch)
376 m_does_branch = eLazyBoolYes;
377 else
378 m_does_branch = eLazyBoolNo;
379 }
380 }
381
382 static RegularExpression s_regex(
383 llvm::StringRef("[ \t]*([^ ^\t]+)[ \t]*([^ ^\t].*)?"));
384
385 RegularExpression::Match matches(3);
386
387 if (s_regex.Execute(out_string, &matches)) {
388 matches.GetMatchAtIndex(out_string.c_str(), 1, m_opcode_name);
389 matches.GetMatchAtIndex(out_string.c_str(), 2, m_mnemonics);
390 }
391 }
392 }
393 }
394
IsValid() const395 bool IsValid() const { return m_is_valid; }
396
UsingFileAddress() const397 bool UsingFileAddress() const { return m_using_file_addr; }
GetByteSize() const398 size_t GetByteSize() const { return m_opcode.GetByteSize(); }
399
400 /// Grants exclusive access to the disassembler and initializes it with the
401 /// given InstructionLLVMC and an optional ExecutionContext.
402 class DisassemblerScope {
403 std::shared_ptr<DisassemblerLLVMC> m_disasm;
404
405 public:
DisassemblerScope(InstructionLLVMC & i,const lldb_private::ExecutionContext * exe_ctx=nullptr)406 explicit DisassemblerScope(
407 InstructionLLVMC &i,
408 const lldb_private::ExecutionContext *exe_ctx = nullptr)
409 : m_disasm(i.m_disasm_wp.lock()) {
410 m_disasm->m_mutex.lock();
411 m_disasm->m_inst = &i;
412 m_disasm->m_exe_ctx = exe_ctx;
413 }
~DisassemblerScope()414 ~DisassemblerScope() { m_disasm->m_mutex.unlock(); }
415
416 /// Evaluates to true if this scope contains a valid disassembler.
operator bool() const417 operator bool() const { return static_cast<bool>(m_disasm); }
418
operator ->()419 std::shared_ptr<DisassemblerLLVMC> operator->() { return m_disasm; }
420 };
421
422 static llvm::StringRef::const_iterator
ConsumeWhitespace(llvm::StringRef::const_iterator osi,llvm::StringRef::const_iterator ose)423 ConsumeWhitespace(llvm::StringRef::const_iterator osi,
424 llvm::StringRef::const_iterator ose) {
425 while (osi != ose) {
426 switch (*osi) {
427 default:
428 return osi;
429 case ' ':
430 case '\t':
431 break;
432 }
433 ++osi;
434 }
435
436 return osi;
437 }
438
439 static std::pair<bool, llvm::StringRef::const_iterator>
ConsumeChar(llvm::StringRef::const_iterator osi,const char c,llvm::StringRef::const_iterator ose)440 ConsumeChar(llvm::StringRef::const_iterator osi, const char c,
441 llvm::StringRef::const_iterator ose) {
442 bool found = false;
443
444 osi = ConsumeWhitespace(osi, ose);
445 if (osi != ose && *osi == c) {
446 found = true;
447 ++osi;
448 }
449
450 return std::make_pair(found, osi);
451 }
452
453 static std::pair<Operand, llvm::StringRef::const_iterator>
ParseRegisterName(llvm::StringRef::const_iterator osi,llvm::StringRef::const_iterator ose)454 ParseRegisterName(llvm::StringRef::const_iterator osi,
455 llvm::StringRef::const_iterator ose) {
456 Operand ret;
457 ret.m_type = Operand::Type::Register;
458 std::string str;
459
460 osi = ConsumeWhitespace(osi, ose);
461
462 while (osi != ose) {
463 if (*osi >= '0' && *osi <= '9') {
464 if (str.empty()) {
465 return std::make_pair(Operand(), osi);
466 } else {
467 str.push_back(*osi);
468 }
469 } else if (*osi >= 'a' && *osi <= 'z') {
470 str.push_back(*osi);
471 } else {
472 switch (*osi) {
473 default:
474 if (str.empty()) {
475 return std::make_pair(Operand(), osi);
476 } else {
477 ret.m_register = ConstString(str);
478 return std::make_pair(ret, osi);
479 }
480 case '%':
481 if (!str.empty()) {
482 return std::make_pair(Operand(), osi);
483 }
484 break;
485 }
486 }
487 ++osi;
488 }
489
490 ret.m_register = ConstString(str);
491 return std::make_pair(ret, osi);
492 }
493
494 static std::pair<Operand, llvm::StringRef::const_iterator>
ParseImmediate(llvm::StringRef::const_iterator osi,llvm::StringRef::const_iterator ose)495 ParseImmediate(llvm::StringRef::const_iterator osi,
496 llvm::StringRef::const_iterator ose) {
497 Operand ret;
498 ret.m_type = Operand::Type::Immediate;
499 std::string str;
500 bool is_hex = false;
501
502 osi = ConsumeWhitespace(osi, ose);
503
504 while (osi != ose) {
505 if (*osi >= '0' && *osi <= '9') {
506 str.push_back(*osi);
507 } else if (*osi >= 'a' && *osi <= 'f') {
508 if (is_hex) {
509 str.push_back(*osi);
510 } else {
511 return std::make_pair(Operand(), osi);
512 }
513 } else {
514 switch (*osi) {
515 default:
516 if (str.empty()) {
517 return std::make_pair(Operand(), osi);
518 } else {
519 ret.m_immediate = strtoull(str.c_str(), nullptr, 0);
520 return std::make_pair(ret, osi);
521 }
522 case 'x':
523 if (!str.compare("0")) {
524 is_hex = true;
525 str.push_back(*osi);
526 } else {
527 return std::make_pair(Operand(), osi);
528 }
529 break;
530 case '#':
531 case '$':
532 if (!str.empty()) {
533 return std::make_pair(Operand(), osi);
534 }
535 break;
536 case '-':
537 if (str.empty()) {
538 ret.m_negative = true;
539 } else {
540 return std::make_pair(Operand(), osi);
541 }
542 }
543 }
544 ++osi;
545 }
546
547 ret.m_immediate = strtoull(str.c_str(), nullptr, 0);
548 return std::make_pair(ret, osi);
549 }
550
551 // -0x5(%rax,%rax,2)
552 static std::pair<Operand, llvm::StringRef::const_iterator>
ParseIntelIndexedAccess(llvm::StringRef::const_iterator osi,llvm::StringRef::const_iterator ose)553 ParseIntelIndexedAccess(llvm::StringRef::const_iterator osi,
554 llvm::StringRef::const_iterator ose) {
555 std::pair<Operand, llvm::StringRef::const_iterator> offset_and_iterator =
556 ParseImmediate(osi, ose);
557 if (offset_and_iterator.first.IsValid()) {
558 osi = offset_and_iterator.second;
559 }
560
561 bool found = false;
562 std::tie(found, osi) = ConsumeChar(osi, '(', ose);
563 if (!found) {
564 return std::make_pair(Operand(), osi);
565 }
566
567 std::pair<Operand, llvm::StringRef::const_iterator> base_and_iterator =
568 ParseRegisterName(osi, ose);
569 if (base_and_iterator.first.IsValid()) {
570 osi = base_and_iterator.second;
571 } else {
572 return std::make_pair(Operand(), osi);
573 }
574
575 std::tie(found, osi) = ConsumeChar(osi, ',', ose);
576 if (!found) {
577 return std::make_pair(Operand(), osi);
578 }
579
580 std::pair<Operand, llvm::StringRef::const_iterator> index_and_iterator =
581 ParseRegisterName(osi, ose);
582 if (index_and_iterator.first.IsValid()) {
583 osi = index_and_iterator.second;
584 } else {
585 return std::make_pair(Operand(), osi);
586 }
587
588 std::tie(found, osi) = ConsumeChar(osi, ',', ose);
589 if (!found) {
590 return std::make_pair(Operand(), osi);
591 }
592
593 std::pair<Operand, llvm::StringRef::const_iterator>
594 multiplier_and_iterator = ParseImmediate(osi, ose);
595 if (index_and_iterator.first.IsValid()) {
596 osi = index_and_iterator.second;
597 } else {
598 return std::make_pair(Operand(), osi);
599 }
600
601 std::tie(found, osi) = ConsumeChar(osi, ')', ose);
602 if (!found) {
603 return std::make_pair(Operand(), osi);
604 }
605
606 Operand product;
607 product.m_type = Operand::Type::Product;
608 product.m_children.push_back(index_and_iterator.first);
609 product.m_children.push_back(multiplier_and_iterator.first);
610
611 Operand index;
612 index.m_type = Operand::Type::Sum;
613 index.m_children.push_back(base_and_iterator.first);
614 index.m_children.push_back(product);
615
616 if (offset_and_iterator.first.IsValid()) {
617 Operand offset;
618 offset.m_type = Operand::Type::Sum;
619 offset.m_children.push_back(offset_and_iterator.first);
620 offset.m_children.push_back(index);
621
622 Operand deref;
623 deref.m_type = Operand::Type::Dereference;
624 deref.m_children.push_back(offset);
625 return std::make_pair(deref, osi);
626 } else {
627 Operand deref;
628 deref.m_type = Operand::Type::Dereference;
629 deref.m_children.push_back(index);
630 return std::make_pair(deref, osi);
631 }
632 }
633
634 // -0x10(%rbp)
635 static std::pair<Operand, llvm::StringRef::const_iterator>
ParseIntelDerefAccess(llvm::StringRef::const_iterator osi,llvm::StringRef::const_iterator ose)636 ParseIntelDerefAccess(llvm::StringRef::const_iterator osi,
637 llvm::StringRef::const_iterator ose) {
638 std::pair<Operand, llvm::StringRef::const_iterator> offset_and_iterator =
639 ParseImmediate(osi, ose);
640 if (offset_and_iterator.first.IsValid()) {
641 osi = offset_and_iterator.second;
642 }
643
644 bool found = false;
645 std::tie(found, osi) = ConsumeChar(osi, '(', ose);
646 if (!found) {
647 return std::make_pair(Operand(), osi);
648 }
649
650 std::pair<Operand, llvm::StringRef::const_iterator> base_and_iterator =
651 ParseRegisterName(osi, ose);
652 if (base_and_iterator.first.IsValid()) {
653 osi = base_and_iterator.second;
654 } else {
655 return std::make_pair(Operand(), osi);
656 }
657
658 std::tie(found, osi) = ConsumeChar(osi, ')', ose);
659 if (!found) {
660 return std::make_pair(Operand(), osi);
661 }
662
663 if (offset_and_iterator.first.IsValid()) {
664 Operand offset;
665 offset.m_type = Operand::Type::Sum;
666 offset.m_children.push_back(offset_and_iterator.first);
667 offset.m_children.push_back(base_and_iterator.first);
668
669 Operand deref;
670 deref.m_type = Operand::Type::Dereference;
671 deref.m_children.push_back(offset);
672 return std::make_pair(deref, osi);
673 } else {
674 Operand deref;
675 deref.m_type = Operand::Type::Dereference;
676 deref.m_children.push_back(base_and_iterator.first);
677 return std::make_pair(deref, osi);
678 }
679 }
680
681 // [sp, #8]!
682 static std::pair<Operand, llvm::StringRef::const_iterator>
ParseARMOffsetAccess(llvm::StringRef::const_iterator osi,llvm::StringRef::const_iterator ose)683 ParseARMOffsetAccess(llvm::StringRef::const_iterator osi,
684 llvm::StringRef::const_iterator ose) {
685 bool found = false;
686 std::tie(found, osi) = ConsumeChar(osi, '[', ose);
687 if (!found) {
688 return std::make_pair(Operand(), osi);
689 }
690
691 std::pair<Operand, llvm::StringRef::const_iterator> base_and_iterator =
692 ParseRegisterName(osi, ose);
693 if (base_and_iterator.first.IsValid()) {
694 osi = base_and_iterator.second;
695 } else {
696 return std::make_pair(Operand(), osi);
697 }
698
699 std::tie(found, osi) = ConsumeChar(osi, ',', ose);
700 if (!found) {
701 return std::make_pair(Operand(), osi);
702 }
703
704 std::pair<Operand, llvm::StringRef::const_iterator> offset_and_iterator =
705 ParseImmediate(osi, ose);
706 if (offset_and_iterator.first.IsValid()) {
707 osi = offset_and_iterator.second;
708 }
709
710 std::tie(found, osi) = ConsumeChar(osi, ']', ose);
711 if (!found) {
712 return std::make_pair(Operand(), osi);
713 }
714
715 Operand offset;
716 offset.m_type = Operand::Type::Sum;
717 offset.m_children.push_back(offset_and_iterator.first);
718 offset.m_children.push_back(base_and_iterator.first);
719
720 Operand deref;
721 deref.m_type = Operand::Type::Dereference;
722 deref.m_children.push_back(offset);
723 return std::make_pair(deref, osi);
724 }
725
726 // [sp]
727 static std::pair<Operand, llvm::StringRef::const_iterator>
ParseARMDerefAccess(llvm::StringRef::const_iterator osi,llvm::StringRef::const_iterator ose)728 ParseARMDerefAccess(llvm::StringRef::const_iterator osi,
729 llvm::StringRef::const_iterator ose) {
730 bool found = false;
731 std::tie(found, osi) = ConsumeChar(osi, '[', ose);
732 if (!found) {
733 return std::make_pair(Operand(), osi);
734 }
735
736 std::pair<Operand, llvm::StringRef::const_iterator> base_and_iterator =
737 ParseRegisterName(osi, ose);
738 if (base_and_iterator.first.IsValid()) {
739 osi = base_and_iterator.second;
740 } else {
741 return std::make_pair(Operand(), osi);
742 }
743
744 std::tie(found, osi) = ConsumeChar(osi, ']', ose);
745 if (!found) {
746 return std::make_pair(Operand(), osi);
747 }
748
749 Operand deref;
750 deref.m_type = Operand::Type::Dereference;
751 deref.m_children.push_back(base_and_iterator.first);
752 return std::make_pair(deref, osi);
753 }
754
DumpOperand(const Operand & op,Stream & s)755 static void DumpOperand(const Operand &op, Stream &s) {
756 switch (op.m_type) {
757 case Operand::Type::Dereference:
758 s.PutCString("*");
759 DumpOperand(op.m_children[0], s);
760 break;
761 case Operand::Type::Immediate:
762 if (op.m_negative) {
763 s.PutCString("-");
764 }
765 s.PutCString(llvm::to_string(op.m_immediate));
766 break;
767 case Operand::Type::Invalid:
768 s.PutCString("Invalid");
769 break;
770 case Operand::Type::Product:
771 s.PutCString("(");
772 DumpOperand(op.m_children[0], s);
773 s.PutCString("*");
774 DumpOperand(op.m_children[1], s);
775 s.PutCString(")");
776 break;
777 case Operand::Type::Register:
778 s.PutCString(op.m_register.AsCString());
779 break;
780 case Operand::Type::Sum:
781 s.PutCString("(");
782 DumpOperand(op.m_children[0], s);
783 s.PutCString("+");
784 DumpOperand(op.m_children[1], s);
785 s.PutCString(")");
786 break;
787 }
788 }
789
ParseOperands(llvm::SmallVectorImpl<Instruction::Operand> & operands)790 bool ParseOperands(
791 llvm::SmallVectorImpl<Instruction::Operand> &operands) override {
792 const char *operands_string = GetOperands(nullptr);
793
794 if (!operands_string) {
795 return false;
796 }
797
798 llvm::StringRef operands_ref(operands_string);
799
800 llvm::StringRef::const_iterator osi = operands_ref.begin();
801 llvm::StringRef::const_iterator ose = operands_ref.end();
802
803 while (osi != ose) {
804 Operand operand;
805 llvm::StringRef::const_iterator iter;
806
807 if ((std::tie(operand, iter) = ParseIntelIndexedAccess(osi, ose),
808 operand.IsValid()) ||
809 (std::tie(operand, iter) = ParseIntelDerefAccess(osi, ose),
810 operand.IsValid()) ||
811 (std::tie(operand, iter) = ParseARMOffsetAccess(osi, ose),
812 operand.IsValid()) ||
813 (std::tie(operand, iter) = ParseARMDerefAccess(osi, ose),
814 operand.IsValid()) ||
815 (std::tie(operand, iter) = ParseRegisterName(osi, ose),
816 operand.IsValid()) ||
817 (std::tie(operand, iter) = ParseImmediate(osi, ose),
818 operand.IsValid())) {
819 osi = iter;
820 operands.push_back(operand);
821 } else {
822 return false;
823 }
824
825 std::pair<bool, llvm::StringRef::const_iterator> found_and_iter =
826 ConsumeChar(osi, ',', ose);
827 if (found_and_iter.first) {
828 osi = found_and_iter.second;
829 }
830
831 osi = ConsumeWhitespace(osi, ose);
832 }
833
834 DisassemblerSP disasm_sp = m_disasm_wp.lock();
835
836 if (disasm_sp && operands.size() > 1) {
837 // TODO tie this into the MC Disassembler's notion of clobbers.
838 switch (disasm_sp->GetArchitecture().GetMachine()) {
839 default:
840 break;
841 case llvm::Triple::x86:
842 case llvm::Triple::x86_64:
843 operands[operands.size() - 1].m_clobbered = true;
844 break;
845 case llvm::Triple::arm:
846 operands[0].m_clobbered = true;
847 break;
848 }
849 }
850
851 if (Log *log =
852 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)) {
853 StreamString ss;
854
855 ss.Printf("[%s] expands to %zu operands:\n", operands_string,
856 operands.size());
857 for (const Operand &operand : operands) {
858 ss.PutCString(" ");
859 DumpOperand(operand, ss);
860 ss.PutCString("\n");
861 }
862
863 log->PutString(ss.GetString());
864 }
865
866 return true;
867 }
868
IsCall()869 bool IsCall() override {
870 if (m_is_call == eLazyBoolCalculate) {
871 DisassemblerScope disasm(*this);
872 if (disasm) {
873 DataExtractor data;
874 if (m_opcode.GetData(data)) {
875 bool is_alternate_isa;
876 lldb::addr_t pc = m_address.GetFileAddress();
877
878 DisassemblerLLVMC::MCDisasmInstance *mc_disasm_ptr =
879 GetDisasmToUse(is_alternate_isa, disasm);
880 const uint8_t *opcode_data = data.GetDataStart();
881 const size_t opcode_data_len = data.GetByteSize();
882 llvm::MCInst inst;
883 const size_t inst_size =
884 mc_disasm_ptr->GetMCInst(opcode_data, opcode_data_len, pc, inst);
885 if (inst_size == 0) {
886 m_is_call = eLazyBoolNo;
887 } else {
888 if (mc_disasm_ptr->IsCall(inst))
889 m_is_call = eLazyBoolYes;
890 else
891 m_is_call = eLazyBoolNo;
892 }
893 }
894 }
895 }
896 return m_is_call == eLazyBoolYes;
897 }
898
899 protected:
900 std::weak_ptr<DisassemblerLLVMC> m_disasm_wp;
901 LazyBool m_does_branch;
902 LazyBool m_has_delay_slot;
903 LazyBool m_is_call;
904 bool m_is_valid;
905 bool m_using_file_addr;
906
907 private:
908 DisassemblerLLVMC::MCDisasmInstance *
GetDisasmToUse(bool & is_alternate_isa,DisassemblerScope & disasm)909 GetDisasmToUse(bool &is_alternate_isa, DisassemblerScope &disasm) {
910 is_alternate_isa = false;
911 if (disasm) {
912 if (disasm->m_alternate_disasm_up) {
913 const AddressClass address_class = GetAddressClass();
914
915 if (address_class == AddressClass::eCodeAlternateISA) {
916 is_alternate_isa = true;
917 return disasm->m_alternate_disasm_up.get();
918 }
919 }
920 return disasm->m_disasm_up.get();
921 }
922 return nullptr;
923 }
924 };
925
926 std::unique_ptr<DisassemblerLLVMC::MCDisasmInstance>
Create(const char * triple,const char * cpu,const char * features_str,unsigned flavor,DisassemblerLLVMC & owner)927 DisassemblerLLVMC::MCDisasmInstance::Create(const char *triple, const char *cpu,
928 const char *features_str,
929 unsigned flavor,
930 DisassemblerLLVMC &owner) {
931 using Instance = std::unique_ptr<DisassemblerLLVMC::MCDisasmInstance>;
932
933 std::string Status;
934 const llvm::Target *curr_target =
935 llvm::TargetRegistry::lookupTarget(triple, Status);
936 if (!curr_target)
937 return Instance();
938
939 std::unique_ptr<llvm::MCInstrInfo> instr_info_up(
940 curr_target->createMCInstrInfo());
941 if (!instr_info_up)
942 return Instance();
943
944 std::unique_ptr<llvm::MCRegisterInfo> reg_info_up(
945 curr_target->createMCRegInfo(triple));
946 if (!reg_info_up)
947 return Instance();
948
949 std::unique_ptr<llvm::MCSubtargetInfo> subtarget_info_up(
950 curr_target->createMCSubtargetInfo(triple, cpu, features_str));
951 if (!subtarget_info_up)
952 return Instance();
953
954 std::unique_ptr<llvm::MCAsmInfo> asm_info_up(
955 curr_target->createMCAsmInfo(*reg_info_up, triple));
956 if (!asm_info_up)
957 return Instance();
958
959 std::unique_ptr<llvm::MCContext> context_up(
960 new llvm::MCContext(asm_info_up.get(), reg_info_up.get(), 0));
961 if (!context_up)
962 return Instance();
963
964 std::unique_ptr<llvm::MCDisassembler> disasm_up(
965 curr_target->createMCDisassembler(*subtarget_info_up, *context_up));
966 if (!disasm_up)
967 return Instance();
968
969 std::unique_ptr<llvm::MCRelocationInfo> rel_info_up(
970 curr_target->createMCRelocationInfo(triple, *context_up));
971 if (!rel_info_up)
972 return Instance();
973
974 std::unique_ptr<llvm::MCSymbolizer> symbolizer_up(
975 curr_target->createMCSymbolizer(
976 triple, nullptr, DisassemblerLLVMC::SymbolLookupCallback, &owner,
977 context_up.get(), std::move(rel_info_up)));
978 disasm_up->setSymbolizer(std::move(symbolizer_up));
979
980 unsigned asm_printer_variant =
981 flavor == ~0U ? asm_info_up->getAssemblerDialect() : flavor;
982
983 std::unique_ptr<llvm::MCInstPrinter> instr_printer_up(
984 curr_target->createMCInstPrinter(llvm::Triple{triple},
985 asm_printer_variant, *asm_info_up,
986 *instr_info_up, *reg_info_up));
987 if (!instr_printer_up)
988 return Instance();
989
990 return Instance(
991 new MCDisasmInstance(std::move(instr_info_up), std::move(reg_info_up),
992 std::move(subtarget_info_up), std::move(asm_info_up),
993 std::move(context_up), std::move(disasm_up),
994 std::move(instr_printer_up)));
995 }
996
MCDisasmInstance(std::unique_ptr<llvm::MCInstrInfo> && instr_info_up,std::unique_ptr<llvm::MCRegisterInfo> && reg_info_up,std::unique_ptr<llvm::MCSubtargetInfo> && subtarget_info_up,std::unique_ptr<llvm::MCAsmInfo> && asm_info_up,std::unique_ptr<llvm::MCContext> && context_up,std::unique_ptr<llvm::MCDisassembler> && disasm_up,std::unique_ptr<llvm::MCInstPrinter> && instr_printer_up)997 DisassemblerLLVMC::MCDisasmInstance::MCDisasmInstance(
998 std::unique_ptr<llvm::MCInstrInfo> &&instr_info_up,
999 std::unique_ptr<llvm::MCRegisterInfo> &®_info_up,
1000 std::unique_ptr<llvm::MCSubtargetInfo> &&subtarget_info_up,
1001 std::unique_ptr<llvm::MCAsmInfo> &&asm_info_up,
1002 std::unique_ptr<llvm::MCContext> &&context_up,
1003 std::unique_ptr<llvm::MCDisassembler> &&disasm_up,
1004 std::unique_ptr<llvm::MCInstPrinter> &&instr_printer_up)
1005 : m_instr_info_up(std::move(instr_info_up)),
1006 m_reg_info_up(std::move(reg_info_up)),
1007 m_subtarget_info_up(std::move(subtarget_info_up)),
1008 m_asm_info_up(std::move(asm_info_up)),
1009 m_context_up(std::move(context_up)), m_disasm_up(std::move(disasm_up)),
1010 m_instr_printer_up(std::move(instr_printer_up)) {
1011 assert(m_instr_info_up && m_reg_info_up && m_subtarget_info_up &&
1012 m_asm_info_up && m_context_up && m_disasm_up && m_instr_printer_up);
1013 }
1014
GetMCInst(const uint8_t * opcode_data,size_t opcode_data_len,lldb::addr_t pc,llvm::MCInst & mc_inst) const1015 uint64_t DisassemblerLLVMC::MCDisasmInstance::GetMCInst(
1016 const uint8_t *opcode_data, size_t opcode_data_len, lldb::addr_t pc,
1017 llvm::MCInst &mc_inst) const {
1018 llvm::ArrayRef<uint8_t> data(opcode_data, opcode_data_len);
1019 llvm::MCDisassembler::DecodeStatus status;
1020
1021 uint64_t new_inst_size;
1022 status = m_disasm_up->getInstruction(mc_inst, new_inst_size, data, pc,
1023 llvm::nulls(), llvm::nulls());
1024 if (status == llvm::MCDisassembler::Success)
1025 return new_inst_size;
1026 else
1027 return 0;
1028 }
1029
PrintMCInst(llvm::MCInst & mc_inst,std::string & inst_string,std::string & comments_string)1030 void DisassemblerLLVMC::MCDisasmInstance::PrintMCInst(
1031 llvm::MCInst &mc_inst, std::string &inst_string,
1032 std::string &comments_string) {
1033 llvm::raw_string_ostream inst_stream(inst_string);
1034 llvm::raw_string_ostream comments_stream(comments_string);
1035
1036 m_instr_printer_up->setCommentStream(comments_stream);
1037 m_instr_printer_up->printInst(&mc_inst, inst_stream, llvm::StringRef(),
1038 *m_subtarget_info_up);
1039 m_instr_printer_up->setCommentStream(llvm::nulls());
1040 comments_stream.flush();
1041
1042 static std::string g_newlines("\r\n");
1043
1044 for (size_t newline_pos = 0;
1045 (newline_pos = comments_string.find_first_of(g_newlines, newline_pos)) !=
1046 comments_string.npos;
1047 /**/) {
1048 comments_string.replace(comments_string.begin() + newline_pos,
1049 comments_string.begin() + newline_pos + 1, 1, ' ');
1050 }
1051 }
1052
SetStyle(bool use_hex_immed,HexImmediateStyle hex_style)1053 void DisassemblerLLVMC::MCDisasmInstance::SetStyle(
1054 bool use_hex_immed, HexImmediateStyle hex_style) {
1055 m_instr_printer_up->setPrintImmHex(use_hex_immed);
1056 switch (hex_style) {
1057 case eHexStyleC:
1058 m_instr_printer_up->setPrintHexStyle(llvm::HexStyle::C);
1059 break;
1060 case eHexStyleAsm:
1061 m_instr_printer_up->setPrintHexStyle(llvm::HexStyle::Asm);
1062 break;
1063 }
1064 }
1065
CanBranch(llvm::MCInst & mc_inst) const1066 bool DisassemblerLLVMC::MCDisasmInstance::CanBranch(
1067 llvm::MCInst &mc_inst) const {
1068 return m_instr_info_up->get(mc_inst.getOpcode())
1069 .mayAffectControlFlow(mc_inst, *m_reg_info_up);
1070 }
1071
HasDelaySlot(llvm::MCInst & mc_inst) const1072 bool DisassemblerLLVMC::MCDisasmInstance::HasDelaySlot(
1073 llvm::MCInst &mc_inst) const {
1074 return m_instr_info_up->get(mc_inst.getOpcode()).hasDelaySlot();
1075 }
1076
IsCall(llvm::MCInst & mc_inst) const1077 bool DisassemblerLLVMC::MCDisasmInstance::IsCall(llvm::MCInst &mc_inst) const {
1078 return m_instr_info_up->get(mc_inst.getOpcode()).isCall();
1079 }
1080
DisassemblerLLVMC(const ArchSpec & arch,const char * flavor_string)1081 DisassemblerLLVMC::DisassemblerLLVMC(const ArchSpec &arch,
1082 const char *flavor_string)
1083 : Disassembler(arch, flavor_string), m_exe_ctx(NULL), m_inst(NULL),
1084 m_data_from_file(false) {
1085 if (!FlavorValidForArchSpec(arch, m_flavor.c_str())) {
1086 m_flavor.assign("default");
1087 }
1088
1089 unsigned flavor = ~0U;
1090 llvm::Triple triple = arch.GetTriple();
1091
1092 // So far the only supported flavor is "intel" on x86. The base class will
1093 // set this correctly coming in.
1094 if (triple.getArch() == llvm::Triple::x86 ||
1095 triple.getArch() == llvm::Triple::x86_64) {
1096 if (m_flavor == "intel") {
1097 flavor = 1;
1098 } else if (m_flavor == "att") {
1099 flavor = 0;
1100 }
1101 }
1102
1103 ArchSpec thumb_arch(arch);
1104 if (triple.getArch() == llvm::Triple::arm) {
1105 std::string thumb_arch_name(thumb_arch.GetTriple().getArchName().str());
1106 // Replace "arm" with "thumb" so we get all thumb variants correct
1107 if (thumb_arch_name.size() > 3) {
1108 thumb_arch_name.erase(0, 3);
1109 thumb_arch_name.insert(0, "thumb");
1110 } else {
1111 thumb_arch_name = "thumbv8.2a";
1112 }
1113 thumb_arch.GetTriple().setArchName(llvm::StringRef(thumb_arch_name));
1114 }
1115
1116 // If no sub architecture specified then use the most recent arm architecture
1117 // so the disassembler will return all instruction. Without it we will see a
1118 // lot of unknow opcode in case the code uses instructions which are not
1119 // available in the oldest arm version (used when no sub architecture is
1120 // specified)
1121 if (triple.getArch() == llvm::Triple::arm &&
1122 triple.getSubArch() == llvm::Triple::NoSubArch)
1123 triple.setArchName("armv8.2a");
1124
1125 std::string features_str = "";
1126 const char *triple_str = triple.getTriple().c_str();
1127
1128 // ARM Cortex M0-M7 devices only execute thumb instructions
1129 if (arch.IsAlwaysThumbInstructions()) {
1130 triple_str = thumb_arch.GetTriple().getTriple().c_str();
1131 features_str += "+fp-armv8,";
1132 }
1133
1134 const char *cpu = "";
1135
1136 switch (arch.GetCore()) {
1137 case ArchSpec::eCore_mips32:
1138 case ArchSpec::eCore_mips32el:
1139 cpu = "mips32";
1140 break;
1141 case ArchSpec::eCore_mips32r2:
1142 case ArchSpec::eCore_mips32r2el:
1143 cpu = "mips32r2";
1144 break;
1145 case ArchSpec::eCore_mips32r3:
1146 case ArchSpec::eCore_mips32r3el:
1147 cpu = "mips32r3";
1148 break;
1149 case ArchSpec::eCore_mips32r5:
1150 case ArchSpec::eCore_mips32r5el:
1151 cpu = "mips32r5";
1152 break;
1153 case ArchSpec::eCore_mips32r6:
1154 case ArchSpec::eCore_mips32r6el:
1155 cpu = "mips32r6";
1156 break;
1157 case ArchSpec::eCore_mips64:
1158 case ArchSpec::eCore_mips64el:
1159 cpu = "mips64";
1160 break;
1161 case ArchSpec::eCore_mips64r2:
1162 case ArchSpec::eCore_mips64r2el:
1163 cpu = "mips64r2";
1164 break;
1165 case ArchSpec::eCore_mips64r3:
1166 case ArchSpec::eCore_mips64r3el:
1167 cpu = "mips64r3";
1168 break;
1169 case ArchSpec::eCore_mips64r5:
1170 case ArchSpec::eCore_mips64r5el:
1171 cpu = "mips64r5";
1172 break;
1173 case ArchSpec::eCore_mips64r6:
1174 case ArchSpec::eCore_mips64r6el:
1175 cpu = "mips64r6";
1176 break;
1177 default:
1178 cpu = "";
1179 break;
1180 }
1181
1182 if (triple.getArch() == llvm::Triple::mips ||
1183 triple.getArch() == llvm::Triple::mipsel ||
1184 triple.getArch() == llvm::Triple::mips64 ||
1185 triple.getArch() == llvm::Triple::mips64el) {
1186 uint32_t arch_flags = arch.GetFlags();
1187 if (arch_flags & ArchSpec::eMIPSAse_msa)
1188 features_str += "+msa,";
1189 if (arch_flags & ArchSpec::eMIPSAse_dsp)
1190 features_str += "+dsp,";
1191 if (arch_flags & ArchSpec::eMIPSAse_dspr2)
1192 features_str += "+dspr2,";
1193 }
1194
1195 // If any AArch64 variant, enable the ARMv8.2 ISA extensions so we can
1196 // disassemble newer instructions.
1197 if (triple.getArch() == llvm::Triple::aarch64)
1198 features_str += "+v8.2a";
1199
1200 // We use m_disasm_ap.get() to tell whether we are valid or not, so if this
1201 // isn't good for some reason, we won't be valid and FindPlugin will fail and
1202 // we won't get used.
1203 m_disasm_up = MCDisasmInstance::Create(triple_str, cpu, features_str.c_str(),
1204 flavor, *this);
1205
1206 llvm::Triple::ArchType llvm_arch = triple.getArch();
1207
1208 // For arm CPUs that can execute arm or thumb instructions, also create a
1209 // thumb instruction disassembler.
1210 if (llvm_arch == llvm::Triple::arm) {
1211 std::string thumb_triple(thumb_arch.GetTriple().getTriple());
1212 m_alternate_disasm_up =
1213 MCDisasmInstance::Create(thumb_triple.c_str(), "", features_str.c_str(),
1214 flavor, *this);
1215 if (!m_alternate_disasm_up)
1216 m_disasm_up.reset();
1217
1218 } else if (llvm_arch == llvm::Triple::mips ||
1219 llvm_arch == llvm::Triple::mipsel ||
1220 llvm_arch == llvm::Triple::mips64 ||
1221 llvm_arch == llvm::Triple::mips64el) {
1222 /* Create alternate disassembler for MIPS16 and microMIPS */
1223 uint32_t arch_flags = arch.GetFlags();
1224 if (arch_flags & ArchSpec::eMIPSAse_mips16)
1225 features_str += "+mips16,";
1226 else if (arch_flags & ArchSpec::eMIPSAse_micromips)
1227 features_str += "+micromips,";
1228
1229 m_alternate_disasm_up = MCDisasmInstance::Create(
1230 triple_str, cpu, features_str.c_str(), flavor, *this);
1231 if (!m_alternate_disasm_up)
1232 m_disasm_up.reset();
1233 }
1234 }
1235
1236 DisassemblerLLVMC::~DisassemblerLLVMC() = default;
1237
CreateInstance(const ArchSpec & arch,const char * flavor)1238 Disassembler *DisassemblerLLVMC::CreateInstance(const ArchSpec &arch,
1239 const char *flavor) {
1240 if (arch.GetTriple().getArch() != llvm::Triple::UnknownArch) {
1241 std::unique_ptr<DisassemblerLLVMC> disasm_ap(
1242 new DisassemblerLLVMC(arch, flavor));
1243
1244 if (disasm_ap.get() && disasm_ap->IsValid())
1245 return disasm_ap.release();
1246 }
1247 return NULL;
1248 }
1249
DecodeInstructions(const Address & base_addr,const DataExtractor & data,lldb::offset_t data_offset,size_t num_instructions,bool append,bool data_from_file)1250 size_t DisassemblerLLVMC::DecodeInstructions(const Address &base_addr,
1251 const DataExtractor &data,
1252 lldb::offset_t data_offset,
1253 size_t num_instructions,
1254 bool append, bool data_from_file) {
1255 if (!append)
1256 m_instruction_list.Clear();
1257
1258 if (!IsValid())
1259 return 0;
1260
1261 m_data_from_file = data_from_file;
1262 uint32_t data_cursor = data_offset;
1263 const size_t data_byte_size = data.GetByteSize();
1264 uint32_t instructions_parsed = 0;
1265 Address inst_addr(base_addr);
1266
1267 while (data_cursor < data_byte_size &&
1268 instructions_parsed < num_instructions) {
1269
1270 AddressClass address_class = AddressClass::eCode;
1271
1272 if (m_alternate_disasm_up)
1273 address_class = inst_addr.GetAddressClass();
1274
1275 InstructionSP inst_sp(
1276 new InstructionLLVMC(*this, inst_addr, address_class));
1277
1278 if (!inst_sp)
1279 break;
1280
1281 uint32_t inst_size = inst_sp->Decode(*this, data, data_cursor);
1282
1283 if (inst_size == 0)
1284 break;
1285
1286 m_instruction_list.Append(inst_sp);
1287 data_cursor += inst_size;
1288 inst_addr.Slide(inst_size);
1289 instructions_parsed++;
1290 }
1291
1292 return data_cursor - data_offset;
1293 }
1294
Initialize()1295 void DisassemblerLLVMC::Initialize() {
1296 PluginManager::RegisterPlugin(GetPluginNameStatic(),
1297 "Disassembler that uses LLVM MC to disassemble "
1298 "i386, x86_64, ARM, and ARM64.",
1299 CreateInstance);
1300
1301 llvm::InitializeAllTargetInfos();
1302 llvm::InitializeAllTargetMCs();
1303 llvm::InitializeAllAsmParsers();
1304 llvm::InitializeAllDisassemblers();
1305 }
1306
Terminate()1307 void DisassemblerLLVMC::Terminate() {
1308 PluginManager::UnregisterPlugin(CreateInstance);
1309 }
1310
GetPluginNameStatic()1311 ConstString DisassemblerLLVMC::GetPluginNameStatic() {
1312 static ConstString g_name("llvm-mc");
1313 return g_name;
1314 }
1315
OpInfoCallback(void * disassembler,uint64_t pc,uint64_t offset,uint64_t size,int tag_type,void * tag_bug)1316 int DisassemblerLLVMC::OpInfoCallback(void *disassembler, uint64_t pc,
1317 uint64_t offset, uint64_t size,
1318 int tag_type, void *tag_bug) {
1319 return static_cast<DisassemblerLLVMC *>(disassembler)
1320 ->OpInfo(pc, offset, size, tag_type, tag_bug);
1321 }
1322
SymbolLookupCallback(void * disassembler,uint64_t value,uint64_t * type,uint64_t pc,const char ** name)1323 const char *DisassemblerLLVMC::SymbolLookupCallback(void *disassembler,
1324 uint64_t value,
1325 uint64_t *type, uint64_t pc,
1326 const char **name) {
1327 return static_cast<DisassemblerLLVMC *>(disassembler)
1328 ->SymbolLookup(value, type, pc, name);
1329 }
1330
FlavorValidForArchSpec(const lldb_private::ArchSpec & arch,const char * flavor)1331 bool DisassemblerLLVMC::FlavorValidForArchSpec(
1332 const lldb_private::ArchSpec &arch, const char *flavor) {
1333 llvm::Triple triple = arch.GetTriple();
1334 if (flavor == NULL || strcmp(flavor, "default") == 0)
1335 return true;
1336
1337 if (triple.getArch() == llvm::Triple::x86 ||
1338 triple.getArch() == llvm::Triple::x86_64) {
1339 return strcmp(flavor, "intel") == 0 || strcmp(flavor, "att") == 0;
1340 } else
1341 return false;
1342 }
1343
IsValid() const1344 bool DisassemblerLLVMC::IsValid() const { return m_disasm_up.operator bool(); }
1345
OpInfo(uint64_t PC,uint64_t Offset,uint64_t Size,int tag_type,void * tag_bug)1346 int DisassemblerLLVMC::OpInfo(uint64_t PC, uint64_t Offset, uint64_t Size,
1347 int tag_type, void *tag_bug) {
1348 switch (tag_type) {
1349 default:
1350 break;
1351 case 1:
1352 memset(tag_bug, 0, sizeof(::LLVMOpInfo1));
1353 break;
1354 }
1355 return 0;
1356 }
1357
SymbolLookup(uint64_t value,uint64_t * type_ptr,uint64_t pc,const char ** name)1358 const char *DisassemblerLLVMC::SymbolLookup(uint64_t value, uint64_t *type_ptr,
1359 uint64_t pc, const char **name) {
1360 if (*type_ptr) {
1361 if (m_exe_ctx && m_inst) {
1362 // std::string remove_this_prior_to_checkin;
1363 Target *target = m_exe_ctx ? m_exe_ctx->GetTargetPtr() : NULL;
1364 Address value_so_addr;
1365 Address pc_so_addr;
1366 if (m_inst->UsingFileAddress()) {
1367 ModuleSP module_sp(m_inst->GetAddress().GetModule());
1368 if (module_sp) {
1369 module_sp->ResolveFileAddress(value, value_so_addr);
1370 module_sp->ResolveFileAddress(pc, pc_so_addr);
1371 }
1372 } else if (target && !target->GetSectionLoadList().IsEmpty()) {
1373 target->GetSectionLoadList().ResolveLoadAddress(value, value_so_addr);
1374 target->GetSectionLoadList().ResolveLoadAddress(pc, pc_so_addr);
1375 }
1376
1377 SymbolContext sym_ctx;
1378 const SymbolContextItem resolve_scope =
1379 eSymbolContextFunction | eSymbolContextSymbol;
1380 if (pc_so_addr.IsValid() && pc_so_addr.GetModule()) {
1381 pc_so_addr.GetModule()->ResolveSymbolContextForAddress(
1382 pc_so_addr, resolve_scope, sym_ctx);
1383 }
1384
1385 if (value_so_addr.IsValid() && value_so_addr.GetSection()) {
1386 StreamString ss;
1387
1388 bool format_omitting_current_func_name = false;
1389 if (sym_ctx.symbol || sym_ctx.function) {
1390 AddressRange range;
1391 if (sym_ctx.GetAddressRange(resolve_scope, 0, false, range) &&
1392 range.GetBaseAddress().IsValid() &&
1393 range.ContainsLoadAddress(value_so_addr, target)) {
1394 format_omitting_current_func_name = true;
1395 }
1396 }
1397
1398 // If the "value" address (the target address we're symbolicating) is
1399 // inside the same SymbolContext as the current instruction pc
1400 // (pc_so_addr), don't print the full function name - just print it
1401 // with DumpStyleNoFunctionName style, e.g. "<+36>".
1402 if (format_omitting_current_func_name) {
1403 value_so_addr.Dump(&ss, target, Address::DumpStyleNoFunctionName,
1404 Address::DumpStyleSectionNameOffset);
1405 } else {
1406 value_so_addr.Dump(
1407 &ss, target,
1408 Address::DumpStyleResolvedDescriptionNoFunctionArguments,
1409 Address::DumpStyleSectionNameOffset);
1410 }
1411
1412 if (!ss.GetString().empty()) {
1413 // If Address::Dump returned a multi-line description, most commonly
1414 // seen when we have multiple levels of inlined functions at an
1415 // address, only show the first line.
1416 std::string str = ss.GetString();
1417 size_t first_eol_char = str.find_first_of("\r\n");
1418 if (first_eol_char != std::string::npos) {
1419 str.erase(first_eol_char);
1420 }
1421 m_inst->AppendComment(str);
1422 }
1423 }
1424 }
1425 }
1426
1427 *type_ptr = LLVMDisassembler_ReferenceType_InOut_None;
1428 *name = NULL;
1429 return NULL;
1430 }
1431
1432 //------------------------------------------------------------------
1433 // PluginInterface protocol
1434 //------------------------------------------------------------------
GetPluginName()1435 ConstString DisassemblerLLVMC::GetPluginName() { return GetPluginNameStatic(); }
1436
GetPluginVersion()1437 uint32_t DisassemblerLLVMC::GetPluginVersion() { return 1; }
1438