Coverage Report

Created: 2022-01-18 06:27

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