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