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 = 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
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 
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
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 
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 
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 
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 
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 
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 
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 
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 
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 
657 bool Instruction::CanSetBreakpoint () {
658   return !HasDelaySlot();
659 }
660 
661 bool Instruction::HasDelaySlot() {
662   // Default is false.
663   return false;
664 }
665 
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 
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 
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 
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 
931 uint32_t Instruction::GetData(DataExtractor &data) {
932   return m_opcode.GetData(data);
933 }
934 
935 InstructionList::InstructionList() : m_instructions() {}
936 
937 InstructionList::~InstructionList() = default;
938 
939 size_t InstructionList::GetSize() const { return m_instructions.size(); }
940 
941 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 
953 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 
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 
984 void InstructionList::Clear() { m_instructions.clear(); }
985 
986 void InstructionList::Append(lldb::InstructionSP &inst_sp) {
987   if (inst_sp)
988     m_instructions.push_back(inst_sp);
989 }
990 
991 uint32_t
992 InstructionList::GetIndexOfNextBranchInstruction(uint32_t start,
993                                                  bool ignore_calls,
994                                                  bool *found_calls) const {
995   size_t num_instructions = m_instructions.size();
996 
997   uint32_t next_branch = UINT32_MAX;
998 
999   if (found_calls)
1000     *found_calls = false;
1001   for (size_t i = start; i < num_instructions; i++) {
1002     if (m_instructions[i]->DoesBranch()) {
1003       if (ignore_calls && m_instructions[i]->IsCall()) {
1004         if (found_calls)
1005           *found_calls = true;
1006         continue;
1007       }
1008       next_branch = i;
1009       break;
1010     }
1011   }
1012 
1013   return next_branch;
1014 }
1015 
1016 uint32_t
1017 InstructionList::GetIndexOfInstructionAtAddress(const Address &address) {
1018   size_t num_instructions = m_instructions.size();
1019   uint32_t index = UINT32_MAX;
1020   for (size_t i = 0; i < num_instructions; i++) {
1021     if (m_instructions[i]->GetAddress() == address) {
1022       index = i;
1023       break;
1024     }
1025   }
1026   return index;
1027 }
1028 
1029 uint32_t
1030 InstructionList::GetIndexOfInstructionAtLoadAddress(lldb::addr_t load_addr,
1031                                                     Target &target) {
1032   Address address;
1033   address.SetLoadAddress(load_addr, &target);
1034   return GetIndexOfInstructionAtAddress(address);
1035 }
1036 
1037 size_t Disassembler::ParseInstructions(Target &target, Address start,
1038                                        Limit limit, Stream *error_strm_ptr,
1039                                        bool prefer_file_cache) {
1040   m_instruction_list.Clear();
1041 
1042   if (!start.IsValid())
1043     return 0;
1044 
1045   start = ResolveAddress(target, start);
1046 
1047   addr_t byte_size = limit.value;
1048   if (limit.kind == Limit::Instructions)
1049     byte_size *= m_arch.GetMaximumOpcodeByteSize();
1050   auto data_sp = std::make_shared<DataBufferHeap>(byte_size, '\0');
1051 
1052   Status error;
1053   lldb::addr_t load_addr = LLDB_INVALID_ADDRESS;
1054   const size_t bytes_read =
1055       target.ReadMemory(start, prefer_file_cache, data_sp->GetBytes(),
1056                         data_sp->GetByteSize(), error, &load_addr);
1057   const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS;
1058 
1059   if (bytes_read == 0) {
1060     if (error_strm_ptr) {
1061       if (const char *error_cstr = error.AsCString())
1062         error_strm_ptr->Printf("error: %s\n", error_cstr);
1063     }
1064     return 0;
1065   }
1066 
1067   if (bytes_read != data_sp->GetByteSize())
1068     data_sp->SetByteSize(bytes_read);
1069   DataExtractor data(data_sp, m_arch.GetByteOrder(),
1070                      m_arch.GetAddressByteSize());
1071   return DecodeInstructions(start, data, 0,
1072                             limit.kind == Limit::Instructions ? limit.value
1073                                                               : UINT32_MAX,
1074                             false, data_from_file);
1075 }
1076 
1077 // Disassembler copy constructor
1078 Disassembler::Disassembler(const ArchSpec &arch, const char *flavor)
1079     : m_arch(arch), m_instruction_list(), m_base_addr(LLDB_INVALID_ADDRESS),
1080       m_flavor() {
1081   if (flavor == nullptr)
1082     m_flavor.assign("default");
1083   else
1084     m_flavor.assign(flavor);
1085 
1086   // If this is an arm variant that can only include thumb (T16, T32)
1087   // instructions, force the arch triple to be "thumbv.." instead of "armv..."
1088   if (arch.IsAlwaysThumbInstructions()) {
1089     std::string thumb_arch_name(arch.GetTriple().getArchName().str());
1090     // Replace "arm" with "thumb" so we get all thumb variants correct
1091     if (thumb_arch_name.size() > 3) {
1092       thumb_arch_name.erase(0, 3);
1093       thumb_arch_name.insert(0, "thumb");
1094     }
1095     m_arch.SetTriple(thumb_arch_name.c_str());
1096   }
1097 }
1098 
1099 Disassembler::~Disassembler() = default;
1100 
1101 InstructionList &Disassembler::GetInstructionList() {
1102   return m_instruction_list;
1103 }
1104 
1105 const InstructionList &Disassembler::GetInstructionList() const {
1106   return m_instruction_list;
1107 }
1108 
1109 // Class PseudoInstruction
1110 
1111 PseudoInstruction::PseudoInstruction()
1112     : Instruction(Address(), AddressClass::eUnknown), m_description() {}
1113 
1114 PseudoInstruction::~PseudoInstruction() = default;
1115 
1116 bool PseudoInstruction::DoesBranch() {
1117   // This is NOT a valid question for a pseudo instruction.
1118   return false;
1119 }
1120 
1121 bool PseudoInstruction::HasDelaySlot() {
1122   // This is NOT a valid question for a pseudo instruction.
1123   return false;
1124 }
1125 
1126 size_t PseudoInstruction::Decode(const lldb_private::Disassembler &disassembler,
1127                                  const lldb_private::DataExtractor &data,
1128                                  lldb::offset_t data_offset) {
1129   return m_opcode.GetByteSize();
1130 }
1131 
1132 void PseudoInstruction::SetOpcode(size_t opcode_size, void *opcode_data) {
1133   if (!opcode_data)
1134     return;
1135 
1136   switch (opcode_size) {
1137   case 8: {
1138     uint8_t value8 = *((uint8_t *)opcode_data);
1139     m_opcode.SetOpcode8(value8, eByteOrderInvalid);
1140     break;
1141   }
1142   case 16: {
1143     uint16_t value16 = *((uint16_t *)opcode_data);
1144     m_opcode.SetOpcode16(value16, eByteOrderInvalid);
1145     break;
1146   }
1147   case 32: {
1148     uint32_t value32 = *((uint32_t *)opcode_data);
1149     m_opcode.SetOpcode32(value32, eByteOrderInvalid);
1150     break;
1151   }
1152   case 64: {
1153     uint64_t value64 = *((uint64_t *)opcode_data);
1154     m_opcode.SetOpcode64(value64, eByteOrderInvalid);
1155     break;
1156   }
1157   default:
1158     break;
1159   }
1160 }
1161 
1162 void PseudoInstruction::SetDescription(llvm::StringRef description) {
1163   m_description = std::string(description);
1164 }
1165 
1166 Instruction::Operand Instruction::Operand::BuildRegister(ConstString &r) {
1167   Operand ret;
1168   ret.m_type = Type::Register;
1169   ret.m_register = r;
1170   return ret;
1171 }
1172 
1173 Instruction::Operand Instruction::Operand::BuildImmediate(lldb::addr_t imm,
1174                                                           bool neg) {
1175   Operand ret;
1176   ret.m_type = Type::Immediate;
1177   ret.m_immediate = imm;
1178   ret.m_negative = neg;
1179   return ret;
1180 }
1181 
1182 Instruction::Operand Instruction::Operand::BuildImmediate(int64_t imm) {
1183   Operand ret;
1184   ret.m_type = Type::Immediate;
1185   if (imm < 0) {
1186     ret.m_immediate = -imm;
1187     ret.m_negative = true;
1188   } else {
1189     ret.m_immediate = imm;
1190     ret.m_negative = false;
1191   }
1192   return ret;
1193 }
1194 
1195 Instruction::Operand
1196 Instruction::Operand::BuildDereference(const Operand &ref) {
1197   Operand ret;
1198   ret.m_type = Type::Dereference;
1199   ret.m_children = {ref};
1200   return ret;
1201 }
1202 
1203 Instruction::Operand Instruction::Operand::BuildSum(const Operand &lhs,
1204                                                     const Operand &rhs) {
1205   Operand ret;
1206   ret.m_type = Type::Sum;
1207   ret.m_children = {lhs, rhs};
1208   return ret;
1209 }
1210 
1211 Instruction::Operand Instruction::Operand::BuildProduct(const Operand &lhs,
1212                                                         const Operand &rhs) {
1213   Operand ret;
1214   ret.m_type = Type::Product;
1215   ret.m_children = {lhs, rhs};
1216   return ret;
1217 }
1218 
1219 std::function<bool(const Instruction::Operand &)>
1220 lldb_private::OperandMatchers::MatchBinaryOp(
1221     std::function<bool(const Instruction::Operand &)> base,
1222     std::function<bool(const Instruction::Operand &)> left,
1223     std::function<bool(const Instruction::Operand &)> right) {
1224   return [base, left, right](const Instruction::Operand &op) -> bool {
1225     return (base(op) && op.m_children.size() == 2 &&
1226             ((left(op.m_children[0]) && right(op.m_children[1])) ||
1227              (left(op.m_children[1]) && right(op.m_children[0]))));
1228   };
1229 }
1230 
1231 std::function<bool(const Instruction::Operand &)>
1232 lldb_private::OperandMatchers::MatchUnaryOp(
1233     std::function<bool(const Instruction::Operand &)> base,
1234     std::function<bool(const Instruction::Operand &)> child) {
1235   return [base, child](const Instruction::Operand &op) -> bool {
1236     return (base(op) && op.m_children.size() == 1 && child(op.m_children[0]));
1237   };
1238 }
1239 
1240 std::function<bool(const Instruction::Operand &)>
1241 lldb_private::OperandMatchers::MatchRegOp(const RegisterInfo &info) {
1242   return [&info](const Instruction::Operand &op) {
1243     return (op.m_type == Instruction::Operand::Type::Register &&
1244             (op.m_register == ConstString(info.name) ||
1245              op.m_register == ConstString(info.alt_name)));
1246   };
1247 }
1248 
1249 std::function<bool(const Instruction::Operand &)>
1250 lldb_private::OperandMatchers::FetchRegOp(ConstString &reg) {
1251   return [&reg](const Instruction::Operand &op) {
1252     if (op.m_type != Instruction::Operand::Type::Register) {
1253       return false;
1254     }
1255     reg = op.m_register;
1256     return true;
1257   };
1258 }
1259 
1260 std::function<bool(const Instruction::Operand &)>
1261 lldb_private::OperandMatchers::MatchImmOp(int64_t imm) {
1262   return [imm](const Instruction::Operand &op) {
1263     return (op.m_type == Instruction::Operand::Type::Immediate &&
1264             ((op.m_negative && op.m_immediate == (uint64_t)-imm) ||
1265              (!op.m_negative && op.m_immediate == (uint64_t)imm)));
1266   };
1267 }
1268 
1269 std::function<bool(const Instruction::Operand &)>
1270 lldb_private::OperandMatchers::FetchImmOp(int64_t &imm) {
1271   return [&imm](const Instruction::Operand &op) {
1272     if (op.m_type != Instruction::Operand::Type::Immediate) {
1273       return false;
1274     }
1275     if (op.m_negative) {
1276       imm = -((int64_t)op.m_immediate);
1277     } else {
1278       imm = ((int64_t)op.m_immediate);
1279     }
1280     return true;
1281   };
1282 }
1283 
1284 std::function<bool(const Instruction::Operand &)>
1285 lldb_private::OperandMatchers::MatchOpType(Instruction::Operand::Type type) {
1286   return [type](const Instruction::Operand &op) { return op.m_type == type; };
1287 }
1288