1 //===-- MainThreadCheckerRuntime.cpp ----------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "MainThreadCheckerRuntime.h"
11 
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"
27 
28 using namespace lldb;
29 using namespace lldb_private;
30 
~MainThreadCheckerRuntime()31 MainThreadCheckerRuntime::~MainThreadCheckerRuntime() {
32   Deactivate();
33 }
34 
35 lldb::InstrumentationRuntimeSP
CreateInstance(const lldb::ProcessSP & process_sp)36 MainThreadCheckerRuntime::CreateInstance(const lldb::ProcessSP &process_sp) {
37   return InstrumentationRuntimeSP(new MainThreadCheckerRuntime(process_sp));
38 }
39 
Initialize()40 void MainThreadCheckerRuntime::Initialize() {
41   PluginManager::RegisterPlugin(
42       GetPluginNameStatic(), "MainThreadChecker instrumentation runtime plugin.",
43       CreateInstance, GetTypeStatic);
44 }
45 
Terminate()46 void MainThreadCheckerRuntime::Terminate() {
47   PluginManager::UnregisterPlugin(CreateInstance);
48 }
49 
GetPluginNameStatic()50 lldb_private::ConstString MainThreadCheckerRuntime::GetPluginNameStatic() {
51   return ConstString("MainThreadChecker");
52 }
53 
GetTypeStatic()54 lldb::InstrumentationRuntimeType MainThreadCheckerRuntime::GetTypeStatic() {
55   return eInstrumentationRuntimeTypeMainThreadChecker;
56 }
57 
58 const RegularExpression &
GetPatternForRuntimeLibrary()59 MainThreadCheckerRuntime::GetPatternForRuntimeLibrary() {
60   static RegularExpression regex(llvm::StringRef("libMainThreadChecker.dylib"));
61   return regex;
62 }
63 
CheckIfRuntimeIsValid(const lldb::ModuleSP module_sp)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;
70 }
71 
72 StructuredData::ObjectSP
RetrieveReportData(ExecutionContextRef exe_ctx_ref)73 MainThreadCheckerRuntime::RetrieveReportData(ExecutionContextRef exe_ctx_ref) {
74   ProcessSP process_sp = GetProcessSP();
75   if (!process_sp)
76     return StructuredData::ObjectSP();
77 
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();
82 
83   if (!frame_sp)
84     return StructuredData::ObjectSP();
85 
86   RegisterContextSP regctx_sp = frame_sp->GetRegisterContext();
87   if (!regctx_sp)
88     return StructuredData::ObjectSP();
89 
90   const RegisterInfo *reginfo = regctx_sp->GetRegisterInfoByName("arg1");
91   if (!reginfo)
92     return StructuredData::ObjectSP();
93 
94   uint64_t apiname_ptr = regctx_sp->ReadRegisterAsUnsigned(reginfo, 0);
95   if (!apiname_ptr)
96     return StructuredData::ObjectSP();
97 
98   std::string apiName = "";
99   Status read_error;
100   target.ReadCStringFromMemory(apiname_ptr, apiName, read_error);
101   if (read_error.Fail())
102     return StructuredData::ObjectSP();
103 
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);
111     }
112   }
113 
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.
122       continue;
123 
124     // The first non-runtime frame is responsible for the bug.
125     if (!responsible_frame)
126       responsible_frame = frame;
127 
128     // First frame in stacktrace should point to a real PC, not return address.
129     if (I != 0 && trace->GetSize() == 0) {
130       addr.Slide(-1);
131     }
132 
133     lldb::addr_t PC = addr.GetLoadAddress(&target);
134     trace->AddItem(StructuredData::ObjectSP(new StructuredData::Integer(PC)));
135   }
136 
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);
147   return dict_sp;
148 }
149 
NotifyBreakpointHit(void * baton,StoppointCallbackContext * context,user_id_t break_id,user_id_t break_loc_id)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");
154   if (!baton)
155     return false; //< false => resume execution.
156 
157   MainThreadCheckerRuntime *const instance =
158       static_cast<MainThreadCheckerRuntime *>(baton);
159 
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())
164     return false;
165 
166   if (process_sp->GetModIDRef().IsLastResumeForUserExpression())
167     return false;
168 
169   StructuredData::ObjectSP report =
170       instance->RetrieveReportData(context->exe_ctx_ref);
171 
172   if (report) {
173     std::string description = report->GetAsDictionary()
174                                 ->GetValueForKey("description")
175                                 ->GetAsString()
176                                 ->GetValue();
177     thread_sp->SetStopInfo(
178         InstrumentationRuntimeStopInfo::CreateStopReasonWithInstrumentationData(
179             *thread_sp, description, report));
180     return true;
181   }
182 
183   return false;
184 }
185 
Activate()186 void MainThreadCheckerRuntime::Activate() {
187   if (IsActive())
188     return;
189 
190   ProcessSP process_sp = GetProcessSP();
191   if (!process_sp)
192     return;
193 
194   ModuleSP runtime_module_sp = GetRuntimeModuleSP();
195 
196   ConstString symbol_name("__main_thread_checker_on_report");
197   const Symbol *symbol = runtime_module_sp->FindFirstSymbolWithNameAndType(
198       symbol_name, eSymbolTypeCode);
199 
200   if (symbol == nullptr)
201     return;
202 
203   if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
204     return;
205 
206   Target &target = process_sp->GetTarget();
207   addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
208 
209   if (symbol_address == LLDB_INVALID_ADDRESS)
210     return;
211 
212   Breakpoint *breakpoint =
213       process_sp->GetTarget()
214           .CreateBreakpoint(symbol_address, /*internal=*/true,
215                             /*hardware=*/false)
216           .get();
217   breakpoint->SetCallback(MainThreadCheckerRuntime::NotifyBreakpointHit, this,
218                           true);
219   breakpoint->SetBreakpointKind("main-thread-checker-report");
220   SetBreakpointID(breakpoint->GetID());
221 
222   SetActive(true);
223 }
224 
Deactivate()225 void MainThreadCheckerRuntime::Deactivate() {
226   SetActive(false);
227 
228   auto BID = GetBreakpointID();
229   if (BID == LLDB_INVALID_BREAK_ID)
230     return;
231 
232   if (ProcessSP process_sp = GetProcessSP()) {
233     process_sp->GetTarget().RemoveBreakpointByID(BID);
234     SetBreakpointID(LLDB_INVALID_BREAK_ID);
235   }
236 }
237 
238 lldb::ThreadCollectionSP
GetBacktracesFromExtendedStopInfo(StructuredData::ObjectSP info)239 MainThreadCheckerRuntime::GetBacktracesFromExtendedStopInfo(
240     StructuredData::ObjectSP info) {
241   ThreadCollectionSP threads;
242   threads.reset(new ThreadCollection());
243 
244   ProcessSP process_sp = GetProcessSP();
245 
246   if (info->GetObjectForDotSeparatedPath("instrumentation_class")
247       ->GetStringValue() != "MainThreadChecker")
248     return threads;
249 
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());
254     return true;
255   });
256 
257   if (PCs.empty())
258     return threads;
259 
260   StructuredData::ObjectSP thread_id_obj =
261       info->GetObjectForDotSeparatedPath("tid");
262   tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0;
263 
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);
269 
270   // Save this in the Process' ExtendedThreadList so a strong pointer retains
271   // the object
272   process_sp->GetExtendedThreadList().AddThread(new_thread_sp);
273   threads->AddThread(new_thread_sp);
274 
275   return threads;
276 }
277