1 //===-- TSanRuntime.cpp -----------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "TSanRuntime.h"
12 #include "Plugins/Process/Utility/HistoryThread.h"
13 #include "lldb/Breakpoint/StoppointCallbackContext.h"
14 #include "lldb/Core/Debugger.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/PluginInterface.h"
17 #include "lldb/Core/PluginManager.h"
18 #include "lldb/Core/StreamFile.h"
19 #include "lldb/Core/ValueObject.h"
20 #include "lldb/Expression/UserExpression.h"
21 #include "lldb/Interpreter/CommandReturnObject.h"
22 #include "lldb/Symbol/Symbol.h"
23 #include "lldb/Symbol/SymbolContext.h"
24 #include "lldb/Symbol/Variable.h"
25 #include "lldb/Symbol/VariableList.h"
26 #include "lldb/Target/InstrumentationRuntimeStopInfo.h"
27 #include "lldb/Target/SectionLoadList.h"
28 #include "lldb/Target/StopInfo.h"
29 #include "lldb/Target/Target.h"
30 #include "lldb/Target/Thread.h"
31 #include "lldb/Utility/RegularExpression.h"
32 #include "lldb/Utility/Stream.h"
35 using namespace lldb_private;
37 lldb::InstrumentationRuntimeSP
38 ThreadSanitizerRuntime::CreateInstance(const lldb::ProcessSP &process_sp) {
39 return InstrumentationRuntimeSP(new ThreadSanitizerRuntime(process_sp));
42 void ThreadSanitizerRuntime::Initialize() {
43 PluginManager::RegisterPlugin(
44 GetPluginNameStatic(), "ThreadSanitizer instrumentation runtime plugin.",
45 CreateInstance, GetTypeStatic);
48 void ThreadSanitizerRuntime::Terminate() {
49 PluginManager::UnregisterPlugin(CreateInstance);
52 lldb_private::ConstString ThreadSanitizerRuntime::GetPluginNameStatic() {
53 return ConstString("ThreadSanitizer");
56 lldb::InstrumentationRuntimeType ThreadSanitizerRuntime::GetTypeStatic() {
57 return eInstrumentationRuntimeTypeThreadSanitizer;
60 ThreadSanitizerRuntime::~ThreadSanitizerRuntime() { Deactivate(); }
62 static constexpr std::chrono::seconds g_retrieve_data_function_timeout(2);
64 const char *thread_sanitizer_retrieve_report_data_prefix = R"(
67 void *__tsan_get_current_report();
68 int __tsan_get_report_data(void *report, const char **description, int *count,
69 int *stack_count, int *mop_count, int *loc_count,
70 int *mutex_count, int *thread_count,
71 int *unique_tid_count, void **sleep_trace,
72 unsigned long trace_size);
73 int __tsan_get_report_stack(void *report, unsigned long idx, void **trace,
74 unsigned long trace_size);
75 int __tsan_get_report_mop(void *report, unsigned long idx, int *tid, void **addr,
76 int *size, int *write, int *atomic, void **trace,
77 unsigned long trace_size);
78 int __tsan_get_report_loc(void *report, unsigned long idx, const char **type,
79 void **addr, unsigned long *start, unsigned long *size, int *tid,
80 int *fd, int *suppressable, void **trace,
81 unsigned long trace_size);
82 int __tsan_get_report_mutex(void *report, unsigned long idx, unsigned long *mutex_id, void **addr,
83 int *destroyed, void **trace, unsigned long trace_size);
84 int __tsan_get_report_thread(void *report, unsigned long idx, int *tid, unsigned long *os_id,
85 int *running, const char **name, int *parent_tid,
86 void **trace, unsigned long trace_size);
87 int __tsan_get_report_unique_tid(void *report, unsigned long idx, int *tid);
89 // TODO: dlsym won't work on Windows.
90 void *dlsym(void* handle, const char* symbol);
91 int (*ptr__tsan_get_report_loc_object_type)(void *report, unsigned long idx, const char **object_type);
94 const int REPORT_TRACE_SIZE = 128;
95 const int REPORT_ARRAY_SIZE = 4;
99 const char *description;
102 void *sleep_trace[REPORT_TRACE_SIZE];
107 void *trace[REPORT_TRACE_SIZE];
108 } stacks[REPORT_ARRAY_SIZE];
118 void *trace[REPORT_TRACE_SIZE];
119 } mops[REPORT_ARRAY_SIZE];
131 void *trace[REPORT_TRACE_SIZE];
132 const char *object_type;
133 } locs[REPORT_ARRAY_SIZE];
138 unsigned long mutex_id;
141 void *trace[REPORT_TRACE_SIZE];
142 } mutexes[REPORT_ARRAY_SIZE];
152 void *trace[REPORT_TRACE_SIZE];
153 } threads[REPORT_ARRAY_SIZE];
155 int unique_tid_count;
159 } unique_tids[REPORT_ARRAY_SIZE];
163 const char *thread_sanitizer_retrieve_report_data_command = R"(
166 ptr__tsan_get_report_loc_object_type = (typeof(ptr__tsan_get_report_loc_object_type))(void *)dlsym((void*)-2 /*RTLD_DEFAULT*/, "__tsan_get_report_loc_object_type");
168 t.report = __tsan_get_current_report();
169 __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);
171 if (t.stack_count > REPORT_ARRAY_SIZE) t.stack_count = REPORT_ARRAY_SIZE;
172 for (int i = 0; i < t.stack_count; i++) {
174 __tsan_get_report_stack(t.report, i, t.stacks[i].trace, REPORT_TRACE_SIZE);
177 if (t.mop_count > REPORT_ARRAY_SIZE) t.mop_count = REPORT_ARRAY_SIZE;
178 for (int i = 0; i < t.mop_count; i++) {
180 __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);
183 if (t.loc_count > REPORT_ARRAY_SIZE) t.loc_count = REPORT_ARRAY_SIZE;
184 for (int i = 0; i < t.loc_count; i++) {
186 __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);
187 if (ptr__tsan_get_report_loc_object_type)
188 ptr__tsan_get_report_loc_object_type(t.report, i, &t.locs[i].object_type);
191 if (t.mutex_count > REPORT_ARRAY_SIZE) t.mutex_count = REPORT_ARRAY_SIZE;
192 for (int i = 0; i < t.mutex_count; i++) {
193 t.mutexes[i].idx = i;
194 __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);
197 if (t.thread_count > REPORT_ARRAY_SIZE) t.thread_count = REPORT_ARRAY_SIZE;
198 for (int i = 0; i < t.thread_count; i++) {
199 t.threads[i].idx = i;
200 __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);
203 if (t.unique_tid_count > REPORT_ARRAY_SIZE) t.unique_tid_count = REPORT_ARRAY_SIZE;
204 for (int i = 0; i < t.unique_tid_count; i++) {
205 t.unique_tids[i].idx = i;
206 __tsan_get_report_unique_tid(t.report, i, &t.unique_tids[i].tid);
212 static StructuredData::Array *
213 CreateStackTrace(ValueObjectSP o,
214 const std::string &trace_item_name = ".trace") {
215 StructuredData::Array *trace = new StructuredData::Array();
216 ValueObjectSP trace_value_object =
217 o->GetValueForExpressionPath(trace_item_name.c_str());
218 size_t count = trace_value_object->GetNumChildren();
219 for (size_t j = 0; j < count; j++) {
221 trace_value_object->GetChildAtIndex(j, true)->GetValueAsUnsigned(0);
225 StructuredData::ObjectSP(new StructuredData::Integer(trace_addr)));
230 static StructuredData::Array *ConvertToStructuredArray(
231 ValueObjectSP return_value_sp, const std::string &items_name,
232 const std::string &count_name,
233 std::function<void(ValueObjectSP o, StructuredData::Dictionary *dict)> const
235 StructuredData::Array *array = new StructuredData::Array();
237 return_value_sp->GetValueForExpressionPath(count_name.c_str())
238 ->GetValueAsUnsigned(0);
239 ValueObjectSP objects =
240 return_value_sp->GetValueForExpressionPath(items_name.c_str());
241 for (unsigned int i = 0; i < count; i++) {
242 ValueObjectSP o = objects->GetChildAtIndex(i, true);
243 StructuredData::Dictionary *dict = new StructuredData::Dictionary();
247 array->AddItem(StructuredData::ObjectSP(dict));
252 static std::string RetrieveString(ValueObjectSP return_value_sp,
253 ProcessSP process_sp,
254 const std::string &expression_path) {
256 return_value_sp->GetValueForExpressionPath(expression_path.c_str())
257 ->GetValueAsUnsigned(0);
260 process_sp->ReadCStringFromMemory(ptr, str, error);
265 GetRenumberedThreadIds(ProcessSP process_sp, ValueObjectSP data,
266 std::map<uint64_t, user_id_t> &thread_id_map) {
267 ConvertToStructuredArray(
268 data, ".threads", ".thread_count",
269 [process_sp, &thread_id_map](ValueObjectSP o,
270 StructuredData::Dictionary *dict) {
272 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0);
273 uint64_t thread_os_id =
274 o->GetValueForExpressionPath(".os_id")->GetValueAsUnsigned(0);
275 user_id_t lldb_user_id = 0;
277 bool can_update = true;
278 ThreadSP lldb_thread = process_sp->GetThreadList().FindThreadByID(
279 thread_os_id, can_update);
281 lldb_user_id = lldb_thread->GetIndexID();
283 // This isn't a live thread anymore. Ask process to assign a new
284 // Index ID (or return an old one if we've already seen this
285 // thread_os_id). It will also make sure that no new threads are
286 // assigned this Index ID.
287 lldb_user_id = process_sp->AssignIndexIDToThread(thread_os_id);
290 thread_id_map[thread_id] = lldb_user_id;
294 static user_id_t Renumber(uint64_t id,
295 std::map<uint64_t, user_id_t> &thread_id_map) {
296 auto IT = thread_id_map.find(id);
297 if (IT == thread_id_map.end())
303 StructuredData::ObjectSP
304 ThreadSanitizerRuntime::RetrieveReportData(ExecutionContextRef exe_ctx_ref) {
305 ProcessSP process_sp = GetProcessSP();
307 return StructuredData::ObjectSP();
309 ThreadSP thread_sp = exe_ctx_ref.GetThreadSP();
310 StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
313 return StructuredData::ObjectSP();
315 EvaluateExpressionOptions options;
316 options.SetUnwindOnError(true);
317 options.SetTryAllThreads(true);
318 options.SetStopOthers(true);
319 options.SetIgnoreBreakpoints(true);
320 options.SetTimeout(g_retrieve_data_function_timeout);
321 options.SetPrefix(thread_sanitizer_retrieve_report_data_prefix);
322 options.SetAutoApplyFixIts(false);
323 options.SetLanguage(eLanguageTypeObjC_plus_plus);
325 ValueObjectSP main_value;
326 ExecutionContext exe_ctx;
328 frame_sp->CalculateExecutionContext(exe_ctx);
329 ExpressionResults result = UserExpression::Evaluate(
330 exe_ctx, options, thread_sanitizer_retrieve_report_data_command, "",
331 main_value, eval_error);
332 if (result != eExpressionCompleted) {
333 process_sp->GetTarget().GetDebugger().GetAsyncOutputStream()->Printf(
334 "Warning: Cannot evaluate ThreadSanitizer expression:\n%s\n",
335 eval_error.AsCString());
336 return StructuredData::ObjectSP();
339 std::map<uint64_t, user_id_t> thread_id_map;
340 GetRenumberedThreadIds(process_sp, main_value, thread_id_map);
342 StructuredData::Dictionary *dict = new StructuredData::Dictionary();
343 dict->AddStringItem("instrumentation_class", "ThreadSanitizer");
344 dict->AddStringItem("issue_type",
345 RetrieveString(main_value, process_sp, ".description"));
346 dict->AddIntegerItem("report_count",
347 main_value->GetValueForExpressionPath(".report_count")
348 ->GetValueAsUnsigned(0));
349 dict->AddItem("sleep_trace", StructuredData::ObjectSP(CreateStackTrace(
350 main_value, ".sleep_trace")));
352 StructuredData::Array *stacks = ConvertToStructuredArray(
353 main_value, ".stacks", ".stack_count",
354 [thread_sp](ValueObjectSP o, StructuredData::Dictionary *dict) {
355 dict->AddIntegerItem(
357 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
358 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
359 // "stacks" happen on the current thread
360 dict->AddIntegerItem("thread_id", thread_sp->GetIndexID());
362 dict->AddItem("stacks", StructuredData::ObjectSP(stacks));
364 StructuredData::Array *mops = ConvertToStructuredArray(
365 main_value, ".mops", ".mop_count",
366 [&thread_id_map](ValueObjectSP o, StructuredData::Dictionary *dict) {
367 dict->AddIntegerItem(
369 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
370 dict->AddIntegerItem(
373 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0),
375 dict->AddIntegerItem(
377 o->GetValueForExpressionPath(".size")->GetValueAsUnsigned(0));
378 dict->AddBooleanItem(
380 o->GetValueForExpressionPath(".write")->GetValueAsUnsigned(0));
381 dict->AddBooleanItem(
383 o->GetValueForExpressionPath(".atomic")->GetValueAsUnsigned(0));
384 dict->AddIntegerItem(
386 o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
387 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
389 dict->AddItem("mops", StructuredData::ObjectSP(mops));
391 StructuredData::Array *locs = ConvertToStructuredArray(
392 main_value, ".locs", ".loc_count",
393 [process_sp, &thread_id_map](ValueObjectSP o,
394 StructuredData::Dictionary *dict) {
395 dict->AddIntegerItem(
397 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
398 dict->AddStringItem("type", RetrieveString(o, process_sp, ".type"));
399 dict->AddIntegerItem(
401 o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
402 dict->AddIntegerItem(
404 o->GetValueForExpressionPath(".start")->GetValueAsUnsigned(0));
405 dict->AddIntegerItem(
407 o->GetValueForExpressionPath(".size")->GetValueAsUnsigned(0));
408 dict->AddIntegerItem(
411 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0),
413 dict->AddIntegerItem(
415 o->GetValueForExpressionPath(".fd")->GetValueAsUnsigned(0));
416 dict->AddIntegerItem("suppressable",
417 o->GetValueForExpressionPath(".suppressable")
418 ->GetValueAsUnsigned(0));
419 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
420 dict->AddStringItem("object_type",
421 RetrieveString(o, process_sp, ".object_type"));
423 dict->AddItem("locs", StructuredData::ObjectSP(locs));
425 StructuredData::Array *mutexes = ConvertToStructuredArray(
426 main_value, ".mutexes", ".mutex_count",
427 [](ValueObjectSP o, StructuredData::Dictionary *dict) {
428 dict->AddIntegerItem(
430 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
431 dict->AddIntegerItem(
433 o->GetValueForExpressionPath(".mutex_id")->GetValueAsUnsigned(0));
434 dict->AddIntegerItem(
436 o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
437 dict->AddIntegerItem(
439 o->GetValueForExpressionPath(".destroyed")->GetValueAsUnsigned(0));
440 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
442 dict->AddItem("mutexes", StructuredData::ObjectSP(mutexes));
444 StructuredData::Array *threads = ConvertToStructuredArray(
445 main_value, ".threads", ".thread_count",
446 [process_sp, &thread_id_map](ValueObjectSP o,
447 StructuredData::Dictionary *dict) {
448 dict->AddIntegerItem(
450 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
451 dict->AddIntegerItem(
454 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0),
456 dict->AddIntegerItem(
458 o->GetValueForExpressionPath(".os_id")->GetValueAsUnsigned(0));
459 dict->AddIntegerItem(
461 o->GetValueForExpressionPath(".running")->GetValueAsUnsigned(0));
462 dict->AddStringItem("name", RetrieveString(o, process_sp, ".name"));
463 dict->AddIntegerItem(
465 Renumber(o->GetValueForExpressionPath(".parent_tid")
466 ->GetValueAsUnsigned(0),
468 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
470 dict->AddItem("threads", StructuredData::ObjectSP(threads));
472 StructuredData::Array *unique_tids = ConvertToStructuredArray(
473 main_value, ".unique_tids", ".unique_tid_count",
474 [&thread_id_map](ValueObjectSP o, StructuredData::Dictionary *dict) {
475 dict->AddIntegerItem(
477 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
478 dict->AddIntegerItem(
481 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0),
484 dict->AddItem("unique_tids", StructuredData::ObjectSP(unique_tids));
486 return StructuredData::ObjectSP(dict);
490 ThreadSanitizerRuntime::FormatDescription(StructuredData::ObjectSP report) {
491 std::string description = report->GetAsDictionary()
492 ->GetValueForKey("issue_type")
496 if (description == "data-race") {
498 } else if (description == "data-race-vptr") {
499 return "Data race on C++ virtual pointer";
500 } else if (description == "heap-use-after-free") {
501 return "Use of deallocated memory";
502 } else if (description == "heap-use-after-free-vptr") {
503 return "Use of deallocated C++ virtual pointer";
504 } else if (description == "thread-leak") {
505 return "Thread leak";
506 } else if (description == "locked-mutex-destroy") {
507 return "Destruction of a locked mutex";
508 } else if (description == "mutex-double-lock") {
509 return "Double lock of a mutex";
510 } else if (description == "mutex-invalid-access") {
511 return "Use of an uninitialized or destroyed mutex";
512 } else if (description == "mutex-bad-unlock") {
513 return "Unlock of an unlocked mutex (or by a wrong thread)";
514 } else if (description == "mutex-bad-read-lock") {
515 return "Read lock of a write locked mutex";
516 } else if (description == "mutex-bad-read-unlock") {
517 return "Read unlock of a write locked mutex";
518 } else if (description == "signal-unsafe-call") {
519 return "Signal-unsafe call inside a signal handler";
520 } else if (description == "errno-in-signal-handler") {
521 return "Overwrite of errno in a signal handler";
522 } else if (description == "lock-order-inversion") {
523 return "Lock order inversion (potential deadlock)";
524 } else if (description == "external-race") {
525 return "Race on a library object";
526 } else if (description == "swift-access-race") {
527 return "Swift access race";
530 // for unknown report codes just show the code
534 static std::string Sprintf(const char *format, ...) {
537 va_start(args, format);
538 s.PrintfVarArg(format, args);
540 return s.GetString();
543 static std::string GetSymbolNameFromAddress(ProcessSP process_sp, addr_t addr) {
544 lldb_private::Address so_addr;
545 if (!process_sp->GetTarget().GetSectionLoadList().ResolveLoadAddress(addr,
549 lldb_private::Symbol *symbol = so_addr.CalculateSymbolContextSymbol();
553 std::string sym_name = symbol->GetName().GetCString();
557 static void GetSymbolDeclarationFromAddress(ProcessSP process_sp, addr_t addr,
559 lldb_private::Address so_addr;
560 if (!process_sp->GetTarget().GetSectionLoadList().ResolveLoadAddress(addr,
564 lldb_private::Symbol *symbol = so_addr.CalculateSymbolContextSymbol();
568 ConstString sym_name = symbol->GetMangled().GetName(
569 lldb::eLanguageTypeUnknown, Mangled::ePreferMangled);
571 ModuleSP module = symbol->CalculateSymbolContextModule();
575 VariableList var_list;
576 module->FindGlobalVariables(sym_name, nullptr, 1U, var_list);
577 if (var_list.GetSize() < 1)
580 VariableSP var = var_list.GetVariableAtIndex(0);
581 decl = var->GetDeclaration();
584 addr_t ThreadSanitizerRuntime::GetFirstNonInternalFramePc(
585 StructuredData::ObjectSP trace, bool skip_one_frame) {
586 ProcessSP process_sp = GetProcessSP();
587 ModuleSP runtime_module_sp = GetRuntimeModuleSP();
589 StructuredData::Array *trace_array = trace->GetAsArray();
590 for (size_t i = 0; i < trace_array->GetSize(); i++) {
591 if (skip_one_frame && i == 0)
595 if (!trace_array->GetItemAtIndexAsInteger(i, addr))
598 lldb_private::Address so_addr;
599 if (!process_sp->GetTarget().GetSectionLoadList().ResolveLoadAddress(
603 if (so_addr.GetModule() == runtime_module_sp)
613 ThreadSanitizerRuntime::GenerateSummary(StructuredData::ObjectSP report) {
614 ProcessSP process_sp = GetProcessSP();
616 std::string summary = report->GetAsDictionary()
617 ->GetValueForKey("description")
620 bool skip_one_frame =
621 report->GetObjectForDotSeparatedPath("issue_type")->GetStringValue() ==
625 if (report->GetAsDictionary()
626 ->GetValueForKey("mops")
629 pc = GetFirstNonInternalFramePc(report->GetAsDictionary()
630 ->GetValueForKey("mops")
634 ->GetValueForKey("trace"),
637 if (report->GetAsDictionary()
638 ->GetValueForKey("stacks")
641 pc = GetFirstNonInternalFramePc(report->GetAsDictionary()
642 ->GetValueForKey("stacks")
646 ->GetValueForKey("trace"),
650 summary = summary + " in " + GetSymbolNameFromAddress(process_sp, pc);
653 if (report->GetAsDictionary()
654 ->GetValueForKey("locs")
657 StructuredData::ObjectSP loc = report->GetAsDictionary()
658 ->GetValueForKey("locs")
661 std::string object_type = loc->GetAsDictionary()
662 ->GetValueForKey("object_type")
665 if (!object_type.empty()) {
666 summary = "Race on " + object_type + " object";
668 addr_t addr = loc->GetAsDictionary()
669 ->GetValueForKey("address")
673 addr = loc->GetAsDictionary()
674 ->GetValueForKey("start")
679 std::string global_name = GetSymbolNameFromAddress(process_sp, addr);
680 if (!global_name.empty()) {
681 summary = summary + " at " + global_name;
683 summary = summary + " at " + Sprintf("0x%llx", addr);
686 int fd = loc->GetAsDictionary()
687 ->GetValueForKey("file_descriptor")
691 summary = summary + " on file descriptor " + Sprintf("%d", fd);
700 ThreadSanitizerRuntime::GetMainRacyAddress(StructuredData::ObjectSP report) {
701 addr_t result = (addr_t)-1;
703 report->GetObjectForDotSeparatedPath("mops")->GetAsArray()->ForEach(
704 [&result](StructuredData::Object *o) -> bool {
706 o->GetObjectForDotSeparatedPath("address")->GetIntegerValue();
712 return (result == (addr_t)-1) ? 0 : result;
715 std::string ThreadSanitizerRuntime::GetLocationDescription(
716 StructuredData::ObjectSP report, addr_t &global_addr,
717 std::string &global_name, std::string &filename, uint32_t &line) {
718 std::string result = "";
720 ProcessSP process_sp = GetProcessSP();
722 if (report->GetAsDictionary()
723 ->GetValueForKey("locs")
726 StructuredData::ObjectSP loc = report->GetAsDictionary()
727 ->GetValueForKey("locs")
731 loc->GetAsDictionary()->GetValueForKey("type")->GetStringValue();
732 if (type == "global") {
733 global_addr = loc->GetAsDictionary()
734 ->GetValueForKey("address")
737 global_name = GetSymbolNameFromAddress(process_sp, global_addr);
738 if (!global_name.empty()) {
739 result = Sprintf("'%s' is a global variable (0x%llx)",
740 global_name.c_str(), global_addr);
742 result = Sprintf("0x%llx is a global variable", global_addr);
746 GetSymbolDeclarationFromAddress(process_sp, global_addr, decl);
747 if (decl.GetFile()) {
748 filename = decl.GetFile().GetPath();
749 line = decl.GetLine();
751 } else if (type == "heap") {
752 addr_t addr = loc->GetAsDictionary()
753 ->GetValueForKey("start")
756 long size = loc->GetAsDictionary()
757 ->GetValueForKey("size")
760 std::string object_type = loc->GetAsDictionary()
761 ->GetValueForKey("object_type")
764 if (!object_type.empty()) {
765 result = Sprintf("Location is a %ld-byte %s object at 0x%llx", size,
766 object_type.c_str(), addr);
769 Sprintf("Location is a %ld-byte heap object at 0x%llx", size, addr);
771 } else if (type == "stack") {
772 int tid = loc->GetAsDictionary()
773 ->GetValueForKey("thread_id")
776 result = Sprintf("Location is stack of thread %d", tid);
777 } else if (type == "tls") {
778 int tid = loc->GetAsDictionary()
779 ->GetValueForKey("thread_id")
782 result = Sprintf("Location is TLS of thread %d", tid);
783 } else if (type == "fd") {
784 int fd = loc->GetAsDictionary()
785 ->GetValueForKey("file_descriptor")
788 result = Sprintf("Location is file descriptor %d", fd);
795 bool ThreadSanitizerRuntime::NotifyBreakpointHit(
796 void *baton, StoppointCallbackContext *context, user_id_t break_id,
797 user_id_t break_loc_id) {
798 assert(baton && "null baton");
802 ThreadSanitizerRuntime *const instance =
803 static_cast<ThreadSanitizerRuntime *>(baton);
805 ProcessSP process_sp = instance->GetProcessSP();
807 if (process_sp->GetModIDRef().IsLastResumeForUserExpression())
810 StructuredData::ObjectSP report =
811 instance->RetrieveReportData(context->exe_ctx_ref);
812 std::string stop_reason_description;
814 std::string issue_description = instance->FormatDescription(report);
815 report->GetAsDictionary()->AddStringItem("description", issue_description);
816 stop_reason_description = issue_description + " detected";
817 report->GetAsDictionary()->AddStringItem("stop_description",
818 stop_reason_description);
819 std::string summary = instance->GenerateSummary(report);
820 report->GetAsDictionary()->AddStringItem("summary", summary);
821 addr_t main_address = instance->GetMainRacyAddress(report);
822 report->GetAsDictionary()->AddIntegerItem("memory_address", main_address);
824 addr_t global_addr = 0;
825 std::string global_name = "";
826 std::string location_filename = "";
827 uint32_t location_line = 0;
828 std::string location_description = instance->GetLocationDescription(
829 report, global_addr, global_name, location_filename, location_line);
830 report->GetAsDictionary()->AddStringItem("location_description",
831 location_description);
832 if (global_addr != 0) {
833 report->GetAsDictionary()->AddIntegerItem("global_address", global_addr);
835 if (!global_name.empty()) {
836 report->GetAsDictionary()->AddStringItem("global_name", global_name);
838 if (location_filename != "") {
839 report->GetAsDictionary()->AddStringItem("location_filename",
841 report->GetAsDictionary()->AddIntegerItem("location_line", location_line);
844 bool all_addresses_are_same = true;
845 report->GetObjectForDotSeparatedPath("mops")->GetAsArray()->ForEach(
846 [&all_addresses_are_same,
847 main_address](StructuredData::Object *o) -> bool {
849 o->GetObjectForDotSeparatedPath("address")->GetIntegerValue();
850 if (main_address != addr)
851 all_addresses_are_same = false;
854 report->GetAsDictionary()->AddBooleanItem("all_addresses_are_same",
855 all_addresses_are_same);
858 // Make sure this is the right process
859 if (process_sp && process_sp == context->exe_ctx_ref.GetProcessSP()) {
860 ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
862 thread_sp->SetStopInfo(
863 InstrumentationRuntimeStopInfo::
864 CreateStopReasonWithInstrumentationData(
865 *thread_sp, stop_reason_description, report));
867 StreamFileSP stream_sp(
868 process_sp->GetTarget().GetDebugger().GetOutputFile());
870 stream_sp->Printf("ThreadSanitizer report breakpoint hit. Use 'thread "
871 "info -s' to get extended information about the "
874 return true; // Return true to stop the target
876 return false; // Let target run
879 const RegularExpression &ThreadSanitizerRuntime::GetPatternForRuntimeLibrary() {
880 static RegularExpression regex(llvm::StringRef("libclang_rt.tsan_"));
884 bool ThreadSanitizerRuntime::CheckIfRuntimeIsValid(
885 const lldb::ModuleSP module_sp) {
886 static ConstString g_tsan_get_current_report("__tsan_get_current_report");
887 const Symbol *symbol = module_sp->FindFirstSymbolWithNameAndType(
888 g_tsan_get_current_report, lldb::eSymbolTypeAny);
889 return symbol != nullptr;
892 void ThreadSanitizerRuntime::Activate() {
896 ProcessSP process_sp = GetProcessSP();
900 ConstString symbol_name("__tsan_on_report");
901 const Symbol *symbol = GetRuntimeModuleSP()->FindFirstSymbolWithNameAndType(
902 symbol_name, eSymbolTypeCode);
907 if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
910 Target &target = process_sp->GetTarget();
911 addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
913 if (symbol_address == LLDB_INVALID_ADDRESS)
916 bool internal = true;
917 bool hardware = false;
918 Breakpoint *breakpoint =
919 process_sp->GetTarget()
920 .CreateBreakpoint(symbol_address, internal, hardware)
922 breakpoint->SetCallback(ThreadSanitizerRuntime::NotifyBreakpointHit, this,
924 breakpoint->SetBreakpointKind("thread-sanitizer-report");
925 SetBreakpointID(breakpoint->GetID());
930 void ThreadSanitizerRuntime::Deactivate() {
931 if (GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
932 ProcessSP process_sp = GetProcessSP();
934 process_sp->GetTarget().RemoveBreakpointByID(GetBreakpointID());
935 SetBreakpointID(LLDB_INVALID_BREAK_ID);
940 static std::string GenerateThreadName(const std::string &path,
941 StructuredData::Object *o,
942 StructuredData::ObjectSP main_info) {
943 std::string result = "additional information";
945 if (path == "mops") {
946 int size = o->GetObjectForDotSeparatedPath("size")->GetIntegerValue();
948 o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
950 o->GetObjectForDotSeparatedPath("is_write")->GetBooleanValue();
952 o->GetObjectForDotSeparatedPath("is_atomic")->GetBooleanValue();
953 addr_t addr = o->GetObjectForDotSeparatedPath("address")->GetIntegerValue();
955 std::string addr_string = Sprintf(" at 0x%llx", addr);
957 if (main_info->GetObjectForDotSeparatedPath("all_addresses_are_same")
958 ->GetBooleanValue()) {
962 if (main_info->GetObjectForDotSeparatedPath("issue_type")
963 ->GetStringValue() == "external-race") {
964 result = Sprintf("%s access by thread %d",
965 is_write ? "mutating" : "read-only", thread_id);
966 } else if (main_info->GetObjectForDotSeparatedPath("issue_type")
967 ->GetStringValue() == "swift-access-race") {
968 result = Sprintf("modifying access by thread %d", thread_id);
970 result = Sprintf("%s%s of size %d%s by thread %d",
971 is_atomic ? "atomic " : "", is_write ? "write" : "read",
972 size, addr_string.c_str(), thread_id);
976 if (path == "threads") {
978 o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
979 result = Sprintf("Thread %d created", thread_id);
982 if (path == "locs") {
984 o->GetAsDictionary()->GetValueForKey("type")->GetStringValue();
986 o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
988 o->GetObjectForDotSeparatedPath("file_descriptor")->GetIntegerValue();
989 if (type == "heap") {
990 result = Sprintf("Heap block allocated by thread %d", thread_id);
991 } else if (type == "fd") {
993 Sprintf("File descriptor %d created by thread %t", fd, thread_id);
997 if (path == "mutexes") {
999 o->GetObjectForDotSeparatedPath("mutex_id")->GetIntegerValue();
1001 result = Sprintf("Mutex M%d created", mutex_id);
1004 if (path == "stacks") {
1006 o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
1007 result = Sprintf("Thread %d", thread_id);
1010 result[0] = toupper(result[0]);
1015 static void AddThreadsForPath(const std::string &path,
1016 ThreadCollectionSP threads, ProcessSP process_sp,
1017 StructuredData::ObjectSP info) {
1018 info->GetObjectForDotSeparatedPath(path)->GetAsArray()->ForEach(
1019 [process_sp, threads, path, info](StructuredData::Object *o) -> bool {
1020 std::vector<lldb::addr_t> pcs;
1021 o->GetObjectForDotSeparatedPath("trace")->GetAsArray()->ForEach(
1022 [&pcs](StructuredData::Object *pc) -> bool {
1023 pcs.push_back(pc->GetAsInteger()->GetValue());
1027 if (pcs.size() == 0)
1030 StructuredData::ObjectSP thread_id_obj =
1031 o->GetObjectForDotSeparatedPath("thread_os_id");
1032 tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0;
1034 uint32_t stop_id = 0;
1035 bool stop_id_is_valid = false;
1036 HistoryThread *history_thread =
1037 new HistoryThread(*process_sp, tid, pcs, stop_id, stop_id_is_valid);
1038 ThreadSP new_thread_sp(history_thread);
1039 new_thread_sp->SetName(GenerateThreadName(path, o, info).c_str());
1041 // Save this in the Process' ExtendedThreadList so a strong pointer
1042 // retains the object
1043 process_sp->GetExtendedThreadList().AddThread(new_thread_sp);
1044 threads->AddThread(new_thread_sp);
1050 lldb::ThreadCollectionSP
1051 ThreadSanitizerRuntime::GetBacktracesFromExtendedStopInfo(
1052 StructuredData::ObjectSP info) {
1053 ThreadCollectionSP threads;
1054 threads.reset(new ThreadCollection());
1056 if (info->GetObjectForDotSeparatedPath("instrumentation_class")
1057 ->GetStringValue() != "ThreadSanitizer")
1060 ProcessSP process_sp = GetProcessSP();
1062 AddThreadsForPath("stacks", threads, process_sp, info);
1063 AddThreadsForPath("mops", threads, process_sp, info);
1064 AddThreadsForPath("locs", threads, process_sp, info);
1065 AddThreadsForPath("mutexes", threads, process_sp, info);
1066 AddThreadsForPath("threads", threads, process_sp, info);