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