blob: 3c15db54662bc65803b3c41d8d46270aee1fe394 [file] [log] [blame]
Kuba Brecka6a831432016-03-23 15:36:22 +00001//===-- ThreadSanitizerRuntime.cpp ------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ThreadSanitizerRuntime.h"
11
12#include "lldb/Breakpoint/StoppointCallbackContext.h"
13#include "lldb/Core/Debugger.h"
14#include "lldb/Core/Module.h"
15#include "lldb/Core/ModuleList.h"
16#include "lldb/Core/RegularExpression.h"
17#include "lldb/Core/PluginInterface.h"
18#include "lldb/Core/PluginManager.h"
19#include "lldb/Core/Stream.h"
20#include "lldb/Core/StreamFile.h"
21#include "lldb/Core/ValueObject.h"
22#include "lldb/Expression/UserExpression.h"
23#include "lldb/Interpreter/CommandReturnObject.h"
24#include "lldb/Symbol/Symbol.h"
25#include "lldb/Symbol/SymbolContext.h"
Kuba Breckabcdce3f2016-04-28 15:27:10 +000026#include "lldb/Symbol/Variable.h"
27#include "lldb/Symbol/VariableList.h"
Kuba Brecka6a831432016-03-23 15:36:22 +000028#include "lldb/Target/InstrumentationRuntimeStopInfo.h"
Kuba Brecka1aad8fb2016-04-10 18:57:38 +000029#include "lldb/Target/SectionLoadList.h"
Kuba Brecka6a831432016-03-23 15:36:22 +000030#include "lldb/Target/StopInfo.h"
31#include "lldb/Target/Target.h"
32#include "lldb/Target/Thread.h"
Kuba Brecka1aad8fb2016-04-10 18:57:38 +000033#include "Plugins/Process/Utility/HistoryThread.h"
Kuba Brecka6a831432016-03-23 15:36:22 +000034
35using namespace lldb;
36using namespace lldb_private;
37
38lldb::InstrumentationRuntimeSP
39ThreadSanitizerRuntime::CreateInstance (const lldb::ProcessSP &process_sp)
40{
41 return InstrumentationRuntimeSP(new ThreadSanitizerRuntime(process_sp));
42}
43
44void
45ThreadSanitizerRuntime::Initialize()
46{
47 PluginManager::RegisterPlugin (GetPluginNameStatic(),
48 "ThreadSanitizer instrumentation runtime plugin.",
49 CreateInstance,
50 GetTypeStatic);
51}
52
53void
54ThreadSanitizerRuntime::Terminate()
55{
56 PluginManager::UnregisterPlugin (CreateInstance);
57}
58
59lldb_private::ConstString
60ThreadSanitizerRuntime::GetPluginNameStatic()
61{
62 return ConstString("ThreadSanitizer");
63}
64
65lldb::InstrumentationRuntimeType
66ThreadSanitizerRuntime::GetTypeStatic()
67{
68 return eInstrumentationRuntimeTypeThreadSanitizer;
69}
70
71ThreadSanitizerRuntime::ThreadSanitizerRuntime(const ProcessSP &process_sp) :
72m_is_active(false),
73m_runtime_module_wp(),
74m_process_wp(),
75m_breakpoint_id(0)
76{
77 if (process_sp)
78 m_process_wp = process_sp;
79}
80
81ThreadSanitizerRuntime::~ThreadSanitizerRuntime()
82{
83 Deactivate();
84}
85
86static bool
87ModuleContainsTSanRuntime(ModuleSP module_sp)
88{
89 static ConstString g_tsan_get_current_report("__tsan_get_current_report");
90 const Symbol* symbol = module_sp->FindFirstSymbolWithNameAndType(g_tsan_get_current_report, lldb::eSymbolTypeAny);
91 return symbol != nullptr;
92}
93
94void
95ThreadSanitizerRuntime::ModulesDidLoad(lldb_private::ModuleList &module_list)
96{
97 if (IsActive())
98 return;
99
100 if (GetRuntimeModuleSP()) {
101 Activate();
102 return;
103 }
104
105 module_list.ForEach ([this](const lldb::ModuleSP module_sp) -> bool
106 {
107 const FileSpec & file_spec = module_sp->GetFileSpec();
108 if (! file_spec)
109 return true; // Keep iterating through modules
110
111 llvm::StringRef module_basename(file_spec.GetFilename().GetStringRef());
112 if (module_sp->IsExecutable() || module_basename.startswith("libclang_rt.tsan_"))
113 {
114 if (ModuleContainsTSanRuntime(module_sp))
115 {
116 m_runtime_module_wp = module_sp;
117 Activate();
118 return false; // Stop iterating
119 }
120 }
121
122 return true; // Keep iterating through modules
123 });
124}
125
126bool
127ThreadSanitizerRuntime::IsActive()
128{
129 return m_is_active;
130}
131
132#define RETRIEVE_REPORT_DATA_FUNCTION_TIMEOUT_USEC 2*1000*1000
133
134const char *
135thread_sanitizer_retrieve_report_data_prefix = R"(
136extern "C"
137{
138 void *__tsan_get_current_report();
139 int __tsan_get_report_data(void *report, const char **description, int *count,
140 int *stack_count, int *mop_count, int *loc_count,
141 int *mutex_count, int *thread_count,
142 int *unique_tid_count, void **sleep_trace,
143 unsigned long trace_size);
144 int __tsan_get_report_stack(void *report, unsigned long idx, void **trace,
145 unsigned long trace_size);
146 int __tsan_get_report_mop(void *report, unsigned long idx, int *tid, void **addr,
147 int *size, int *write, int *atomic, void **trace,
148 unsigned long trace_size);
149 int __tsan_get_report_loc(void *report, unsigned long idx, const char **type,
150 void **addr, unsigned long *start, unsigned long *size, int *tid,
151 int *fd, int *suppressable, void **trace,
152 unsigned long trace_size);
153 int __tsan_get_report_mutex(void *report, unsigned long idx, unsigned long *mutex_id, void **addr,
154 int *destroyed, void **trace, unsigned long trace_size);
Kuba Brecka5b31c422016-04-22 10:40:14 +0000155 int __tsan_get_report_thread(void *report, unsigned long idx, int *tid, unsigned long *os_id,
Kuba Brecka6a831432016-03-23 15:36:22 +0000156 int *running, const char **name, int *parent_tid,
157 void **trace, unsigned long trace_size);
158 int __tsan_get_report_unique_tid(void *report, unsigned long idx, int *tid);
159}
160
161const int REPORT_TRACE_SIZE = 128;
162const int REPORT_ARRAY_SIZE = 4;
163
164struct data {
165 void *report;
166 const char *description;
167 int report_count;
168
169 void *sleep_trace[REPORT_TRACE_SIZE];
170
171 int stack_count;
172 struct {
173 int idx;
174 void *trace[REPORT_TRACE_SIZE];
175 } stacks[REPORT_ARRAY_SIZE];
176
177 int mop_count;
178 struct {
179 int idx;
180 int tid;
181 int size;
182 int write;
183 int atomic;
184 void *addr;
185 void *trace[REPORT_TRACE_SIZE];
186 } mops[REPORT_ARRAY_SIZE];
187
188 int loc_count;
189 struct {
190 int idx;
191 const char *type;
192 void *addr;
193 unsigned long start;
194 unsigned long size;
195 int tid;
196 int fd;
197 int suppressable;
198 void *trace[REPORT_TRACE_SIZE];
199 } locs[REPORT_ARRAY_SIZE];
200
201 int mutex_count;
202 struct {
203 int idx;
204 unsigned long mutex_id;
205 void *addr;
206 int destroyed;
207 void *trace[REPORT_TRACE_SIZE];
208 } mutexes[REPORT_ARRAY_SIZE];
209
210 int thread_count;
211 struct {
212 int idx;
213 int tid;
Kuba Brecka5b31c422016-04-22 10:40:14 +0000214 unsigned long os_id;
Kuba Brecka6a831432016-03-23 15:36:22 +0000215 int running;
216 const char *name;
217 int parent_tid;
218 void *trace[REPORT_TRACE_SIZE];
219 } threads[REPORT_ARRAY_SIZE];
220
221 int unique_tid_count;
222 struct {
223 int idx;
224 int tid;
225 } unique_tids[REPORT_ARRAY_SIZE];
226};
227)";
228
229const char *
230thread_sanitizer_retrieve_report_data_command = R"(
231data t = {0};
232
233t.report = __tsan_get_current_report();
234__tsan_get_report_data(t.report, &t.description, &t.report_count, &t.stack_count, &t.mop_count, &t.loc_count, &t.mutex_count, &t.thread_count, &t.unique_tid_count, t.sleep_trace, REPORT_TRACE_SIZE);
235
236if (t.stack_count > REPORT_ARRAY_SIZE) t.stack_count = REPORT_ARRAY_SIZE;
237for (int i = 0; i < t.stack_count; i++) {
238 t.stacks[i].idx = i;
239 __tsan_get_report_stack(t.report, i, t.stacks[i].trace, REPORT_TRACE_SIZE);
240}
241
242if (t.mop_count > REPORT_ARRAY_SIZE) t.mop_count = REPORT_ARRAY_SIZE;
243for (int i = 0; i < t.mop_count; i++) {
244 t.mops[i].idx = i;
245 __tsan_get_report_mop(t.report, i, &t.mops[i].tid, &t.mops[i].addr, &t.mops[i].size, &t.mops[i].write, &t.mops[i].atomic, t.mops[i].trace, REPORT_TRACE_SIZE);
246}
247
248if (t.loc_count > REPORT_ARRAY_SIZE) t.loc_count = REPORT_ARRAY_SIZE;
249for (int i = 0; i < t.loc_count; i++) {
250 t.locs[i].idx = i;
251 __tsan_get_report_loc(t.report, i, &t.locs[i].type, &t.locs[i].addr, &t.locs[i].start, &t.locs[i].size, &t.locs[i].tid, &t.locs[i].fd, &t.locs[i].suppressable, t.locs[i].trace, REPORT_TRACE_SIZE);
252}
253
254if (t.mutex_count > REPORT_ARRAY_SIZE) t.mutex_count = REPORT_ARRAY_SIZE;
255for (int i = 0; i < t.mutex_count; i++) {
256 t.mutexes[i].idx = i;
257 __tsan_get_report_mutex(t.report, i, &t.mutexes[i].mutex_id, &t.mutexes[i].addr, &t.mutexes[i].destroyed, t.mutexes[i].trace, REPORT_TRACE_SIZE);
258}
259
260if (t.thread_count > REPORT_ARRAY_SIZE) t.thread_count = REPORT_ARRAY_SIZE;
261for (int i = 0; i < t.thread_count; i++) {
262 t.threads[i].idx = i;
Kuba Brecka5b31c422016-04-22 10:40:14 +0000263 __tsan_get_report_thread(t.report, i, &t.threads[i].tid, &t.threads[i].os_id, &t.threads[i].running, &t.threads[i].name, &t.threads[i].parent_tid, t.threads[i].trace, REPORT_TRACE_SIZE);
Kuba Brecka6a831432016-03-23 15:36:22 +0000264}
265
Kuba Brecka058c3022016-03-30 10:50:24 +0000266if (t.unique_tid_count > REPORT_ARRAY_SIZE) t.unique_tid_count = REPORT_ARRAY_SIZE;
Kuba Brecka6a831432016-03-23 15:36:22 +0000267for (int i = 0; i < t.unique_tid_count; i++) {
268 t.unique_tids[i].idx = i;
269 __tsan_get_report_unique_tid(t.report, i, &t.unique_tids[i].tid);
270}
271
272t;
273)";
274
275static StructuredData::Array *
276CreateStackTrace(ValueObjectSP o, std::string trace_item_name = ".trace") {
277 StructuredData::Array *trace = new StructuredData::Array();
278 ValueObjectSP trace_value_object = o->GetValueForExpressionPath(trace_item_name.c_str());
279 for (int j = 0; j < 8; j++) {
280 addr_t trace_addr = trace_value_object->GetChildAtIndex(j, true)->GetValueAsUnsigned(0);
281 if (trace_addr == 0)
282 break;
283 trace->AddItem(StructuredData::ObjectSP(new StructuredData::Integer(trace_addr)));
284 }
285 return trace;
286}
287
288static StructuredData::Array *
289ConvertToStructuredArray(ValueObjectSP return_value_sp, std::string items_name, std::string count_name, std::function <void(ValueObjectSP o, StructuredData::Dictionary *dict)> const &callback)
290{
291 StructuredData::Array *array = new StructuredData::Array();
292 unsigned int count = return_value_sp->GetValueForExpressionPath(count_name.c_str())->GetValueAsUnsigned(0);
293 ValueObjectSP objects = return_value_sp->GetValueForExpressionPath(items_name.c_str());
Pavel Labath1b46a722016-03-30 09:42:59 +0000294 for (unsigned int i = 0; i < count; i++) {
Kuba Brecka6a831432016-03-23 15:36:22 +0000295 ValueObjectSP o = objects->GetChildAtIndex(i, true);
296 StructuredData::Dictionary *dict = new StructuredData::Dictionary();
297
298 callback(o, dict);
299
300 array->AddItem(StructuredData::ObjectSP(dict));
301 }
302 return array;
303}
304
305static std::string
306RetrieveString(ValueObjectSP return_value_sp, ProcessSP process_sp, std::string expression_path)
307{
308 addr_t ptr = return_value_sp->GetValueForExpressionPath(expression_path.c_str())->GetValueAsUnsigned(0);
309 std::string str;
310 Error error;
311 process_sp->ReadCStringFromMemory(ptr, str, error);
312 return str;
313}
314
Kuba Brecka5b31c422016-04-22 10:40:14 +0000315static void
316GetRenumberedThreadIds(ProcessSP process_sp, ValueObjectSP data, std::map<uint64_t, user_id_t> &thread_id_map)
317{
318 ConvertToStructuredArray(data, ".threads", ".thread_count", [process_sp, &thread_id_map] (ValueObjectSP o, StructuredData::Dictionary *dict) {
319 uint64_t thread_id = o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0);
320 uint64_t thread_os_id = o->GetValueForExpressionPath(".os_id")->GetValueAsUnsigned(0);
321 user_id_t lldb_user_id = 0;
322
323 bool can_update = true;
324 ThreadSP lldb_thread = process_sp->GetThreadList().FindThreadByID(thread_os_id, can_update);
325 if (lldb_thread) {
326 lldb_user_id = lldb_thread->GetIndexID();
327 } else {
328 // This isn't a live thread anymore. Ask process to assign a new Index ID (or return an old one if we've already seen this thread_os_id).
329 // It will also make sure that no new threads are assigned this Index ID.
330 lldb_user_id = process_sp->AssignIndexIDToThread(thread_os_id);
331 }
332
333 thread_id_map[thread_id] = lldb_user_id;
334 });
335}
336
337static user_id_t Renumber(uint64_t id, std::map<uint64_t, user_id_t> &thread_id_map) {
338 if (! thread_id_map.count(id))
339 return 0;
340
341 return thread_id_map[id];
342}
343
Kuba Brecka6a831432016-03-23 15:36:22 +0000344StructuredData::ObjectSP
345ThreadSanitizerRuntime::RetrieveReportData(ExecutionContextRef exe_ctx_ref)
346{
347 ProcessSP process_sp = GetProcessSP();
348 if (!process_sp)
349 return StructuredData::ObjectSP();
350
351 ThreadSP thread_sp = exe_ctx_ref.GetThreadSP();
352 StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
353
354 if (!frame_sp)
355 return StructuredData::ObjectSP();
356
357 EvaluateExpressionOptions options;
358 options.SetUnwindOnError(true);
359 options.SetTryAllThreads(true);
360 options.SetStopOthers(true);
361 options.SetIgnoreBreakpoints(true);
362 options.SetTimeoutUsec(RETRIEVE_REPORT_DATA_FUNCTION_TIMEOUT_USEC);
363 options.SetPrefix(thread_sanitizer_retrieve_report_data_prefix);
364
365 ValueObjectSP main_value;
366 ExecutionContext exe_ctx;
367 Error eval_error;
368 frame_sp->CalculateExecutionContext(exe_ctx);
369 ExpressionResults result = UserExpression::Evaluate (exe_ctx,
370 options,
371 thread_sanitizer_retrieve_report_data_command,
372 "",
373 main_value,
374 eval_error);
375 if (result != eExpressionCompleted) {
376 process_sp->GetTarget().GetDebugger().GetAsyncOutputStream()->Printf("Warning: Cannot evaluate ThreadSanitizer expression:\n%s\n", eval_error.AsCString());
377 return StructuredData::ObjectSP();
378 }
379
Kuba Brecka5b31c422016-04-22 10:40:14 +0000380 std::map<uint64_t, user_id_t> thread_id_map;
381 GetRenumberedThreadIds(process_sp, main_value, thread_id_map);
382
Kuba Brecka6a831432016-03-23 15:36:22 +0000383 StructuredData::Dictionary *dict = new StructuredData::Dictionary();
384 dict->AddStringItem("instrumentation_class", "ThreadSanitizer");
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000385 dict->AddStringItem("issue_type", RetrieveString(main_value, process_sp, ".description"));
Kuba Brecka6a831432016-03-23 15:36:22 +0000386 dict->AddIntegerItem("report_count", main_value->GetValueForExpressionPath(".report_count")->GetValueAsUnsigned(0));
387 dict->AddItem("sleep_trace", StructuredData::ObjectSP(CreateStackTrace(main_value, ".sleep_trace")));
388
389 StructuredData::Array *stacks = ConvertToStructuredArray(main_value, ".stacks", ".stack_count", [] (ValueObjectSP o, StructuredData::Dictionary *dict) {
390 dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
391 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
392 });
393 dict->AddItem("stacks", StructuredData::ObjectSP(stacks));
394
Kuba Brecka5b31c422016-04-22 10:40:14 +0000395 StructuredData::Array *mops = ConvertToStructuredArray(main_value, ".mops", ".mop_count", [&thread_id_map] (ValueObjectSP o, StructuredData::Dictionary *dict) {
Kuba Brecka6a831432016-03-23 15:36:22 +0000396 dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
Kuba Brecka5b31c422016-04-22 10:40:14 +0000397 dict->AddIntegerItem("thread_id", Renumber(o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0), thread_id_map));
Kuba Brecka6a831432016-03-23 15:36:22 +0000398 dict->AddIntegerItem("size", o->GetValueForExpressionPath(".size")->GetValueAsUnsigned(0));
399 dict->AddBooleanItem("is_write", o->GetValueForExpressionPath(".write")->GetValueAsUnsigned(0));
400 dict->AddBooleanItem("is_atomic", o->GetValueForExpressionPath(".atomic")->GetValueAsUnsigned(0));
401 dict->AddIntegerItem("address", o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
402 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
403 });
404 dict->AddItem("mops", StructuredData::ObjectSP(mops));
405
Kuba Brecka5b31c422016-04-22 10:40:14 +0000406 StructuredData::Array *locs = ConvertToStructuredArray(main_value, ".locs", ".loc_count", [process_sp, &thread_id_map] (ValueObjectSP o, StructuredData::Dictionary *dict) {
Kuba Brecka6a831432016-03-23 15:36:22 +0000407 dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
408 dict->AddStringItem("type", RetrieveString(o, process_sp, ".type"));
409 dict->AddIntegerItem("address", o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
410 dict->AddIntegerItem("start", o->GetValueForExpressionPath(".start")->GetValueAsUnsigned(0));
411 dict->AddIntegerItem("size", o->GetValueForExpressionPath(".size")->GetValueAsUnsigned(0));
Kuba Brecka5b31c422016-04-22 10:40:14 +0000412 dict->AddIntegerItem("thread_id", Renumber(o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0), thread_id_map));
Kuba Brecka6a831432016-03-23 15:36:22 +0000413 dict->AddIntegerItem("file_descriptor", o->GetValueForExpressionPath(".fd")->GetValueAsUnsigned(0));
414 dict->AddIntegerItem("suppressable", o->GetValueForExpressionPath(".suppressable")->GetValueAsUnsigned(0));
415 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
416 });
417 dict->AddItem("locs", StructuredData::ObjectSP(locs));
418
419 StructuredData::Array *mutexes = ConvertToStructuredArray(main_value, ".mutexes", ".mutex_count", [] (ValueObjectSP o, StructuredData::Dictionary *dict) {
420 dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
421 dict->AddIntegerItem("mutex_id", o->GetValueForExpressionPath(".mutex_id")->GetValueAsUnsigned(0));
422 dict->AddIntegerItem("address", o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
423 dict->AddIntegerItem("destroyed", o->GetValueForExpressionPath(".destroyed")->GetValueAsUnsigned(0));
424 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
425 });
426 dict->AddItem("mutexes", StructuredData::ObjectSP(mutexes));
427
Kuba Brecka5b31c422016-04-22 10:40:14 +0000428 StructuredData::Array *threads = ConvertToStructuredArray(main_value, ".threads", ".thread_count", [process_sp, &thread_id_map] (ValueObjectSP o, StructuredData::Dictionary *dict) {
Kuba Brecka6a831432016-03-23 15:36:22 +0000429 dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
Kuba Brecka5b31c422016-04-22 10:40:14 +0000430 dict->AddIntegerItem("thread_id", Renumber(o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0), thread_id_map));
431 dict->AddIntegerItem("thread_os_id", o->GetValueForExpressionPath(".os_id")->GetValueAsUnsigned(0));
Kuba Brecka6a831432016-03-23 15:36:22 +0000432 dict->AddIntegerItem("running", o->GetValueForExpressionPath(".running")->GetValueAsUnsigned(0));
433 dict->AddStringItem("name", RetrieveString(o, process_sp, ".name"));
Kuba Brecka5b31c422016-04-22 10:40:14 +0000434 dict->AddIntegerItem("parent_thread_id", Renumber(o->GetValueForExpressionPath(".parent_tid")->GetValueAsUnsigned(0), thread_id_map));
Kuba Brecka6a831432016-03-23 15:36:22 +0000435 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
436 });
437 dict->AddItem("threads", StructuredData::ObjectSP(threads));
438
Kuba Brecka5b31c422016-04-22 10:40:14 +0000439 StructuredData::Array *unique_tids = ConvertToStructuredArray(main_value, ".unique_tids", ".unique_tid_count", [&thread_id_map] (ValueObjectSP o, StructuredData::Dictionary *dict) {
Kuba Brecka6a831432016-03-23 15:36:22 +0000440 dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
Kuba Brecka5b31c422016-04-22 10:40:14 +0000441 dict->AddIntegerItem("tid", Renumber(o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0), thread_id_map));
Kuba Brecka6a831432016-03-23 15:36:22 +0000442 });
443 dict->AddItem("unique_tids", StructuredData::ObjectSP(unique_tids));
444
445 return StructuredData::ObjectSP(dict);
446}
447
448std::string
449ThreadSanitizerRuntime::FormatDescription(StructuredData::ObjectSP report)
450{
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000451 std::string description = report->GetAsDictionary()->GetValueForKey("issue_type")->GetAsString()->GetValue();
Kuba Brecka6a831432016-03-23 15:36:22 +0000452
453 if (description == "data-race") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000454 return "Data race";
Kuba Brecka6a831432016-03-23 15:36:22 +0000455 } else if (description == "data-race-vptr") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000456 return "Data race on C++ virtual pointer";
Kuba Brecka6a831432016-03-23 15:36:22 +0000457 } else if (description == "heap-use-after-free") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000458 return "Use of deallocated memory";
Kuba Brecka6a831432016-03-23 15:36:22 +0000459 } else if (description == "heap-use-after-free-vptr") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000460 return "Use of deallocated C++ virtual pointer";
Kuba Brecka6a831432016-03-23 15:36:22 +0000461 } else if (description == "thread-leak") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000462 return "Thread leak";
Kuba Brecka6a831432016-03-23 15:36:22 +0000463 } else if (description == "locked-mutex-destroy") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000464 return "Destruction of a locked mutex";
Kuba Brecka6a831432016-03-23 15:36:22 +0000465 } else if (description == "mutex-double-lock") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000466 return "Double lock of a mutex";
Kuba Brecka6a831432016-03-23 15:36:22 +0000467 } else if (description == "mutex-invalid-access") {
Kuba Brecka52ded802016-05-22 14:32:45 +0000468 return "Use of an uninitialized or destroyed mutex";
Kuba Brecka6a831432016-03-23 15:36:22 +0000469 } else if (description == "mutex-bad-unlock") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000470 return "Unlock of an unlocked mutex (or by a wrong thread)";
Kuba Brecka6a831432016-03-23 15:36:22 +0000471 } else if (description == "mutex-bad-read-lock") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000472 return "Read lock of a write locked mutex";
Kuba Brecka6a831432016-03-23 15:36:22 +0000473 } else if (description == "mutex-bad-read-unlock") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000474 return "Read unlock of a write locked mutex";
Kuba Brecka6a831432016-03-23 15:36:22 +0000475 } else if (description == "signal-unsafe-call") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000476 return "Signal-unsafe call inside a signal handler";
Kuba Brecka6a831432016-03-23 15:36:22 +0000477 } else if (description == "errno-in-signal-handler") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000478 return "Overwrite of errno in a signal handler";
Kuba Brecka6a831432016-03-23 15:36:22 +0000479 } else if (description == "lock-order-inversion") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000480 return "Lock order inversion (potential deadlock)";
Kuba Brecka6a831432016-03-23 15:36:22 +0000481 }
482
483 // for unknown report codes just show the code
484 return description;
485}
486
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000487static std::string
488Sprintf(const char *format, ...)
489{
490 StreamString s;
491 va_list args;
492 va_start (args, format);
493 s.PrintfVarArg(format, args);
494 va_end (args);
495 return s.GetString();
496}
497
498static std::string
499GetSymbolNameFromAddress(ProcessSP process_sp, addr_t addr)
500{
501 lldb_private::Address so_addr;
502 if (! process_sp->GetTarget().GetSectionLoadList().ResolveLoadAddress(addr, so_addr))
503 return "";
504
505 lldb_private::Symbol *symbol = so_addr.CalculateSymbolContextSymbol();
506 if (! symbol)
507 return "";
508
509 std::string sym_name = symbol->GetName().GetCString();
510 return sym_name;
511}
512
Kuba Breckabcdce3f2016-04-28 15:27:10 +0000513static void
514GetSymbolDeclarationFromAddress(ProcessSP process_sp, addr_t addr, Declaration &decl)
515{
516 lldb_private::Address so_addr;
517 if (! process_sp->GetTarget().GetSectionLoadList().ResolveLoadAddress(addr, so_addr))
518 return;
519
520 lldb_private::Symbol *symbol = so_addr.CalculateSymbolContextSymbol();
521 if (! symbol)
522 return;
523
524 ConstString sym_name = symbol->GetName();
525
526 ModuleSP module = symbol->CalculateSymbolContextModule();
527 if (! module)
528 return;
529
530 VariableList var_list;
531 module->FindGlobalVariables(sym_name, nullptr, true, 1U, var_list);
532 if (var_list.GetSize() < 1)
533 return;
534
535 VariableSP var = var_list.GetVariableAtIndex(0);
536 decl = var->GetDeclaration();
537}
538
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000539addr_t
540ThreadSanitizerRuntime::GetFirstNonInternalFramePc(StructuredData::ObjectSP trace)
541{
542 ProcessSP process_sp = GetProcessSP();
543 ModuleSP runtime_module_sp = GetRuntimeModuleSP();
544
545 addr_t result = 0;
546 trace->GetAsArray()->ForEach([process_sp, runtime_module_sp, &result] (StructuredData::Object *o) -> bool {
547 addr_t addr = o->GetIntegerValue();
548 lldb_private::Address so_addr;
549 if (! process_sp->GetTarget().GetSectionLoadList().ResolveLoadAddress(addr, so_addr))
550 return true;
551
552 if (so_addr.GetModule() == runtime_module_sp)
553 return true;
554
555 result = addr;
556 return false;
557 });
558
559 return result;
560}
561
562std::string
563ThreadSanitizerRuntime::GenerateSummary(StructuredData::ObjectSP report)
564{
565 ProcessSP process_sp = GetProcessSP();
566
567 std::string summary = report->GetAsDictionary()->GetValueForKey("description")->GetAsString()->GetValue();
568 addr_t pc = 0;
569 if (report->GetAsDictionary()->GetValueForKey("mops")->GetAsArray()->GetSize() > 0)
570 pc = GetFirstNonInternalFramePc(report->GetAsDictionary()->GetValueForKey("mops")->GetAsArray()->GetItemAtIndex(0)->GetAsDictionary()->GetValueForKey("trace"));
571
572 if (report->GetAsDictionary()->GetValueForKey("stacks")->GetAsArray()->GetSize() > 0)
573 pc = GetFirstNonInternalFramePc(report->GetAsDictionary()->GetValueForKey("stacks")->GetAsArray()->GetItemAtIndex(0)->GetAsDictionary()->GetValueForKey("trace"));
574
575 if (pc != 0) {
576 summary = summary + " in " + GetSymbolNameFromAddress(process_sp, pc);
577 }
578
579 if (report->GetAsDictionary()->GetValueForKey("locs")->GetAsArray()->GetSize() > 0) {
580 StructuredData::ObjectSP loc = report->GetAsDictionary()->GetValueForKey("locs")->GetAsArray()->GetItemAtIndex(0);
581 addr_t addr = loc->GetAsDictionary()->GetValueForKey("address")->GetAsInteger()->GetValue();
582 if (addr == 0)
583 addr = loc->GetAsDictionary()->GetValueForKey("start")->GetAsInteger()->GetValue();
584
585 if (addr != 0) {
586 summary = summary + " at " + Sprintf("0x%llx", addr);
587 } else {
588 int fd = loc->GetAsDictionary()->GetValueForKey("file_descriptor")->GetAsInteger()->GetValue();
589 if (fd != 0) {
590 summary = summary + " on file descriptor " + Sprintf("%d", fd);
591 }
592 }
593 }
594
595 return summary;
596}
597
598addr_t
599ThreadSanitizerRuntime::GetMainRacyAddress(StructuredData::ObjectSP report)
600{
601 addr_t result = (addr_t)-1;
602
603 report->GetObjectForDotSeparatedPath("mops")->GetAsArray()->ForEach([&result] (StructuredData::Object *o) -> bool {
604 addr_t addr = o->GetObjectForDotSeparatedPath("address")->GetIntegerValue();
605 if (addr < result) result = addr;
606 return true;
607 });
608
609 return (result == (addr_t)-1) ? 0 : result;
610}
611
612std::string
Kuba Breckabcdce3f2016-04-28 15:27:10 +0000613ThreadSanitizerRuntime::GetLocationDescription(StructuredData::ObjectSP report, std::string &filename, uint32_t &line)
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000614{
615 std::string result = "";
616
617 ProcessSP process_sp = GetProcessSP();
618
619 if (report->GetAsDictionary()->GetValueForKey("locs")->GetAsArray()->GetSize() > 0) {
620 StructuredData::ObjectSP loc = report->GetAsDictionary()->GetValueForKey("locs")->GetAsArray()->GetItemAtIndex(0);
621 std::string type = loc->GetAsDictionary()->GetValueForKey("type")->GetStringValue();
622 if (type == "global") {
623 addr_t addr = loc->GetAsDictionary()->GetValueForKey("address")->GetAsInteger()->GetValue();
624 std::string global_name = GetSymbolNameFromAddress(process_sp, addr);
625 result = Sprintf("Location is a global '%s'", global_name.c_str());
Kuba Breckabcdce3f2016-04-28 15:27:10 +0000626
627 Declaration decl;
628 GetSymbolDeclarationFromAddress(process_sp, addr, decl);
629 if (decl.GetFile()) {
630 filename = decl.GetFile().GetPath();
631 line = decl.GetLine();
632 }
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000633 } else if (type == "heap") {
634 addr_t addr = loc->GetAsDictionary()->GetValueForKey("start")->GetAsInteger()->GetValue();
635 long size = loc->GetAsDictionary()->GetValueForKey("size")->GetAsInteger()->GetValue();
636 result = Sprintf("Location is a %ld-byte heap object at 0x%llx", size, addr);
637 } else if (type == "stack") {
638 int tid = loc->GetAsDictionary()->GetValueForKey("thread_id")->GetAsInteger()->GetValue();
Kuba Brecka5c7b3632016-05-01 11:26:06 +0000639 result = Sprintf("Location is stack of Thread %d", tid);
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000640 } else if (type == "tls") {
641 int tid = loc->GetAsDictionary()->GetValueForKey("thread_id")->GetAsInteger()->GetValue();
Kuba Brecka5c7b3632016-05-01 11:26:06 +0000642 result = Sprintf("Location is TLS of Thread %d", tid);
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000643 } else if (type == "fd") {
644 int fd = loc->GetAsDictionary()->GetValueForKey("file_descriptor")->GetAsInteger()->GetValue();
645 result = Sprintf("Location is file descriptor %d", fd);
646 }
647 }
648
649 return result;
650}
651
Kuba Brecka6a831432016-03-23 15:36:22 +0000652bool
653ThreadSanitizerRuntime::NotifyBreakpointHit(void *baton, StoppointCallbackContext *context, user_id_t break_id, user_id_t break_loc_id)
654{
655 assert (baton && "null baton");
656 if (!baton)
657 return false;
658
659 ThreadSanitizerRuntime *const instance = static_cast<ThreadSanitizerRuntime*>(baton);
660
661 StructuredData::ObjectSP report = instance->RetrieveReportData(context->exe_ctx_ref);
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000662 std::string stop_reason_description;
Kuba Brecka6a831432016-03-23 15:36:22 +0000663 if (report) {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000664 std::string issue_description = instance->FormatDescription(report);
665 report->GetAsDictionary()->AddStringItem("description", issue_description);
666 stop_reason_description = issue_description + " detected";
667 report->GetAsDictionary()->AddStringItem("stop_description", stop_reason_description);
668 std::string summary = instance->GenerateSummary(report);
669 report->GetAsDictionary()->AddStringItem("summary", summary);
670 addr_t main_address = instance->GetMainRacyAddress(report);
671 report->GetAsDictionary()->AddIntegerItem("memory_address", main_address);
Kuba Breckabcdce3f2016-04-28 15:27:10 +0000672
673 std::string location_filename = "";
674 uint32_t location_line = 0;
675 std::string location_description = instance->GetLocationDescription(report, location_filename, location_line);
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000676 report->GetAsDictionary()->AddStringItem("location_description", location_description);
Kuba Breckabcdce3f2016-04-28 15:27:10 +0000677 if (location_filename != "") {
678 report->GetAsDictionary()->AddStringItem("location_filename", location_filename);
679 report->GetAsDictionary()->AddIntegerItem("location_line", location_line);
680 }
Kuba Brecka6a831432016-03-23 15:36:22 +0000681 }
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000682
Kuba Brecka6a831432016-03-23 15:36:22 +0000683 ProcessSP process_sp = instance->GetProcessSP();
684 // Make sure this is the right process
685 if (process_sp && process_sp == context->exe_ctx_ref.GetProcessSP())
686 {
687 ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
688 if (thread_sp)
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000689 thread_sp->SetStopInfo(InstrumentationRuntimeStopInfo::CreateStopReasonWithInstrumentationData(*thread_sp, stop_reason_description.c_str(), report));
Kuba Brecka6a831432016-03-23 15:36:22 +0000690
691 StreamFileSP stream_sp (process_sp->GetTarget().GetDebugger().GetOutputFile());
692 if (stream_sp)
693 {
694 stream_sp->Printf ("ThreadSanitizer report breakpoint hit. Use 'thread info -s' to get extended information about the report.\n");
695 }
696 return true; // Return true to stop the target
697 }
698 else
699 return false; // Let target run
700}
701
702void
703ThreadSanitizerRuntime::Activate()
704{
705 if (m_is_active)
706 return;
707
708 ProcessSP process_sp = GetProcessSP();
709 if (!process_sp)
710 return;
711
712 ConstString symbol_name ("__tsan_on_report");
713 const Symbol *symbol = GetRuntimeModuleSP()->FindFirstSymbolWithNameAndType (symbol_name, eSymbolTypeCode);
714
715 if (symbol == NULL)
716 return;
717
718 if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
719 return;
720
721 Target &target = process_sp->GetTarget();
722 addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
723
724 if (symbol_address == LLDB_INVALID_ADDRESS)
725 return;
726
727 bool internal = true;
728 bool hardware = false;
729 Breakpoint *breakpoint = process_sp->GetTarget().CreateBreakpoint(symbol_address, internal, hardware).get();
730 breakpoint->SetCallback (ThreadSanitizerRuntime::NotifyBreakpointHit, this, true);
731 breakpoint->SetBreakpointKind ("thread-sanitizer-report");
732 m_breakpoint_id = breakpoint->GetID();
733
734 StreamFileSP stream_sp (process_sp->GetTarget().GetDebugger().GetOutputFile());
735 if (stream_sp)
736 {
737 stream_sp->Printf ("ThreadSanitizer debugger support is active.\n");
738 }
739
740 m_is_active = true;
741}
742
743void
744ThreadSanitizerRuntime::Deactivate()
745{
746 if (m_breakpoint_id != LLDB_INVALID_BREAK_ID)
747 {
748 ProcessSP process_sp = GetProcessSP();
749 if (process_sp)
750 {
751 process_sp->GetTarget().RemoveBreakpointByID(m_breakpoint_id);
752 m_breakpoint_id = LLDB_INVALID_BREAK_ID;
753 }
754 }
755 m_is_active = false;
756}
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000757
758static std::string
759GenerateThreadName(std::string path, StructuredData::Object *o) {
760 std::string result = "additional information";
761
762 if (path == "mops") {
763 int size = o->GetObjectForDotSeparatedPath("size")->GetIntegerValue();
764 int thread_id = o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
765 bool is_write = o->GetObjectForDotSeparatedPath("is_write")->GetBooleanValue();
766 bool is_atomic = o->GetObjectForDotSeparatedPath("is_atomic")->GetBooleanValue();
767 addr_t addr = o->GetObjectForDotSeparatedPath("address")->GetIntegerValue();
768
Kuba Brecka5c7b3632016-05-01 11:26:06 +0000769 result = Sprintf("%s%s of size %d at 0x%llx by Thread %d", is_atomic ? "atomic " : "", is_write ? "write" : "read", size, addr, thread_id);
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000770 }
771
772 if (path == "threads") {
773 int thread_id = o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
Kuba Brecka5c7b3632016-05-01 11:26:06 +0000774 result = Sprintf("Thread %d created", thread_id);
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000775 }
776
777 if (path == "locs") {
778 std::string type = o->GetAsDictionary()->GetValueForKey("type")->GetStringValue();
779 int thread_id = o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
780 int fd = o->GetObjectForDotSeparatedPath("file_descriptor")->GetIntegerValue();
781 if (type == "heap") {
Kuba Brecka5c7b3632016-05-01 11:26:06 +0000782 result = Sprintf("Heap block allocated by Thread %d", thread_id);
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000783 } else if (type == "fd") {
Kuba Brecka5c7b3632016-05-01 11:26:06 +0000784 result = Sprintf("File descriptor %d created by Thread %t", fd, thread_id);
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000785 }
786 }
787
788 if (path == "mutexes") {
789 int mutex_id = o->GetObjectForDotSeparatedPath("mutex_id")->GetIntegerValue();
790
Kuba Brecka5c7b3632016-05-01 11:26:06 +0000791 result = Sprintf("Mutex M%d created", mutex_id);
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000792 }
793
794 if (path == "stacks") {
795 result = "happened at";
796 }
797
798 result[0] = toupper(result[0]);
799
800 return result;
801}
802
803static void
804AddThreadsForPath(std::string path, ThreadCollectionSP threads, ProcessSP process_sp, StructuredData::ObjectSP info)
805{
806 info->GetObjectForDotSeparatedPath(path)->GetAsArray()->ForEach([process_sp, threads, path] (StructuredData::Object *o) -> bool {
807 std::vector<lldb::addr_t> pcs;
808 o->GetObjectForDotSeparatedPath("trace")->GetAsArray()->ForEach([&pcs] (StructuredData::Object *pc) -> bool {
809 pcs.push_back(pc->GetAsInteger()->GetValue());
810 return true;
811 });
812
813 if (pcs.size() == 0)
814 return true;
815
Kuba Brecka5b31c422016-04-22 10:40:14 +0000816 StructuredData::ObjectSP thread_id_obj = o->GetObjectForDotSeparatedPath("thread_os_id");
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000817 tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0;
818
819 uint32_t stop_id = 0;
820 bool stop_id_is_valid = false;
821 HistoryThread *history_thread = new HistoryThread(*process_sp, tid, pcs, stop_id, stop_id_is_valid);
822 ThreadSP new_thread_sp(history_thread);
823 new_thread_sp->SetName(GenerateThreadName(path, o).c_str());
824
825 // Save this in the Process' ExtendedThreadList so a strong pointer retains the object
826 process_sp->GetExtendedThreadList().AddThread(new_thread_sp);
827 threads->AddThread(new_thread_sp);
828
829 return true;
830 });
831}
832
833lldb::ThreadCollectionSP
834ThreadSanitizerRuntime::GetBacktracesFromExtendedStopInfo(StructuredData::ObjectSP info)
835{
836 ThreadCollectionSP threads;
837 threads.reset(new ThreadCollection());
838
839 if (info->GetObjectForDotSeparatedPath("instrumentation_class")->GetStringValue() != "ThreadSanitizer")
840 return threads;
841
842 ProcessSP process_sp = GetProcessSP();
843
844 AddThreadsForPath("stacks", threads, process_sp, info);
845 AddThreadsForPath("mops", threads, process_sp, info);
846 AddThreadsForPath("locs", threads, process_sp, info);
847 AddThreadsForPath("mutexes", threads, process_sp, info);
848 AddThreadsForPath("threads", threads, process_sp, info);
849
850 return threads;
851}