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