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"
17 #include "lldb/Symbol/Variable.h"
22 #include "lldb/Target/StopInfo.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Target/Thread.h"
26 
27 #include <memory>
28 
29 using namespace lldb;
30 using namespace lldb_private;
31 
33 
34 InstrumentationRuntimeMainThreadChecker::
35  ~InstrumentationRuntimeMainThreadChecker() {
36  Deactivate();
37 }
38 
39 lldb::InstrumentationRuntimeSP
40 InstrumentationRuntimeMainThreadChecker::CreateInstance(
41  const lldb::ProcessSP &process_sp) {
42  return InstrumentationRuntimeSP(
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 
58 InstrumentationRuntimeMainThreadChecker::GetPluginNameStatic() {
59  return ConstString("MainThreadChecker");
60 }
61 
63 InstrumentationRuntimeMainThreadChecker::GetTypeStatic() {
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 
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.
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);
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 
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 
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 
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 
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
249 InstrumentationRuntimeMainThreadChecker::GetBacktracesFromExtendedStopInfo(
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 }
Address & GetAddressRef()
Definition: Symbol.h:57
A class that represents a running process on the host machine.
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition: Address.cpp:310
General Outline: A breakpoint has four main parts, a filter, a resolver, the list of breakpoint locat...
Definition: Breakpoint.h:78
lldb::ProcessSP GetProcessSP() const
Get accessor that creates a strong reference from the weak process reference contained in this object...
void SetBreakpointKind(const char *kind)
Set the "kind" description for a breakpoint.
Definition: Breakpoint.h:441
Target & GetTarget()
Accessor for the breakpoint Target.
Definition: Breakpoint.h:452
void SetCallback(BreakpointHitCallback callback, void *baton, bool is_synchronous=false)
Set the callback action invoked when the breakpoint is hit.
Definition: Breakpoint.cpp:433
lldb::ThreadSP GetThreadSP() const
Get accessor that creates a strong reference from the weak thread reference contained in this object...
bool Slide(int64_t offset)
Definition: Address.h:436
#define LLDB_INVALID_ADDRESS
Invalid value definitions.
Definition: lldb-defines.h:85
uint64_t user_id_t
Definition: lldb-types.h:84
#define LLDB_PLUGIN_DEFINE(PluginName)
Definition: PluginManager.h:31
InstrumentationRuntimeType
lldb::break_id_t GetID() const
Definition: Stoppoint.cpp:22
uint64_t tid_t
Definition: lldb-types.h:86
lldb::addr_t GetOpcodeLoadAddress(Target *target, AddressClass addr_class=AddressClass::eInvalid) const
Get the load address as an opcode load address.
Definition: Address.cpp:367
bool ValueIsAddress() const
Definition: Symbol.cpp:118
Execution context objects refer to objects in the execution of the program that is being debugged...
bool IsValid() const
Check if the object state is valid.
Definition: Address.h:332
A section + offset based address class.
Definition: Address.h:59
A thread object representing a backtrace from a previous point in the process execution.
Definition: HistoryThread.h:33
uint64_t addr_t
Definition: lldb-types.h:83
A uniqued constant string class.
Definition: ConstString.h:40
lldb::ModuleSP GetModule() const
Get accessor for the module for this address.
Definition: Address.cpp:282
bool Fail() const
Test for error condition.
Definition: Status.cpp:182
Definition: SBAddress.h:15
std::shared_ptr< Object > ObjectSP
#define LLDB_INVALID_BREAK_ID
Definition: lldb-defines.h:49
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
size_t ReadCStringFromMemory(const Address &addr, std::string &out_str, Status &error)
Definition: Target.cpp:1808
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:323
StructuredData::ObjectSP RetrieveReportData(ExecutionContextRef exe_ctx_ref)
An error handling class.
Definition: Status.h:44