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 
9 #include "InstrumentationRuntimeMainThreadChecker.h"
10 
11 #include "Plugins/Process/Utility/HistoryThread.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 
27 #include <memory>
28 
29 using namespace lldb;
30 using namespace lldb_private;
31 
LLDB_PLUGIN_DEFINE(InstrumentationRuntimeMainThreadChecker)32 LLDB_PLUGIN_DEFINE(InstrumentationRuntimeMainThreadChecker)
33 
34 InstrumentationRuntimeMainThreadChecker::
35     ~InstrumentationRuntimeMainThreadChecker() {
36   Deactivate();
37 }
38 
39 lldb::InstrumentationRuntimeSP
CreateInstance(const lldb::ProcessSP & process_sp)40 InstrumentationRuntimeMainThreadChecker::CreateInstance(
41     const lldb::ProcessSP &process_sp) {
42   return InstrumentationRuntimeSP(
43       new InstrumentationRuntimeMainThreadChecker(process_sp));
44 }
45 
Initialize()46 void InstrumentationRuntimeMainThreadChecker::Initialize() {
47   PluginManager::RegisterPlugin(
48       GetPluginNameStatic(),
49       "MainThreadChecker instrumentation runtime plugin.", CreateInstance,
50       GetTypeStatic);
51 }
52 
Terminate()53 void InstrumentationRuntimeMainThreadChecker::Terminate() {
54   PluginManager::UnregisterPlugin(CreateInstance);
55 }
56 
57 lldb_private::ConstString
GetPluginNameStatic()58 InstrumentationRuntimeMainThreadChecker::GetPluginNameStatic() {
59   return ConstString("MainThreadChecker");
60 }
61 
62 lldb::InstrumentationRuntimeType
GetTypeStatic()63 InstrumentationRuntimeMainThreadChecker::GetTypeStatic() {
64   return eInstrumentationRuntimeTypeMainThreadChecker;
65 }
66 
67 const RegularExpression &
GetPatternForRuntimeLibrary()68 InstrumentationRuntimeMainThreadChecker::GetPatternForRuntimeLibrary() {
69   static RegularExpression regex(llvm::StringRef("libMainThreadChecker.dylib"));
70   return regex;
71 }
72 
CheckIfRuntimeIsValid(const lldb::ModuleSP module_sp)73 bool InstrumentationRuntimeMainThreadChecker::CheckIfRuntimeIsValid(
74     const lldb::ModuleSP module_sp) {
75   static ConstString test_sym("__main_thread_checker_on_report");
76   const Symbol *symbol =
77       module_sp->FindFirstSymbolWithNameAndType(test_sym, lldb::eSymbolTypeAny);
78   return symbol != nullptr;
79 }
80 
81 StructuredData::ObjectSP
RetrieveReportData(ExecutionContextRef exe_ctx_ref)82 InstrumentationRuntimeMainThreadChecker::RetrieveReportData(
83     ExecutionContextRef exe_ctx_ref) {
84   ProcessSP process_sp = GetProcessSP();
85   if (!process_sp)
86     return StructuredData::ObjectSP();
87 
88   ThreadSP thread_sp = exe_ctx_ref.GetThreadSP();
89   StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
90   ModuleSP runtime_module_sp = GetRuntimeModuleSP();
91   Target &target = process_sp->GetTarget();
92 
93   if (!frame_sp)
94     return StructuredData::ObjectSP();
95 
96   RegisterContextSP regctx_sp = frame_sp->GetRegisterContext();
97   if (!regctx_sp)
98     return StructuredData::ObjectSP();
99 
100   const RegisterInfo *reginfo = regctx_sp->GetRegisterInfoByName("arg1");
101   if (!reginfo)
102     return StructuredData::ObjectSP();
103 
104   uint64_t apiname_ptr = regctx_sp->ReadRegisterAsUnsigned(reginfo, 0);
105   if (!apiname_ptr)
106     return StructuredData::ObjectSP();
107 
108   std::string apiName = "";
109   Status read_error;
110   target.ReadCStringFromMemory(apiname_ptr, apiName, read_error);
111   if (read_error.Fail())
112     return StructuredData::ObjectSP();
113 
114   std::string className = "";
115   std::string selector = "";
116   if (apiName.substr(0, 2) == "-[") {
117     size_t spacePos = apiName.find(" ");
118     if (spacePos != std::string::npos) {
119       className = apiName.substr(2, spacePos - 2);
120       selector = apiName.substr(spacePos + 1, apiName.length() - spacePos - 2);
121     }
122   }
123 
124   // Gather the PCs of the user frames in the backtrace.
125   StructuredData::Array *trace = new StructuredData::Array();
126   auto trace_sp = StructuredData::ObjectSP(trace);
127   StackFrameSP responsible_frame;
128   for (unsigned I = 0; I < thread_sp->GetStackFrameCount(); ++I) {
129     StackFrameSP frame = thread_sp->GetStackFrameAtIndex(I);
130     Address addr = frame->GetFrameCodeAddress();
131     if (addr.GetModule() == runtime_module_sp) // Skip PCs from the runtime.
132       continue;
133 
134     // The first non-runtime frame is responsible for the bug.
135     if (!responsible_frame)
136       responsible_frame = frame;
137 
138     // First frame in stacktrace should point to a real PC, not return address.
139     if (I != 0 && trace->GetSize() == 0) {
140       addr.Slide(-1);
141     }
142 
143     lldb::addr_t PC = addr.GetLoadAddress(&target);
144     trace->AddItem(StructuredData::ObjectSP(new StructuredData::Integer(PC)));
145   }
146 
147   auto *d = new StructuredData::Dictionary();
148   auto dict_sp = StructuredData::ObjectSP(d);
149   d->AddStringItem("instrumentation_class", "MainThreadChecker");
150   d->AddStringItem("api_name", apiName);
151   d->AddStringItem("class_name", className);
152   d->AddStringItem("selector", selector);
153   d->AddStringItem("description",
154                    apiName + " must be used from main thread only");
155   d->AddIntegerItem("tid", thread_sp->GetIndexID());
156   d->AddItem("trace", trace_sp);
157   return dict_sp;
158 }
159 
NotifyBreakpointHit(void * baton,StoppointCallbackContext * context,user_id_t break_id,user_id_t break_loc_id)160 bool InstrumentationRuntimeMainThreadChecker::NotifyBreakpointHit(
161     void *baton, StoppointCallbackContext *context, user_id_t break_id,
162     user_id_t break_loc_id) {
163   assert(baton && "null baton");
164   if (!baton)
165     return false; ///< false => resume execution.
166 
167   InstrumentationRuntimeMainThreadChecker *const instance =
168       static_cast<InstrumentationRuntimeMainThreadChecker *>(baton);
169 
170   ProcessSP process_sp = instance->GetProcessSP();
171   ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
172   if (!process_sp || !thread_sp ||
173       process_sp != context->exe_ctx_ref.GetProcessSP())
174     return false;
175 
176   if (process_sp->GetModIDRef().IsLastResumeForUserExpression())
177     return false;
178 
179   StructuredData::ObjectSP report =
180       instance->RetrieveReportData(context->exe_ctx_ref);
181 
182   if (report) {
183     std::string description = std::string(report->GetAsDictionary()
184                                               ->GetValueForKey("description")
185                                               ->GetAsString()
186                                               ->GetValue());
187     thread_sp->SetStopInfo(
188         InstrumentationRuntimeStopInfo::CreateStopReasonWithInstrumentationData(
189             *thread_sp, description, report));
190     return true;
191   }
192 
193   return false;
194 }
195 
Activate()196 void InstrumentationRuntimeMainThreadChecker::Activate() {
197   if (IsActive())
198     return;
199 
200   ProcessSP process_sp = GetProcessSP();
201   if (!process_sp)
202     return;
203 
204   ModuleSP runtime_module_sp = GetRuntimeModuleSP();
205 
206   ConstString symbol_name("__main_thread_checker_on_report");
207   const Symbol *symbol = runtime_module_sp->FindFirstSymbolWithNameAndType(
208       symbol_name, eSymbolTypeCode);
209 
210   if (symbol == nullptr)
211     return;
212 
213   if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
214     return;
215 
216   Target &target = process_sp->GetTarget();
217   addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
218 
219   if (symbol_address == LLDB_INVALID_ADDRESS)
220     return;
221 
222   Breakpoint *breakpoint =
223       process_sp->GetTarget()
224           .CreateBreakpoint(symbol_address, /*internal=*/true,
225                             /*hardware=*/false)
226           .get();
227   breakpoint->SetCallback(
228       InstrumentationRuntimeMainThreadChecker::NotifyBreakpointHit, this, true);
229   breakpoint->SetBreakpointKind("main-thread-checker-report");
230   SetBreakpointID(breakpoint->GetID());
231 
232   SetActive(true);
233 }
234 
Deactivate()235 void InstrumentationRuntimeMainThreadChecker::Deactivate() {
236   SetActive(false);
237 
238   auto BID = GetBreakpointID();
239   if (BID == LLDB_INVALID_BREAK_ID)
240     return;
241 
242   if (ProcessSP process_sp = GetProcessSP()) {
243     process_sp->GetTarget().RemoveBreakpointByID(BID);
244     SetBreakpointID(LLDB_INVALID_BREAK_ID);
245   }
246 }
247 
248 lldb::ThreadCollectionSP
GetBacktracesFromExtendedStopInfo(StructuredData::ObjectSP info)249 InstrumentationRuntimeMainThreadChecker::GetBacktracesFromExtendedStopInfo(
250     StructuredData::ObjectSP info) {
251   ThreadCollectionSP threads;
252   threads = std::make_shared<ThreadCollection>();
253 
254   ProcessSP process_sp = GetProcessSP();
255 
256   if (info->GetObjectForDotSeparatedPath("instrumentation_class")
257           ->GetStringValue() != "MainThreadChecker")
258     return threads;
259 
260   std::vector<lldb::addr_t> PCs;
261   auto trace = info->GetObjectForDotSeparatedPath("trace")->GetAsArray();
262   trace->ForEach([&PCs](StructuredData::Object *PC) -> bool {
263     PCs.push_back(PC->GetAsInteger()->GetValue());
264     return true;
265   });
266 
267   if (PCs.empty())
268     return threads;
269 
270   StructuredData::ObjectSP thread_id_obj =
271       info->GetObjectForDotSeparatedPath("tid");
272   tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0;
273 
274   HistoryThread *history_thread = new HistoryThread(*process_sp, tid, PCs);
275   ThreadSP new_thread_sp(history_thread);
276 
277   // Save this in the Process' ExtendedThreadList so a strong pointer retains
278   // the object
279   process_sp->GetExtendedThreadList().AddThread(new_thread_sp);
280   threads->AddThread(new_thread_sp);
281 
282   return threads;
283 }
284