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->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);
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 
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(
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 }
RegularExpression.h
lldb_private::StructuredData::Dictionary
Definition: StructuredData.h:352
lldb_private::RegularExpression
Definition: RegularExpression.h:18
lldb_private::StoppointCallbackContext
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
Definition: StoppointCallbackContext.h:26
lldb_private::Stoppoint::GetID
lldb::break_id_t GetID() const
Definition: Stoppoint.cpp:22
lldb_private::Address::IsValid
bool IsValid() const
Check if the object state is valid.
Definition: Address.h:332
lldb::eSymbolTypeCode
@ eSymbolTypeCode
Definition: lldb-enumerations.h:615
lldb_private::StructuredData::Array
Definition: StructuredData.h:165
lldb_private::Symbol
Definition: Symbol.h:20
lldb_private::Symbol::ValueIsAddress
bool ValueIsAddress() const
Definition: Symbol.cpp:118
lldb_private::StructuredData::Integer
Definition: StructuredData.h:285
lldb_private::ExecutionContextRef::GetThreadSP
lldb::ThreadSP GetThreadSP() const
Get accessor that creates a strong reference from the weak thread reference contained in this object.
Definition: ExecutionContext.cpp:581
lldb_private::Breakpoint::SetBreakpointKind
void SetBreakpointKind(const char *kind)
Set the "kind" description for a breakpoint.
Definition: Breakpoint.h:442
Module.h
lldb_private::StoppointCallbackContext::exe_ctx_ref
ExecutionContextRef exe_ctx_ref
Definition: StoppointCallbackContext.h:43
StoppointCallbackContext.h
SectionLoadList.h
HistoryThread.h
lldb_private::Target::CreateBreakpoint
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:329
lldb::addr_t
uint64_t addr_t
Definition: lldb-types.h:83
lldb_private::StructuredData::Object::GetAsInteger
Integer * GetAsInteger()
Definition: StructuredData.h:97
lldb_private::Target
Definition: Target.h:447
lldb_private::Address::GetOpcodeLoadAddress
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
lldb_private::StructuredData::Integer::GetValue
uint64_t GetValue()
Definition: StructuredData.h:294
Target.h
lldb_private::InstrumentationRuntimeMainThreadChecker
Definition: InstrumentationRuntimeMainThreadChecker.h:19
lldb::eSymbolTypeAny
@ eSymbolTypeAny
Definition: lldb-enumerations.h:612
InstrumentationRuntimeStopInfo.h
lldb_private::Status::Fail
bool Fail() const
Test for error condition.
Definition: Status.cpp:182
lldb_private::StructuredData::ObjectSP
std::shared_ptr< Object > ObjectSP
Definition: StructuredData.h:59
lldb_private::Symbol::GetAddressRef
Address & GetAddressRef()
Definition: Symbol.h:57
lldb_private::ConstString
Definition: ConstString.h:40
lldb_private::InstrumentationRuntimeMainThreadChecker::RetrieveReportData
StructuredData::ObjectSP RetrieveReportData(ExecutionContextRef exe_ctx_ref)
Definition: InstrumentationRuntimeMainThreadChecker.cpp:82
lldb_private::StructuredData::Array::AddItem
void AddItem(const ObjectSP &item)
Definition: StructuredData.h:276
string
string(SUBSTRING ${p} 10 -1 pStripped) if($
Definition: Plugins/CMakeLists.txt:38
Thread.h
VariableList.h
LLDB_INVALID_BREAK_ID
#define LLDB_INVALID_BREAK_ID
Definition: lldb-defines.h:49
Symbol.h
lldb_private::Status
Definition: Status.h:44
lldb::eInstrumentationRuntimeTypeMainThreadChecker
@ eInstrumentationRuntimeTypeMainThreadChecker
Definition: lldb-enumerations.h:489
InstrumentationRuntimeMainThreadChecker.h
lldb_private::Address
Definition: Address.h:59
lldb_private::Breakpoint::SetCallback
void SetCallback(BreakpointHitCallback callback, void *baton, bool is_synchronous=false)
Set the callback action invoked when the breakpoint is hit.
Definition: Breakpoint.cpp:429
lldb_private::Address::GetLoadAddress
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition: Address.cpp:310
StopInfo.h
PluginManager.h
LLDB_INVALID_ADDRESS
#define LLDB_INVALID_ADDRESS
Invalid value definitions.
Definition: lldb-defines.h:85
lldb::user_id_t
uint64_t user_id_t
Definition: lldb-types.h:84
SymbolContext.h
lldb_private::Target::ReadCStringFromMemory
size_t ReadCStringFromMemory(const Address &addr, std::string &out_str, Status &error)
Definition: Target.cpp:1838
lldb_private
A class that represents a running process on the host machine.
Definition: SBCommandInterpreterRunOptions.h:16
lldb_private::Breakpoint::GetTarget
Target & GetTarget()
Accessor for the breakpoint Target.
Definition: Breakpoint.h:453
lldb_private::InstrumentationRuntime::GetProcessSP
lldb::ProcessSP GetProcessSP()
Definition: InstrumentationRuntime.h:51
lldb_private::Address::GetModule
lldb::ModuleSP GetModule() const
Get accessor for the module for this address.
Definition: Address.cpp:282
LLDB_PLUGIN_DEFINE
#define LLDB_PLUGIN_DEFINE(PluginName)
Definition: PluginManager.h:31
lldb_private::ExecutionContextRef::GetProcessSP
lldb::ProcessSP GetProcessSP() const
Get accessor that creates a strong reference from the weak process reference contained in this object...
Definition: ExecutionContext.cpp:574
Variable.h
lldb_private::StructuredData::Object
Definition: StructuredData.h:70
lldb
Definition: SBAddress.h:15
RegisterContext.h
lldb_private::ExecutionContextRef
Execution context objects refer to objects in the execution of the program that is being debugged.
Definition: ExecutionContext.h:72
lldb_private::Breakpoint
General Outline: A breakpoint has four main parts, a filter, a resolver, the list of breakpoint locat...
Definition: Breakpoint.h:79
lldb::tid_t
uint64_t tid_t
Definition: lldb-types.h:86
lldb::InstrumentationRuntimeType
InstrumentationRuntimeType
Definition: lldb-enumerations.h:485