1//===-- Disassembler.cpp --------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "lldb/Core/Disassembler.h"
10
11#include "lldb/Core/AddressRange.h"
12#include "lldb/Core/Debugger.h"
13#include "lldb/Core/EmulateInstruction.h"
14#include "lldb/Core/Mangled.h"
15#include "lldb/Core/Module.h"
16#include "lldb/Core/ModuleList.h"
17#include "lldb/Core/PluginManager.h"
18#include "lldb/Core/SourceManager.h"
19#include "lldb/Host/FileSystem.h"
20#include "lldb/Interpreter/OptionValue.h"
21#include "lldb/Interpreter/OptionValueArray.h"
22#include "lldb/Interpreter/OptionValueDictionary.h"
23#include "lldb/Interpreter/OptionValueRegex.h"
24#include "lldb/Interpreter/OptionValueString.h"
25#include "lldb/Interpreter/OptionValueUInt64.h"
26#include "lldb/Symbol/Function.h"
27#include "lldb/Symbol/Symbol.h"
28#include "lldb/Symbol/SymbolContext.h"
29#include "lldb/Target/ExecutionContext.h"
30#include "lldb/Target/SectionLoadList.h"
31#include "lldb/Target/StackFrame.h"
32#include "lldb/Target/Target.h"
33#include "lldb/Target/Thread.h"
34#include "lldb/Utility/DataBufferHeap.h"
35#include "lldb/Utility/DataExtractor.h"
36#include "lldb/Utility/RegularExpression.h"
37#include "lldb/Utility/Status.h"
38#include "lldb/Utility/Stream.h"
39#include "lldb/Utility/StreamString.h"
40#include "lldb/Utility/Timer.h"
41#include "lldb/lldb-private-enumerations.h"
42#include "lldb/lldb-private-interfaces.h"
43#include "lldb/lldb-private-types.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/TargetParser/Triple.h"
46
47#include <cstdint>
48#include <cstring>
49#include <utility>
50
51#include <cassert>
52
53#define DEFAULT_DISASM_BYTE_SIZE 32
54
55using namespace lldb;
56using namespace lldb_private;
57
58DisassemblerSP Disassembler::FindPlugin(const ArchSpec &arch,
59 const char *flavor, const char *cpu,
60 const char *features,
61 const char *plugin_name) {
62 LLDB_SCOPED_TIMERF("Disassembler::FindPlugin (arch = %s, plugin_name = %s)",
63 arch.GetArchitectureName(), plugin_name);
64
65 DisassemblerCreateInstance create_callback = nullptr;
66
67 if (plugin_name) {
68 create_callback =
69 PluginManager::GetDisassemblerCreateCallbackForPluginName(name: plugin_name);
70 if (create_callback) {
71 if (auto disasm_sp = create_callback(arch, flavor, cpu, features))
72 return disasm_sp;
73 }
74 } else {
75 for (uint32_t idx = 0;
76 (create_callback = PluginManager::GetDisassemblerCreateCallbackAtIndex(
77 idx)) != nullptr;
78 ++idx) {
79 if (auto disasm_sp = create_callback(arch, flavor, cpu, features))
80 return disasm_sp;
81 }
82 }
83 return DisassemblerSP();
84}
85
86DisassemblerSP Disassembler::FindPluginForTarget(
87 const Target &target, const ArchSpec &arch, const char *flavor,
88 const char *cpu, const char *features, const char *plugin_name) {
89 if (!flavor) {
90 // FIXME - we don't have the mechanism in place to do per-architecture
91 // settings. But since we know that for now we only support flavors on x86
92 // & x86_64,
93 if (arch.GetTriple().getArch() == llvm::Triple::x86 ||
94 arch.GetTriple().getArch() == llvm::Triple::x86_64)
95 flavor = target.GetDisassemblyFlavor();
96 }
97 if (!cpu)
98 cpu = target.GetDisassemblyCPU();
99 if (!features)
100 features = target.GetDisassemblyFeatures();
101
102 return FindPlugin(arch, flavor, cpu, features, plugin_name);
103}
104
105static Address ResolveAddress(Target &target, const Address &addr) {
106 if (!addr.IsSectionOffset()) {
107 Address resolved_addr;
108 // If we weren't passed in a section offset address range, try and resolve
109 // it to something
110 bool is_resolved =
111 target.HasLoadedSections()
112 ? target.ResolveLoadAddress(load_addr: addr.GetOffset(), so_addr&: resolved_addr)
113 : target.GetImages().ResolveFileAddress(vm_addr: addr.GetOffset(),
114 so_addr&: resolved_addr);
115
116 // We weren't able to resolve the address, just treat it as a raw address
117 if (is_resolved && resolved_addr.IsValid())
118 return resolved_addr;
119 }
120 return addr;
121}
122
123lldb::DisassemblerSP Disassembler::DisassembleRange(
124 const ArchSpec &arch, const char *plugin_name, const char *flavor,
125 const char *cpu, const char *features, Target &target,
126 llvm::ArrayRef<AddressRange> disasm_ranges, bool force_live_memory) {
127 lldb::DisassemblerSP disasm_sp = Disassembler::FindPluginForTarget(
128 target, arch, flavor, cpu, features, plugin_name);
129
130 if (!disasm_sp)
131 return {};
132
133 size_t bytes_disassembled = 0;
134 for (const AddressRange &range : disasm_ranges) {
135 bytes_disassembled += disasm_sp->AppendInstructions(
136 target, address: range.GetBaseAddress(), limit: {.kind: Limit::Bytes, .value: range.GetByteSize()},
137 error_strm_ptr: nullptr, force_live_memory);
138 }
139 if (bytes_disassembled == 0)
140 return {};
141
142 return disasm_sp;
143}
144
145lldb::DisassemblerSP
146Disassembler::DisassembleBytes(const ArchSpec &arch, const char *plugin_name,
147 const char *flavor, const char *cpu,
148 const char *features, const Address &start,
149 const void *src, size_t src_len,
150 uint32_t num_instructions, bool data_from_file) {
151 if (!src)
152 return {};
153
154 lldb::DisassemblerSP disasm_sp =
155 Disassembler::FindPlugin(arch, flavor, cpu, features, plugin_name);
156
157 if (!disasm_sp)
158 return {};
159
160 DataExtractor data(src, src_len, arch.GetByteOrder(),
161 arch.GetAddressByteSize());
162
163 (void)disasm_sp->DecodeInstructions(base_addr: start, data, data_offset: 0, num_instructions, append: false,
164 data_from_file);
165 return disasm_sp;
166}
167
168bool Disassembler::Disassemble(Debugger &debugger, const ArchSpec &arch,
169 const char *plugin_name, const char *flavor,
170 const char *cpu, const char *features,
171 const ExecutionContext &exe_ctx,
172 const Address &address, Limit limit,
173 bool mixed_source_and_assembly,
174 uint32_t num_mixed_context_lines,
175 uint32_t options, Stream &strm) {
176 if (!exe_ctx.GetTargetPtr())
177 return false;
178
179 lldb::DisassemblerSP disasm_sp(Disassembler::FindPluginForTarget(
180 target: exe_ctx.GetTargetRef(), arch, flavor, cpu, features, plugin_name));
181 if (!disasm_sp)
182 return false;
183
184 const bool force_live_memory = true;
185 size_t bytes_disassembled = disasm_sp->ParseInstructions(
186 target&: exe_ctx.GetTargetRef(), address, limit, error_strm_ptr: &strm, force_live_memory);
187 if (bytes_disassembled == 0)
188 return false;
189
190 disasm_sp->PrintInstructions(debugger, arch, exe_ctx,
191 mixed_source_and_assembly,
192 num_mixed_context_lines, options, strm);
193 return true;
194}
195
196Disassembler::SourceLine
197Disassembler::GetFunctionDeclLineEntry(const SymbolContext &sc) {
198 if (!sc.function)
199 return {};
200
201 if (!sc.line_entry.IsValid())
202 return {};
203
204 LineEntry prologue_end_line = sc.line_entry;
205 SupportFileSP func_decl_file_sp;
206 uint32_t func_decl_line;
207 sc.function->GetStartLineSourceInfo(source_file_sp&: func_decl_file_sp, line_no&: func_decl_line);
208
209 if (!func_decl_file_sp)
210 return {};
211 if (!func_decl_file_sp->Equal(other: *prologue_end_line.file_sp,
212 equality: SupportFile::eEqualFileSpecAndChecksumIfSet) &&
213 !func_decl_file_sp->Equal(other: *prologue_end_line.original_file_sp,
214 equality: SupportFile::eEqualFileSpecAndChecksumIfSet))
215 return {};
216
217 SourceLine decl_line;
218 decl_line.file = func_decl_file_sp->GetSpecOnly();
219 decl_line.line = func_decl_line;
220 // TODO: Do we care about column on these entries? If so, we need to plumb
221 // that through GetStartLineSourceInfo.
222 decl_line.column = 0;
223 return decl_line;
224}
225
226void Disassembler::AddLineToSourceLineTables(
227 SourceLine &line,
228 std::map<FileSpec, std::set<uint32_t>> &source_lines_seen) {
229 if (line.IsValid()) {
230 auto source_lines_seen_pos = source_lines_seen.find(x: line.file);
231 if (source_lines_seen_pos == source_lines_seen.end()) {
232 std::set<uint32_t> lines;
233 lines.insert(x: line.line);
234 source_lines_seen.emplace(args&: line.file, args&: lines);
235 } else {
236 source_lines_seen_pos->second.insert(x: line.line);
237 }
238 }
239}
240
241bool Disassembler::ElideMixedSourceAndDisassemblyLine(
242 const ExecutionContext &exe_ctx, const SymbolContext &sc,
243 SourceLine &line) {
244
245 // TODO: should we also check target.process.thread.step-avoid-libraries ?
246
247 const RegularExpression *avoid_regex = nullptr;
248
249 // Skip any line #0 entries - they are implementation details
250 if (line.line == 0)
251 return true;
252
253 ThreadSP thread_sp = exe_ctx.GetThreadSP();
254 if (thread_sp) {
255 avoid_regex = thread_sp->GetSymbolsToAvoidRegexp();
256 } else {
257 TargetSP target_sp = exe_ctx.GetTargetSP();
258 if (target_sp) {
259 Status error;
260 OptionValueSP value_sp = target_sp->GetDebugger().GetPropertyValue(
261 exe_ctx: &exe_ctx, property_path: "target.process.thread.step-avoid-regexp", error);
262 if (value_sp && value_sp->GetType() == OptionValue::eTypeRegex) {
263 OptionValueRegex *re = value_sp->GetAsRegex();
264 if (re) {
265 avoid_regex = re->GetCurrentValue();
266 }
267 }
268 }
269 }
270 if (avoid_regex && sc.symbol != nullptr) {
271 const char *function_name =
272 sc.GetFunctionName(preference: Mangled::ePreferDemangledWithoutArguments)
273 .GetCString();
274 if (function_name && avoid_regex->Execute(string: function_name)) {
275 // skip this source line
276 return true;
277 }
278 }
279 // don't skip this source line
280 return false;
281}
282
283void Disassembler::PrintInstructions(Debugger &debugger, const ArchSpec &arch,
284 const ExecutionContext &exe_ctx,
285 bool mixed_source_and_assembly,
286 uint32_t num_mixed_context_lines,
287 uint32_t options, Stream &strm) {
288 // We got some things disassembled...
289 size_t num_instructions_found = GetInstructionList().GetSize();
290
291 const uint32_t max_opcode_byte_size =
292 GetInstructionList().GetMaxOpcocdeByteSize();
293 SymbolContext sc;
294 SymbolContext prev_sc;
295 AddressRange current_source_line_range;
296 const Address *pc_addr_ptr = nullptr;
297 StackFrame *frame = exe_ctx.GetFramePtr();
298
299 TargetSP target_sp(exe_ctx.GetTargetSP());
300 SourceManager &source_manager =
301 target_sp ? target_sp->GetSourceManager() : debugger.GetSourceManager();
302
303 if (frame) {
304 pc_addr_ptr = &frame->GetFrameCodeAddress();
305 }
306 const uint32_t scope =
307 eSymbolContextLineEntry | eSymbolContextFunction | eSymbolContextSymbol;
308 const bool use_inline_block_range = false;
309
310 const FormatEntity::Entry *disassembly_format = nullptr;
311 FormatEntity::Entry format;
312 if (exe_ctx.HasTargetScope()) {
313 format = exe_ctx.GetTargetRef().GetDebugger().GetDisassemblyFormat();
314 disassembly_format = &format;
315 } else {
316 FormatEntity::Parse(format: "${addr}: ", entry&: format);
317 disassembly_format = &format;
318 }
319
320 // First pass: step through the list of instructions, find how long the
321 // initial addresses strings are, insert padding in the second pass so the
322 // opcodes all line up nicely.
323
324 // Also build up the source line mapping if this is mixed source & assembly
325 // mode. Calculate the source line for each assembly instruction (eliding
326 // inlined functions which the user wants to skip).
327
328 std::map<FileSpec, std::set<uint32_t>> source_lines_seen;
329 Symbol *previous_symbol = nullptr;
330
331 size_t address_text_size = 0;
332 for (size_t i = 0; i < num_instructions_found; ++i) {
333 Instruction *inst = GetInstructionList().GetInstructionAtIndex(idx: i).get();
334 if (inst) {
335 const Address &addr = inst->GetAddress();
336 ModuleSP module_sp(addr.GetModule());
337 if (module_sp) {
338 const SymbolContextItem resolve_mask = eSymbolContextFunction |
339 eSymbolContextSymbol |
340 eSymbolContextLineEntry;
341 uint32_t resolved_mask =
342 module_sp->ResolveSymbolContextForAddress(so_addr: addr, resolve_scope: resolve_mask, sc);
343 if (resolved_mask) {
344 StreamString strmstr;
345 Debugger::FormatDisassemblerAddress(format: disassembly_format, sc: &sc, prev_sc: nullptr,
346 exe_ctx: &exe_ctx, addr: &addr, s&: strmstr);
347 size_t cur_line = strmstr.GetSizeOfLastLine();
348 if (cur_line > address_text_size)
349 address_text_size = cur_line;
350
351 // Add entries to our "source_lines_seen" map+set which list which
352 // sources lines occur in this disassembly session. We will print
353 // lines of context around a source line, but we don't want to print
354 // a source line that has a line table entry of its own - we'll leave
355 // that source line to be printed when it actually occurs in the
356 // disassembly.
357
358 if (mixed_source_and_assembly && sc.line_entry.IsValid()) {
359 if (sc.symbol != previous_symbol) {
360 SourceLine decl_line = GetFunctionDeclLineEntry(sc);
361 if (!ElideMixedSourceAndDisassemblyLine(exe_ctx, sc, line&: decl_line))
362 AddLineToSourceLineTables(line&: decl_line, source_lines_seen);
363 }
364 if (sc.line_entry.IsValid()) {
365 SourceLine this_line;
366 this_line.file = sc.line_entry.GetFile();
367 this_line.line = sc.line_entry.line;
368 this_line.column = sc.line_entry.column;
369 if (!ElideMixedSourceAndDisassemblyLine(exe_ctx, sc, line&: this_line))
370 AddLineToSourceLineTables(line&: this_line, source_lines_seen);
371 }
372 }
373 }
374 sc.Clear(clear_target: false);
375 }
376 }
377 }
378
379 previous_symbol = nullptr;
380 SourceLine previous_line;
381 for (size_t i = 0; i < num_instructions_found; ++i) {
382 Instruction *inst = GetInstructionList().GetInstructionAtIndex(idx: i).get();
383
384 if (inst) {
385 const Address &addr = inst->GetAddress();
386 const bool inst_is_at_pc = pc_addr_ptr && addr == *pc_addr_ptr;
387 SourceLinesToDisplay source_lines_to_display;
388
389 prev_sc = sc;
390
391 ModuleSP module_sp(addr.GetModule());
392 if (module_sp) {
393 uint32_t resolved_mask = module_sp->ResolveSymbolContextForAddress(
394 so_addr: addr, resolve_scope: eSymbolContextEverything, sc);
395 if (resolved_mask) {
396 if (mixed_source_and_assembly) {
397
398 // If we've started a new function (non-inlined), print all of the
399 // source lines from the function declaration until the first line
400 // table entry - typically the opening curly brace of the function.
401 if (previous_symbol != sc.symbol) {
402 // The default disassembly format puts an extra blank line
403 // between functions - so when we're displaying the source
404 // context for a function, we don't want to add a blank line
405 // after the source context or we'll end up with two of them.
406 if (previous_symbol != nullptr)
407 source_lines_to_display.print_source_context_end_eol = false;
408
409 previous_symbol = sc.symbol;
410 if (sc.function && sc.line_entry.IsValid()) {
411 LineEntry prologue_end_line = sc.line_entry;
412 if (!ElideMixedSourceAndDisassemblyLine(exe_ctx, sc,
413 line&: prologue_end_line)) {
414 SupportFileSP func_decl_file_sp;
415 uint32_t func_decl_line;
416 sc.function->GetStartLineSourceInfo(source_file_sp&: func_decl_file_sp,
417 line_no&: func_decl_line);
418 if (func_decl_file_sp &&
419 (func_decl_file_sp->Equal(
420 other: *prologue_end_line.file_sp,
421 equality: SupportFile::eEqualFileSpecAndChecksumIfSet) ||
422 func_decl_file_sp->Equal(
423 other: *prologue_end_line.original_file_sp,
424 equality: SupportFile::eEqualFileSpecAndChecksumIfSet))) {
425 // Add all the lines between the function declaration and
426 // the first non-prologue source line to the list of lines
427 // to print.
428 for (uint32_t lineno = func_decl_line;
429 lineno <= prologue_end_line.line; lineno++) {
430 SourceLine this_line;
431 this_line.file = func_decl_file_sp->GetSpecOnly();
432 this_line.line = lineno;
433 source_lines_to_display.lines.push_back(x: this_line);
434 }
435 // Mark the last line as the "current" one. Usually this
436 // is the open curly brace.
437 if (source_lines_to_display.lines.size() > 0)
438 source_lines_to_display.current_source_line =
439 source_lines_to_display.lines.size() - 1;
440 }
441 }
442 }
443 sc.GetAddressRange(scope, range_idx: 0, use_inline_block_range,
444 range&: current_source_line_range);
445 }
446
447 // If we've left a previous source line's address range, print a
448 // new source line
449 if (!current_source_line_range.ContainsFileAddress(so_addr: addr)) {
450 sc.GetAddressRange(scope, range_idx: 0, use_inline_block_range,
451 range&: current_source_line_range);
452
453 if (sc != prev_sc && sc.comp_unit && sc.line_entry.IsValid()) {
454 SourceLine this_line;
455 this_line.file = sc.line_entry.GetFile();
456 this_line.line = sc.line_entry.line;
457
458 if (!ElideMixedSourceAndDisassemblyLine(exe_ctx, sc,
459 line&: this_line)) {
460 // Only print this source line if it is different from the
461 // last source line we printed. There may have been inlined
462 // functions between these lines that we elided, resulting in
463 // the same line being printed twice in a row for a
464 // contiguous block of assembly instructions.
465 if (this_line != previous_line) {
466
467 std::vector<uint32_t> previous_lines;
468 for (uint32_t i = 0;
469 i < num_mixed_context_lines &&
470 (this_line.line - num_mixed_context_lines) > 0;
471 i++) {
472 uint32_t line =
473 this_line.line - num_mixed_context_lines + i;
474 auto pos = source_lines_seen.find(x: this_line.file);
475 if (pos != source_lines_seen.end()) {
476 if (pos->second.count(x: line) == 1) {
477 previous_lines.clear();
478 } else {
479 previous_lines.push_back(x: line);
480 }
481 }
482 }
483 for (size_t i = 0; i < previous_lines.size(); i++) {
484 SourceLine previous_line;
485 previous_line.file = this_line.file;
486 previous_line.line = previous_lines[i];
487 auto pos = source_lines_seen.find(x: previous_line.file);
488 if (pos != source_lines_seen.end()) {
489 pos->second.insert(x: previous_line.line);
490 }
491 source_lines_to_display.lines.push_back(x: previous_line);
492 }
493
494 source_lines_to_display.lines.push_back(x: this_line);
495 source_lines_to_display.current_source_line =
496 source_lines_to_display.lines.size() - 1;
497
498 for (uint32_t i = 0; i < num_mixed_context_lines; i++) {
499 SourceLine next_line;
500 next_line.file = this_line.file;
501 next_line.line = this_line.line + i + 1;
502 auto pos = source_lines_seen.find(x: next_line.file);
503 if (pos != source_lines_seen.end()) {
504 if (pos->second.count(x: next_line.line) == 1)
505 break;
506 pos->second.insert(x: next_line.line);
507 }
508 source_lines_to_display.lines.push_back(x: next_line);
509 }
510 }
511 previous_line = this_line;
512 }
513 }
514 }
515 }
516 } else {
517 sc.Clear(clear_target: true);
518 }
519 }
520
521 if (source_lines_to_display.lines.size() > 0) {
522 strm.EOL();
523 for (size_t idx = 0; idx < source_lines_to_display.lines.size();
524 idx++) {
525 SourceLine ln = source_lines_to_display.lines[idx];
526 const char *line_highlight = "";
527 if (inst_is_at_pc && (options & eOptionMarkPCSourceLine)) {
528 line_highlight = "->";
529 } else if (idx == source_lines_to_display.current_source_line) {
530 line_highlight = "**";
531 }
532 source_manager.DisplaySourceLinesWithLineNumbers(
533 support_file_sp: std::make_shared<SupportFile>(args&: ln.file), line: ln.line, column: ln.column, context_before: 0, context_after: 0,
534 current_line_cstr: line_highlight, s: &strm);
535 }
536 if (source_lines_to_display.print_source_context_end_eol)
537 strm.EOL();
538 }
539
540 const bool show_bytes = (options & eOptionShowBytes) != 0;
541 const bool show_control_flow_kind =
542 (options & eOptionShowControlFlowKind) != 0;
543 inst->Dump(s: &strm, max_opcode_byte_size, show_address: true, show_bytes,
544 show_control_flow_kind, exe_ctx: &exe_ctx, sym_ctx: &sc, prev_sym_ctx: &prev_sc, disassembly_addr_format: nullptr,
545 max_address_text_size: address_text_size);
546 strm.EOL();
547 } else {
548 break;
549 }
550 }
551}
552
553bool Disassembler::Disassemble(Debugger &debugger, const ArchSpec &arch,
554 StackFrame &frame, Stream &strm) {
555 constexpr const char *plugin_name = nullptr;
556 constexpr const char *flavor = nullptr;
557 constexpr const char *cpu = nullptr;
558 constexpr const char *features = nullptr;
559 constexpr bool mixed_source_and_assembly = false;
560 constexpr uint32_t num_mixed_context_lines = 0;
561 constexpr uint32_t options = 0;
562
563 SymbolContext sc(
564 frame.GetSymbolContext(resolve_scope: eSymbolContextFunction | eSymbolContextSymbol));
565 if (sc.function) {
566 if (DisassemblerSP disasm_sp = DisassembleRange(
567 arch, plugin_name, flavor, cpu, features, target&: *frame.CalculateTarget(),
568 disasm_ranges: sc.function->GetAddressRanges())) {
569 disasm_sp->PrintInstructions(debugger, arch, exe_ctx: frame,
570 mixed_source_and_assembly,
571 num_mixed_context_lines, options, strm);
572 return true;
573 }
574 return false;
575 }
576
577 AddressRange range;
578 if (sc.symbol && sc.symbol->ValueIsAddress()) {
579 range.GetBaseAddress() = sc.symbol->GetAddressRef();
580 range.SetByteSize(sc.symbol->GetByteSize());
581 } else {
582 range.GetBaseAddress() = frame.GetFrameCodeAddress();
583 }
584
585 if (range.GetBaseAddress().IsValid() && range.GetByteSize() == 0)
586 range.SetByteSize(DEFAULT_DISASM_BYTE_SIZE);
587
588 Disassembler::Limit limit = {.kind: Disassembler::Limit::Bytes, .value: range.GetByteSize()};
589 if (limit.value == 0)
590 limit.value = DEFAULT_DISASM_BYTE_SIZE;
591
592 return Disassemble(debugger, arch, plugin_name, flavor, cpu, features, exe_ctx: frame,
593 address: range.GetBaseAddress(), limit, mixed_source_and_assembly,
594 num_mixed_context_lines, options, strm);
595}
596
597Instruction::Instruction(const Address &address, AddressClass addr_class)
598 : m_address(address), m_address_class(addr_class), m_opcode(),
599 m_calculated_strings(false) {}
600
601Instruction::~Instruction() = default;
602
603AddressClass Instruction::GetAddressClass() {
604 if (m_address_class == AddressClass::eInvalid)
605 m_address_class = m_address.GetAddressClass();
606 return m_address_class;
607}
608
609const char *Instruction::GetNameForInstructionControlFlowKind(
610 lldb::InstructionControlFlowKind instruction_control_flow_kind) {
611 switch (instruction_control_flow_kind) {
612 case eInstructionControlFlowKindUnknown:
613 return "unknown";
614 case eInstructionControlFlowKindOther:
615 return "other";
616 case eInstructionControlFlowKindCall:
617 return "call";
618 case eInstructionControlFlowKindReturn:
619 return "return";
620 case eInstructionControlFlowKindJump:
621 return "jump";
622 case eInstructionControlFlowKindCondJump:
623 return "cond jump";
624 case eInstructionControlFlowKindFarCall:
625 return "far call";
626 case eInstructionControlFlowKindFarReturn:
627 return "far return";
628 case eInstructionControlFlowKindFarJump:
629 return "far jump";
630 }
631 llvm_unreachable("Fully covered switch above!");
632}
633
634void Instruction::Dump(lldb_private::Stream *s, uint32_t max_opcode_byte_size,
635 bool show_address, bool show_bytes,
636 bool show_control_flow_kind,
637 const ExecutionContext *exe_ctx,
638 const SymbolContext *sym_ctx,
639 const SymbolContext *prev_sym_ctx,
640 const FormatEntity::Entry *disassembly_addr_format,
641 size_t max_address_text_size) {
642 size_t opcode_column_width = 7;
643 const size_t operand_column_width = 25;
644
645 CalculateMnemonicOperandsAndCommentIfNeeded(exe_ctx);
646
647 StreamString ss;
648
649 if (show_address) {
650 Debugger::FormatDisassemblerAddress(format: disassembly_addr_format, sc: sym_ctx,
651 prev_sc: prev_sym_ctx, exe_ctx, addr: &m_address, s&: ss);
652 ss.FillLastLineToColumn(column: max_address_text_size, fill_char: ' ');
653 }
654
655 if (show_bytes) {
656 if (m_opcode.GetType() == Opcode::eTypeBytes) {
657 // x86_64 and i386 are the only ones that use bytes right now so pad out
658 // the byte dump to be able to always show 15 bytes (3 chars each) plus a
659 // space
660 if (max_opcode_byte_size > 0)
661 m_opcode.Dump(s: &ss, min_byte_width: max_opcode_byte_size * 3 + 1);
662 else
663 m_opcode.Dump(s: &ss, min_byte_width: 15 * 3 + 1);
664 } else {
665 // Else, we have ARM or MIPS which can show up to a uint32_t 0x00000000
666 // (10 spaces) plus two for padding...
667 if (max_opcode_byte_size > 0)
668 m_opcode.Dump(s: &ss, min_byte_width: max_opcode_byte_size * 3 + 1);
669 else
670 m_opcode.Dump(s: &ss, min_byte_width: 12);
671 }
672 }
673
674 if (show_control_flow_kind) {
675 lldb::InstructionControlFlowKind instruction_control_flow_kind =
676 GetControlFlowKind(exe_ctx);
677 ss.Printf(format: "%-12s", GetNameForInstructionControlFlowKind(
678 instruction_control_flow_kind));
679 }
680
681 bool show_color = false;
682 if (exe_ctx) {
683 if (TargetSP target_sp = exe_ctx->GetTargetSP()) {
684 show_color = target_sp->GetDebugger().GetUseColor();
685 }
686 }
687 const size_t opcode_pos = ss.GetSizeOfLastLine();
688 std::string &opcode_name = show_color ? m_markup_opcode_name : m_opcode_name;
689 const std::string &mnemonics = show_color ? m_markup_mnemonics : m_mnemonics;
690
691 if (opcode_name.empty())
692 opcode_name = "<unknown>";
693
694 // The default opcode size of 7 characters is plenty for most architectures
695 // but some like arm can pull out the occasional vqrshrun.s16. We won't get
696 // consistent column spacing in these cases, unfortunately. Also note that we
697 // need to directly use m_opcode_name here (instead of opcode_name) so we
698 // don't include color codes as characters.
699 if (m_opcode_name.length() >= opcode_column_width) {
700 opcode_column_width = m_opcode_name.length() + 1;
701 }
702
703 ss.PutCString(cstr: opcode_name);
704 ss.FillLastLineToColumn(column: opcode_pos + opcode_column_width, fill_char: ' ');
705 ss.PutCString(cstr: mnemonics);
706
707 if (!m_comment.empty()) {
708 ss.FillLastLineToColumn(
709 column: opcode_pos + opcode_column_width + operand_column_width, fill_char: ' ');
710 ss.PutCString(cstr: " ; ");
711 ss.PutCString(cstr: m_comment);
712 }
713 s->PutCString(cstr: ss.GetString());
714}
715
716bool Instruction::DumpEmulation(const ArchSpec &arch) {
717 std::unique_ptr<EmulateInstruction> insn_emulator_up(
718 EmulateInstruction::FindPlugin(arch, supported_inst_type: eInstructionTypeAny, plugin_name: nullptr));
719 if (insn_emulator_up) {
720 insn_emulator_up->SetInstruction(insn_opcode: GetOpcode(), inst_addr: GetAddress(), target: nullptr);
721 return insn_emulator_up->EvaluateInstruction(evaluate_options: 0);
722 }
723
724 return false;
725}
726
727bool Instruction::CanSetBreakpoint () {
728 return !HasDelaySlot();
729}
730
731bool Instruction::HasDelaySlot() {
732 // Default is false.
733 return false;
734}
735
736OptionValueSP Instruction::ReadArray(FILE *in_file, Stream &out_stream,
737 OptionValue::Type data_type) {
738 bool done = false;
739 char buffer[1024];
740
741 auto option_value_sp = std::make_shared<OptionValueArray>(args: 1u << data_type);
742
743 int idx = 0;
744 while (!done) {
745 if (!fgets(s: buffer, n: 1023, stream: in_file)) {
746 out_stream.Printf(
747 format: "Instruction::ReadArray: Error reading file (fgets).\n");
748 option_value_sp.reset();
749 return option_value_sp;
750 }
751
752 std::string line(buffer);
753
754 size_t len = line.size();
755 if (line[len - 1] == '\n') {
756 line[len - 1] = '\0';
757 line.resize(n: len - 1);
758 }
759
760 if ((line.size() == 1) && line[0] == ']') {
761 done = true;
762 line.clear();
763 }
764
765 if (!line.empty()) {
766 std::string value;
767 static RegularExpression g_reg_exp(
768 llvm::StringRef("^[ \t]*([^ \t]+)[ \t]*$"));
769 llvm::SmallVector<llvm::StringRef, 2> matches;
770 if (g_reg_exp.Execute(string: line, matches: &matches))
771 value = matches[1].str();
772 else
773 value = line;
774
775 OptionValueSP data_value_sp;
776 switch (data_type) {
777 case OptionValue::eTypeUInt64:
778 data_value_sp = std::make_shared<OptionValueUInt64>(args: 0, args: 0);
779 data_value_sp->SetValueFromString(value);
780 break;
781 // Other types can be added later as needed.
782 default:
783 data_value_sp = std::make_shared<OptionValueString>(args: value.c_str(), args: "");
784 break;
785 }
786
787 option_value_sp->GetAsArray()->InsertValue(idx, value_sp: data_value_sp);
788 ++idx;
789 }
790 }
791
792 return option_value_sp;
793}
794
795OptionValueSP Instruction::ReadDictionary(FILE *in_file, Stream &out_stream) {
796 bool done = false;
797 char buffer[1024];
798
799 auto option_value_sp = std::make_shared<OptionValueDictionary>();
800 static constexpr llvm::StringLiteral encoding_key("data_encoding");
801 OptionValue::Type data_type = OptionValue::eTypeInvalid;
802
803 while (!done) {
804 // Read the next line in the file
805 if (!fgets(s: buffer, n: 1023, stream: in_file)) {
806 out_stream.Printf(
807 format: "Instruction::ReadDictionary: Error reading file (fgets).\n");
808 option_value_sp.reset();
809 return option_value_sp;
810 }
811
812 // Check to see if the line contains the end-of-dictionary marker ("}")
813 std::string line(buffer);
814
815 size_t len = line.size();
816 if (line[len - 1] == '\n') {
817 line[len - 1] = '\0';
818 line.resize(n: len - 1);
819 }
820
821 if ((line.size() == 1) && (line[0] == '}')) {
822 done = true;
823 line.clear();
824 }
825
826 // Try to find a key-value pair in the current line and add it to the
827 // dictionary.
828 if (!line.empty()) {
829 static RegularExpression g_reg_exp(llvm::StringRef(
830 "^[ \t]*([a-zA-Z_][a-zA-Z0-9_]*)[ \t]*=[ \t]*(.*)[ \t]*$"));
831
832 llvm::SmallVector<llvm::StringRef, 3> matches;
833
834 bool reg_exp_success = g_reg_exp.Execute(string: line, matches: &matches);
835 std::string key;
836 std::string value;
837 if (reg_exp_success) {
838 key = matches[1].str();
839 value = matches[2].str();
840 } else {
841 out_stream.Printf(format: "Instruction::ReadDictionary: Failure executing "
842 "regular expression.\n");
843 option_value_sp.reset();
844 return option_value_sp;
845 }
846
847 // Check value to see if it's the start of an array or dictionary.
848
849 lldb::OptionValueSP value_sp;
850 assert(value.empty() == false);
851 assert(key.empty() == false);
852
853 if (value[0] == '{') {
854 assert(value.size() == 1);
855 // value is a dictionary
856 value_sp = ReadDictionary(in_file, out_stream);
857 if (!value_sp) {
858 option_value_sp.reset();
859 return option_value_sp;
860 }
861 } else if (value[0] == '[') {
862 assert(value.size() == 1);
863 // value is an array
864 value_sp = ReadArray(in_file, out_stream, data_type);
865 if (!value_sp) {
866 option_value_sp.reset();
867 return option_value_sp;
868 }
869 // We've used the data_type to read an array; re-set the type to
870 // Invalid
871 data_type = OptionValue::eTypeInvalid;
872 } else if ((value[0] == '0') && (value[1] == 'x')) {
873 value_sp = std::make_shared<OptionValueUInt64>(args: 0, args: 0);
874 value_sp->SetValueFromString(value);
875 } else {
876 size_t len = value.size();
877 if ((value[0] == '"') && (value[len - 1] == '"'))
878 value = value.substr(pos: 1, n: len - 2);
879 value_sp = std::make_shared<OptionValueString>(args: value.c_str(), args: "");
880 }
881
882 if (key == encoding_key) {
883 // A 'data_encoding=..." is NOT a normal key-value pair; it is meta-data
884 // indicating the data type of an upcoming array (usually the next bit
885 // of data to be read in).
886 if (llvm::StringRef(value) == "uint32_t")
887 data_type = OptionValue::eTypeUInt64;
888 } else
889 option_value_sp->GetAsDictionary()->SetValueForKey(key, value_sp,
890 can_replace: false);
891 }
892 }
893
894 return option_value_sp;
895}
896
897bool Instruction::TestEmulation(Stream &out_stream, const char *file_name) {
898 if (!file_name) {
899 out_stream.Printf(format: "Instruction::TestEmulation: Missing file_name.");
900 return false;
901 }
902 FILE *test_file = FileSystem::Instance().Fopen(path: file_name, mode: "r");
903 if (!test_file) {
904 out_stream.Printf(
905 format: "Instruction::TestEmulation: Attempt to open test file failed.");
906 return false;
907 }
908
909 char buffer[256];
910 if (!fgets(s: buffer, n: 255, stream: test_file)) {
911 out_stream.Printf(
912 format: "Instruction::TestEmulation: Error reading first line of test file.\n");
913 fclose(stream: test_file);
914 return false;
915 }
916
917 if (strncmp(s1: buffer, s2: "InstructionEmulationState={", n: 27) != 0) {
918 out_stream.Printf(format: "Instructin::TestEmulation: Test file does not contain "
919 "emulation state dictionary\n");
920 fclose(stream: test_file);
921 return false;
922 }
923
924 // Read all the test information from the test file into an
925 // OptionValueDictionary.
926
927 OptionValueSP data_dictionary_sp(ReadDictionary(in_file: test_file, out_stream));
928 if (!data_dictionary_sp) {
929 out_stream.Printf(
930 format: "Instruction::TestEmulation: Error reading Dictionary Object.\n");
931 fclose(stream: test_file);
932 return false;
933 }
934
935 fclose(stream: test_file);
936
937 OptionValueDictionary *data_dictionary =
938 data_dictionary_sp->GetAsDictionary();
939 static constexpr llvm::StringLiteral description_key("assembly_string");
940 static constexpr llvm::StringLiteral triple_key("triple");
941
942 OptionValueSP value_sp = data_dictionary->GetValueForKey(key: description_key);
943
944 if (!value_sp) {
945 out_stream.Printf(format: "Instruction::TestEmulation: Test file does not "
946 "contain description string.\n");
947 return false;
948 }
949
950 SetDescription(value_sp->GetValueAs<llvm::StringRef>().value_or(u: ""));
951
952 value_sp = data_dictionary->GetValueForKey(key: triple_key);
953 if (!value_sp) {
954 out_stream.Printf(
955 format: "Instruction::TestEmulation: Test file does not contain triple.\n");
956 return false;
957 }
958
959 ArchSpec arch;
960 arch.SetTriple(
961 llvm::Triple(value_sp->GetValueAs<llvm::StringRef>().value_or(u: "")));
962
963 bool success = false;
964 std::unique_ptr<EmulateInstruction> insn_emulator_up(
965 EmulateInstruction::FindPlugin(arch, supported_inst_type: eInstructionTypeAny, plugin_name: nullptr));
966 if (insn_emulator_up)
967 success =
968 insn_emulator_up->TestEmulation(out_stream, arch, test_data: data_dictionary);
969
970 if (success)
971 out_stream.Printf(format: "Emulation test succeeded.");
972 else
973 out_stream.Printf(format: "Emulation test failed.");
974
975 return success;
976}
977
978bool Instruction::Emulate(
979 const ArchSpec &arch, uint32_t evaluate_options, void *baton,
980 EmulateInstruction::ReadMemoryCallback read_mem_callback,
981 EmulateInstruction::WriteMemoryCallback write_mem_callback,
982 EmulateInstruction::ReadRegisterCallback read_reg_callback,
983 EmulateInstruction::WriteRegisterCallback write_reg_callback) {
984 std::unique_ptr<EmulateInstruction> insn_emulator_up(
985 EmulateInstruction::FindPlugin(arch, supported_inst_type: eInstructionTypeAny, plugin_name: nullptr));
986 if (insn_emulator_up) {
987 insn_emulator_up->SetBaton(baton);
988 insn_emulator_up->SetCallbacks(read_mem_callback, write_mem_callback,
989 read_reg_callback, write_reg_callback);
990 insn_emulator_up->SetInstruction(insn_opcode: GetOpcode(), inst_addr: GetAddress(), target: nullptr);
991 return insn_emulator_up->EvaluateInstruction(evaluate_options);
992 }
993
994 return false;
995}
996
997uint32_t Instruction::GetData(DataExtractor &data) {
998 return m_opcode.GetData(data);
999}
1000
1001InstructionList::InstructionList() : m_instructions() {}
1002
1003InstructionList::~InstructionList() = default;
1004
1005size_t InstructionList::GetSize() const { return m_instructions.size(); }
1006
1007uint32_t InstructionList::GetMaxOpcocdeByteSize() const {
1008 uint32_t max_inst_size = 0;
1009 collection::const_iterator pos, end;
1010 for (pos = m_instructions.begin(), end = m_instructions.end(); pos != end;
1011 ++pos) {
1012 uint32_t inst_size = (*pos)->GetOpcode().GetByteSize();
1013 if (max_inst_size < inst_size)
1014 max_inst_size = inst_size;
1015 }
1016 return max_inst_size;
1017}
1018
1019InstructionSP InstructionList::GetInstructionAtIndex(size_t idx) const {
1020 InstructionSP inst_sp;
1021 if (idx < m_instructions.size())
1022 inst_sp = m_instructions[idx];
1023 return inst_sp;
1024}
1025
1026InstructionSP InstructionList::GetInstructionAtAddress(const Address &address) {
1027 uint32_t index = GetIndexOfInstructionAtAddress(addr: address);
1028 if (index != UINT32_MAX)
1029 return GetInstructionAtIndex(idx: index);
1030 return nullptr;
1031}
1032
1033void InstructionList::Dump(Stream *s, bool show_address, bool show_bytes,
1034 bool show_control_flow_kind,
1035 const ExecutionContext *exe_ctx) {
1036 const uint32_t max_opcode_byte_size = GetMaxOpcocdeByteSize();
1037 collection::const_iterator pos, begin, end;
1038
1039 const FormatEntity::Entry *disassembly_format = nullptr;
1040 FormatEntity::Entry format;
1041 if (exe_ctx && exe_ctx->HasTargetScope()) {
1042 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1043 disassembly_format = &format;
1044 } else {
1045 FormatEntity::Parse(format: "${addr}: ", entry&: format);
1046 disassembly_format = &format;
1047 }
1048
1049 for (begin = m_instructions.begin(), end = m_instructions.end(), pos = begin;
1050 pos != end; ++pos) {
1051 if (pos != begin)
1052 s->EOL();
1053 (*pos)->Dump(s, max_opcode_byte_size, show_address, show_bytes,
1054 show_control_flow_kind, exe_ctx, sym_ctx: nullptr, prev_sym_ctx: nullptr,
1055 disassembly_addr_format: disassembly_format, max_address_text_size: 0);
1056 }
1057}
1058
1059void InstructionList::Clear() { m_instructions.clear(); }
1060
1061void InstructionList::Append(lldb::InstructionSP &inst_sp) {
1062 if (inst_sp)
1063 m_instructions.push_back(x: inst_sp);
1064}
1065
1066uint32_t
1067InstructionList::GetIndexOfNextBranchInstruction(uint32_t start,
1068 bool ignore_calls,
1069 bool *found_calls) const {
1070 size_t num_instructions = m_instructions.size();
1071
1072 uint32_t next_branch = UINT32_MAX;
1073
1074 if (found_calls)
1075 *found_calls = false;
1076 for (size_t i = start; i < num_instructions; i++) {
1077 if (m_instructions[i]->DoesBranch()) {
1078 if (ignore_calls && m_instructions[i]->IsCall()) {
1079 if (found_calls)
1080 *found_calls = true;
1081 continue;
1082 }
1083 next_branch = i;
1084 break;
1085 }
1086 }
1087
1088 return next_branch;
1089}
1090
1091uint32_t
1092InstructionList::GetIndexOfInstructionAtAddress(const Address &address) {
1093 size_t num_instructions = m_instructions.size();
1094 uint32_t index = UINT32_MAX;
1095 for (size_t i = 0; i < num_instructions; i++) {
1096 if (m_instructions[i]->GetAddress() == address) {
1097 index = i;
1098 break;
1099 }
1100 }
1101 return index;
1102}
1103
1104uint32_t
1105InstructionList::GetIndexOfInstructionAtLoadAddress(lldb::addr_t load_addr,
1106 Target &target) {
1107 Address address;
1108 address.SetLoadAddress(load_addr, target: &target);
1109 return GetIndexOfInstructionAtAddress(address);
1110}
1111
1112size_t Disassembler::AppendInstructions(Target &target, Address start,
1113 Limit limit, Stream *error_strm_ptr,
1114 bool force_live_memory) {
1115 if (!start.IsValid())
1116 return 0;
1117
1118 start = ResolveAddress(target, addr: start);
1119
1120 addr_t byte_size = limit.value;
1121 if (limit.kind == Limit::Instructions)
1122 byte_size *= m_arch.GetMaximumOpcodeByteSize();
1123 auto data_sp = std::make_shared<DataBufferHeap>(args&: byte_size, args: '\0');
1124
1125 Status error;
1126 lldb::addr_t load_addr = LLDB_INVALID_ADDRESS;
1127 const size_t bytes_read =
1128 target.ReadMemory(addr: start, dst: data_sp->GetBytes(), dst_len: data_sp->GetByteSize(),
1129 error, force_live_memory, load_addr_ptr: &load_addr);
1130 const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS;
1131
1132 if (bytes_read == 0) {
1133 if (error_strm_ptr) {
1134 if (const char *error_cstr = error.AsCString())
1135 error_strm_ptr->Printf(format: "error: %s\n", error_cstr);
1136 }
1137 return 0;
1138 }
1139
1140 if (bytes_read != data_sp->GetByteSize())
1141 data_sp->SetByteSize(bytes_read);
1142 DataExtractor data(data_sp, m_arch.GetByteOrder(),
1143 m_arch.GetAddressByteSize());
1144 return DecodeInstructions(base_addr: start, data, data_offset: 0,
1145 num_instructions: limit.kind == Limit::Instructions ? limit.value
1146 : UINT32_MAX,
1147 /*append=*/true, data_from_file);
1148}
1149
1150// Disassembler copy constructor
1151Disassembler::Disassembler(const ArchSpec &arch, const char *flavor)
1152 : m_arch(arch), m_instruction_list(), m_flavor() {
1153 if (flavor == nullptr)
1154 m_flavor.assign(s: "default");
1155 else
1156 m_flavor.assign(s: flavor);
1157
1158 // If this is an arm variant that can only include thumb (T16, T32)
1159 // instructions, force the arch triple to be "thumbv.." instead of "armv..."
1160 if (arch.IsAlwaysThumbInstructions()) {
1161 std::string thumb_arch_name(arch.GetTriple().getArchName().str());
1162 // Replace "arm" with "thumb" so we get all thumb variants correct
1163 if (thumb_arch_name.size() > 3) {
1164 thumb_arch_name.erase(pos: 0, n: 3);
1165 thumb_arch_name.insert(pos: 0, s: "thumb");
1166 }
1167 m_arch.SetTriple(thumb_arch_name.c_str());
1168 }
1169}
1170
1171Disassembler::~Disassembler() = default;
1172
1173InstructionList &Disassembler::GetInstructionList() {
1174 return m_instruction_list;
1175}
1176
1177const InstructionList &Disassembler::GetInstructionList() const {
1178 return m_instruction_list;
1179}
1180
1181// Class PseudoInstruction
1182
1183PseudoInstruction::PseudoInstruction()
1184 : Instruction(Address(), AddressClass::eUnknown), m_description() {}
1185
1186PseudoInstruction::~PseudoInstruction() = default;
1187
1188bool PseudoInstruction::DoesBranch() {
1189 // This is NOT a valid question for a pseudo instruction.
1190 return false;
1191}
1192
1193bool PseudoInstruction::HasDelaySlot() {
1194 // This is NOT a valid question for a pseudo instruction.
1195 return false;
1196}
1197
1198bool PseudoInstruction::IsLoad() { return false; }
1199
1200bool PseudoInstruction::IsAuthenticated() { return false; }
1201
1202size_t PseudoInstruction::Decode(const lldb_private::Disassembler &disassembler,
1203 const lldb_private::DataExtractor &data,
1204 lldb::offset_t data_offset) {
1205 return m_opcode.GetByteSize();
1206}
1207
1208void PseudoInstruction::SetOpcode(size_t opcode_size, void *opcode_data) {
1209 if (!opcode_data)
1210 return;
1211
1212 switch (opcode_size) {
1213 case 8: {
1214 uint8_t value8 = *((uint8_t *)opcode_data);
1215 m_opcode.SetOpcode8(inst: value8, order: eByteOrderInvalid);
1216 break;
1217 }
1218 case 16: {
1219 uint16_t value16 = *((uint16_t *)opcode_data);
1220 m_opcode.SetOpcode16(inst: value16, order: eByteOrderInvalid);
1221 break;
1222 }
1223 case 32: {
1224 uint32_t value32 = *((uint32_t *)opcode_data);
1225 m_opcode.SetOpcode32(inst: value32, order: eByteOrderInvalid);
1226 break;
1227 }
1228 case 64: {
1229 uint64_t value64 = *((uint64_t *)opcode_data);
1230 m_opcode.SetOpcode64(inst: value64, order: eByteOrderInvalid);
1231 break;
1232 }
1233 default:
1234 break;
1235 }
1236}
1237
1238void PseudoInstruction::SetDescription(llvm::StringRef description) {
1239 m_description = std::string(description);
1240}
1241
1242Instruction::Operand Instruction::Operand::BuildRegister(ConstString &r) {
1243 Operand ret;
1244 ret.m_type = Type::Register;
1245 ret.m_register = r;
1246 return ret;
1247}
1248
1249Instruction::Operand Instruction::Operand::BuildImmediate(lldb::addr_t imm,
1250 bool neg) {
1251 Operand ret;
1252 ret.m_type = Type::Immediate;
1253 ret.m_immediate = imm;
1254 ret.m_negative = neg;
1255 return ret;
1256}
1257
1258Instruction::Operand Instruction::Operand::BuildImmediate(int64_t imm) {
1259 Operand ret;
1260 ret.m_type = Type::Immediate;
1261 if (imm < 0) {
1262 ret.m_immediate = -imm;
1263 ret.m_negative = true;
1264 } else {
1265 ret.m_immediate = imm;
1266 ret.m_negative = false;
1267 }
1268 return ret;
1269}
1270
1271Instruction::Operand
1272Instruction::Operand::BuildDereference(const Operand &ref) {
1273 Operand ret;
1274 ret.m_type = Type::Dereference;
1275 ret.m_children = {ref};
1276 return ret;
1277}
1278
1279Instruction::Operand Instruction::Operand::BuildSum(const Operand &lhs,
1280 const Operand &rhs) {
1281 Operand ret;
1282 ret.m_type = Type::Sum;
1283 ret.m_children = {lhs, rhs};
1284 return ret;
1285}
1286
1287Instruction::Operand Instruction::Operand::BuildProduct(const Operand &lhs,
1288 const Operand &rhs) {
1289 Operand ret;
1290 ret.m_type = Type::Product;
1291 ret.m_children = {lhs, rhs};
1292 return ret;
1293}
1294
1295std::function<bool(const Instruction::Operand &)>
1296lldb_private::OperandMatchers::MatchBinaryOp(
1297 std::function<bool(const Instruction::Operand &)> base,
1298 std::function<bool(const Instruction::Operand &)> left,
1299 std::function<bool(const Instruction::Operand &)> right) {
1300 return [base, left, right](const Instruction::Operand &op) -> bool {
1301 return (base(op) && op.m_children.size() == 2 &&
1302 ((left(op.m_children[0]) && right(op.m_children[1])) ||
1303 (left(op.m_children[1]) && right(op.m_children[0]))));
1304 };
1305}
1306
1307std::function<bool(const Instruction::Operand &)>
1308lldb_private::OperandMatchers::MatchUnaryOp(
1309 std::function<bool(const Instruction::Operand &)> base,
1310 std::function<bool(const Instruction::Operand &)> child) {
1311 return [base, child](const Instruction::Operand &op) -> bool {
1312 return (base(op) && op.m_children.size() == 1 && child(op.m_children[0]));
1313 };
1314}
1315
1316std::function<bool(const Instruction::Operand &)>
1317lldb_private::OperandMatchers::MatchRegOp(const RegisterInfo &info) {
1318 return [&info](const Instruction::Operand &op) {
1319 return (op.m_type == Instruction::Operand::Type::Register &&
1320 (op.m_register == ConstString(info.name) ||
1321 op.m_register == ConstString(info.alt_name)));
1322 };
1323}
1324
1325std::function<bool(const Instruction::Operand &)>
1326lldb_private::OperandMatchers::FetchRegOp(ConstString &reg) {
1327 return [&reg](const Instruction::Operand &op) {
1328 if (op.m_type != Instruction::Operand::Type::Register) {
1329 return false;
1330 }
1331 reg = op.m_register;
1332 return true;
1333 };
1334}
1335
1336std::function<bool(const Instruction::Operand &)>
1337lldb_private::OperandMatchers::MatchImmOp(int64_t imm) {
1338 return [imm](const Instruction::Operand &op) {
1339 return (op.m_type == Instruction::Operand::Type::Immediate &&
1340 ((op.m_negative && op.m_immediate == (uint64_t)-imm) ||
1341 (!op.m_negative && op.m_immediate == (uint64_t)imm)));
1342 };
1343}
1344
1345std::function<bool(const Instruction::Operand &)>
1346lldb_private::OperandMatchers::FetchImmOp(int64_t &imm) {
1347 return [&imm](const Instruction::Operand &op) {
1348 if (op.m_type != Instruction::Operand::Type::Immediate) {
1349 return false;
1350 }
1351 if (op.m_negative) {
1352 imm = -((int64_t)op.m_immediate);
1353 } else {
1354 imm = ((int64_t)op.m_immediate);
1355 }
1356 return true;
1357 };
1358}
1359
1360std::function<bool(const Instruction::Operand &)>
1361lldb_private::OperandMatchers::MatchOpType(Instruction::Operand::Type type) {
1362 return [type](const Instruction::Operand &op) { return op.m_type == type; };
1363}
1364

source code of lldb/source/Core/Disassembler.cpp