LLDB mainline
InstrumentationRuntimeMainThreadChecker.cpp
Go to the documentation of this file.
1//===-- InstrumentationRuntimeMainThreadChecker.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
10
13#include "lldb/Core/Module.h"
15#include "lldb/Symbol/Symbol.h"
23#include "lldb/Target/Target.h"
24#include "lldb/Target/Thread.h"
26
27#include <memory>
28
29using namespace lldb;
30using namespace lldb_private;
31
33
36 Deactivate();
37}
38
41 const lldb::ProcessSP &process_sp) {
44}
45
49 "MainThreadChecker instrumentation runtime plugin.", CreateInstance,
51}
52
55}
56
60}
61
64 static RegularExpression regex(llvm::StringRef("libMainThreadChecker.dylib"));
65 return regex;
66}
67
69 const lldb::ModuleSP module_sp) {
70 static ConstString test_sym("__main_thread_checker_on_report");
71 const Symbol *symbol =
72 module_sp->FindFirstSymbolWithNameAndType(test_sym, lldb::eSymbolTypeAny);
73 return symbol != nullptr;
74}
75
78 ExecutionContextRef exe_ctx_ref) {
79 ProcessSP process_sp = GetProcessSP();
80 if (!process_sp)
82
83 ThreadSP thread_sp = exe_ctx_ref.GetThreadSP();
84 StackFrameSP frame_sp =
85 thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame);
86 ModuleSP runtime_module_sp = GetRuntimeModuleSP();
87 Target &target = process_sp->GetTarget();
88
89 if (!frame_sp)
91
92 RegisterContextSP regctx_sp = frame_sp->GetRegisterContext();
93 if (!regctx_sp)
95
96 const RegisterInfo *reginfo = regctx_sp->GetRegisterInfoByName("arg1");
97 if (!reginfo)
99
100 uint64_t apiname_ptr = regctx_sp->ReadRegisterAsUnsigned(reginfo, 0);
101 if (!apiname_ptr)
103
104 std::string apiName;
105 Status read_error;
106 target.ReadCStringFromMemory(apiname_ptr, apiName, read_error);
107 if (read_error.Fail())
109
110 std::string className;
111 std::string selector;
112 if (apiName.substr(0, 2) == "-[") {
113 size_t spacePos = apiName.find(' ');
114 if (spacePos != std::string::npos) {
115 className = apiName.substr(2, spacePos - 2);
116 selector = apiName.substr(spacePos + 1, apiName.length() - spacePos - 2);
117 }
118 }
119
120 // Gather the PCs of the user frames in the backtrace.
122 auto trace_sp = StructuredData::ObjectSP(trace);
123 StackFrameSP responsible_frame;
124 for (unsigned I = 0; I < thread_sp->GetStackFrameCount(); ++I) {
125 StackFrameSP frame = thread_sp->GetStackFrameAtIndex(I);
126 Address addr = frame->GetFrameCodeAddressForSymbolication();
127 if (addr.GetModule() == runtime_module_sp) // Skip PCs from the runtime.
128 continue;
129
130 // The first non-runtime frame is responsible for the bug.
131 if (!responsible_frame)
132 responsible_frame = frame;
133
134 lldb::addr_t PC = addr.GetLoadAddress(&target);
135 trace->AddIntegerItem(PC);
136 }
137
138 auto *d = new StructuredData::Dictionary();
139 auto dict_sp = StructuredData::ObjectSP(d);
140 d->AddStringItem("instrumentation_class", "MainThreadChecker");
141 d->AddStringItem("api_name", apiName);
142 d->AddStringItem("class_name", className);
143 d->AddStringItem("selector", selector);
144 d->AddStringItem("description",
145 apiName + " must be used from main thread only");
146 d->AddIntegerItem("tid", thread_sp->GetIndexID());
147 d->AddItem("trace", trace_sp);
148 return dict_sp;
149}
150
152 void *baton, StoppointCallbackContext *context, user_id_t break_id,
153 user_id_t break_loc_id) {
154 assert(baton && "null baton");
155 if (!baton)
156 return false; ///< false => resume execution.
157
159 static_cast<InstrumentationRuntimeMainThreadChecker *>(baton);
160
161 ProcessSP process_sp = instance->GetProcessSP();
162 ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
163 if (!process_sp || !thread_sp ||
164 process_sp != context->exe_ctx_ref.GetProcessSP())
165 return false;
166
167 if (process_sp->GetModIDRef().IsLastResumeForUserExpression())
168 return false;
169
171 instance->RetrieveReportData(context->exe_ctx_ref);
172
173 if (report) {
174 std::string description = std::string(report->GetAsDictionary()
175 ->GetValueForKey("description")
176 ->GetAsString()
177 ->GetValue());
178 thread_sp->SetStopInfo(
180 *thread_sp, description, report));
181 return true;
182 }
183
184 return false;
185}
186
188 if (IsActive())
189 return;
190
191 ProcessSP process_sp = GetProcessSP();
192 if (!process_sp)
193 return;
194
195 ModuleSP runtime_module_sp = GetRuntimeModuleSP();
196
197 ConstString symbol_name("__main_thread_checker_on_report");
198 const Symbol *symbol = runtime_module_sp->FindFirstSymbolWithNameAndType(
199 symbol_name, eSymbolTypeCode);
200
201 if (symbol == nullptr)
202 return;
203
204 if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
205 return;
206
207 Target &target = process_sp->GetTarget();
208 addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
209
210 if (symbol_address == LLDB_INVALID_ADDRESS)
211 return;
212
213 Breakpoint *breakpoint =
214 process_sp->GetTarget()
215 .CreateBreakpoint(symbol_address, /*internal=*/true,
216 /*hardware=*/false)
217 .get();
218 const bool sync = false;
219 breakpoint->SetCallback(
221 breakpoint->SetBreakpointKind("main-thread-checker-report");
222 SetBreakpointID(breakpoint->GetID());
223
224 SetActive(true);
225}
226
228 SetActive(false);
229
230 auto BID = GetBreakpointID();
231 if (BID == LLDB_INVALID_BREAK_ID)
232 return;
233
234 if (ProcessSP process_sp = GetProcessSP()) {
235 process_sp->GetTarget().RemoveBreakpointByID(BID);
237 }
238}
239
243 ThreadCollectionSP threads;
244 threads = std::make_shared<ThreadCollection>();
245
246 ProcessSP process_sp = GetProcessSP();
247
248 if (info->GetObjectForDotSeparatedPath("instrumentation_class")
249 ->GetStringValue() != "MainThreadChecker")
250 return threads;
251
252 std::vector<lldb::addr_t> PCs;
253 auto trace = info->GetObjectForDotSeparatedPath("trace")->GetAsArray();
254 trace->ForEach([&PCs](StructuredData::Object *PC) -> bool {
255 PCs.push_back(PC->GetUnsignedIntegerValue());
256 return true;
257 });
258
259 if (PCs.empty())
260 return threads;
261
262 StructuredData::ObjectSP thread_id_obj =
263 info->GetObjectForDotSeparatedPath("tid");
264 tid_t tid = thread_id_obj ? thread_id_obj->GetUnsignedIntegerValue() : 0;
265
266 // We gather symbolication addresses above, so no need for HistoryThread to
267 // try to infer the call addresses.
268 bool pcs_are_call_addresses = true;
269 ThreadSP new_thread_sp = std::make_shared<HistoryThread>(
270 *process_sp, tid, PCs, pcs_are_call_addresses);
271
272 // Save this in the Process' ExtendedThreadList so a strong pointer retains
273 // the object
274 process_sp->GetExtendedThreadList().AddThread(new_thread_sp);
275 threads->AddThread(new_thread_sp);
276
277 return threads;
278}
#define LLDB_PLUGIN_DEFINE(PluginName)
Definition: PluginManager.h:31
A section + offset based address class.
Definition: Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition: Address.cpp:313
lldb::addr_t GetOpcodeLoadAddress(Target *target, AddressClass addr_class=AddressClass::eInvalid) const
Get the load address as an opcode load address.
Definition: Address.cpp:370
lldb::ModuleSP GetModule() const
Get accessor for the module for this address.
Definition: Address.cpp:285
bool IsValid() const
Check if the object state is valid.
Definition: Address.h:355
General Outline: A breakpoint has four main parts, a filter, a resolver, the list of breakpoint locat...
Definition: Breakpoint.h:81
void SetBreakpointKind(const char *kind)
Set the "kind" description for a breakpoint.
Definition: Breakpoint.h:452
Target & GetTarget()
Accessor for the breakpoint Target.
Definition: Breakpoint.h:463
void SetCallback(BreakpointHitCallback callback, void *baton, bool is_synchronous=false)
Set the callback action invoked when the breakpoint is hit.
Definition: Breakpoint.cpp:408
A uniqued constant string class.
Definition: ConstString.h:40
Execution context objects refer to objects in the execution of the program that is being debugged.
lldb::ThreadSP GetThreadSP() const
Get accessor that creates a strong reference from the weak thread reference contained in this object.
lldb::ProcessSP GetProcessSP() const
Get accessor that creates a strong reference from the weak process reference contained in this object...
lldb::ThreadCollectionSP GetBacktracesFromExtendedStopInfo(StructuredData::ObjectSP info) override
void Activate() override
Register a breakpoint in the runtime library and perform any other necessary initialization.
static lldb::InstrumentationRuntimeSP CreateInstance(const lldb::ProcessSP &process_sp)
StructuredData::ObjectSP RetrieveReportData(ExecutionContextRef exe_ctx_ref)
static bool NotifyBreakpointHit(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
const RegularExpression & GetPatternForRuntimeLibrary() override
Return a regular expression which can be used to identify a valid version of the runtime library.
bool CheckIfRuntimeIsValid(const lldb::ModuleSP module_sp) override
Check whether module_sp corresponds to a valid runtime library.
static lldb::StopInfoSP CreateStopReasonWithInstrumentationData(Thread &thread, std::string description, StructuredData::ObjectSP additional_data)
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
An error handling class.
Definition: Status.h:44
bool Fail() const
Test for error condition.
Definition: Status.cpp:181
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
lldb::break_id_t GetID() const
Definition: Stoppoint.cpp:22
uint64_t GetUnsignedIntegerValue(uint64_t fail_value=0)
std::shared_ptr< Object > ObjectSP
bool ValueIsAddress() const
Definition: Symbol.cpp:169
Address & GetAddressRef()
Definition: Symbol.h:72
size_t ReadCStringFromMemory(const Address &addr, std::string &out_str, Status &error, bool force_live_memory=false)
Definition: Target.cpp:1949
lldb::BreakpointSP CreateBreakpoint(const FileSpecList *containingModules, const FileSpec &file, uint32_t line_no, uint32_t column, lldb::addr_t offset, LazyBool check_inlines, LazyBool skip_prologue, bool internal, bool request_hardware, LazyBool move_to_nearest_code)
Definition: Target.cpp:395
#define LLDB_INVALID_BREAK_ID
Definition: lldb-defines.h:37
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:82
@ DoNoSelectMostRelevantFrame
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
Definition: SBAddress.h:15
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
Definition: lldb-forward.h:412
std::shared_ptr< lldb_private::Thread > ThreadSP
Definition: lldb-forward.h:438
std::shared_ptr< lldb_private::Process > ProcessSP
Definition: lldb-forward.h:381
InstrumentationRuntimeType
@ eInstrumentationRuntimeTypeMainThreadChecker
uint64_t user_id_t
Definition: lldb-types.h:80
uint64_t addr_t
Definition: lldb-types.h:79
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
Definition: lldb-forward.h:386
std::shared_ptr< lldb_private::InstrumentationRuntime > InstrumentationRuntimeSP
Definition: lldb-forward.h:352
uint64_t tid_t
Definition: lldb-types.h:82
std::shared_ptr< lldb_private::Module > ModuleSP
Definition: lldb-forward.h:365
std::shared_ptr< lldb_private::ThreadCollection > ThreadCollectionSP
Definition: lldb-forward.h:440
Every register is described in detail including its name, alternate name (optional),...