1 //===-- ThreadPlanTracer.cpp ------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include <cstring>
10 
11 #include "lldb/Core/Debugger.h"
12 #include "lldb/Core/Disassembler.h"
13 #include "lldb/Core/DumpRegisterValue.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/StreamFile.h"
16 #include "lldb/Core/Value.h"
17 #include "lldb/Symbol/TypeList.h"
18 #include "lldb/Symbol/TypeSystem.h"
19 #include "lldb/Target/ABI.h"
20 #include "lldb/Target/Process.h"
21 #include "lldb/Target/RegisterContext.h"
22 #include "lldb/Target/SectionLoadList.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Target/Thread.h"
25 #include "lldb/Target/ThreadPlan.h"
26 #include "lldb/Utility/DataBufferHeap.h"
27 #include "lldb/Utility/DataExtractor.h"
28 #include "lldb/Utility/Log.h"
29 #include "lldb/Utility/State.h"
30 
31 using namespace lldb;
32 using namespace lldb_private;
33 
34 #pragma mark ThreadPlanTracer
35 
36 ThreadPlanTracer::ThreadPlanTracer(Thread &thread, lldb::StreamSP &stream_sp)
37     : m_thread(thread), m_single_step(true), m_enabled(false),
38       m_stream_sp(stream_sp) {}
39 
40 ThreadPlanTracer::ThreadPlanTracer(Thread &thread)
41     : m_thread(thread), m_single_step(true), m_enabled(false), m_stream_sp() {}
42 
43 Stream *ThreadPlanTracer::GetLogStream() {
44   if (m_stream_sp)
45     return m_stream_sp.get();
46   else {
47     TargetSP target_sp(m_thread.CalculateTarget());
48     if (target_sp)
49       return &(target_sp->GetDebugger().GetOutputStream());
50   }
51   return nullptr;
52 }
53 
54 void ThreadPlanTracer::Log() {
55   SymbolContext sc;
56   bool show_frame_index = false;
57   bool show_fullpaths = false;
58 
59   Stream *stream = GetLogStream();
60   if (stream) {
61     m_thread.GetStackFrameAtIndex(0)->Dump(stream, show_frame_index,
62                                            show_fullpaths);
63     stream->Printf("\n");
64     stream->Flush();
65   }
66 }
67 
68 bool ThreadPlanTracer::TracerExplainsStop() {
69   if (m_enabled && m_single_step) {
70     lldb::StopInfoSP stop_info = m_thread.GetStopInfo();
71     return (stop_info->GetStopReason() == eStopReasonTrace);
72   } else
73     return false;
74 }
75 
76 #pragma mark ThreadPlanAssemblyTracer
77 
78 ThreadPlanAssemblyTracer::ThreadPlanAssemblyTracer(Thread &thread,
79                                                    lldb::StreamSP &stream_sp)
80     : ThreadPlanTracer(thread, stream_sp), m_disassembler_sp(), m_intptr_type(),
81       m_register_values() {}
82 
83 ThreadPlanAssemblyTracer::ThreadPlanAssemblyTracer(Thread &thread)
84     : ThreadPlanTracer(thread), m_disassembler_sp(), m_intptr_type(),
85       m_register_values() {}
86 
87 Disassembler *ThreadPlanAssemblyTracer::GetDisassembler() {
88   if (!m_disassembler_sp)
89     m_disassembler_sp = Disassembler::FindPlugin(
90         m_thread.GetProcess()->GetTarget().GetArchitecture(), nullptr, nullptr);
91   return m_disassembler_sp.get();
92 }
93 
94 TypeFromUser ThreadPlanAssemblyTracer::GetIntPointerType() {
95   if (!m_intptr_type.IsValid()) {
96     if (auto target_sp = m_thread.CalculateTarget()) {
97       auto type_system_or_err =
98           target_sp->GetScratchTypeSystemForLanguage(eLanguageTypeC);
99       if (auto err = type_system_or_err.takeError()) {
100         LLDB_LOG_ERROR(
101             lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TYPES),
102             std::move(err),
103             "Unable to get integer pointer type from TypeSystem");
104       } else {
105         m_intptr_type = TypeFromUser(
106             type_system_or_err->GetBuiltinTypeForEncodingAndBitSize(
107                 eEncodingUint,
108                 target_sp->GetArchitecture().GetAddressByteSize() * 8));
109       }
110     }
111   }
112   return m_intptr_type;
113 }
114 
115 ThreadPlanAssemblyTracer::~ThreadPlanAssemblyTracer() = default;
116 
117 void ThreadPlanAssemblyTracer::TracingStarted() {
118   RegisterContext *reg_ctx = m_thread.GetRegisterContext().get();
119 
120   if (m_register_values.empty())
121     m_register_values.resize(reg_ctx->GetRegisterCount());
122 }
123 
124 void ThreadPlanAssemblyTracer::TracingEnded() { m_register_values.clear(); }
125 
126 void ThreadPlanAssemblyTracer::Log() {
127   Stream *stream = GetLogStream();
128 
129   if (!stream)
130     return;
131 
132   RegisterContext *reg_ctx = m_thread.GetRegisterContext().get();
133 
134   lldb::addr_t pc = reg_ctx->GetPC();
135   ProcessSP process_sp(m_thread.GetProcess());
136   Address pc_addr;
137   bool addr_valid = false;
138   uint8_t buffer[16] = {0}; // Must be big enough for any single instruction
139   addr_valid = process_sp->GetTarget().GetSectionLoadList().ResolveLoadAddress(
140       pc, pc_addr);
141 
142   pc_addr.Dump(stream, &m_thread, Address::DumpStyleResolvedDescription,
143                Address::DumpStyleModuleWithFileAddress);
144   stream->PutCString(" ");
145 
146   Disassembler *disassembler = GetDisassembler();
147   if (disassembler) {
148     Status err;
149     process_sp->ReadMemory(pc, buffer, sizeof(buffer), err);
150 
151     if (err.Success()) {
152       DataExtractor extractor(buffer, sizeof(buffer),
153                               process_sp->GetByteOrder(),
154                               process_sp->GetAddressByteSize());
155 
156       bool data_from_file = false;
157       if (addr_valid)
158         disassembler->DecodeInstructions(pc_addr, extractor, 0, 1, false,
159                                          data_from_file);
160       else
161         disassembler->DecodeInstructions(Address(pc), extractor, 0, 1, false,
162                                          data_from_file);
163 
164       InstructionList &instruction_list = disassembler->GetInstructionList();
165       const uint32_t max_opcode_byte_size =
166           instruction_list.GetMaxOpcocdeByteSize();
167 
168       if (instruction_list.GetSize()) {
169         const bool show_bytes = true;
170         const bool show_address = true;
171         Instruction *instruction =
172             instruction_list.GetInstructionAtIndex(0).get();
173         const FormatEntity::Entry *disassemble_format =
174             m_thread.GetProcess()
175                 ->GetTarget()
176                 .GetDebugger()
177                 .GetDisassemblyFormat();
178         instruction->Dump(stream, max_opcode_byte_size, show_address,
179                           show_bytes, nullptr, nullptr, nullptr,
180                           disassemble_format, 0);
181       }
182     }
183   }
184 
185   const ABI *abi = process_sp->GetABI().get();
186   TypeFromUser intptr_type = GetIntPointerType();
187 
188   if (abi && intptr_type.IsValid()) {
189     ValueList value_list;
190     const int num_args = 1;
191 
192     for (int arg_index = 0; arg_index < num_args; ++arg_index) {
193       Value value;
194       value.SetValueType(Value::eValueTypeScalar);
195       value.SetCompilerType(intptr_type);
196       value_list.PushValue(value);
197     }
198 
199     if (abi->GetArgumentValues(m_thread, value_list)) {
200       for (int arg_index = 0; arg_index < num_args; ++arg_index) {
201         stream->Printf(
202             "\n\targ[%d]=%llx", arg_index,
203             value_list.GetValueAtIndex(arg_index)->GetScalar().ULongLong());
204 
205         if (arg_index + 1 < num_args)
206           stream->PutCString(", ");
207       }
208     }
209   }
210 
211   RegisterValue reg_value;
212   for (uint32_t reg_num = 0, num_registers = reg_ctx->GetRegisterCount();
213        reg_num < num_registers; ++reg_num) {
214     const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg_num);
215     if (reg_ctx->ReadRegister(reg_info, reg_value)) {
216       assert(reg_num < m_register_values.size());
217       if (m_register_values[reg_num].GetType() == RegisterValue::eTypeInvalid ||
218           reg_value != m_register_values[reg_num]) {
219         if (reg_value.GetType() != RegisterValue::eTypeInvalid) {
220           stream->PutCString("\n\t");
221           DumpRegisterValue(reg_value, stream, reg_info, true, false,
222                             eFormatDefault);
223         }
224       }
225       m_register_values[reg_num] = reg_value;
226     }
227   }
228   stream->EOL();
229   stream->Flush();
230 }
231