blob: beac52679144dacd04a8cc5f372cb7bc52ed5577 [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"
26#include "lldb/Target/InstrumentationRuntimeStopInfo.h"
Kuba Brecka1aad8fb2016-04-10 18:57:38 +000027#include "lldb/Target/SectionLoadList.h"
Kuba Brecka6a831432016-03-23 15:36:22 +000028#include "lldb/Target/StopInfo.h"
29#include "lldb/Target/Target.h"
30#include "lldb/Target/Thread.h"
Kuba Brecka1aad8fb2016-04-10 18:57:38 +000031#include "Plugins/Process/Utility/HistoryThread.h"
Kuba Brecka6a831432016-03-23 15:36:22 +000032
33using namespace lldb;
34using namespace lldb_private;
35
36lldb::InstrumentationRuntimeSP
37ThreadSanitizerRuntime::CreateInstance (const lldb::ProcessSP &process_sp)
38{
39 return InstrumentationRuntimeSP(new ThreadSanitizerRuntime(process_sp));
40}
41
42void
43ThreadSanitizerRuntime::Initialize()
44{
45 PluginManager::RegisterPlugin (GetPluginNameStatic(),
46 "ThreadSanitizer instrumentation runtime plugin.",
47 CreateInstance,
48 GetTypeStatic);
49}
50
51void
52ThreadSanitizerRuntime::Terminate()
53{
54 PluginManager::UnregisterPlugin (CreateInstance);
55}
56
57lldb_private::ConstString
58ThreadSanitizerRuntime::GetPluginNameStatic()
59{
60 return ConstString("ThreadSanitizer");
61}
62
63lldb::InstrumentationRuntimeType
64ThreadSanitizerRuntime::GetTypeStatic()
65{
66 return eInstrumentationRuntimeTypeThreadSanitizer;
67}
68
69ThreadSanitizerRuntime::ThreadSanitizerRuntime(const ProcessSP &process_sp) :
70m_is_active(false),
71m_runtime_module_wp(),
72m_process_wp(),
73m_breakpoint_id(0)
74{
75 if (process_sp)
76 m_process_wp = process_sp;
77}
78
79ThreadSanitizerRuntime::~ThreadSanitizerRuntime()
80{
81 Deactivate();
82}
83
84static bool
85ModuleContainsTSanRuntime(ModuleSP module_sp)
86{
87 static ConstString g_tsan_get_current_report("__tsan_get_current_report");
88 const Symbol* symbol = module_sp->FindFirstSymbolWithNameAndType(g_tsan_get_current_report, lldb::eSymbolTypeAny);
89 return symbol != nullptr;
90}
91
92void
93ThreadSanitizerRuntime::ModulesDidLoad(lldb_private::ModuleList &module_list)
94{
95 if (IsActive())
96 return;
97
98 if (GetRuntimeModuleSP()) {
99 Activate();
100 return;
101 }
102
103 module_list.ForEach ([this](const lldb::ModuleSP module_sp) -> bool
104 {
105 const FileSpec & file_spec = module_sp->GetFileSpec();
106 if (! file_spec)
107 return true; // Keep iterating through modules
108
109 llvm::StringRef module_basename(file_spec.GetFilename().GetStringRef());
110 if (module_sp->IsExecutable() || module_basename.startswith("libclang_rt.tsan_"))
111 {
112 if (ModuleContainsTSanRuntime(module_sp))
113 {
114 m_runtime_module_wp = module_sp;
115 Activate();
116 return false; // Stop iterating
117 }
118 }
119
120 return true; // Keep iterating through modules
121 });
122}
123
124bool
125ThreadSanitizerRuntime::IsActive()
126{
127 return m_is_active;
128}
129
130#define RETRIEVE_REPORT_DATA_FUNCTION_TIMEOUT_USEC 2*1000*1000
131
132const char *
133thread_sanitizer_retrieve_report_data_prefix = R"(
134extern "C"
135{
136 void *__tsan_get_current_report();
137 int __tsan_get_report_data(void *report, const char **description, int *count,
138 int *stack_count, int *mop_count, int *loc_count,
139 int *mutex_count, int *thread_count,
140 int *unique_tid_count, void **sleep_trace,
141 unsigned long trace_size);
142 int __tsan_get_report_stack(void *report, unsigned long idx, void **trace,
143 unsigned long trace_size);
144 int __tsan_get_report_mop(void *report, unsigned long idx, int *tid, void **addr,
145 int *size, int *write, int *atomic, void **trace,
146 unsigned long trace_size);
147 int __tsan_get_report_loc(void *report, unsigned long idx, const char **type,
148 void **addr, unsigned long *start, unsigned long *size, int *tid,
149 int *fd, int *suppressable, void **trace,
150 unsigned long trace_size);
151 int __tsan_get_report_mutex(void *report, unsigned long idx, unsigned long *mutex_id, void **addr,
152 int *destroyed, void **trace, unsigned long trace_size);
153 int __tsan_get_report_thread(void *report, unsigned long idx, int *tid, unsigned long *pid,
154 int *running, const char **name, int *parent_tid,
155 void **trace, unsigned long trace_size);
156 int __tsan_get_report_unique_tid(void *report, unsigned long idx, int *tid);
157}
158
159const int REPORT_TRACE_SIZE = 128;
160const int REPORT_ARRAY_SIZE = 4;
161
162struct data {
163 void *report;
164 const char *description;
165 int report_count;
166
167 void *sleep_trace[REPORT_TRACE_SIZE];
168
169 int stack_count;
170 struct {
171 int idx;
172 void *trace[REPORT_TRACE_SIZE];
173 } stacks[REPORT_ARRAY_SIZE];
174
175 int mop_count;
176 struct {
177 int idx;
178 int tid;
179 int size;
180 int write;
181 int atomic;
182 void *addr;
183 void *trace[REPORT_TRACE_SIZE];
184 } mops[REPORT_ARRAY_SIZE];
185
186 int loc_count;
187 struct {
188 int idx;
189 const char *type;
190 void *addr;
191 unsigned long start;
192 unsigned long size;
193 int tid;
194 int fd;
195 int suppressable;
196 void *trace[REPORT_TRACE_SIZE];
197 } locs[REPORT_ARRAY_SIZE];
198
199 int mutex_count;
200 struct {
201 int idx;
202 unsigned long mutex_id;
203 void *addr;
204 int destroyed;
205 void *trace[REPORT_TRACE_SIZE];
206 } mutexes[REPORT_ARRAY_SIZE];
207
208 int thread_count;
209 struct {
210 int idx;
211 int tid;
212 unsigned long pid;
213 int running;
214 const char *name;
215 int parent_tid;
216 void *trace[REPORT_TRACE_SIZE];
217 } threads[REPORT_ARRAY_SIZE];
218
219 int unique_tid_count;
220 struct {
221 int idx;
222 int tid;
223 } unique_tids[REPORT_ARRAY_SIZE];
224};
225)";
226
227const char *
228thread_sanitizer_retrieve_report_data_command = R"(
229data t = {0};
230
231t.report = __tsan_get_current_report();
232__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);
233
234if (t.stack_count > REPORT_ARRAY_SIZE) t.stack_count = REPORT_ARRAY_SIZE;
235for (int i = 0; i < t.stack_count; i++) {
236 t.stacks[i].idx = i;
237 __tsan_get_report_stack(t.report, i, t.stacks[i].trace, REPORT_TRACE_SIZE);
238}
239
240if (t.mop_count > REPORT_ARRAY_SIZE) t.mop_count = REPORT_ARRAY_SIZE;
241for (int i = 0; i < t.mop_count; i++) {
242 t.mops[i].idx = i;
243 __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);
244}
245
246if (t.loc_count > REPORT_ARRAY_SIZE) t.loc_count = REPORT_ARRAY_SIZE;
247for (int i = 0; i < t.loc_count; i++) {
248 t.locs[i].idx = i;
249 __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);
250}
251
252if (t.mutex_count > REPORT_ARRAY_SIZE) t.mutex_count = REPORT_ARRAY_SIZE;
253for (int i = 0; i < t.mutex_count; i++) {
254 t.mutexes[i].idx = i;
255 __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);
256}
257
258if (t.thread_count > REPORT_ARRAY_SIZE) t.thread_count = REPORT_ARRAY_SIZE;
259for (int i = 0; i < t.thread_count; i++) {
260 t.threads[i].idx = i;
261 __tsan_get_report_thread(t.report, i, &t.threads[i].tid, &t.threads[i].pid, &t.threads[i].running, &t.threads[i].name, &t.threads[i].parent_tid, t.threads[i].trace, REPORT_TRACE_SIZE);
262}
263
Kuba Brecka058c3022016-03-30 10:50:24 +0000264if (t.unique_tid_count > REPORT_ARRAY_SIZE) t.unique_tid_count = REPORT_ARRAY_SIZE;
Kuba Brecka6a831432016-03-23 15:36:22 +0000265for (int i = 0; i < t.unique_tid_count; i++) {
266 t.unique_tids[i].idx = i;
267 __tsan_get_report_unique_tid(t.report, i, &t.unique_tids[i].tid);
268}
269
270t;
271)";
272
273static StructuredData::Array *
274CreateStackTrace(ValueObjectSP o, std::string trace_item_name = ".trace") {
275 StructuredData::Array *trace = new StructuredData::Array();
276 ValueObjectSP trace_value_object = o->GetValueForExpressionPath(trace_item_name.c_str());
277 for (int j = 0; j < 8; j++) {
278 addr_t trace_addr = trace_value_object->GetChildAtIndex(j, true)->GetValueAsUnsigned(0);
279 if (trace_addr == 0)
280 break;
281 trace->AddItem(StructuredData::ObjectSP(new StructuredData::Integer(trace_addr)));
282 }
283 return trace;
284}
285
286static StructuredData::Array *
287ConvertToStructuredArray(ValueObjectSP return_value_sp, std::string items_name, std::string count_name, std::function <void(ValueObjectSP o, StructuredData::Dictionary *dict)> const &callback)
288{
289 StructuredData::Array *array = new StructuredData::Array();
290 unsigned int count = return_value_sp->GetValueForExpressionPath(count_name.c_str())->GetValueAsUnsigned(0);
291 ValueObjectSP objects = return_value_sp->GetValueForExpressionPath(items_name.c_str());
Pavel Labath1b46a722016-03-30 09:42:59 +0000292 for (unsigned int i = 0; i < count; i++) {
Kuba Brecka6a831432016-03-23 15:36:22 +0000293 ValueObjectSP o = objects->GetChildAtIndex(i, true);
294 StructuredData::Dictionary *dict = new StructuredData::Dictionary();
295
296 callback(o, dict);
297
298 array->AddItem(StructuredData::ObjectSP(dict));
299 }
300 return array;
301}
302
303static std::string
304RetrieveString(ValueObjectSP return_value_sp, ProcessSP process_sp, std::string expression_path)
305{
306 addr_t ptr = return_value_sp->GetValueForExpressionPath(expression_path.c_str())->GetValueAsUnsigned(0);
307 std::string str;
308 Error error;
309 process_sp->ReadCStringFromMemory(ptr, str, error);
310 return str;
311}
312
313StructuredData::ObjectSP
314ThreadSanitizerRuntime::RetrieveReportData(ExecutionContextRef exe_ctx_ref)
315{
316 ProcessSP process_sp = GetProcessSP();
317 if (!process_sp)
318 return StructuredData::ObjectSP();
319
320 ThreadSP thread_sp = exe_ctx_ref.GetThreadSP();
321 StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
322
323 if (!frame_sp)
324 return StructuredData::ObjectSP();
325
326 EvaluateExpressionOptions options;
327 options.SetUnwindOnError(true);
328 options.SetTryAllThreads(true);
329 options.SetStopOthers(true);
330 options.SetIgnoreBreakpoints(true);
331 options.SetTimeoutUsec(RETRIEVE_REPORT_DATA_FUNCTION_TIMEOUT_USEC);
332 options.SetPrefix(thread_sanitizer_retrieve_report_data_prefix);
333
334 ValueObjectSP main_value;
335 ExecutionContext exe_ctx;
336 Error eval_error;
337 frame_sp->CalculateExecutionContext(exe_ctx);
338 ExpressionResults result = UserExpression::Evaluate (exe_ctx,
339 options,
340 thread_sanitizer_retrieve_report_data_command,
341 "",
342 main_value,
343 eval_error);
344 if (result != eExpressionCompleted) {
345 process_sp->GetTarget().GetDebugger().GetAsyncOutputStream()->Printf("Warning: Cannot evaluate ThreadSanitizer expression:\n%s\n", eval_error.AsCString());
346 return StructuredData::ObjectSP();
347 }
348
349 StructuredData::Dictionary *dict = new StructuredData::Dictionary();
350 dict->AddStringItem("instrumentation_class", "ThreadSanitizer");
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000351 dict->AddStringItem("issue_type", RetrieveString(main_value, process_sp, ".description"));
Kuba Brecka6a831432016-03-23 15:36:22 +0000352 dict->AddIntegerItem("report_count", main_value->GetValueForExpressionPath(".report_count")->GetValueAsUnsigned(0));
353 dict->AddItem("sleep_trace", StructuredData::ObjectSP(CreateStackTrace(main_value, ".sleep_trace")));
354
355 StructuredData::Array *stacks = ConvertToStructuredArray(main_value, ".stacks", ".stack_count", [] (ValueObjectSP o, StructuredData::Dictionary *dict) {
356 dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
357 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
358 });
359 dict->AddItem("stacks", StructuredData::ObjectSP(stacks));
360
361 StructuredData::Array *mops = ConvertToStructuredArray(main_value, ".mops", ".mop_count", [] (ValueObjectSP o, StructuredData::Dictionary *dict) {
362 dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
363 dict->AddIntegerItem("thread_id", o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0));
364 dict->AddIntegerItem("size", o->GetValueForExpressionPath(".size")->GetValueAsUnsigned(0));
365 dict->AddBooleanItem("is_write", o->GetValueForExpressionPath(".write")->GetValueAsUnsigned(0));
366 dict->AddBooleanItem("is_atomic", o->GetValueForExpressionPath(".atomic")->GetValueAsUnsigned(0));
367 dict->AddIntegerItem("address", o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
368 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
369 });
370 dict->AddItem("mops", StructuredData::ObjectSP(mops));
371
372 StructuredData::Array *locs = ConvertToStructuredArray(main_value, ".locs", ".loc_count", [process_sp] (ValueObjectSP o, StructuredData::Dictionary *dict) {
373 dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
374 dict->AddStringItem("type", RetrieveString(o, process_sp, ".type"));
375 dict->AddIntegerItem("address", o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
376 dict->AddIntegerItem("start", o->GetValueForExpressionPath(".start")->GetValueAsUnsigned(0));
377 dict->AddIntegerItem("size", o->GetValueForExpressionPath(".size")->GetValueAsUnsigned(0));
378 dict->AddIntegerItem("thread_id", o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0));
379 dict->AddIntegerItem("file_descriptor", o->GetValueForExpressionPath(".fd")->GetValueAsUnsigned(0));
380 dict->AddIntegerItem("suppressable", o->GetValueForExpressionPath(".suppressable")->GetValueAsUnsigned(0));
381 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
382 });
383 dict->AddItem("locs", StructuredData::ObjectSP(locs));
384
385 StructuredData::Array *mutexes = ConvertToStructuredArray(main_value, ".mutexes", ".mutex_count", [] (ValueObjectSP o, StructuredData::Dictionary *dict) {
386 dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
387 dict->AddIntegerItem("mutex_id", o->GetValueForExpressionPath(".mutex_id")->GetValueAsUnsigned(0));
388 dict->AddIntegerItem("address", o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
389 dict->AddIntegerItem("destroyed", o->GetValueForExpressionPath(".destroyed")->GetValueAsUnsigned(0));
390 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
391 });
392 dict->AddItem("mutexes", StructuredData::ObjectSP(mutexes));
393
394 StructuredData::Array *threads = ConvertToStructuredArray(main_value, ".threads", ".thread_count", [process_sp] (ValueObjectSP o, StructuredData::Dictionary *dict) {
395 dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
396 dict->AddIntegerItem("thread_id", o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0));
397 dict->AddIntegerItem("process_id", o->GetValueForExpressionPath(".pid")->GetValueAsUnsigned(0));
398 dict->AddIntegerItem("running", o->GetValueForExpressionPath(".running")->GetValueAsUnsigned(0));
399 dict->AddStringItem("name", RetrieveString(o, process_sp, ".name"));
400 dict->AddIntegerItem("parent_thread_id", o->GetValueForExpressionPath(".parent_tid")->GetValueAsUnsigned(0));
401 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
402 });
403 dict->AddItem("threads", StructuredData::ObjectSP(threads));
404
405 StructuredData::Array *unique_tids = ConvertToStructuredArray(main_value, ".unique_tids", ".unique_tid_count", [] (ValueObjectSP o, StructuredData::Dictionary *dict) {
406 dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
407 dict->AddIntegerItem("tid", o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0));
408 });
409 dict->AddItem("unique_tids", StructuredData::ObjectSP(unique_tids));
410
411 return StructuredData::ObjectSP(dict);
412}
413
414std::string
415ThreadSanitizerRuntime::FormatDescription(StructuredData::ObjectSP report)
416{
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000417 std::string description = report->GetAsDictionary()->GetValueForKey("issue_type")->GetAsString()->GetValue();
Kuba Brecka6a831432016-03-23 15:36:22 +0000418
419 if (description == "data-race") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000420 return "Data race";
Kuba Brecka6a831432016-03-23 15:36:22 +0000421 } else if (description == "data-race-vptr") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000422 return "Data race on C++ virtual pointer";
Kuba Brecka6a831432016-03-23 15:36:22 +0000423 } else if (description == "heap-use-after-free") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000424 return "Use of deallocated memory";
Kuba Brecka6a831432016-03-23 15:36:22 +0000425 } else if (description == "heap-use-after-free-vptr") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000426 return "Use of deallocated C++ virtual pointer";
Kuba Brecka6a831432016-03-23 15:36:22 +0000427 } else if (description == "thread-leak") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000428 return "Thread leak";
Kuba Brecka6a831432016-03-23 15:36:22 +0000429 } else if (description == "locked-mutex-destroy") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000430 return "Destruction of a locked mutex";
Kuba Brecka6a831432016-03-23 15:36:22 +0000431 } else if (description == "mutex-double-lock") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000432 return "Double lock of a mutex";
Kuba Brecka6a831432016-03-23 15:36:22 +0000433 } else if (description == "mutex-invalid-access") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000434 return "Use of an invalid mutex (e.g. uninitialized or destroyed)";
Kuba Brecka6a831432016-03-23 15:36:22 +0000435 } else if (description == "mutex-bad-unlock") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000436 return "Unlock of an unlocked mutex (or by a wrong thread)";
Kuba Brecka6a831432016-03-23 15:36:22 +0000437 } else if (description == "mutex-bad-read-lock") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000438 return "Read lock of a write locked mutex";
Kuba Brecka6a831432016-03-23 15:36:22 +0000439 } else if (description == "mutex-bad-read-unlock") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000440 return "Read unlock of a write locked mutex";
Kuba Brecka6a831432016-03-23 15:36:22 +0000441 } else if (description == "signal-unsafe-call") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000442 return "Signal-unsafe call inside a signal handler";
Kuba Brecka6a831432016-03-23 15:36:22 +0000443 } else if (description == "errno-in-signal-handler") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000444 return "Overwrite of errno in a signal handler";
Kuba Brecka6a831432016-03-23 15:36:22 +0000445 } else if (description == "lock-order-inversion") {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000446 return "Lock order inversion (potential deadlock)";
Kuba Brecka6a831432016-03-23 15:36:22 +0000447 }
448
449 // for unknown report codes just show the code
450 return description;
451}
452
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000453static std::string
454Sprintf(const char *format, ...)
455{
456 StreamString s;
457 va_list args;
458 va_start (args, format);
459 s.PrintfVarArg(format, args);
460 va_end (args);
461 return s.GetString();
462}
463
464static std::string
465GetSymbolNameFromAddress(ProcessSP process_sp, addr_t addr)
466{
467 lldb_private::Address so_addr;
468 if (! process_sp->GetTarget().GetSectionLoadList().ResolveLoadAddress(addr, so_addr))
469 return "";
470
471 lldb_private::Symbol *symbol = so_addr.CalculateSymbolContextSymbol();
472 if (! symbol)
473 return "";
474
475 std::string sym_name = symbol->GetName().GetCString();
476 return sym_name;
477}
478
479addr_t
480ThreadSanitizerRuntime::GetFirstNonInternalFramePc(StructuredData::ObjectSP trace)
481{
482 ProcessSP process_sp = GetProcessSP();
483 ModuleSP runtime_module_sp = GetRuntimeModuleSP();
484
485 addr_t result = 0;
486 trace->GetAsArray()->ForEach([process_sp, runtime_module_sp, &result] (StructuredData::Object *o) -> bool {
487 addr_t addr = o->GetIntegerValue();
488 lldb_private::Address so_addr;
489 if (! process_sp->GetTarget().GetSectionLoadList().ResolveLoadAddress(addr, so_addr))
490 return true;
491
492 if (so_addr.GetModule() == runtime_module_sp)
493 return true;
494
495 result = addr;
496 return false;
497 });
498
499 return result;
500}
501
502std::string
503ThreadSanitizerRuntime::GenerateSummary(StructuredData::ObjectSP report)
504{
505 ProcessSP process_sp = GetProcessSP();
506
507 std::string summary = report->GetAsDictionary()->GetValueForKey("description")->GetAsString()->GetValue();
508 addr_t pc = 0;
509 if (report->GetAsDictionary()->GetValueForKey("mops")->GetAsArray()->GetSize() > 0)
510 pc = GetFirstNonInternalFramePc(report->GetAsDictionary()->GetValueForKey("mops")->GetAsArray()->GetItemAtIndex(0)->GetAsDictionary()->GetValueForKey("trace"));
511
512 if (report->GetAsDictionary()->GetValueForKey("stacks")->GetAsArray()->GetSize() > 0)
513 pc = GetFirstNonInternalFramePc(report->GetAsDictionary()->GetValueForKey("stacks")->GetAsArray()->GetItemAtIndex(0)->GetAsDictionary()->GetValueForKey("trace"));
514
515 if (pc != 0) {
516 summary = summary + " in " + GetSymbolNameFromAddress(process_sp, pc);
517 }
518
519 if (report->GetAsDictionary()->GetValueForKey("locs")->GetAsArray()->GetSize() > 0) {
520 StructuredData::ObjectSP loc = report->GetAsDictionary()->GetValueForKey("locs")->GetAsArray()->GetItemAtIndex(0);
521 addr_t addr = loc->GetAsDictionary()->GetValueForKey("address")->GetAsInteger()->GetValue();
522 if (addr == 0)
523 addr = loc->GetAsDictionary()->GetValueForKey("start")->GetAsInteger()->GetValue();
524
525 if (addr != 0) {
526 summary = summary + " at " + Sprintf("0x%llx", addr);
527 } else {
528 int fd = loc->GetAsDictionary()->GetValueForKey("file_descriptor")->GetAsInteger()->GetValue();
529 if (fd != 0) {
530 summary = summary + " on file descriptor " + Sprintf("%d", fd);
531 }
532 }
533 }
534
535 return summary;
536}
537
538addr_t
539ThreadSanitizerRuntime::GetMainRacyAddress(StructuredData::ObjectSP report)
540{
541 addr_t result = (addr_t)-1;
542
543 report->GetObjectForDotSeparatedPath("mops")->GetAsArray()->ForEach([&result] (StructuredData::Object *o) -> bool {
544 addr_t addr = o->GetObjectForDotSeparatedPath("address")->GetIntegerValue();
545 if (addr < result) result = addr;
546 return true;
547 });
548
549 return (result == (addr_t)-1) ? 0 : result;
550}
551
552std::string
553ThreadSanitizerRuntime::GetLocationDescription(StructuredData::ObjectSP report)
554{
555 std::string result = "";
556
557 ProcessSP process_sp = GetProcessSP();
558
559 if (report->GetAsDictionary()->GetValueForKey("locs")->GetAsArray()->GetSize() > 0) {
560 StructuredData::ObjectSP loc = report->GetAsDictionary()->GetValueForKey("locs")->GetAsArray()->GetItemAtIndex(0);
561 std::string type = loc->GetAsDictionary()->GetValueForKey("type")->GetStringValue();
562 if (type == "global") {
563 addr_t addr = loc->GetAsDictionary()->GetValueForKey("address")->GetAsInteger()->GetValue();
564 std::string global_name = GetSymbolNameFromAddress(process_sp, addr);
565 result = Sprintf("Location is a global '%s'", global_name.c_str());
566 } else if (type == "heap") {
567 addr_t addr = loc->GetAsDictionary()->GetValueForKey("start")->GetAsInteger()->GetValue();
568 long size = loc->GetAsDictionary()->GetValueForKey("size")->GetAsInteger()->GetValue();
569 result = Sprintf("Location is a %ld-byte heap object at 0x%llx", size, addr);
570 } else if (type == "stack") {
571 int tid = loc->GetAsDictionary()->GetValueForKey("thread_id")->GetAsInteger()->GetValue();
572 result = Sprintf("Location is stack of thread %d", tid);
573 } else if (type == "tls") {
574 int tid = loc->GetAsDictionary()->GetValueForKey("thread_id")->GetAsInteger()->GetValue();
575 result = Sprintf("Location is TLS of thread %d", tid);
576 } else if (type == "fd") {
577 int fd = loc->GetAsDictionary()->GetValueForKey("file_descriptor")->GetAsInteger()->GetValue();
578 result = Sprintf("Location is file descriptor %d", fd);
579 }
580 }
581
582 return result;
583}
584
Kuba Brecka6a831432016-03-23 15:36:22 +0000585bool
586ThreadSanitizerRuntime::NotifyBreakpointHit(void *baton, StoppointCallbackContext *context, user_id_t break_id, user_id_t break_loc_id)
587{
588 assert (baton && "null baton");
589 if (!baton)
590 return false;
591
592 ThreadSanitizerRuntime *const instance = static_cast<ThreadSanitizerRuntime*>(baton);
593
594 StructuredData::ObjectSP report = instance->RetrieveReportData(context->exe_ctx_ref);
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000595 std::string stop_reason_description;
Kuba Brecka6a831432016-03-23 15:36:22 +0000596 if (report) {
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000597 std::string issue_description = instance->FormatDescription(report);
598 report->GetAsDictionary()->AddStringItem("description", issue_description);
599 stop_reason_description = issue_description + " detected";
600 report->GetAsDictionary()->AddStringItem("stop_description", stop_reason_description);
601 std::string summary = instance->GenerateSummary(report);
602 report->GetAsDictionary()->AddStringItem("summary", summary);
603 addr_t main_address = instance->GetMainRacyAddress(report);
604 report->GetAsDictionary()->AddIntegerItem("memory_address", main_address);
605 std::string location_description = instance->GetLocationDescription(report);
606 report->GetAsDictionary()->AddStringItem("location_description", location_description);
Kuba Brecka6a831432016-03-23 15:36:22 +0000607 }
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000608
Kuba Brecka6a831432016-03-23 15:36:22 +0000609 ProcessSP process_sp = instance->GetProcessSP();
610 // Make sure this is the right process
611 if (process_sp && process_sp == context->exe_ctx_ref.GetProcessSP())
612 {
613 ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
614 if (thread_sp)
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000615 thread_sp->SetStopInfo(InstrumentationRuntimeStopInfo::CreateStopReasonWithInstrumentationData(*thread_sp, stop_reason_description.c_str(), report));
Kuba Brecka6a831432016-03-23 15:36:22 +0000616
617 StreamFileSP stream_sp (process_sp->GetTarget().GetDebugger().GetOutputFile());
618 if (stream_sp)
619 {
620 stream_sp->Printf ("ThreadSanitizer report breakpoint hit. Use 'thread info -s' to get extended information about the report.\n");
621 }
622 return true; // Return true to stop the target
623 }
624 else
625 return false; // Let target run
626}
627
628void
629ThreadSanitizerRuntime::Activate()
630{
631 if (m_is_active)
632 return;
633
634 ProcessSP process_sp = GetProcessSP();
635 if (!process_sp)
636 return;
637
638 ConstString symbol_name ("__tsan_on_report");
639 const Symbol *symbol = GetRuntimeModuleSP()->FindFirstSymbolWithNameAndType (symbol_name, eSymbolTypeCode);
640
641 if (symbol == NULL)
642 return;
643
644 if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
645 return;
646
647 Target &target = process_sp->GetTarget();
648 addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
649
650 if (symbol_address == LLDB_INVALID_ADDRESS)
651 return;
652
653 bool internal = true;
654 bool hardware = false;
655 Breakpoint *breakpoint = process_sp->GetTarget().CreateBreakpoint(symbol_address, internal, hardware).get();
656 breakpoint->SetCallback (ThreadSanitizerRuntime::NotifyBreakpointHit, this, true);
657 breakpoint->SetBreakpointKind ("thread-sanitizer-report");
658 m_breakpoint_id = breakpoint->GetID();
659
660 StreamFileSP stream_sp (process_sp->GetTarget().GetDebugger().GetOutputFile());
661 if (stream_sp)
662 {
663 stream_sp->Printf ("ThreadSanitizer debugger support is active.\n");
664 }
665
666 m_is_active = true;
667}
668
669void
670ThreadSanitizerRuntime::Deactivate()
671{
672 if (m_breakpoint_id != LLDB_INVALID_BREAK_ID)
673 {
674 ProcessSP process_sp = GetProcessSP();
675 if (process_sp)
676 {
677 process_sp->GetTarget().RemoveBreakpointByID(m_breakpoint_id);
678 m_breakpoint_id = LLDB_INVALID_BREAK_ID;
679 }
680 }
681 m_is_active = false;
682}
Kuba Brecka1aad8fb2016-04-10 18:57:38 +0000683
684static std::string
685GenerateThreadName(std::string path, StructuredData::Object *o) {
686 std::string result = "additional information";
687
688 if (path == "mops") {
689 int size = o->GetObjectForDotSeparatedPath("size")->GetIntegerValue();
690 int thread_id = o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
691 bool is_write = o->GetObjectForDotSeparatedPath("is_write")->GetBooleanValue();
692 bool is_atomic = o->GetObjectForDotSeparatedPath("is_atomic")->GetBooleanValue();
693 addr_t addr = o->GetObjectForDotSeparatedPath("address")->GetIntegerValue();
694
695 result = Sprintf("%s%s of size %d at 0x%llx by thread %d", is_atomic ? "atomic " : "", is_write ? "write" : "read", size, addr, thread_id);
696 }
697
698 if (path == "threads") {
699 int thread_id = o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
700 int parent_thread_id = o->GetObjectForDotSeparatedPath("parent_thread_id")->GetIntegerValue();
701
702 result = Sprintf("thread %d created by thread %d at", thread_id, parent_thread_id);
703 }
704
705 if (path == "locs") {
706 std::string type = o->GetAsDictionary()->GetValueForKey("type")->GetStringValue();
707 int thread_id = o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
708 int fd = o->GetObjectForDotSeparatedPath("file_descriptor")->GetIntegerValue();
709 if (type == "heap") {
710 result = Sprintf("Heap block allocated by thread %d at", thread_id);
711 } else if (type == "fd") {
712 result = Sprintf("File descriptor %d created by thread %t at", fd, thread_id);
713 }
714 }
715
716 if (path == "mutexes") {
717 int mutex_id = o->GetObjectForDotSeparatedPath("mutex_id")->GetIntegerValue();
718
719 result = Sprintf("mutex M%d created at", mutex_id);
720 }
721
722 if (path == "stacks") {
723 result = "happened at";
724 }
725
726 result[0] = toupper(result[0]);
727
728 return result;
729}
730
731static void
732AddThreadsForPath(std::string path, ThreadCollectionSP threads, ProcessSP process_sp, StructuredData::ObjectSP info)
733{
734 info->GetObjectForDotSeparatedPath(path)->GetAsArray()->ForEach([process_sp, threads, path] (StructuredData::Object *o) -> bool {
735 std::vector<lldb::addr_t> pcs;
736 o->GetObjectForDotSeparatedPath("trace")->GetAsArray()->ForEach([&pcs] (StructuredData::Object *pc) -> bool {
737 pcs.push_back(pc->GetAsInteger()->GetValue());
738 return true;
739 });
740
741 if (pcs.size() == 0)
742 return true;
743
744 StructuredData::ObjectSP thread_id_obj = o->GetObjectForDotSeparatedPath("thread_id");
745 tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0;
746
747 uint32_t stop_id = 0;
748 bool stop_id_is_valid = false;
749 HistoryThread *history_thread = new HistoryThread(*process_sp, tid, pcs, stop_id, stop_id_is_valid);
750 ThreadSP new_thread_sp(history_thread);
751 new_thread_sp->SetName(GenerateThreadName(path, o).c_str());
752
753 // Save this in the Process' ExtendedThreadList so a strong pointer retains the object
754 process_sp->GetExtendedThreadList().AddThread(new_thread_sp);
755 threads->AddThread(new_thread_sp);
756
757 return true;
758 });
759}
760
761lldb::ThreadCollectionSP
762ThreadSanitizerRuntime::GetBacktracesFromExtendedStopInfo(StructuredData::ObjectSP info)
763{
764 ThreadCollectionSP threads;
765 threads.reset(new ThreadCollection());
766
767 if (info->GetObjectForDotSeparatedPath("instrumentation_class")->GetStringValue() != "ThreadSanitizer")
768 return threads;
769
770 ProcessSP process_sp = GetProcessSP();
771
772 AddThreadsForPath("stacks", threads, process_sp, info);
773 AddThreadsForPath("mops", threads, process_sp, info);
774 AddThreadsForPath("locs", threads, process_sp, info);
775 AddThreadsForPath("mutexes", threads, process_sp, info);
776 AddThreadsForPath("threads", threads, process_sp, info);
777
778 return threads;
779}