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