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
31using namespace lldb;
32using namespace lldb_private;
33
34#pragma mark ThreadPlanTracer
35
36ThreadPlanTracer::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
40ThreadPlanTracer::ThreadPlanTracer(Thread &thread)
41    : m_thread(thread), m_single_step(true), m_enabled(false), m_stream_sp() {}
42
43Stream *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
54void 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
68bool 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
78ThreadPlanAssemblyTracer::ThreadPlanAssemblyTracer(Thread &thread,
79                                                   lldb::StreamSP &stream_sp)
80    : ThreadPlanTracer(thread, stream_sp), m_disassembler_sp(), m_intptr_type(),
81      m_register_values() {}
82
83ThreadPlanAssemblyTracer::ThreadPlanAssemblyTracer(Thread &thread)
84    : ThreadPlanTracer(thread), m_disassembler_sp(), m_intptr_type(),
85      m_register_values() {}
86
87Disassembler *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
94TypeFromUser 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
115ThreadPlanAssemblyTracer::~ThreadPlanAssemblyTracer() = default;
116
117void ThreadPlanAssemblyTracer::TracingStarted() {
118}
119
120void ThreadPlanAssemblyTracer::TracingEnded() { m_register_values.clear(); }
121
122void ThreadPlanAssemblyTracer::Log() {
123  Stream *stream = GetLogStream();
124
125  if (!stream)
126    return;
127
128  RegisterContext *reg_ctx = m_thread.GetRegisterContext().get();
129
130  lldb::addr_t pc = reg_ctx->GetPC();
131  ProcessSP process_sp(m_thread.GetProcess());
132  Address pc_addr;
133  bool addr_valid = false;
134  uint8_t buffer[16] = {0}; // Must be big enough for any single instruction
135  addr_valid = process_sp->GetTarget().GetSectionLoadList().ResolveLoadAddress(
136      pc, pc_addr);
137
138  pc_addr.Dump(stream, &m_thread, Address::DumpStyleResolvedDescription,
139               Address::DumpStyleModuleWithFileAddress);
140  stream->PutCString(" ");
141
142  Disassembler *disassembler = GetDisassembler();
143  if (disassembler) {
144    Status err;
145    process_sp->ReadMemory(pc, buffer, sizeof(buffer), err);
146
147    if (err.Success()) {
148      DataExtractor extractor(buffer, sizeof(buffer),
149                              process_sp->GetByteOrder(),
150                              process_sp->GetAddressByteSize());
151
152      bool data_from_file = false;
153      if (addr_valid)
154        disassembler->DecodeInstructions(pc_addr, extractor, 0, 1, false,
155                                         data_from_file);
156      else
157        disassembler->DecodeInstructions(Address(pc), extractor, 0, 1, false,
158                                         data_from_file);
159
160      InstructionList &instruction_list = disassembler->GetInstructionList();
161      const uint32_t max_opcode_byte_size =
162          instruction_list.GetMaxOpcocdeByteSize();
163
164      if (instruction_list.GetSize()) {
165        const bool show_bytes = true;
166        const bool show_address = true;
167        Instruction *instruction =
168            instruction_list.GetInstructionAtIndex(0).get();
169        const FormatEntity::Entry *disassemble_format =
170            m_thread.GetProcess()
171                ->GetTarget()
172                .GetDebugger()
173                .GetDisassemblyFormat();
174        instruction->Dump(stream, max_opcode_byte_size, show_address,
175                          show_bytes, nullptr, nullptr, nullptr,
176                          disassemble_format, 0);
177      }
178    }
179  }
180
181  const ABI *abi = process_sp->GetABI().get();
182  TypeFromUser intptr_type = GetIntPointerType();
183
184  if (abi && intptr_type.IsValid()) {
185    ValueList value_list;
186    const int num_args = 1;
187
188    for (int arg_index = 0; arg_index < num_args; ++arg_index) {
189      Value value;
190      value.SetValueType(Value::eValueTypeScalar);
191      value.SetCompilerType(intptr_type);
192      value_list.PushValue(value);
193    }
194
195    if (abi->GetArgumentValues(m_thread, value_list)) {
196      for (int arg_index = 0; arg_index < num_args; ++arg_index) {
197        stream->Printf(
198            "\n\targ[%d]=%llx", arg_index,
199            value_list.GetValueAtIndex(arg_index)->GetScalar().ULongLong());
200
201        if (arg_index + 1 < num_args)
202          stream->PutCString(", ");
203      }
204    }
205  }
206
207  if (m_register_values.empty()) {
208    RegisterContext *reg_ctx = m_thread.GetRegisterContext().get();
209    m_register_values.resize(reg_ctx->GetRegisterCount());
210  }
211
212  RegisterValue reg_value;
213  for (uint32_t reg_num = 0, num_registers = reg_ctx->GetRegisterCount();
214       reg_num < num_registers; ++reg_num) {
215    const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg_num);
216    if (reg_ctx->ReadRegister(reg_info, reg_value)) {
217      assert(reg_num < m_register_values.size());
218      if (m_register_values[reg_num].GetType() == RegisterValue::eTypeInvalid ||
219          reg_value != m_register_values[reg_num]) {
220        if (reg_value.GetType() != RegisterValue::eTypeInvalid) {
221          stream->PutCString("\n\t");
222          DumpRegisterValue(reg_value, stream, reg_info, true, false,
223                            eFormatDefault);
224        }
225      }
226      m_register_values[reg_num] = reg_value;
227    }
228  }
229  stream->EOL();
230  stream->Flush();
231}
232