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