xref: /llvm-project/lldb/source/Core/Disassembler.cpp (revision eb96c8c105226956c8ed5ab30699206f53de74f7)
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, 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(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 
86 DisassemblerSP 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 
105 static 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(addr.GetOffset(), resolved_addr)
113             : target.GetImages().ResolveFileAddress(addr.GetOffset(),
114                                                     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 
123 lldb::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, range.GetBaseAddress(), {Limit::Bytes, range.GetByteSize()},
137         nullptr, force_live_memory);
138   }
139   if (bytes_disassembled == 0)
140     return {};
141 
142   return disasm_sp;
143 }
144 
145 lldb::DisassemblerSP
146 Disassembler::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(start, data, 0, num_instructions, false,
164                                       data_from_file);
165   return disasm_sp;
166 }
167 
168 bool 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       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       exe_ctx.GetTargetRef(), address, limit, &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 
196 Disassembler::SourceLine
197 Disassembler::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(func_decl_file_sp, func_decl_line);
208 
209   if (!func_decl_file_sp)
210     return {};
211   if (!func_decl_file_sp->Equal(*prologue_end_line.file_sp,
212                                 SupportFile::eEqualFileSpecAndChecksumIfSet) &&
213       !func_decl_file_sp->Equal(*prologue_end_line.original_file_sp,
214                                 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 
226 void 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(line.file);
231     if (source_lines_seen_pos == source_lines_seen.end()) {
232       std::set<uint32_t> lines;
233       lines.insert(line.line);
234       source_lines_seen.emplace(line.file, lines);
235     } else {
236       source_lines_seen_pos->second.insert(line.line);
237     }
238   }
239 }
240 
241 bool 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, "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(Mangled::ePreferDemangledWithoutArguments)
273             .GetCString();
274     if (function_name && avoid_regex->Execute(function_name)) {
275       // skip this source line
276       return true;
277     }
278   }
279   // don't skip this source line
280   return false;
281 }
282 
283 void 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     disassembly_format =
314         exe_ctx.GetTargetRef().GetDebugger().GetDisassemblyFormat();
315   } else {
316     FormatEntity::Parse("${addr}: ", 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(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(addr, resolve_mask, sc);
343         if (resolved_mask) {
344           StreamString strmstr;
345           Debugger::FormatDisassemblerAddress(disassembly_format, &sc, nullptr,
346                                               &exe_ctx, &addr, 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, decl_line))
362                 AddLineToSourceLineTables(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, this_line))
370                 AddLineToSourceLineTables(this_line, source_lines_seen);
371             }
372           }
373         }
374         sc.Clear(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(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             addr, 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                                                         prologue_end_line)) {
414                   SupportFileSP func_decl_file_sp;
415                   uint32_t func_decl_line;
416                   sc.function->GetStartLineSourceInfo(func_decl_file_sp,
417                                                       func_decl_line);
418                   if (func_decl_file_sp &&
419                       (func_decl_file_sp->Equal(
420                            *prologue_end_line.file_sp,
421                            SupportFile::eEqualFileSpecAndChecksumIfSet) ||
422                        func_decl_file_sp->Equal(
423                            *prologue_end_line.original_file_sp,
424                            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(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, 0, use_inline_block_range,
444                                  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(addr)) {
450               sc.GetAddressRange(scope, 0, use_inline_block_range,
451                                  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                                                         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(this_line.file);
475                       if (pos != source_lines_seen.end()) {
476                         if (pos->second.count(line) == 1) {
477                           previous_lines.clear();
478                         } else {
479                           previous_lines.push_back(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(previous_line.file);
488                       if (pos != source_lines_seen.end()) {
489                         pos->second.insert(previous_line.line);
490                       }
491                       source_lines_to_display.lines.push_back(previous_line);
492                     }
493 
494                     source_lines_to_display.lines.push_back(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(next_line.file);
503                       if (pos != source_lines_seen.end()) {
504                         if (pos->second.count(next_line.line) == 1)
505                           break;
506                         pos->second.insert(next_line.line);
507                       }
508                       source_lines_to_display.lines.push_back(next_line);
509                     }
510                   }
511                   previous_line = this_line;
512                 }
513               }
514             }
515           }
516         } else {
517           sc.Clear(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               std::make_shared<SupportFile>(ln.file), ln.line, ln.column, 0, 0,
534               line_highlight, &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(&strm, max_opcode_byte_size, true, show_bytes,
544                  show_control_flow_kind, &exe_ctx, &sc, &prev_sc, nullptr,
545                  address_text_size);
546       strm.EOL();
547     } else {
548       break;
549     }
550   }
551 }
552 
553 bool Disassembler::Disassemble(Debugger &debugger, const ArchSpec &arch,
554                                StackFrame &frame, Stream &strm) {
555   AddressRange range;
556   SymbolContext sc(
557       frame.GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol));
558   if (sc.function) {
559     range = sc.function->GetAddressRange();
560   } else if (sc.symbol && sc.symbol->ValueIsAddress()) {
561     range.GetBaseAddress() = sc.symbol->GetAddressRef();
562     range.SetByteSize(sc.symbol->GetByteSize());
563   } else {
564     range.GetBaseAddress() = frame.GetFrameCodeAddress();
565   }
566 
567     if (range.GetBaseAddress().IsValid() && range.GetByteSize() == 0)
568       range.SetByteSize(DEFAULT_DISASM_BYTE_SIZE);
569 
570     Disassembler::Limit limit = {Disassembler::Limit::Bytes,
571                                  range.GetByteSize()};
572     if (limit.value == 0)
573       limit.value = DEFAULT_DISASM_BYTE_SIZE;
574 
575     return Disassemble(debugger, arch, nullptr, nullptr, nullptr, nullptr,
576                        frame, range.GetBaseAddress(), limit, false, 0, 0, strm);
577 }
578 
579 Instruction::Instruction(const Address &address, AddressClass addr_class)
580     : m_address(address), m_address_class(addr_class), m_opcode(),
581       m_calculated_strings(false) {}
582 
583 Instruction::~Instruction() = default;
584 
585 AddressClass Instruction::GetAddressClass() {
586   if (m_address_class == AddressClass::eInvalid)
587     m_address_class = m_address.GetAddressClass();
588   return m_address_class;
589 }
590 
591 const char *Instruction::GetNameForInstructionControlFlowKind(
592     lldb::InstructionControlFlowKind instruction_control_flow_kind) {
593   switch (instruction_control_flow_kind) {
594   case eInstructionControlFlowKindUnknown:
595     return "unknown";
596   case eInstructionControlFlowKindOther:
597     return "other";
598   case eInstructionControlFlowKindCall:
599     return "call";
600   case eInstructionControlFlowKindReturn:
601     return "return";
602   case eInstructionControlFlowKindJump:
603     return "jump";
604   case eInstructionControlFlowKindCondJump:
605     return "cond jump";
606   case eInstructionControlFlowKindFarCall:
607     return "far call";
608   case eInstructionControlFlowKindFarReturn:
609     return "far return";
610   case eInstructionControlFlowKindFarJump:
611     return "far jump";
612   }
613   llvm_unreachable("Fully covered switch above!");
614 }
615 
616 void Instruction::Dump(lldb_private::Stream *s, uint32_t max_opcode_byte_size,
617                        bool show_address, bool show_bytes,
618                        bool show_control_flow_kind,
619                        const ExecutionContext *exe_ctx,
620                        const SymbolContext *sym_ctx,
621                        const SymbolContext *prev_sym_ctx,
622                        const FormatEntity::Entry *disassembly_addr_format,
623                        size_t max_address_text_size) {
624   size_t opcode_column_width = 7;
625   const size_t operand_column_width = 25;
626 
627   CalculateMnemonicOperandsAndCommentIfNeeded(exe_ctx);
628 
629   StreamString ss;
630 
631   if (show_address) {
632     Debugger::FormatDisassemblerAddress(disassembly_addr_format, sym_ctx,
633                                         prev_sym_ctx, exe_ctx, &m_address, ss);
634     ss.FillLastLineToColumn(max_address_text_size, ' ');
635   }
636 
637   if (show_bytes) {
638     if (m_opcode.GetType() == Opcode::eTypeBytes) {
639       // x86_64 and i386 are the only ones that use bytes right now so pad out
640       // the byte dump to be able to always show 15 bytes (3 chars each) plus a
641       // space
642       if (max_opcode_byte_size > 0)
643         m_opcode.Dump(&ss, max_opcode_byte_size * 3 + 1);
644       else
645         m_opcode.Dump(&ss, 15 * 3 + 1);
646     } else {
647       // Else, we have ARM or MIPS which can show up to a uint32_t 0x00000000
648       // (10 spaces) plus two for padding...
649       if (max_opcode_byte_size > 0)
650         m_opcode.Dump(&ss, max_opcode_byte_size * 3 + 1);
651       else
652         m_opcode.Dump(&ss, 12);
653     }
654   }
655 
656   if (show_control_flow_kind) {
657     lldb::InstructionControlFlowKind instruction_control_flow_kind =
658         GetControlFlowKind(exe_ctx);
659     ss.Printf("%-12s", GetNameForInstructionControlFlowKind(
660                            instruction_control_flow_kind));
661   }
662 
663   bool show_color = false;
664   if (exe_ctx) {
665     if (TargetSP target_sp = exe_ctx->GetTargetSP()) {
666       show_color = target_sp->GetDebugger().GetUseColor();
667     }
668   }
669   const size_t opcode_pos = ss.GetSizeOfLastLine();
670   const std::string &opcode_name =
671       show_color ? m_markup_opcode_name : m_opcode_name;
672   const std::string &mnemonics = show_color ? m_markup_mnemonics : m_mnemonics;
673 
674   // The default opcode size of 7 characters is plenty for most architectures
675   // but some like arm can pull out the occasional vqrshrun.s16.  We won't get
676   // consistent column spacing in these cases, unfortunately. Also note that we
677   // need to directly use m_opcode_name here (instead of opcode_name) so we
678   // don't include color codes as characters.
679   if (m_opcode_name.length() >= opcode_column_width) {
680     opcode_column_width = m_opcode_name.length() + 1;
681   }
682 
683   ss.PutCString(opcode_name);
684   ss.FillLastLineToColumn(opcode_pos + opcode_column_width, ' ');
685   ss.PutCString(mnemonics);
686 
687   if (!m_comment.empty()) {
688     ss.FillLastLineToColumn(
689         opcode_pos + opcode_column_width + operand_column_width, ' ');
690     ss.PutCString(" ; ");
691     ss.PutCString(m_comment);
692   }
693   s->PutCString(ss.GetString());
694 }
695 
696 bool Instruction::DumpEmulation(const ArchSpec &arch) {
697   std::unique_ptr<EmulateInstruction> insn_emulator_up(
698       EmulateInstruction::FindPlugin(arch, eInstructionTypeAny, nullptr));
699   if (insn_emulator_up) {
700     insn_emulator_up->SetInstruction(GetOpcode(), GetAddress(), nullptr);
701     return insn_emulator_up->EvaluateInstruction(0);
702   }
703 
704   return false;
705 }
706 
707 bool Instruction::CanSetBreakpoint () {
708   return !HasDelaySlot();
709 }
710 
711 bool Instruction::HasDelaySlot() {
712   // Default is false.
713   return false;
714 }
715 
716 OptionValueSP Instruction::ReadArray(FILE *in_file, Stream &out_stream,
717                                      OptionValue::Type data_type) {
718   bool done = false;
719   char buffer[1024];
720 
721   auto option_value_sp = std::make_shared<OptionValueArray>(1u << data_type);
722 
723   int idx = 0;
724   while (!done) {
725     if (!fgets(buffer, 1023, in_file)) {
726       out_stream.Printf(
727           "Instruction::ReadArray:  Error reading file (fgets).\n");
728       option_value_sp.reset();
729       return option_value_sp;
730     }
731 
732     std::string line(buffer);
733 
734     size_t len = line.size();
735     if (line[len - 1] == '\n') {
736       line[len - 1] = '\0';
737       line.resize(len - 1);
738     }
739 
740     if ((line.size() == 1) && line[0] == ']') {
741       done = true;
742       line.clear();
743     }
744 
745     if (!line.empty()) {
746       std::string value;
747       static RegularExpression g_reg_exp(
748           llvm::StringRef("^[ \t]*([^ \t]+)[ \t]*$"));
749       llvm::SmallVector<llvm::StringRef, 2> matches;
750       if (g_reg_exp.Execute(line, &matches))
751         value = matches[1].str();
752       else
753         value = line;
754 
755       OptionValueSP data_value_sp;
756       switch (data_type) {
757       case OptionValue::eTypeUInt64:
758         data_value_sp = std::make_shared<OptionValueUInt64>(0, 0);
759         data_value_sp->SetValueFromString(value);
760         break;
761       // Other types can be added later as needed.
762       default:
763         data_value_sp = std::make_shared<OptionValueString>(value.c_str(), "");
764         break;
765       }
766 
767       option_value_sp->GetAsArray()->InsertValue(idx, data_value_sp);
768       ++idx;
769     }
770   }
771 
772   return option_value_sp;
773 }
774 
775 OptionValueSP Instruction::ReadDictionary(FILE *in_file, Stream &out_stream) {
776   bool done = false;
777   char buffer[1024];
778 
779   auto option_value_sp = std::make_shared<OptionValueDictionary>();
780   static constexpr llvm::StringLiteral encoding_key("data_encoding");
781   OptionValue::Type data_type = OptionValue::eTypeInvalid;
782 
783   while (!done) {
784     // Read the next line in the file
785     if (!fgets(buffer, 1023, in_file)) {
786       out_stream.Printf(
787           "Instruction::ReadDictionary: Error reading file (fgets).\n");
788       option_value_sp.reset();
789       return option_value_sp;
790     }
791 
792     // Check to see if the line contains the end-of-dictionary marker ("}")
793     std::string line(buffer);
794 
795     size_t len = line.size();
796     if (line[len - 1] == '\n') {
797       line[len - 1] = '\0';
798       line.resize(len - 1);
799     }
800 
801     if ((line.size() == 1) && (line[0] == '}')) {
802       done = true;
803       line.clear();
804     }
805 
806     // Try to find a key-value pair in the current line and add it to the
807     // dictionary.
808     if (!line.empty()) {
809       static RegularExpression g_reg_exp(llvm::StringRef(
810           "^[ \t]*([a-zA-Z_][a-zA-Z0-9_]*)[ \t]*=[ \t]*(.*)[ \t]*$"));
811 
812       llvm::SmallVector<llvm::StringRef, 3> matches;
813 
814       bool reg_exp_success = g_reg_exp.Execute(line, &matches);
815       std::string key;
816       std::string value;
817       if (reg_exp_success) {
818         key = matches[1].str();
819         value = matches[2].str();
820       } else {
821         out_stream.Printf("Instruction::ReadDictionary: Failure executing "
822                           "regular expression.\n");
823         option_value_sp.reset();
824         return option_value_sp;
825       }
826 
827       // Check value to see if it's the start of an array or dictionary.
828 
829       lldb::OptionValueSP value_sp;
830       assert(value.empty() == false);
831       assert(key.empty() == false);
832 
833       if (value[0] == '{') {
834         assert(value.size() == 1);
835         // value is a dictionary
836         value_sp = ReadDictionary(in_file, out_stream);
837         if (!value_sp) {
838           option_value_sp.reset();
839           return option_value_sp;
840         }
841       } else if (value[0] == '[') {
842         assert(value.size() == 1);
843         // value is an array
844         value_sp = ReadArray(in_file, out_stream, data_type);
845         if (!value_sp) {
846           option_value_sp.reset();
847           return option_value_sp;
848         }
849         // We've used the data_type to read an array; re-set the type to
850         // Invalid
851         data_type = OptionValue::eTypeInvalid;
852       } else if ((value[0] == '0') && (value[1] == 'x')) {
853         value_sp = std::make_shared<OptionValueUInt64>(0, 0);
854         value_sp->SetValueFromString(value);
855       } else {
856         size_t len = value.size();
857         if ((value[0] == '"') && (value[len - 1] == '"'))
858           value = value.substr(1, len - 2);
859         value_sp = std::make_shared<OptionValueString>(value.c_str(), "");
860       }
861 
862       if (key == encoding_key) {
863         // A 'data_encoding=..." is NOT a normal key-value pair; it is meta-data
864         // indicating the data type of an upcoming array (usually the next bit
865         // of data to be read in).
866         if (llvm::StringRef(value) == "uint32_t")
867           data_type = OptionValue::eTypeUInt64;
868       } else
869         option_value_sp->GetAsDictionary()->SetValueForKey(key, value_sp,
870                                                            false);
871     }
872   }
873 
874   return option_value_sp;
875 }
876 
877 bool Instruction::TestEmulation(Stream &out_stream, const char *file_name) {
878   if (!file_name) {
879     out_stream.Printf("Instruction::TestEmulation:  Missing file_name.");
880     return false;
881   }
882   FILE *test_file = FileSystem::Instance().Fopen(file_name, "r");
883   if (!test_file) {
884     out_stream.Printf(
885         "Instruction::TestEmulation: Attempt to open test file failed.");
886     return false;
887   }
888 
889   char buffer[256];
890   if (!fgets(buffer, 255, test_file)) {
891     out_stream.Printf(
892         "Instruction::TestEmulation: Error reading first line of test file.\n");
893     fclose(test_file);
894     return false;
895   }
896 
897   if (strncmp(buffer, "InstructionEmulationState={", 27) != 0) {
898     out_stream.Printf("Instructin::TestEmulation: Test file does not contain "
899                       "emulation state dictionary\n");
900     fclose(test_file);
901     return false;
902   }
903 
904   // Read all the test information from the test file into an
905   // OptionValueDictionary.
906 
907   OptionValueSP data_dictionary_sp(ReadDictionary(test_file, out_stream));
908   if (!data_dictionary_sp) {
909     out_stream.Printf(
910         "Instruction::TestEmulation:  Error reading Dictionary Object.\n");
911     fclose(test_file);
912     return false;
913   }
914 
915   fclose(test_file);
916 
917   OptionValueDictionary *data_dictionary =
918       data_dictionary_sp->GetAsDictionary();
919   static constexpr llvm::StringLiteral description_key("assembly_string");
920   static constexpr llvm::StringLiteral triple_key("triple");
921 
922   OptionValueSP value_sp = data_dictionary->GetValueForKey(description_key);
923 
924   if (!value_sp) {
925     out_stream.Printf("Instruction::TestEmulation:  Test file does not "
926                       "contain description string.\n");
927     return false;
928   }
929 
930   SetDescription(value_sp->GetValueAs<llvm::StringRef>().value_or(""));
931 
932   value_sp = data_dictionary->GetValueForKey(triple_key);
933   if (!value_sp) {
934     out_stream.Printf(
935         "Instruction::TestEmulation: Test file does not contain triple.\n");
936     return false;
937   }
938 
939   ArchSpec arch;
940   arch.SetTriple(
941       llvm::Triple(value_sp->GetValueAs<llvm::StringRef>().value_or("")));
942 
943   bool success = false;
944   std::unique_ptr<EmulateInstruction> insn_emulator_up(
945       EmulateInstruction::FindPlugin(arch, eInstructionTypeAny, nullptr));
946   if (insn_emulator_up)
947     success =
948         insn_emulator_up->TestEmulation(out_stream, arch, data_dictionary);
949 
950   if (success)
951     out_stream.Printf("Emulation test succeeded.");
952   else
953     out_stream.Printf("Emulation test failed.");
954 
955   return success;
956 }
957 
958 bool Instruction::Emulate(
959     const ArchSpec &arch, uint32_t evaluate_options, void *baton,
960     EmulateInstruction::ReadMemoryCallback read_mem_callback,
961     EmulateInstruction::WriteMemoryCallback write_mem_callback,
962     EmulateInstruction::ReadRegisterCallback read_reg_callback,
963     EmulateInstruction::WriteRegisterCallback write_reg_callback) {
964   std::unique_ptr<EmulateInstruction> insn_emulator_up(
965       EmulateInstruction::FindPlugin(arch, eInstructionTypeAny, nullptr));
966   if (insn_emulator_up) {
967     insn_emulator_up->SetBaton(baton);
968     insn_emulator_up->SetCallbacks(read_mem_callback, write_mem_callback,
969                                    read_reg_callback, write_reg_callback);
970     insn_emulator_up->SetInstruction(GetOpcode(), GetAddress(), nullptr);
971     return insn_emulator_up->EvaluateInstruction(evaluate_options);
972   }
973 
974   return false;
975 }
976 
977 uint32_t Instruction::GetData(DataExtractor &data) {
978   return m_opcode.GetData(data);
979 }
980 
981 InstructionList::InstructionList() : m_instructions() {}
982 
983 InstructionList::~InstructionList() = default;
984 
985 size_t InstructionList::GetSize() const { return m_instructions.size(); }
986 
987 uint32_t InstructionList::GetMaxOpcocdeByteSize() const {
988   uint32_t max_inst_size = 0;
989   collection::const_iterator pos, end;
990   for (pos = m_instructions.begin(), end = m_instructions.end(); pos != end;
991        ++pos) {
992     uint32_t inst_size = (*pos)->GetOpcode().GetByteSize();
993     if (max_inst_size < inst_size)
994       max_inst_size = inst_size;
995   }
996   return max_inst_size;
997 }
998 
999 InstructionSP InstructionList::GetInstructionAtIndex(size_t idx) const {
1000   InstructionSP inst_sp;
1001   if (idx < m_instructions.size())
1002     inst_sp = m_instructions[idx];
1003   return inst_sp;
1004 }
1005 
1006 InstructionSP InstructionList::GetInstructionAtAddress(const Address &address) {
1007   uint32_t index = GetIndexOfInstructionAtAddress(address);
1008   if (index != UINT32_MAX)
1009     return GetInstructionAtIndex(index);
1010   return nullptr;
1011 }
1012 
1013 void InstructionList::Dump(Stream *s, bool show_address, bool show_bytes,
1014                            bool show_control_flow_kind,
1015                            const ExecutionContext *exe_ctx) {
1016   const uint32_t max_opcode_byte_size = GetMaxOpcocdeByteSize();
1017   collection::const_iterator pos, begin, end;
1018 
1019   const FormatEntity::Entry *disassembly_format = nullptr;
1020   FormatEntity::Entry format;
1021   if (exe_ctx && exe_ctx->HasTargetScope()) {
1022     disassembly_format =
1023         exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1024   } else {
1025     FormatEntity::Parse("${addr}: ", format);
1026     disassembly_format = &format;
1027   }
1028 
1029   for (begin = m_instructions.begin(), end = m_instructions.end(), pos = begin;
1030        pos != end; ++pos) {
1031     if (pos != begin)
1032       s->EOL();
1033     (*pos)->Dump(s, max_opcode_byte_size, show_address, show_bytes,
1034                  show_control_flow_kind, exe_ctx, nullptr, nullptr,
1035                  disassembly_format, 0);
1036   }
1037 }
1038 
1039 void InstructionList::Clear() { m_instructions.clear(); }
1040 
1041 void InstructionList::Append(lldb::InstructionSP &inst_sp) {
1042   if (inst_sp)
1043     m_instructions.push_back(inst_sp);
1044 }
1045 
1046 uint32_t
1047 InstructionList::GetIndexOfNextBranchInstruction(uint32_t start,
1048                                                  bool ignore_calls,
1049                                                  bool *found_calls) const {
1050   size_t num_instructions = m_instructions.size();
1051 
1052   uint32_t next_branch = UINT32_MAX;
1053 
1054   if (found_calls)
1055     *found_calls = false;
1056   for (size_t i = start; i < num_instructions; i++) {
1057     if (m_instructions[i]->DoesBranch()) {
1058       if (ignore_calls && m_instructions[i]->IsCall()) {
1059         if (found_calls)
1060           *found_calls = true;
1061         continue;
1062       }
1063       next_branch = i;
1064       break;
1065     }
1066   }
1067 
1068   return next_branch;
1069 }
1070 
1071 uint32_t
1072 InstructionList::GetIndexOfInstructionAtAddress(const Address &address) {
1073   size_t num_instructions = m_instructions.size();
1074   uint32_t index = UINT32_MAX;
1075   for (size_t i = 0; i < num_instructions; i++) {
1076     if (m_instructions[i]->GetAddress() == address) {
1077       index = i;
1078       break;
1079     }
1080   }
1081   return index;
1082 }
1083 
1084 uint32_t
1085 InstructionList::GetIndexOfInstructionAtLoadAddress(lldb::addr_t load_addr,
1086                                                     Target &target) {
1087   Address address;
1088   address.SetLoadAddress(load_addr, &target);
1089   return GetIndexOfInstructionAtAddress(address);
1090 }
1091 
1092 size_t Disassembler::AppendInstructions(Target &target, Address start,
1093                                         Limit limit, Stream *error_strm_ptr,
1094                                         bool force_live_memory) {
1095   if (!start.IsValid())
1096     return 0;
1097 
1098   start = ResolveAddress(target, start);
1099 
1100   addr_t byte_size = limit.value;
1101   if (limit.kind == Limit::Instructions)
1102     byte_size *= m_arch.GetMaximumOpcodeByteSize();
1103   auto data_sp = std::make_shared<DataBufferHeap>(byte_size, '\0');
1104 
1105   Status error;
1106   lldb::addr_t load_addr = LLDB_INVALID_ADDRESS;
1107   const size_t bytes_read =
1108       target.ReadMemory(start, data_sp->GetBytes(), data_sp->GetByteSize(),
1109                         error, force_live_memory, &load_addr);
1110   const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS;
1111 
1112   if (bytes_read == 0) {
1113     if (error_strm_ptr) {
1114       if (const char *error_cstr = error.AsCString())
1115         error_strm_ptr->Printf("error: %s\n", error_cstr);
1116     }
1117     return 0;
1118   }
1119 
1120   if (bytes_read != data_sp->GetByteSize())
1121     data_sp->SetByteSize(bytes_read);
1122   DataExtractor data(data_sp, m_arch.GetByteOrder(),
1123                      m_arch.GetAddressByteSize());
1124   return DecodeInstructions(start, data, 0,
1125                             limit.kind == Limit::Instructions ? limit.value
1126                                                               : UINT32_MAX,
1127                             /*append=*/true, data_from_file);
1128 }
1129 
1130 // Disassembler copy constructor
1131 Disassembler::Disassembler(const ArchSpec &arch, const char *flavor)
1132     : m_arch(arch), m_instruction_list(), m_flavor() {
1133   if (flavor == nullptr)
1134     m_flavor.assign("default");
1135   else
1136     m_flavor.assign(flavor);
1137 
1138   // If this is an arm variant that can only include thumb (T16, T32)
1139   // instructions, force the arch triple to be "thumbv.." instead of "armv..."
1140   if (arch.IsAlwaysThumbInstructions()) {
1141     std::string thumb_arch_name(arch.GetTriple().getArchName().str());
1142     // Replace "arm" with "thumb" so we get all thumb variants correct
1143     if (thumb_arch_name.size() > 3) {
1144       thumb_arch_name.erase(0, 3);
1145       thumb_arch_name.insert(0, "thumb");
1146     }
1147     m_arch.SetTriple(thumb_arch_name.c_str());
1148   }
1149 }
1150 
1151 Disassembler::~Disassembler() = default;
1152 
1153 InstructionList &Disassembler::GetInstructionList() {
1154   return m_instruction_list;
1155 }
1156 
1157 const InstructionList &Disassembler::GetInstructionList() const {
1158   return m_instruction_list;
1159 }
1160 
1161 // Class PseudoInstruction
1162 
1163 PseudoInstruction::PseudoInstruction()
1164     : Instruction(Address(), AddressClass::eUnknown), m_description() {}
1165 
1166 PseudoInstruction::~PseudoInstruction() = default;
1167 
1168 bool PseudoInstruction::DoesBranch() {
1169   // This is NOT a valid question for a pseudo instruction.
1170   return false;
1171 }
1172 
1173 bool PseudoInstruction::HasDelaySlot() {
1174   // This is NOT a valid question for a pseudo instruction.
1175   return false;
1176 }
1177 
1178 bool PseudoInstruction::IsLoad() { return false; }
1179 
1180 bool PseudoInstruction::IsAuthenticated() { return false; }
1181 
1182 size_t PseudoInstruction::Decode(const lldb_private::Disassembler &disassembler,
1183                                  const lldb_private::DataExtractor &data,
1184                                  lldb::offset_t data_offset) {
1185   return m_opcode.GetByteSize();
1186 }
1187 
1188 void PseudoInstruction::SetOpcode(size_t opcode_size, void *opcode_data) {
1189   if (!opcode_data)
1190     return;
1191 
1192   switch (opcode_size) {
1193   case 8: {
1194     uint8_t value8 = *((uint8_t *)opcode_data);
1195     m_opcode.SetOpcode8(value8, eByteOrderInvalid);
1196     break;
1197   }
1198   case 16: {
1199     uint16_t value16 = *((uint16_t *)opcode_data);
1200     m_opcode.SetOpcode16(value16, eByteOrderInvalid);
1201     break;
1202   }
1203   case 32: {
1204     uint32_t value32 = *((uint32_t *)opcode_data);
1205     m_opcode.SetOpcode32(value32, eByteOrderInvalid);
1206     break;
1207   }
1208   case 64: {
1209     uint64_t value64 = *((uint64_t *)opcode_data);
1210     m_opcode.SetOpcode64(value64, eByteOrderInvalid);
1211     break;
1212   }
1213   default:
1214     break;
1215   }
1216 }
1217 
1218 void PseudoInstruction::SetDescription(llvm::StringRef description) {
1219   m_description = std::string(description);
1220 }
1221 
1222 Instruction::Operand Instruction::Operand::BuildRegister(ConstString &r) {
1223   Operand ret;
1224   ret.m_type = Type::Register;
1225   ret.m_register = r;
1226   return ret;
1227 }
1228 
1229 Instruction::Operand Instruction::Operand::BuildImmediate(lldb::addr_t imm,
1230                                                           bool neg) {
1231   Operand ret;
1232   ret.m_type = Type::Immediate;
1233   ret.m_immediate = imm;
1234   ret.m_negative = neg;
1235   return ret;
1236 }
1237 
1238 Instruction::Operand Instruction::Operand::BuildImmediate(int64_t imm) {
1239   Operand ret;
1240   ret.m_type = Type::Immediate;
1241   if (imm < 0) {
1242     ret.m_immediate = -imm;
1243     ret.m_negative = true;
1244   } else {
1245     ret.m_immediate = imm;
1246     ret.m_negative = false;
1247   }
1248   return ret;
1249 }
1250 
1251 Instruction::Operand
1252 Instruction::Operand::BuildDereference(const Operand &ref) {
1253   Operand ret;
1254   ret.m_type = Type::Dereference;
1255   ret.m_children = {ref};
1256   return ret;
1257 }
1258 
1259 Instruction::Operand Instruction::Operand::BuildSum(const Operand &lhs,
1260                                                     const Operand &rhs) {
1261   Operand ret;
1262   ret.m_type = Type::Sum;
1263   ret.m_children = {lhs, rhs};
1264   return ret;
1265 }
1266 
1267 Instruction::Operand Instruction::Operand::BuildProduct(const Operand &lhs,
1268                                                         const Operand &rhs) {
1269   Operand ret;
1270   ret.m_type = Type::Product;
1271   ret.m_children = {lhs, rhs};
1272   return ret;
1273 }
1274 
1275 std::function<bool(const Instruction::Operand &)>
1276 lldb_private::OperandMatchers::MatchBinaryOp(
1277     std::function<bool(const Instruction::Operand &)> base,
1278     std::function<bool(const Instruction::Operand &)> left,
1279     std::function<bool(const Instruction::Operand &)> right) {
1280   return [base, left, right](const Instruction::Operand &op) -> bool {
1281     return (base(op) && op.m_children.size() == 2 &&
1282             ((left(op.m_children[0]) && right(op.m_children[1])) ||
1283              (left(op.m_children[1]) && right(op.m_children[0]))));
1284   };
1285 }
1286 
1287 std::function<bool(const Instruction::Operand &)>
1288 lldb_private::OperandMatchers::MatchUnaryOp(
1289     std::function<bool(const Instruction::Operand &)> base,
1290     std::function<bool(const Instruction::Operand &)> child) {
1291   return [base, child](const Instruction::Operand &op) -> bool {
1292     return (base(op) && op.m_children.size() == 1 && child(op.m_children[0]));
1293   };
1294 }
1295 
1296 std::function<bool(const Instruction::Operand &)>
1297 lldb_private::OperandMatchers::MatchRegOp(const RegisterInfo &info) {
1298   return [&info](const Instruction::Operand &op) {
1299     return (op.m_type == Instruction::Operand::Type::Register &&
1300             (op.m_register == ConstString(info.name) ||
1301              op.m_register == ConstString(info.alt_name)));
1302   };
1303 }
1304 
1305 std::function<bool(const Instruction::Operand &)>
1306 lldb_private::OperandMatchers::FetchRegOp(ConstString &reg) {
1307   return [&reg](const Instruction::Operand &op) {
1308     if (op.m_type != Instruction::Operand::Type::Register) {
1309       return false;
1310     }
1311     reg = op.m_register;
1312     return true;
1313   };
1314 }
1315 
1316 std::function<bool(const Instruction::Operand &)>
1317 lldb_private::OperandMatchers::MatchImmOp(int64_t imm) {
1318   return [imm](const Instruction::Operand &op) {
1319     return (op.m_type == Instruction::Operand::Type::Immediate &&
1320             ((op.m_negative && op.m_immediate == (uint64_t)-imm) ||
1321              (!op.m_negative && op.m_immediate == (uint64_t)imm)));
1322   };
1323 }
1324 
1325 std::function<bool(const Instruction::Operand &)>
1326 lldb_private::OperandMatchers::FetchImmOp(int64_t &imm) {
1327   return [&imm](const Instruction::Operand &op) {
1328     if (op.m_type != Instruction::Operand::Type::Immediate) {
1329       return false;
1330     }
1331     if (op.m_negative) {
1332       imm = -((int64_t)op.m_immediate);
1333     } else {
1334       imm = ((int64_t)op.m_immediate);
1335     }
1336     return true;
1337   };
1338 }
1339 
1340 std::function<bool(const Instruction::Operand &)>
1341 lldb_private::OperandMatchers::MatchOpType(Instruction::Operand::Type type) {
1342   return [type](const Instruction::Operand &op) { return op.m_type == type; };
1343 }
1344