Coverage Report

Created: 2023-09-21 18:56

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