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::GetTypeStatic() {
60 }
61 
62 const RegularExpression &
63 InstrumentationRuntimeMainThreadChecker::GetPatternForRuntimeLibrary() {
64  static RegularExpression regex(llvm::StringRef("libMainThreadChecker.dylib"));
65  return regex;
66 }
67 
68 bool InstrumentationRuntimeMainThreadChecker::CheckIfRuntimeIsValid(
69  const lldb::ModuleSP module_sp) {
70  static ConstString test_sym("__main_thread_checker_on_report");
71  const Symbol *symbol =
72  module_sp->FindFirstSymbolWithNameAndType(test_sym, lldb::eSymbolTypeAny);
73  return symbol != nullptr;
74 }
75 
77 InstrumentationRuntimeMainThreadChecker::RetrieveReportData(
78  ExecutionContextRef exe_ctx_ref) {
79  ProcessSP process_sp = GetProcessSP();
80  if (!process_sp)
81  return StructuredData::ObjectSP();
82 
83  ThreadSP thread_sp = exe_ctx_ref.GetThreadSP();
84  StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
85  ModuleSP runtime_module_sp = GetRuntimeModuleSP();
86  Target &target = process_sp->GetTarget();
87 
88  if (!frame_sp)
89  return StructuredData::ObjectSP();
90 
91  RegisterContextSP regctx_sp = frame_sp->GetRegisterContext();
92  if (!regctx_sp)
93  return StructuredData::ObjectSP();
94 
95  const RegisterInfo *reginfo = regctx_sp->GetRegisterInfoByName("arg1");
96  if (!reginfo)
97  return StructuredData::ObjectSP();
98 
99  uint64_t apiname_ptr = regctx_sp->ReadRegisterAsUnsigned(reginfo, 0);
100  if (!apiname_ptr)
101  return StructuredData::ObjectSP();
102 
103  std::string apiName;
104  Status read_error;
105  target.ReadCStringFromMemory(apiname_ptr, apiName, read_error);
106  if (read_error.Fail())
107  return StructuredData::ObjectSP();
108 
109  std::string className;
110  std::string selector;
111  if (apiName.substr(0, 2) == "-[") {
112  size_t spacePos = apiName.find(' ');
113  if (spacePos != std::string::npos) {
114  className = apiName.substr(2, spacePos - 2);
115  selector = apiName.substr(spacePos + 1, apiName.length() - spacePos - 2);
116  }
117  }
118 
119  // Gather the PCs of the user frames in the backtrace.
121  auto trace_sp = StructuredData::ObjectSP(trace);
122  StackFrameSP responsible_frame;
123  for (unsigned I = 0; I < thread_sp->GetStackFrameCount(); ++I) {
124  StackFrameSP frame = thread_sp->GetStackFrameAtIndex(I);
125  Address addr = frame->GetFrameCodeAddressForSymbolication();
126  if (addr.GetModule() == runtime_module_sp) // Skip PCs from the runtime.
127  continue;
128 
129  // The first non-runtime frame is responsible for the bug.
130  if (!responsible_frame)
131  responsible_frame = frame;
132 
133  lldb::addr_t PC = addr.GetLoadAddress(&target);
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 
150 bool InstrumentationRuntimeMainThreadChecker::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 
158  static_cast<InstrumentationRuntimeMainThreadChecker *>(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 = std::string(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 
186 void InstrumentationRuntimeMainThreadChecker::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(
218  InstrumentationRuntimeMainThreadChecker::NotifyBreakpointHit, this, true);
219  breakpoint->SetBreakpointKind("main-thread-checker-report");
220  SetBreakpointID(breakpoint->GetID());
221 
222  SetActive(true);
223 }
224 
225 void InstrumentationRuntimeMainThreadChecker::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
239 InstrumentationRuntimeMainThreadChecker::GetBacktracesFromExtendedStopInfo(
241  ThreadCollectionSP threads;
242  threads = std::make_shared<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  // We gather symbolication addresses above, so no need for HistoryThread to
265  // try to infer the call addresses.
266  bool pcs_are_call_addresses = true;
267  ThreadSP new_thread_sp = std::make_shared<HistoryThread>(
268  *process_sp, tid, PCs, pcs_are_call_addresses);
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 }
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:345
lldb::eSymbolTypeCode
@ eSymbolTypeCode
Definition: lldb-enumerations.h:624
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:117
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:574
lldb_private::Breakpoint::SetBreakpointKind
void SetBreakpointKind(const char *kind)
Set the "kind" description for a breakpoint.
Definition: Breakpoint.h:447
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:351
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:467
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:368
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:621
lldb_private::Target::ReadCStringFromMemory
size_t ReadCStringFromMemory(const Address &addr, std::string &out_str, Status &error, bool force_live_memory=false)
Definition: Target.cpp:1857
InstrumentationRuntimeStopInfo.h
lldb_private::Status::Fail
bool Fail() const
Test for error condition.
Definition: Status.cpp:181
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:77
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:40
Thread.h
VariableList.h
LLDB_INVALID_BREAK_ID
#define LLDB_INVALID_BREAK_ID
Definition: lldb-defines.h:37
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:413
lldb_private::Address::GetLoadAddress
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition: Address.cpp:311
StopInfo.h
PluginManager.h
LLDB_INVALID_ADDRESS
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:74
lldb::user_id_t
uint64_t user_id_t
Definition: lldb-types.h:84
SymbolContext.h
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:458
lldb_private::InstrumentationRuntime::GetProcessSP
lldb::ProcessSP GetProcessSP()
Definition: InstrumentationRuntime.h:50
lldb_private::Address::GetModule
lldb::ModuleSP GetModule() const
Get accessor for the module for this address.
Definition: Address.cpp:283
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:567
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:80
lldb::tid_t
uint64_t tid_t
Definition: lldb-types.h:86
lldb::InstrumentationRuntimeType
InstrumentationRuntimeType
Definition: lldb-enumerations.h:485