1 //===-- MainThreadCheckerRuntime.cpp ----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MainThreadCheckerRuntime.h"
12 #include "lldb/Breakpoint/StoppointCallbackContext.h"
13 #include "lldb/Core/Module.h"
14 #include "lldb/Core/PluginManager.h"
15 #include "lldb/Symbol/Symbol.h"
16 #include "lldb/Symbol/SymbolContext.h"
17 #include "lldb/Symbol/Variable.h"
18 #include "lldb/Symbol/VariableList.h"
19 #include "lldb/Target/InstrumentationRuntimeStopInfo.h"
20 #include "lldb/Target/RegisterContext.h"
21 #include "lldb/Target/SectionLoadList.h"
22 #include "lldb/Target/StopInfo.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Target/Thread.h"
25 #include "lldb/Utility/RegularExpression.h"
26 #include "Plugins/Process/Utility/HistoryThread.h"
29 using namespace lldb_private;
31 MainThreadCheckerRuntime::~MainThreadCheckerRuntime() {
35 lldb::InstrumentationRuntimeSP
36 MainThreadCheckerRuntime::CreateInstance(const lldb::ProcessSP &process_sp) {
37 return InstrumentationRuntimeSP(new MainThreadCheckerRuntime(process_sp));
40 void MainThreadCheckerRuntime::Initialize() {
41 PluginManager::RegisterPlugin(
42 GetPluginNameStatic(), "MainThreadChecker instrumentation runtime plugin.",
43 CreateInstance, GetTypeStatic);
46 void MainThreadCheckerRuntime::Terminate() {
47 PluginManager::UnregisterPlugin(CreateInstance);
50 lldb_private::ConstString MainThreadCheckerRuntime::GetPluginNameStatic() {
51 return ConstString("MainThreadChecker");
54 lldb::InstrumentationRuntimeType MainThreadCheckerRuntime::GetTypeStatic() {
55 return eInstrumentationRuntimeTypeMainThreadChecker;
58 const RegularExpression &
59 MainThreadCheckerRuntime::GetPatternForRuntimeLibrary() {
60 static RegularExpression regex(llvm::StringRef("libMainThreadChecker.dylib"));
64 bool MainThreadCheckerRuntime::CheckIfRuntimeIsValid(
65 const lldb::ModuleSP module_sp) {
66 static ConstString test_sym("__main_thread_checker_on_report");
67 const Symbol *symbol =
68 module_sp->FindFirstSymbolWithNameAndType(test_sym, lldb::eSymbolTypeAny);
69 return symbol != nullptr;
72 StructuredData::ObjectSP
73 MainThreadCheckerRuntime::RetrieveReportData(ExecutionContextRef exe_ctx_ref) {
74 ProcessSP process_sp = GetProcessSP();
76 return StructuredData::ObjectSP();
78 ThreadSP thread_sp = exe_ctx_ref.GetThreadSP();
79 StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
80 ModuleSP runtime_module_sp = GetRuntimeModuleSP();
81 Target &target = process_sp->GetTarget();
84 return StructuredData::ObjectSP();
86 RegisterContextSP regctx_sp = frame_sp->GetRegisterContext();
88 return StructuredData::ObjectSP();
90 const RegisterInfo *reginfo = regctx_sp->GetRegisterInfoByName("arg1");
92 return StructuredData::ObjectSP();
94 uint64_t apiname_ptr = regctx_sp->ReadRegisterAsUnsigned(reginfo, 0);
96 return StructuredData::ObjectSP();
98 std::string apiName = "";
100 target.ReadCStringFromMemory(apiname_ptr, apiName, read_error);
101 if (read_error.Fail())
102 return StructuredData::ObjectSP();
104 std::string className = "";
105 std::string selector = "";
106 if (apiName.substr(0, 2) == "-[") {
107 size_t spacePos = apiName.find(" ");
108 if (spacePos != std::string::npos) {
109 className = apiName.substr(2, spacePos - 2);
110 selector = apiName.substr(spacePos + 1, apiName.length() - spacePos - 2);
114 // Gather the PCs of the user frames in the backtrace.
115 StructuredData::Array *trace = new StructuredData::Array();
116 auto trace_sp = StructuredData::ObjectSP(trace);
117 StackFrameSP responsible_frame;
118 for (unsigned I = 0; I < thread_sp->GetStackFrameCount(); ++I) {
119 StackFrameSP frame = thread_sp->GetStackFrameAtIndex(I);
120 Address addr = frame->GetFrameCodeAddress();
121 if (addr.GetModule() == runtime_module_sp) // Skip PCs from the runtime.
124 // The first non-runtime frame is responsible for the bug.
125 if (!responsible_frame)
126 responsible_frame = frame;
128 // First frame in stacktrace should point to a real PC, not return address.
129 if (I != 0 && trace->GetSize() == 0) {
133 lldb::addr_t PC = addr.GetLoadAddress(&target);
134 trace->AddItem(StructuredData::ObjectSP(new StructuredData::Integer(PC)));
137 auto *d = new StructuredData::Dictionary();
138 auto dict_sp = StructuredData::ObjectSP(d);
139 d->AddStringItem("instrumentation_class", "MainThreadChecker");
140 d->AddStringItem("api_name", apiName);
141 d->AddStringItem("class_name", className);
142 d->AddStringItem("selector", selector);
143 d->AddStringItem("description",
144 apiName + " must be used from main thread only");
145 d->AddIntegerItem("tid", thread_sp->GetIndexID());
146 d->AddItem("trace", trace_sp);
150 bool MainThreadCheckerRuntime::NotifyBreakpointHit(
151 void *baton, StoppointCallbackContext *context, user_id_t break_id,
152 user_id_t break_loc_id) {
153 assert(baton && "null baton");
155 return false; //< false => resume execution.
157 MainThreadCheckerRuntime *const instance =
158 static_cast<MainThreadCheckerRuntime *>(baton);
160 ProcessSP process_sp = instance->GetProcessSP();
161 ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
162 if (!process_sp || !thread_sp ||
163 process_sp != context->exe_ctx_ref.GetProcessSP())
166 if (process_sp->GetModIDRef().IsLastResumeForUserExpression())
169 StructuredData::ObjectSP report =
170 instance->RetrieveReportData(context->exe_ctx_ref);
173 std::string description = report->GetAsDictionary()
174 ->GetValueForKey("description")
177 thread_sp->SetStopInfo(
178 InstrumentationRuntimeStopInfo::CreateStopReasonWithInstrumentationData(
179 *thread_sp, description, report));
186 void MainThreadCheckerRuntime::Activate() {
190 ProcessSP process_sp = GetProcessSP();
194 ModuleSP runtime_module_sp = GetRuntimeModuleSP();
196 ConstString symbol_name("__main_thread_checker_on_report");
197 const Symbol *symbol = runtime_module_sp->FindFirstSymbolWithNameAndType(
198 symbol_name, eSymbolTypeCode);
200 if (symbol == nullptr)
203 if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
206 Target &target = process_sp->GetTarget();
207 addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
209 if (symbol_address == LLDB_INVALID_ADDRESS)
212 Breakpoint *breakpoint =
213 process_sp->GetTarget()
214 .CreateBreakpoint(symbol_address, /*internal=*/true,
217 breakpoint->SetCallback(MainThreadCheckerRuntime::NotifyBreakpointHit, this,
219 breakpoint->SetBreakpointKind("main-thread-checker-report");
220 SetBreakpointID(breakpoint->GetID());
225 void MainThreadCheckerRuntime::Deactivate() {
228 auto BID = GetBreakpointID();
229 if (BID == LLDB_INVALID_BREAK_ID)
232 if (ProcessSP process_sp = GetProcessSP()) {
233 process_sp->GetTarget().RemoveBreakpointByID(BID);
234 SetBreakpointID(LLDB_INVALID_BREAK_ID);
238 lldb::ThreadCollectionSP
239 MainThreadCheckerRuntime::GetBacktracesFromExtendedStopInfo(
240 StructuredData::ObjectSP info) {
241 ThreadCollectionSP threads;
242 threads.reset(new ThreadCollection());
244 ProcessSP process_sp = GetProcessSP();
246 if (info->GetObjectForDotSeparatedPath("instrumentation_class")
247 ->GetStringValue() != "MainThreadChecker")
250 std::vector<lldb::addr_t> PCs;
251 auto trace = info->GetObjectForDotSeparatedPath("trace")->GetAsArray();
252 trace->ForEach([&PCs](StructuredData::Object *PC) -> bool {
253 PCs.push_back(PC->GetAsInteger()->GetValue());
260 StructuredData::ObjectSP thread_id_obj =
261 info->GetObjectForDotSeparatedPath("tid");
262 tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0;
264 uint32_t stop_id = 0;
265 bool stop_id_is_valid = false;
266 HistoryThread *history_thread =
267 new HistoryThread(*process_sp, tid, PCs, stop_id, stop_id_is_valid);
268 ThreadSP new_thread_sp(history_thread);
270 // Save this in the Process' ExtendedThreadList so a strong pointer retains
272 process_sp->GetExtendedThreadList().AddThread(new_thread_sp);
273 threads->AddThread(new_thread_sp);