1 //===-- ThreadSanitizerRuntime.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 "ThreadSanitizerRuntime.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/RegularExpression.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/Symbol/Variable.h"
27 #include "lldb/Symbol/VariableList.h"
28 #include "lldb/Target/InstrumentationRuntimeStopInfo.h"
29 #include "lldb/Target/SectionLoadList.h"
30 #include "lldb/Target/StopInfo.h"
31 #include "lldb/Target/Target.h"
32 #include "lldb/Target/Thread.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);
90 const int REPORT_TRACE_SIZE = 128;
91 const int REPORT_ARRAY_SIZE = 4;
95 const char *description;
98 void *sleep_trace[REPORT_TRACE_SIZE];
103 void *trace[REPORT_TRACE_SIZE];
104 } stacks[REPORT_ARRAY_SIZE];
114 void *trace[REPORT_TRACE_SIZE];
115 } mops[REPORT_ARRAY_SIZE];
127 void *trace[REPORT_TRACE_SIZE];
128 } locs[REPORT_ARRAY_SIZE];
133 unsigned long mutex_id;
136 void *trace[REPORT_TRACE_SIZE];
137 } mutexes[REPORT_ARRAY_SIZE];
147 void *trace[REPORT_TRACE_SIZE];
148 } threads[REPORT_ARRAY_SIZE];
150 int unique_tid_count;
154 } unique_tids[REPORT_ARRAY_SIZE];
158 const char *thread_sanitizer_retrieve_report_data_command = R"(
161 t.report = __tsan_get_current_report();
162 __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);
164 if (t.stack_count > REPORT_ARRAY_SIZE) t.stack_count = REPORT_ARRAY_SIZE;
165 for (int i = 0; i < t.stack_count; i++) {
167 __tsan_get_report_stack(t.report, i, t.stacks[i].trace, REPORT_TRACE_SIZE);
170 if (t.mop_count > REPORT_ARRAY_SIZE) t.mop_count = REPORT_ARRAY_SIZE;
171 for (int i = 0; i < t.mop_count; i++) {
173 __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);
176 if (t.loc_count > REPORT_ARRAY_SIZE) t.loc_count = REPORT_ARRAY_SIZE;
177 for (int i = 0; i < t.loc_count; i++) {
179 __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);
182 if (t.mutex_count > REPORT_ARRAY_SIZE) t.mutex_count = REPORT_ARRAY_SIZE;
183 for (int i = 0; i < t.mutex_count; i++) {
184 t.mutexes[i].idx = i;
185 __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);
188 if (t.thread_count > REPORT_ARRAY_SIZE) t.thread_count = REPORT_ARRAY_SIZE;
189 for (int i = 0; i < t.thread_count; i++) {
190 t.threads[i].idx = i;
191 __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);
194 if (t.unique_tid_count > REPORT_ARRAY_SIZE) t.unique_tid_count = REPORT_ARRAY_SIZE;
195 for (int i = 0; i < t.unique_tid_count; i++) {
196 t.unique_tids[i].idx = i;
197 __tsan_get_report_unique_tid(t.report, i, &t.unique_tids[i].tid);
203 static StructuredData::Array *
204 CreateStackTrace(ValueObjectSP o,
205 const std::string &trace_item_name = ".trace") {
206 StructuredData::Array *trace = new StructuredData::Array();
207 ValueObjectSP trace_value_object =
208 o->GetValueForExpressionPath(trace_item_name.c_str());
209 for (int j = 0; j < 8; j++) {
211 trace_value_object->GetChildAtIndex(j, true)->GetValueAsUnsigned(0);
215 StructuredData::ObjectSP(new StructuredData::Integer(trace_addr)));
220 static StructuredData::Array *ConvertToStructuredArray(
221 ValueObjectSP return_value_sp, const std::string &items_name,
222 const std::string &count_name,
223 std::function<void(ValueObjectSP o, StructuredData::Dictionary *dict)> const
225 StructuredData::Array *array = new StructuredData::Array();
227 return_value_sp->GetValueForExpressionPath(count_name.c_str())
228 ->GetValueAsUnsigned(0);
229 ValueObjectSP objects =
230 return_value_sp->GetValueForExpressionPath(items_name.c_str());
231 for (unsigned int i = 0; i < count; i++) {
232 ValueObjectSP o = objects->GetChildAtIndex(i, true);
233 StructuredData::Dictionary *dict = new StructuredData::Dictionary();
237 array->AddItem(StructuredData::ObjectSP(dict));
242 static std::string RetrieveString(ValueObjectSP return_value_sp,
243 ProcessSP process_sp,
244 const std::string &expression_path) {
246 return_value_sp->GetValueForExpressionPath(expression_path.c_str())
247 ->GetValueAsUnsigned(0);
250 process_sp->ReadCStringFromMemory(ptr, str, error);
255 GetRenumberedThreadIds(ProcessSP process_sp, ValueObjectSP data,
256 std::map<uint64_t, user_id_t> &thread_id_map) {
257 ConvertToStructuredArray(
258 data, ".threads", ".thread_count",
259 [process_sp, &thread_id_map](ValueObjectSP o,
260 StructuredData::Dictionary *dict) {
262 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0);
263 uint64_t thread_os_id =
264 o->GetValueForExpressionPath(".os_id")->GetValueAsUnsigned(0);
265 user_id_t lldb_user_id = 0;
267 bool can_update = true;
268 ThreadSP lldb_thread = process_sp->GetThreadList().FindThreadByID(
269 thread_os_id, can_update);
271 lldb_user_id = lldb_thread->GetIndexID();
273 // This isn't a live thread anymore. Ask process to assign a new
274 // Index ID (or return an old one if we've already seen this
276 // It will also make sure that no new threads are assigned this Index
278 lldb_user_id = process_sp->AssignIndexIDToThread(thread_os_id);
281 thread_id_map[thread_id] = lldb_user_id;
285 static user_id_t Renumber(uint64_t id,
286 std::map<uint64_t, user_id_t> &thread_id_map) {
287 auto IT = thread_id_map.find(id);
288 if (IT == thread_id_map.end())
294 StructuredData::ObjectSP
295 ThreadSanitizerRuntime::RetrieveReportData(ExecutionContextRef exe_ctx_ref) {
296 ProcessSP process_sp = GetProcessSP();
298 return StructuredData::ObjectSP();
300 ThreadSP thread_sp = exe_ctx_ref.GetThreadSP();
301 StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
304 return StructuredData::ObjectSP();
306 EvaluateExpressionOptions options;
307 options.SetUnwindOnError(true);
308 options.SetTryAllThreads(true);
309 options.SetStopOthers(true);
310 options.SetIgnoreBreakpoints(true);
311 options.SetTimeout(g_retrieve_data_function_timeout);
312 options.SetPrefix(thread_sanitizer_retrieve_report_data_prefix);
313 options.SetAutoApplyFixIts(false);
314 options.SetLanguage(eLanguageTypeObjC_plus_plus);
316 ValueObjectSP main_value;
317 ExecutionContext exe_ctx;
319 frame_sp->CalculateExecutionContext(exe_ctx);
320 ExpressionResults result = UserExpression::Evaluate(
321 exe_ctx, options, thread_sanitizer_retrieve_report_data_command, "",
322 main_value, eval_error);
323 if (result != eExpressionCompleted) {
324 process_sp->GetTarget().GetDebugger().GetAsyncOutputStream()->Printf(
325 "Warning: Cannot evaluate ThreadSanitizer expression:\n%s\n",
326 eval_error.AsCString());
327 return StructuredData::ObjectSP();
330 std::map<uint64_t, user_id_t> thread_id_map;
331 GetRenumberedThreadIds(process_sp, main_value, thread_id_map);
333 StructuredData::Dictionary *dict = new StructuredData::Dictionary();
334 dict->AddStringItem("instrumentation_class", "ThreadSanitizer");
335 dict->AddStringItem("issue_type",
336 RetrieveString(main_value, process_sp, ".description"));
337 dict->AddIntegerItem("report_count",
338 main_value->GetValueForExpressionPath(".report_count")
339 ->GetValueAsUnsigned(0));
340 dict->AddItem("sleep_trace", StructuredData::ObjectSP(CreateStackTrace(
341 main_value, ".sleep_trace")));
343 StructuredData::Array *stacks = ConvertToStructuredArray(
344 main_value, ".stacks", ".stack_count",
345 [thread_sp](ValueObjectSP o, StructuredData::Dictionary *dict) {
346 dict->AddIntegerItem(
348 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
349 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
350 // "stacks" happen on the current thread
351 dict->AddIntegerItem("thread_id", thread_sp->GetIndexID());
353 dict->AddItem("stacks", StructuredData::ObjectSP(stacks));
355 StructuredData::Array *mops = ConvertToStructuredArray(
356 main_value, ".mops", ".mop_count",
357 [&thread_id_map](ValueObjectSP o, StructuredData::Dictionary *dict) {
358 dict->AddIntegerItem(
360 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
361 dict->AddIntegerItem(
364 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0),
366 dict->AddIntegerItem(
368 o->GetValueForExpressionPath(".size")->GetValueAsUnsigned(0));
369 dict->AddBooleanItem(
371 o->GetValueForExpressionPath(".write")->GetValueAsUnsigned(0));
372 dict->AddBooleanItem(
374 o->GetValueForExpressionPath(".atomic")->GetValueAsUnsigned(0));
375 dict->AddIntegerItem(
377 o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
378 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
380 dict->AddItem("mops", StructuredData::ObjectSP(mops));
382 StructuredData::Array *locs = ConvertToStructuredArray(
383 main_value, ".locs", ".loc_count",
384 [process_sp, &thread_id_map](ValueObjectSP o,
385 StructuredData::Dictionary *dict) {
386 dict->AddIntegerItem(
388 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
389 dict->AddStringItem("type", RetrieveString(o, process_sp, ".type"));
390 dict->AddIntegerItem(
392 o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
393 dict->AddIntegerItem(
395 o->GetValueForExpressionPath(".start")->GetValueAsUnsigned(0));
396 dict->AddIntegerItem(
398 o->GetValueForExpressionPath(".size")->GetValueAsUnsigned(0));
399 dict->AddIntegerItem(
402 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0),
404 dict->AddIntegerItem(
406 o->GetValueForExpressionPath(".fd")->GetValueAsUnsigned(0));
407 dict->AddIntegerItem("suppressable",
408 o->GetValueForExpressionPath(".suppressable")
409 ->GetValueAsUnsigned(0));
410 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
412 dict->AddItem("locs", StructuredData::ObjectSP(locs));
414 StructuredData::Array *mutexes = ConvertToStructuredArray(
415 main_value, ".mutexes", ".mutex_count",
416 [](ValueObjectSP o, StructuredData::Dictionary *dict) {
417 dict->AddIntegerItem(
419 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
420 dict->AddIntegerItem(
422 o->GetValueForExpressionPath(".mutex_id")->GetValueAsUnsigned(0));
423 dict->AddIntegerItem(
425 o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
426 dict->AddIntegerItem(
428 o->GetValueForExpressionPath(".destroyed")->GetValueAsUnsigned(0));
429 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
431 dict->AddItem("mutexes", StructuredData::ObjectSP(mutexes));
433 StructuredData::Array *threads = ConvertToStructuredArray(
434 main_value, ".threads", ".thread_count",
435 [process_sp, &thread_id_map](ValueObjectSP o,
436 StructuredData::Dictionary *dict) {
437 dict->AddIntegerItem(
439 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
440 dict->AddIntegerItem(
443 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0),
445 dict->AddIntegerItem(
447 o->GetValueForExpressionPath(".os_id")->GetValueAsUnsigned(0));
448 dict->AddIntegerItem(
450 o->GetValueForExpressionPath(".running")->GetValueAsUnsigned(0));
451 dict->AddStringItem("name", RetrieveString(o, process_sp, ".name"));
452 dict->AddIntegerItem(
454 Renumber(o->GetValueForExpressionPath(".parent_tid")
455 ->GetValueAsUnsigned(0),
457 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
459 dict->AddItem("threads", StructuredData::ObjectSP(threads));
461 StructuredData::Array *unique_tids = ConvertToStructuredArray(
462 main_value, ".unique_tids", ".unique_tid_count",
463 [&thread_id_map](ValueObjectSP o, StructuredData::Dictionary *dict) {
464 dict->AddIntegerItem(
466 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
467 dict->AddIntegerItem(
470 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0),
473 dict->AddItem("unique_tids", StructuredData::ObjectSP(unique_tids));
475 return StructuredData::ObjectSP(dict);
479 ThreadSanitizerRuntime::FormatDescription(StructuredData::ObjectSP report) {
480 std::string description = report->GetAsDictionary()
481 ->GetValueForKey("issue_type")
485 if (description == "data-race") {
487 } else if (description == "data-race-vptr") {
488 return "Data race on C++ virtual pointer";
489 } else if (description == "heap-use-after-free") {
490 return "Use of deallocated memory";
491 } else if (description == "heap-use-after-free-vptr") {
492 return "Use of deallocated C++ virtual pointer";
493 } else if (description == "thread-leak") {
494 return "Thread leak";
495 } else if (description == "locked-mutex-destroy") {
496 return "Destruction of a locked mutex";
497 } else if (description == "mutex-double-lock") {
498 return "Double lock of a mutex";
499 } else if (description == "mutex-invalid-access") {
500 return "Use of an uninitialized or destroyed mutex";
501 } else if (description == "mutex-bad-unlock") {
502 return "Unlock of an unlocked mutex (or by a wrong thread)";
503 } else if (description == "mutex-bad-read-lock") {
504 return "Read lock of a write locked mutex";
505 } else if (description == "mutex-bad-read-unlock") {
506 return "Read unlock of a write locked mutex";
507 } else if (description == "signal-unsafe-call") {
508 return "Signal-unsafe call inside a signal handler";
509 } else if (description == "errno-in-signal-handler") {
510 return "Overwrite of errno in a signal handler";
511 } else if (description == "lock-order-inversion") {
512 return "Lock order inversion (potential deadlock)";
515 // for unknown report codes just show the code
519 static std::string Sprintf(const char *format, ...) {
522 va_start(args, format);
523 s.PrintfVarArg(format, args);
525 return s.GetString();
528 static std::string GetSymbolNameFromAddress(ProcessSP process_sp, addr_t addr) {
529 lldb_private::Address so_addr;
530 if (!process_sp->GetTarget().GetSectionLoadList().ResolveLoadAddress(addr,
534 lldb_private::Symbol *symbol = so_addr.CalculateSymbolContextSymbol();
538 std::string sym_name = symbol->GetName().GetCString();
542 static void GetSymbolDeclarationFromAddress(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 ConstString sym_name = symbol->GetMangled().GetName(
554 lldb::eLanguageTypeUnknown, Mangled::ePreferMangled);
556 ModuleSP module = symbol->CalculateSymbolContextModule();
560 VariableList var_list;
561 module->FindGlobalVariables(sym_name, nullptr, true, 1U, var_list);
562 if (var_list.GetSize() < 1)
565 VariableSP var = var_list.GetVariableAtIndex(0);
566 decl = var->GetDeclaration();
569 addr_t ThreadSanitizerRuntime::GetFirstNonInternalFramePc(
570 StructuredData::ObjectSP trace) {
571 ProcessSP process_sp = GetProcessSP();
572 ModuleSP runtime_module_sp = GetRuntimeModuleSP();
575 trace->GetAsArray()->ForEach([process_sp, runtime_module_sp,
576 &result](StructuredData::Object *o) -> bool {
577 addr_t addr = o->GetIntegerValue();
578 lldb_private::Address so_addr;
579 if (!process_sp->GetTarget().GetSectionLoadList().ResolveLoadAddress(
583 if (so_addr.GetModule() == runtime_module_sp)
594 ThreadSanitizerRuntime::GenerateSummary(StructuredData::ObjectSP report) {
595 ProcessSP process_sp = GetProcessSP();
597 std::string summary = report->GetAsDictionary()
598 ->GetValueForKey("description")
602 if (report->GetAsDictionary()
603 ->GetValueForKey("mops")
606 pc = GetFirstNonInternalFramePc(report->GetAsDictionary()
607 ->GetValueForKey("mops")
611 ->GetValueForKey("trace"));
613 if (report->GetAsDictionary()
614 ->GetValueForKey("stacks")
617 pc = GetFirstNonInternalFramePc(report->GetAsDictionary()
618 ->GetValueForKey("stacks")
622 ->GetValueForKey("trace"));
625 summary = summary + " in " + GetSymbolNameFromAddress(process_sp, pc);
628 if (report->GetAsDictionary()
629 ->GetValueForKey("locs")
632 StructuredData::ObjectSP loc = report->GetAsDictionary()
633 ->GetValueForKey("locs")
636 addr_t addr = loc->GetAsDictionary()
637 ->GetValueForKey("address")
641 addr = loc->GetAsDictionary()
642 ->GetValueForKey("start")
647 std::string global_name = GetSymbolNameFromAddress(process_sp, addr);
648 if (!global_name.empty()) {
649 summary = summary + " at " + global_name;
651 summary = summary + " at " + Sprintf("0x%llx", addr);
654 int fd = loc->GetAsDictionary()
655 ->GetValueForKey("file_descriptor")
659 summary = summary + " on file descriptor " + Sprintf("%d", fd);
668 ThreadSanitizerRuntime::GetMainRacyAddress(StructuredData::ObjectSP report) {
669 addr_t result = (addr_t)-1;
671 report->GetObjectForDotSeparatedPath("mops")->GetAsArray()->ForEach(
672 [&result](StructuredData::Object *o) -> bool {
674 o->GetObjectForDotSeparatedPath("address")->GetIntegerValue();
680 return (result == (addr_t)-1) ? 0 : result;
683 std::string ThreadSanitizerRuntime::GetLocationDescription(
684 StructuredData::ObjectSP report, addr_t &global_addr,
685 std::string &global_name, std::string &filename, uint32_t &line) {
686 std::string result = "";
688 ProcessSP process_sp = GetProcessSP();
690 if (report->GetAsDictionary()
691 ->GetValueForKey("locs")
694 StructuredData::ObjectSP loc = report->GetAsDictionary()
695 ->GetValueForKey("locs")
699 loc->GetAsDictionary()->GetValueForKey("type")->GetStringValue();
700 if (type == "global") {
701 global_addr = loc->GetAsDictionary()
702 ->GetValueForKey("address")
705 global_name = GetSymbolNameFromAddress(process_sp, global_addr);
706 if (!global_name.empty()) {
707 result = Sprintf("'%s' is a global variable (0x%llx)",
708 global_name.c_str(), global_addr);
710 result = Sprintf("0x%llx is a global variable", global_addr);
714 GetSymbolDeclarationFromAddress(process_sp, global_addr, decl);
715 if (decl.GetFile()) {
716 filename = decl.GetFile().GetPath();
717 line = decl.GetLine();
719 } else if (type == "heap") {
720 addr_t addr = loc->GetAsDictionary()
721 ->GetValueForKey("start")
724 long size = loc->GetAsDictionary()
725 ->GetValueForKey("size")
729 Sprintf("Location is a %ld-byte heap object at 0x%llx", size, addr);
730 } else if (type == "stack") {
731 int tid = loc->GetAsDictionary()
732 ->GetValueForKey("thread_id")
735 result = Sprintf("Location is stack of thread %d", tid);
736 } else if (type == "tls") {
737 int tid = loc->GetAsDictionary()
738 ->GetValueForKey("thread_id")
741 result = Sprintf("Location is TLS of thread %d", tid);
742 } else if (type == "fd") {
743 int fd = loc->GetAsDictionary()
744 ->GetValueForKey("file_descriptor")
747 result = Sprintf("Location is file descriptor %d", fd);
754 bool ThreadSanitizerRuntime::NotifyBreakpointHit(
755 void *baton, StoppointCallbackContext *context, user_id_t break_id,
756 user_id_t break_loc_id) {
757 assert(baton && "null baton");
761 ThreadSanitizerRuntime *const instance =
762 static_cast<ThreadSanitizerRuntime *>(baton);
764 StructuredData::ObjectSP report =
765 instance->RetrieveReportData(context->exe_ctx_ref);
766 std::string stop_reason_description;
768 std::string issue_description = instance->FormatDescription(report);
769 report->GetAsDictionary()->AddStringItem("description", issue_description);
770 stop_reason_description = issue_description + " detected";
771 report->GetAsDictionary()->AddStringItem("stop_description",
772 stop_reason_description);
773 std::string summary = instance->GenerateSummary(report);
774 report->GetAsDictionary()->AddStringItem("summary", summary);
775 addr_t main_address = instance->GetMainRacyAddress(report);
776 report->GetAsDictionary()->AddIntegerItem("memory_address", main_address);
778 addr_t global_addr = 0;
779 std::string global_name = "";
780 std::string location_filename = "";
781 uint32_t location_line = 0;
782 std::string location_description = instance->GetLocationDescription(
783 report, global_addr, global_name, location_filename, location_line);
784 report->GetAsDictionary()->AddStringItem("location_description",
785 location_description);
786 if (global_addr != 0) {
787 report->GetAsDictionary()->AddIntegerItem("global_address", global_addr);
789 if (!global_name.empty()) {
790 report->GetAsDictionary()->AddStringItem("global_name", global_name);
792 if (location_filename != "") {
793 report->GetAsDictionary()->AddStringItem("location_filename",
795 report->GetAsDictionary()->AddIntegerItem("location_line", location_line);
798 bool all_addresses_are_same = true;
799 report->GetObjectForDotSeparatedPath("mops")->GetAsArray()->ForEach(
800 [&all_addresses_are_same,
801 main_address](StructuredData::Object *o) -> bool {
803 o->GetObjectForDotSeparatedPath("address")->GetIntegerValue();
804 if (main_address != addr)
805 all_addresses_are_same = false;
808 report->GetAsDictionary()->AddBooleanItem("all_addresses_are_same",
809 all_addresses_are_same);
812 ProcessSP process_sp = instance->GetProcessSP();
813 // Make sure this is the right process
814 if (process_sp && process_sp == context->exe_ctx_ref.GetProcessSP()) {
815 ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
817 thread_sp->SetStopInfo(
818 InstrumentationRuntimeStopInfo::
819 CreateStopReasonWithInstrumentationData(
820 *thread_sp, stop_reason_description, report));
822 StreamFileSP stream_sp(
823 process_sp->GetTarget().GetDebugger().GetOutputFile());
825 stream_sp->Printf("ThreadSanitizer report breakpoint hit. Use 'thread "
826 "info -s' to get extended information about the "
829 return true; // Return true to stop the target
831 return false; // Let target run
834 const RegularExpression &ThreadSanitizerRuntime::GetPatternForRuntimeLibrary() {
835 static RegularExpression regex(llvm::StringRef("libclang_rt.tsan_"));
839 bool ThreadSanitizerRuntime::CheckIfRuntimeIsValid(
840 const lldb::ModuleSP module_sp) {
841 static ConstString g_tsan_get_current_report("__tsan_get_current_report");
842 const Symbol *symbol = module_sp->FindFirstSymbolWithNameAndType(
843 g_tsan_get_current_report, lldb::eSymbolTypeAny);
844 return symbol != nullptr;
847 void ThreadSanitizerRuntime::Activate() {
851 ProcessSP process_sp = GetProcessSP();
855 ConstString symbol_name("__tsan_on_report");
856 const Symbol *symbol = GetRuntimeModuleSP()->FindFirstSymbolWithNameAndType(
857 symbol_name, eSymbolTypeCode);
862 if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
865 Target &target = process_sp->GetTarget();
866 addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
868 if (symbol_address == LLDB_INVALID_ADDRESS)
871 bool internal = true;
872 bool hardware = false;
873 Breakpoint *breakpoint =
874 process_sp->GetTarget()
875 .CreateBreakpoint(symbol_address, internal, hardware)
877 breakpoint->SetCallback(ThreadSanitizerRuntime::NotifyBreakpointHit, this,
879 breakpoint->SetBreakpointKind("thread-sanitizer-report");
880 SetBreakpointID(breakpoint->GetID());
882 StreamFileSP stream_sp(process_sp->GetTarget().GetDebugger().GetOutputFile());
884 stream_sp->Printf("ThreadSanitizer debugger support is active.\n");
890 void ThreadSanitizerRuntime::Deactivate() {
891 if (GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
892 ProcessSP process_sp = GetProcessSP();
894 process_sp->GetTarget().RemoveBreakpointByID(GetBreakpointID());
895 SetBreakpointID(LLDB_INVALID_BREAK_ID);
900 static std::string GenerateThreadName(const std::string &path,
901 StructuredData::Object *o,
902 StructuredData::ObjectSP main_info) {
903 std::string result = "additional information";
905 if (path == "mops") {
906 int size = o->GetObjectForDotSeparatedPath("size")->GetIntegerValue();
908 o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
910 o->GetObjectForDotSeparatedPath("is_write")->GetBooleanValue();
912 o->GetObjectForDotSeparatedPath("is_atomic")->GetBooleanValue();
913 addr_t addr = o->GetObjectForDotSeparatedPath("address")->GetIntegerValue();
915 std::string addr_string = Sprintf(" at 0x%llx", addr);
917 if (main_info->GetObjectForDotSeparatedPath("all_addresses_are_same")
918 ->GetBooleanValue()) {
922 result = Sprintf("%s%s of size %d%s by thread %d",
923 is_atomic ? "atomic " : "", is_write ? "write" : "read",
924 size, addr_string.c_str(), thread_id);
927 if (path == "threads") {
929 o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
930 result = Sprintf("Thread %d created", thread_id);
933 if (path == "locs") {
935 o->GetAsDictionary()->GetValueForKey("type")->GetStringValue();
937 o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
939 o->GetObjectForDotSeparatedPath("file_descriptor")->GetIntegerValue();
940 if (type == "heap") {
941 result = Sprintf("Heap block allocated by thread %d", thread_id);
942 } else if (type == "fd") {
944 Sprintf("File descriptor %d created by thread %t", fd, thread_id);
948 if (path == "mutexes") {
950 o->GetObjectForDotSeparatedPath("mutex_id")->GetIntegerValue();
952 result = Sprintf("Mutex M%d created", mutex_id);
955 if (path == "stacks") {
957 o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
958 result = Sprintf("Thread %d", thread_id);
961 result[0] = toupper(result[0]);
966 static void AddThreadsForPath(const std::string &path,
967 ThreadCollectionSP threads, ProcessSP process_sp,
968 StructuredData::ObjectSP info) {
969 info->GetObjectForDotSeparatedPath(path)->GetAsArray()->ForEach(
970 [process_sp, threads, path, info](StructuredData::Object *o) -> bool {
971 std::vector<lldb::addr_t> pcs;
972 o->GetObjectForDotSeparatedPath("trace")->GetAsArray()->ForEach(
973 [&pcs](StructuredData::Object *pc) -> bool {
974 pcs.push_back(pc->GetAsInteger()->GetValue());
981 StructuredData::ObjectSP thread_id_obj =
982 o->GetObjectForDotSeparatedPath("thread_os_id");
983 tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0;
985 uint32_t stop_id = 0;
986 bool stop_id_is_valid = false;
987 HistoryThread *history_thread =
988 new HistoryThread(*process_sp, tid, pcs, stop_id, stop_id_is_valid);
989 ThreadSP new_thread_sp(history_thread);
990 new_thread_sp->SetName(GenerateThreadName(path, o, info).c_str());
992 // Save this in the Process' ExtendedThreadList so a strong pointer
993 // retains the object
994 process_sp->GetExtendedThreadList().AddThread(new_thread_sp);
995 threads->AddThread(new_thread_sp);
1001 lldb::ThreadCollectionSP
1002 ThreadSanitizerRuntime::GetBacktracesFromExtendedStopInfo(
1003 StructuredData::ObjectSP info) {
1004 ThreadCollectionSP threads;
1005 threads.reset(new ThreadCollection());
1007 if (info->GetObjectForDotSeparatedPath("instrumentation_class")
1008 ->GetStringValue() != "ThreadSanitizer")
1011 ProcessSP process_sp = GetProcessSP();
1013 AddThreadsForPath("stacks", threads, process_sp, info);
1014 AddThreadsForPath("mops", threads, process_sp, info);
1015 AddThreadsForPath("locs", threads, process_sp, info);
1016 AddThreadsForPath("mutexes", threads, process_sp, info);
1017 AddThreadsForPath("threads", threads, process_sp, info);