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