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 
32 LLDB_PLUGIN_DEFINE(InstrumentationRuntimeMainThreadChecker)
33 
34 InstrumentationRuntimeMainThreadChecker::
35     ~InstrumentationRuntimeMainThreadChecker() {
36   Deactivate();
37 }
38 
39 lldb::InstrumentationRuntimeSP
40 InstrumentationRuntimeMainThreadChecker::CreateInstance(
41     const lldb::ProcessSP &process_sp) {
42   return InstrumentationRuntimeSP(
43       new InstrumentationRuntimeMainThreadChecker(process_sp));
44 }
45 
46 void InstrumentationRuntimeMainThreadChecker::Initialize() {
47   PluginManager::RegisterPlugin(
48       GetPluginNameStatic(),
49       "MainThreadChecker instrumentation runtime plugin.", CreateInstance,
50       GetTypeStatic);
51 }
52 
53 void InstrumentationRuntimeMainThreadChecker::Terminate() {
54   PluginManager::UnregisterPlugin(CreateInstance);
55 }
56 
57 lldb_private::ConstString
58 InstrumentationRuntimeMainThreadChecker::GetPluginNameStatic() {
59   return ConstString("MainThreadChecker");
60 }
61 
62 lldb::InstrumentationRuntimeType
63 InstrumentationRuntimeMainThreadChecker::GetTypeStatic() {
64   return eInstrumentationRuntimeTypeMainThreadChecker;
65 }
66 
67 const RegularExpression &
68 InstrumentationRuntimeMainThreadChecker::GetPatternForRuntimeLibrary() {
69   static RegularExpression regex(llvm::StringRef("libMainThreadChecker.dylib"));
70   return regex;
71 }
72 
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
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->GetFrameCodeAddressForSymbolication();
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     lldb::addr_t PC = addr.GetLoadAddress(&target);
139     trace->AddItem(StructuredData::ObjectSP(new StructuredData::Integer(PC)));
140   }
141 
142   auto *d = new StructuredData::Dictionary();
143   auto dict_sp = StructuredData::ObjectSP(d);
144   d->AddStringItem("instrumentation_class", "MainThreadChecker");
145   d->AddStringItem("api_name", apiName);
146   d->AddStringItem("class_name", className);
147   d->AddStringItem("selector", selector);
148   d->AddStringItem("description",
149                    apiName + " must be used from main thread only");
150   d->AddIntegerItem("tid", thread_sp->GetIndexID());
151   d->AddItem("trace", trace_sp);
152   return dict_sp;
153 }
154 
155 bool InstrumentationRuntimeMainThreadChecker::NotifyBreakpointHit(
156     void *baton, StoppointCallbackContext *context, user_id_t break_id,
157     user_id_t break_loc_id) {
158   assert(baton && "null baton");
159   if (!baton)
160     return false; ///< false => resume execution.
161 
162   InstrumentationRuntimeMainThreadChecker *const instance =
163       static_cast<InstrumentationRuntimeMainThreadChecker *>(baton);
164 
165   ProcessSP process_sp = instance->GetProcessSP();
166   ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
167   if (!process_sp || !thread_sp ||
168       process_sp != context->exe_ctx_ref.GetProcessSP())
169     return false;
170 
171   if (process_sp->GetModIDRef().IsLastResumeForUserExpression())
172     return false;
173 
174   StructuredData::ObjectSP report =
175       instance->RetrieveReportData(context->exe_ctx_ref);
176 
177   if (report) {
178     std::string description = std::string(report->GetAsDictionary()
179                                               ->GetValueForKey("description")
180                                               ->GetAsString()
181                                               ->GetValue());
182     thread_sp->SetStopInfo(
183         InstrumentationRuntimeStopInfo::CreateStopReasonWithInstrumentationData(
184             *thread_sp, description, report));
185     return true;
186   }
187 
188   return false;
189 }
190 
191 void InstrumentationRuntimeMainThreadChecker::Activate() {
192   if (IsActive())
193     return;
194 
195   ProcessSP process_sp = GetProcessSP();
196   if (!process_sp)
197     return;
198 
199   ModuleSP runtime_module_sp = GetRuntimeModuleSP();
200 
201   ConstString symbol_name("__main_thread_checker_on_report");
202   const Symbol *symbol = runtime_module_sp->FindFirstSymbolWithNameAndType(
203       symbol_name, eSymbolTypeCode);
204 
205   if (symbol == nullptr)
206     return;
207 
208   if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
209     return;
210 
211   Target &target = process_sp->GetTarget();
212   addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
213 
214   if (symbol_address == LLDB_INVALID_ADDRESS)
215     return;
216 
217   Breakpoint *breakpoint =
218       process_sp->GetTarget()
219           .CreateBreakpoint(symbol_address, /*internal=*/true,
220                             /*hardware=*/false)
221           .get();
222   breakpoint->SetCallback(
223       InstrumentationRuntimeMainThreadChecker::NotifyBreakpointHit, this, true);
224   breakpoint->SetBreakpointKind("main-thread-checker-report");
225   SetBreakpointID(breakpoint->GetID());
226 
227   SetActive(true);
228 }
229 
230 void InstrumentationRuntimeMainThreadChecker::Deactivate() {
231   SetActive(false);
232 
233   auto BID = GetBreakpointID();
234   if (BID == LLDB_INVALID_BREAK_ID)
235     return;
236 
237   if (ProcessSP process_sp = GetProcessSP()) {
238     process_sp->GetTarget().RemoveBreakpointByID(BID);
239     SetBreakpointID(LLDB_INVALID_BREAK_ID);
240   }
241 }
242 
243 lldb::ThreadCollectionSP
244 InstrumentationRuntimeMainThreadChecker::GetBacktracesFromExtendedStopInfo(
245     StructuredData::ObjectSP info) {
246   ThreadCollectionSP threads;
247   threads = std::make_shared<ThreadCollection>();
248 
249   ProcessSP process_sp = GetProcessSP();
250 
251   if (info->GetObjectForDotSeparatedPath("instrumentation_class")
252           ->GetStringValue() != "MainThreadChecker")
253     return threads;
254 
255   std::vector<lldb::addr_t> PCs;
256   auto trace = info->GetObjectForDotSeparatedPath("trace")->GetAsArray();
257   trace->ForEach([&PCs](StructuredData::Object *PC) -> bool {
258     PCs.push_back(PC->GetAsInteger()->GetValue());
259     return true;
260   });
261 
262   if (PCs.empty())
263     return threads;
264 
265   StructuredData::ObjectSP thread_id_obj =
266       info->GetObjectForDotSeparatedPath("tid");
267   tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0;
268 
269   // We gather symbolication addresses above, so no need for HistoryThread to
270   // try to infer the call addresses.
271   bool pcs_are_call_addresses = true;
272   ThreadSP new_thread_sp = std::make_shared<HistoryThread>(
273       *process_sp, tid, PCs, pcs_are_call_addresses);
274 
275   // Save this in the Process' ExtendedThreadList so a strong pointer retains
276   // the object
277   process_sp->GetExtendedThreadList().AddThread(new_thread_sp);
278   threads->AddThread(new_thread_sp);
279 
280   return threads;
281 }
282