LLDB mainline
InstrumentationRuntimeTSan.cpp
Go to the documentation of this file.
1//===-- InstrumentationRuntimeTSan.cpp ------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
13#include "lldb/Core/Debugger.h"
14#include "lldb/Core/Module.h"
20#include "lldb/Symbol/Symbol.h"
27#include "lldb/Target/Target.h"
28#include "lldb/Target/Thread.h"
30#include "lldb/Utility/Log.h"
32#include "lldb/Utility/Stream.h"
34
35#include <memory>
36
37using namespace lldb;
38using namespace lldb_private;
39
41
46
49 GetPluginNameStatic(), "ThreadSanitizer instrumentation runtime plugin.",
51}
52
56
60
62
64extern "C"
65{
66 void *__tsan_get_current_report();
67 int __tsan_get_report_data(void *report, const char **description, int *count,
68 int *stack_count, int *mop_count, int *loc_count,
69 int *mutex_count, int *thread_count,
70 int *unique_tid_count, void **sleep_trace,
71 unsigned long trace_size);
72 int __tsan_get_report_stack(void *report, unsigned long idx, void **trace,
73 unsigned long trace_size);
74 int __tsan_get_report_mop(void *report, unsigned long idx, int *tid, void **addr,
75 int *size, int *write, int *atomic, void **trace,
76 unsigned long trace_size);
77 int __tsan_get_report_loc(void *report, unsigned long idx, const char **type,
78 void **addr, unsigned long *start, unsigned long *size, int *tid,
79 int *fd, int *suppressable, void **trace,
80 unsigned long trace_size);
81 int __tsan_get_report_mutex(void *report, unsigned long idx, unsigned long *mutex_id, void **addr,
82 int *destroyed, void **trace, unsigned long trace_size);
83 int __tsan_get_report_thread(void *report, unsigned long idx, int *tid, unsigned long *os_id,
84 int *running, const char **name, int *parent_tid,
85 void **trace, unsigned long trace_size);
86 int __tsan_get_report_unique_tid(void *report, unsigned long idx, int *tid);
87
88 // TODO: dlsym won't work on Windows.
89 void *dlsym(void* handle, const char* symbol);
90 int (*ptr__tsan_get_report_loc_object_type)(void *report, unsigned long idx, const char **object_type);
91#if defined(__linux__)
92#define RTLD_DEFAULT ((void *) 0)
93#else
94#define RTLD_DEFAULT ((void *) -2)
95#endif
96 }
97)";
98
100
101const int REPORT_TRACE_SIZE = 128;
102const int REPORT_ARRAY_SIZE = 4;
103
104struct {
105 void *report;
106 const char *description;
107 int report_count;
108
109 void *sleep_trace[REPORT_TRACE_SIZE];
110
111 int stack_count;
112 struct {
113 int idx;
114 void *trace[REPORT_TRACE_SIZE];
115 } stacks[REPORT_ARRAY_SIZE];
116
117 int mop_count;
118 struct {
119 int idx;
120 int tid;
121 int size;
122 int write;
123 int atomic;
124 void *addr;
125 void *trace[REPORT_TRACE_SIZE];
126 } mops[REPORT_ARRAY_SIZE];
127
128 int loc_count;
129 struct {
130 int idx;
131 const char *type;
132 void *addr;
133 unsigned long start;
134 unsigned long size;
135 int tid;
136 int fd;
137 int suppressable;
138 void *trace[REPORT_TRACE_SIZE];
139 const char *object_type;
140 } locs[REPORT_ARRAY_SIZE];
141
142 int mutex_count;
143 struct {
144 int idx;
145 unsigned long mutex_id;
146 void *addr;
147 int destroyed;
148 void *trace[REPORT_TRACE_SIZE];
149 } mutexes[REPORT_ARRAY_SIZE];
150
151 int thread_count;
152 struct {
153 int idx;
154 int tid;
155 unsigned long os_id;
156 int running;
157 const char *name;
158 int parent_tid;
159 void *trace[REPORT_TRACE_SIZE];
160 } threads[REPORT_ARRAY_SIZE];
161
162 int unique_tid_count;
163 struct {
164 int idx;
165 int tid;
166 } unique_tids[REPORT_ARRAY_SIZE];
167} t = {0};
168
169ptr__tsan_get_report_loc_object_type = (typeof(ptr__tsan_get_report_loc_object_type))(void *)dlsym(RTLD_DEFAULT, "__tsan_get_report_loc_object_type");
170
171t.report = __tsan_get_current_report();
172__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);
173
174if (t.stack_count > REPORT_ARRAY_SIZE) t.stack_count = REPORT_ARRAY_SIZE;
175for (int i = 0; i < t.stack_count; i++) {
176 t.stacks[i].idx = i;
177 __tsan_get_report_stack(t.report, i, t.stacks[i].trace, REPORT_TRACE_SIZE);
178}
179
180if (t.mop_count > REPORT_ARRAY_SIZE) t.mop_count = REPORT_ARRAY_SIZE;
181for (int i = 0; i < t.mop_count; i++) {
182 t.mops[i].idx = i;
183 __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);
184}
185
186if (t.loc_count > REPORT_ARRAY_SIZE) t.loc_count = REPORT_ARRAY_SIZE;
187for (int i = 0; i < t.loc_count; i++) {
188 t.locs[i].idx = i;
189 __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);
190 if (ptr__tsan_get_report_loc_object_type)
191 ptr__tsan_get_report_loc_object_type(t.report, i, &t.locs[i].object_type);
192}
193
194if (t.mutex_count > REPORT_ARRAY_SIZE) t.mutex_count = REPORT_ARRAY_SIZE;
195for (int i = 0; i < t.mutex_count; i++) {
196 t.mutexes[i].idx = i;
197 __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);
198}
199
200if (t.thread_count > REPORT_ARRAY_SIZE) t.thread_count = REPORT_ARRAY_SIZE;
201for (int i = 0; i < t.thread_count; i++) {
202 t.threads[i].idx = i;
203 __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);
204}
205
206if (t.unique_tid_count > REPORT_ARRAY_SIZE) t.unique_tid_count = REPORT_ARRAY_SIZE;
207for (int i = 0; i < t.unique_tid_count; i++) {
208 t.unique_tids[i].idx = i;
209 __tsan_get_report_unique_tid(t.report, i, &t.unique_tids[i].tid);
210}
211
212t;
213)";
214
217 const std::string &trace_item_name = ".trace") {
218 auto trace_sp = std::make_shared<StructuredData::Array>();
219 ValueObjectSP trace_value_object =
220 o->GetValueForExpressionPath(trace_item_name.c_str());
221 size_t count = trace_value_object->GetNumChildrenIgnoringErrors();
222 for (size_t j = 0; j < count; j++) {
223 addr_t trace_addr =
224 trace_value_object->GetChildAtIndex(j)->GetValueAsUnsigned(0);
225 if (trace_addr == 0)
226 break;
227 trace_sp->AddIntegerItem(trace_addr);
228 }
229 return trace_sp;
230}
231
233 ValueObjectSP return_value_sp, const std::string &items_name,
234 const std::string &count_name,
235 std::function<void(const ValueObjectSP &o,
236 const StructuredData::DictionarySP &dict)> const
237 &callback) {
238 auto array_sp = std::make_shared<StructuredData::Array>();
239 unsigned int count =
240 return_value_sp->GetValueForExpressionPath(count_name.c_str())
241 ->GetValueAsUnsigned(0);
242 ValueObjectSP objects =
243 return_value_sp->GetValueForExpressionPath(items_name.c_str());
244 for (unsigned int i = 0; i < count; i++) {
245 ValueObjectSP o = objects->GetChildAtIndex(i);
246 auto dict_sp = std::make_shared<StructuredData::Dictionary>();
247
248 callback(o, dict_sp);
249
250 array_sp->AddItem(dict_sp);
251 }
252 return array_sp;
253}
254
255static std::string RetrieveString(ValueObjectSP return_value_sp,
256 ProcessSP process_sp,
257 const std::string &expression_path) {
258 addr_t ptr =
259 return_value_sp->GetValueForExpressionPath(expression_path.c_str())
260 ->GetValueAsUnsigned(0);
261 std::string str;
263 process_sp->ReadCStringFromMemory(ptr, str, error);
264 return str;
265}
266
267static void
269 std::map<uint64_t, user_id_t> &thread_id_map) {
271 data, ".threads", ".thread_count",
272 [process_sp, &thread_id_map](const ValueObjectSP &o,
273 const StructuredData::DictionarySP &dict) {
274 uint64_t thread_id =
275 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0);
276 uint64_t thread_os_id =
277 o->GetValueForExpressionPath(".os_id")->GetValueAsUnsigned(0);
278 user_id_t lldb_user_id = 0;
279
280 bool can_update = true;
281 ThreadSP lldb_thread = process_sp->GetThreadList().FindThreadByID(
282 thread_os_id, can_update);
283 if (lldb_thread) {
284 lldb_user_id = lldb_thread->GetIndexID();
285 } else {
286 // This isn't a live thread anymore. Ask process to assign a new
287 // Index ID (or return an old one if we've already seen this
288 // thread_os_id). It will also make sure that no new threads are
289 // assigned this Index ID.
290 lldb_user_id = process_sp->AssignIndexIDToThread(thread_os_id);
291 }
292
293 thread_id_map[thread_id] = lldb_user_id;
294 });
295}
296
297static user_id_t Renumber(uint64_t id,
298 std::map<uint64_t, user_id_t> &thread_id_map) {
299 auto IT = thread_id_map.find(id);
300 if (IT == thread_id_map.end())
301 return 0;
302
303 return IT->second;
304}
305
307 ExecutionContextRef exe_ctx_ref) {
308 ProcessSP process_sp = GetProcessSP();
309 if (!process_sp)
311
312 ThreadSP thread_sp = exe_ctx_ref.GetThreadSP();
313 StackFrameSP frame_sp =
314 thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame);
315
316 if (!frame_sp)
318
320 options.SetUnwindOnError(true);
321 options.SetTryAllThreads(true);
322 options.SetStopOthers(true);
323 options.SetIgnoreBreakpoints(true);
324 options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
326 options.SetAutoApplyFixIts(false);
328
329 ValueObjectSP main_value;
330 ExecutionContext exe_ctx;
331 frame_sp->CalculateExecutionContext(exe_ctx);
334 main_value);
335 if (result != eExpressionCompleted) {
336 StreamString ss;
337 ss << "cannot evaluate ThreadSanitizer expression:\n";
338 if (main_value)
339 ss << main_value->GetError().AsCString();
341 process_sp->GetTarget().GetDebugger().GetID());
343 }
344
345 std::map<uint64_t, user_id_t> thread_id_map;
346 GetRenumberedThreadIds(process_sp, main_value, thread_id_map);
347
348 auto dict = std::make_shared<StructuredData::Dictionary>();
349 dict->AddStringItem("instrumentation_class", "ThreadSanitizer");
350 dict->AddStringItem("issue_type",
351 RetrieveString(main_value, process_sp, ".description"));
352 dict->AddIntegerItem("report_count",
353 main_value->GetValueForExpressionPath(".report_count")
354 ->GetValueAsUnsigned(0));
355 dict->AddItem("sleep_trace", CreateStackTrace(
356 main_value, ".sleep_trace"));
357
359 main_value, ".stacks", ".stack_count",
360 [thread_sp](const ValueObjectSP &o,
361 const StructuredData::DictionarySP &dict) {
362 dict->AddIntegerItem(
363 "index",
364 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
365 dict->AddItem("trace", CreateStackTrace(o));
366 // "stacks" happen on the current thread
367 dict->AddIntegerItem("thread_id", thread_sp->GetIndexID());
368 });
369 dict->AddItem("stacks", stacks);
370
372 main_value, ".mops", ".mop_count",
373 [&thread_id_map](const ValueObjectSP &o,
374 const StructuredData::DictionarySP &dict) {
375 dict->AddIntegerItem(
376 "index",
377 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
378 dict->AddIntegerItem(
379 "thread_id",
380 Renumber(
381 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0),
382 thread_id_map));
383 dict->AddIntegerItem(
384 "size",
385 o->GetValueForExpressionPath(".size")->GetValueAsUnsigned(0));
386 dict->AddBooleanItem(
387 "is_write",
388 o->GetValueForExpressionPath(".write")->GetValueAsUnsigned(0));
389 dict->AddBooleanItem(
390 "is_atomic",
391 o->GetValueForExpressionPath(".atomic")->GetValueAsUnsigned(0));
392 dict->AddIntegerItem(
393 "address",
394 o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
395 dict->AddItem("trace", CreateStackTrace(o));
396 });
397 dict->AddItem("mops", mops);
398
400 main_value, ".locs", ".loc_count",
401 [process_sp, &thread_id_map](const ValueObjectSP &o,
402 const StructuredData::DictionarySP &dict) {
403 dict->AddIntegerItem(
404 "index",
405 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
406 dict->AddStringItem("type", RetrieveString(o, process_sp, ".type"));
407 dict->AddIntegerItem(
408 "address",
409 o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
410 dict->AddIntegerItem(
411 "start",
412 o->GetValueForExpressionPath(".start")->GetValueAsUnsigned(0));
413 dict->AddIntegerItem(
414 "size",
415 o->GetValueForExpressionPath(".size")->GetValueAsUnsigned(0));
416 dict->AddIntegerItem(
417 "thread_id",
418 Renumber(
419 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0),
420 thread_id_map));
421 dict->AddIntegerItem(
422 "file_descriptor",
423 o->GetValueForExpressionPath(".fd")->GetValueAsUnsigned(0));
424 dict->AddIntegerItem("suppressable",
425 o->GetValueForExpressionPath(".suppressable")
426 ->GetValueAsUnsigned(0));
427 dict->AddItem("trace", CreateStackTrace(o));
428 dict->AddStringItem("object_type",
429 RetrieveString(o, process_sp, ".object_type"));
430 });
431 dict->AddItem("locs", locs);
432
434 main_value, ".mutexes", ".mutex_count",
435 [](const ValueObjectSP &o, const StructuredData::DictionarySP &dict) {
436 dict->AddIntegerItem(
437 "index",
438 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
439 dict->AddIntegerItem(
440 "mutex_id",
441 o->GetValueForExpressionPath(".mutex_id")->GetValueAsUnsigned(0));
442 dict->AddIntegerItem(
443 "address",
444 o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
445 dict->AddIntegerItem(
446 "destroyed",
447 o->GetValueForExpressionPath(".destroyed")->GetValueAsUnsigned(0));
448 dict->AddItem("trace", CreateStackTrace(o));
449 });
450 dict->AddItem("mutexes", mutexes);
451
453 main_value, ".threads", ".thread_count",
454 [process_sp, &thread_id_map](const ValueObjectSP &o,
455 const StructuredData::DictionarySP &dict) {
456 dict->AddIntegerItem(
457 "index",
458 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
459 dict->AddIntegerItem(
460 "thread_id",
461 Renumber(
462 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0),
463 thread_id_map));
464 dict->AddIntegerItem(
465 "thread_os_id",
466 o->GetValueForExpressionPath(".os_id")->GetValueAsUnsigned(0));
467 dict->AddIntegerItem(
468 "running",
469 o->GetValueForExpressionPath(".running")->GetValueAsUnsigned(0));
470 dict->AddStringItem("name", RetrieveString(o, process_sp, ".name"));
471 dict->AddIntegerItem(
472 "parent_thread_id",
473 Renumber(o->GetValueForExpressionPath(".parent_tid")
474 ->GetValueAsUnsigned(0),
475 thread_id_map));
476 dict->AddItem("trace", CreateStackTrace(o));
477 });
478 dict->AddItem("threads", threads);
479
481 main_value, ".unique_tids", ".unique_tid_count",
482 [&thread_id_map](const ValueObjectSP &o,
483 const StructuredData::DictionarySP &dict) {
484 dict->AddIntegerItem(
485 "index",
486 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
487 dict->AddIntegerItem(
488 "tid",
489 Renumber(
490 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0),
491 thread_id_map));
492 });
493 dict->AddItem("unique_tids", unique_tids);
494
495 return dict;
496}
497
498std::string
500 std::string description = std::string(report->GetAsDictionary()
501 ->GetValueForKey("issue_type")
502 ->GetAsString()
503 ->GetValue());
504
505 if (description == "data-race") {
506 return "Data race";
507 } else if (description == "data-race-vptr") {
508 return "Data race on C++ virtual pointer";
509 } else if (description == "heap-use-after-free") {
510 return "Use of deallocated memory";
511 } else if (description == "heap-use-after-free-vptr") {
512 return "Use of deallocated C++ virtual pointer";
513 } else if (description == "thread-leak") {
514 return "Thread leak";
515 } else if (description == "locked-mutex-destroy") {
516 return "Destruction of a locked mutex";
517 } else if (description == "mutex-double-lock") {
518 return "Double lock of a mutex";
519 } else if (description == "mutex-invalid-access") {
520 return "Use of an uninitialized or destroyed mutex";
521 } else if (description == "mutex-bad-unlock") {
522 return "Unlock of an unlocked mutex (or by a wrong thread)";
523 } else if (description == "mutex-bad-read-lock") {
524 return "Read lock of a write locked mutex";
525 } else if (description == "mutex-bad-read-unlock") {
526 return "Read unlock of a write locked mutex";
527 } else if (description == "signal-unsafe-call") {
528 return "Signal-unsafe call inside a signal handler";
529 } else if (description == "errno-in-signal-handler") {
530 return "Overwrite of errno in a signal handler";
531 } else if (description == "lock-order-inversion") {
532 return "Lock order inversion (potential deadlock)";
533 } else if (description == "external-race") {
534 return "Race on a library object";
535 } else if (description == "swift-access-race") {
536 return "Swift access race";
537 }
538
539 // for unknown report codes just show the code
540 return description;
541}
542
543static std::string Sprintf(const char *format, ...) {
544 StreamString s;
545 va_list args;
546 va_start(args, format);
547 s.PrintfVarArg(format, args);
548 va_end(args);
549 return std::string(s.GetString());
550}
551
552static std::string GetSymbolNameFromAddress(ProcessSP process_sp, addr_t addr) {
553 lldb_private::Address so_addr;
554 if (!process_sp->GetTarget().ResolveLoadAddress(addr, so_addr))
555 return "";
556
557 const lldb_private::Symbol *symbol = so_addr.CalculateSymbolContextSymbol();
558 if (!symbol)
559 return "";
560
561 std::string sym_name = symbol->GetName().GetCString();
562 return sym_name;
563}
564
566 Declaration &decl) {
567 lldb_private::Address so_addr;
568 if (!process_sp->GetTarget().ResolveLoadAddress(addr, so_addr))
569 return;
570
572 if (!symbol)
573 return;
574
576
577 ModuleSP module = symbol->CalculateSymbolContextModule();
578 if (!module)
579 return;
580
581 VariableList var_list;
582 module->FindGlobalVariables(sym_name, CompilerDeclContext(), 1U, var_list);
583 if (var_list.GetSize() < 1)
584 return;
585
586 VariableSP var = var_list.GetVariableAtIndex(0);
587 decl = var->GetDeclaration();
588}
589
591 StructuredData::ObjectSP trace, bool skip_one_frame) {
592 ProcessSP process_sp = GetProcessSP();
593 ModuleSP runtime_module_sp = GetRuntimeModuleSP();
594
595 StructuredData::Array *trace_array = trace->GetAsArray();
596 for (size_t i = 0; i < trace_array->GetSize(); i++) {
597 if (skip_one_frame && i == 0)
598 continue;
599
600 auto maybe_addr = trace_array->GetItemAtIndexAsInteger<addr_t>(i);
601 if (!maybe_addr)
602 continue;
603 addr_t addr = *maybe_addr;
604
605 lldb_private::Address so_addr;
606 if (!process_sp->GetTarget().ResolveLoadAddress(addr, so_addr))
607 continue;
608
609 if (so_addr.GetModule() == runtime_module_sp)
610 continue;
611
612 return addr;
613 }
614
615 return 0;
616}
617
618std::string
620 ProcessSP process_sp = GetProcessSP();
621
622 std::string summary = std::string(report->GetAsDictionary()
623 ->GetValueForKey("description")
624 ->GetAsString()
625 ->GetValue());
626 bool skip_one_frame =
627 report->GetObjectForDotSeparatedPath("issue_type")->GetStringValue() ==
628 "external-race";
629
630 addr_t pc = 0;
631 if (report->GetAsDictionary()
632 ->GetValueForKey("mops")
633 ->GetAsArray()
634 ->GetSize() > 0)
635 pc = GetFirstNonInternalFramePc(report->GetAsDictionary()
636 ->GetValueForKey("mops")
637 ->GetAsArray()
638 ->GetItemAtIndex(0)
639 ->GetAsDictionary()
640 ->GetValueForKey("trace"),
641 skip_one_frame);
642
643 if (report->GetAsDictionary()
644 ->GetValueForKey("stacks")
645 ->GetAsArray()
646 ->GetSize() > 0)
647 pc = GetFirstNonInternalFramePc(report->GetAsDictionary()
648 ->GetValueForKey("stacks")
649 ->GetAsArray()
650 ->GetItemAtIndex(0)
651 ->GetAsDictionary()
652 ->GetValueForKey("trace"),
653 skip_one_frame);
654
655 if (pc != 0) {
656 summary = summary + " in " + GetSymbolNameFromAddress(process_sp, pc);
657 }
658
659 if (report->GetAsDictionary()
660 ->GetValueForKey("locs")
661 ->GetAsArray()
662 ->GetSize() > 0) {
663 StructuredData::ObjectSP loc = report->GetAsDictionary()
664 ->GetValueForKey("locs")
665 ->GetAsArray()
666 ->GetItemAtIndex(0);
667 std::string object_type = std::string(loc->GetAsDictionary()
668 ->GetValueForKey("object_type")
669 ->GetAsString()
670 ->GetValue());
671 if (!object_type.empty()) {
672 summary = "Race on " + object_type + " object";
673 }
674 addr_t addr = loc->GetAsDictionary()
675 ->GetValueForKey("address")
676 ->GetUnsignedIntegerValue();
677 if (addr == 0)
678 addr = loc->GetAsDictionary()
679 ->GetValueForKey("start")
680 ->GetUnsignedIntegerValue();
681
682 if (addr != 0) {
683 std::string global_name = GetSymbolNameFromAddress(process_sp, addr);
684 if (!global_name.empty()) {
685 summary = summary + " at " + global_name;
686 } else {
687 summary = summary + " at " + Sprintf("0x%llx", addr);
688 }
689 } else {
690 int fd = loc->GetAsDictionary()
691 ->GetValueForKey("file_descriptor")
692 ->GetSignedIntegerValue();
693 if (fd != 0) {
694 summary = summary + " on file descriptor " + Sprintf("%d", fd);
695 }
696 }
697 }
698
699 return summary;
700}
701
704 addr_t result = (addr_t)-1;
705
706 report->GetObjectForDotSeparatedPath("mops")->GetAsArray()->ForEach(
707 [&result](StructuredData::Object *o) -> bool {
708 addr_t addr = o->GetObjectForDotSeparatedPath("address")
709 ->GetUnsignedIntegerValue();
710 if (addr < result)
711 result = addr;
712 return true;
713 });
714
715 return (result == (addr_t)-1) ? 0 : result;
716}
717
719 StructuredData::ObjectSP report, addr_t &global_addr,
720 std::string &global_name, std::string &filename, uint32_t &line) {
721 std::string result;
722
723 ProcessSP process_sp = GetProcessSP();
724
725 if (report->GetAsDictionary()
726 ->GetValueForKey("locs")
727 ->GetAsArray()
728 ->GetSize() > 0) {
729 StructuredData::ObjectSP loc = report->GetAsDictionary()
730 ->GetValueForKey("locs")
731 ->GetAsArray()
732 ->GetItemAtIndex(0);
733 std::string type = std::string(
734 loc->GetAsDictionary()->GetValueForKey("type")->GetStringValue());
735 if (type == "global") {
736 global_addr = loc->GetAsDictionary()
737 ->GetValueForKey("address")
738 ->GetUnsignedIntegerValue();
739
740 global_name = GetSymbolNameFromAddress(process_sp, global_addr);
741 if (!global_name.empty()) {
742 result = Sprintf("'%s' is a global variable (0x%llx)",
743 global_name.c_str(), global_addr);
744 } else {
745 result = Sprintf("0x%llx is a global variable", global_addr);
746 }
747
748 Declaration decl;
749 GetSymbolDeclarationFromAddress(process_sp, global_addr, decl);
750 if (decl.GetFile()) {
751 filename = decl.GetFile().GetPath();
752 line = decl.GetLine();
753 }
754 } else if (type == "heap") {
755 addr_t addr = loc->GetAsDictionary()
756 ->GetValueForKey("start")
757 ->GetUnsignedIntegerValue();
758
759 size_t size = loc->GetAsDictionary()
760 ->GetValueForKey("size")
761 ->GetUnsignedIntegerValue();
762
763 std::string object_type = std::string(loc->GetAsDictionary()
764 ->GetValueForKey("object_type")
765 ->GetAsString()
766 ->GetValue());
767 if (!object_type.empty()) {
768 result = Sprintf("Location is a %ld-byte %s object at 0x%llx", size,
769 object_type.c_str(), addr);
770 } else {
771 result =
772 Sprintf("Location is a %ld-byte heap object at 0x%llx", size, addr);
773 }
774 } else if (type == "stack") {
775 lldb::tid_t tid = loc->GetAsDictionary()
776 ->GetValueForKey("thread_id")
777 ->GetUnsignedIntegerValue();
778
779 result = Sprintf("Location is stack of thread %d", tid);
780 } else if (type == "tls") {
781 lldb::tid_t tid = loc->GetAsDictionary()
782 ->GetValueForKey("thread_id")
783 ->GetUnsignedIntegerValue();
784
785 result = Sprintf("Location is TLS of thread %d", tid);
786 } else if (type == "fd") {
787 int fd = loc->GetAsDictionary()
788 ->GetValueForKey("file_descriptor")
789 ->GetSignedIntegerValue();
790
791 result = Sprintf("Location is file descriptor %d", fd);
792 }
793 }
794
795 return result;
796}
797
799 void *baton, StoppointCallbackContext *context, user_id_t break_id,
800 user_id_t break_loc_id) {
801 assert(baton && "null baton");
802 if (!baton)
803 return false;
804
805 InstrumentationRuntimeTSan *const instance =
806 static_cast<InstrumentationRuntimeTSan *>(baton);
807
808 ProcessSP process_sp = instance->GetProcessSP();
809
810 if (process_sp->GetModIDRef().IsLastResumeForUserExpression())
811 return false;
812
814 instance->RetrieveReportData(context->exe_ctx_ref);
815 std::string stop_reason_description =
816 "unknown thread sanitizer fault (unable to extract thread sanitizer "
817 "report)";
818 if (report) {
819 std::string issue_description = instance->FormatDescription(report);
820 report->GetAsDictionary()->AddStringItem("description", issue_description);
821 stop_reason_description = issue_description + " detected";
822 report->GetAsDictionary()->AddStringItem("stop_description",
823 stop_reason_description);
824 std::string summary = instance->GenerateSummary(report);
825 report->GetAsDictionary()->AddStringItem("summary", summary);
826 addr_t main_address = instance->GetMainRacyAddress(report);
827 report->GetAsDictionary()->AddIntegerItem("memory_address", main_address);
828
829 addr_t global_addr = 0;
830 std::string global_name;
831 std::string location_filename;
832 uint32_t location_line = 0;
833 std::string location_description = instance->GetLocationDescription(
834 report, global_addr, global_name, location_filename, location_line);
835 report->GetAsDictionary()->AddStringItem("location_description",
836 location_description);
837 if (global_addr != 0) {
838 report->GetAsDictionary()->AddIntegerItem("global_address", global_addr);
839 }
840 if (!global_name.empty()) {
841 report->GetAsDictionary()->AddStringItem("global_name", global_name);
842 }
843 if (location_filename != "") {
844 report->GetAsDictionary()->AddStringItem("location_filename",
845 location_filename);
846 report->GetAsDictionary()->AddIntegerItem("location_line", location_line);
847 }
848
849 bool all_addresses_are_same = true;
850 report->GetObjectForDotSeparatedPath("mops")->GetAsArray()->ForEach(
851 [&all_addresses_are_same,
852 main_address](StructuredData::Object *o) -> bool {
853 addr_t addr = o->GetObjectForDotSeparatedPath("address")
854 ->GetUnsignedIntegerValue();
855 if (main_address != addr)
856 all_addresses_are_same = false;
857 return true;
858 });
859 report->GetAsDictionary()->AddBooleanItem("all_addresses_are_same",
860 all_addresses_are_same);
861 }
862
863 // Make sure this is the right process
864 if (process_sp && process_sp == context->exe_ctx_ref.GetProcessSP()) {
865 ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
866 if (thread_sp)
867 thread_sp->SetStopInfo(
869 CreateStopReasonWithInstrumentationData(
870 *thread_sp, stop_reason_description, report));
871
873 process_sp->GetTarget().GetDebugger().GetAsyncOutputStream();
874 s->Printf("ThreadSanitizer report breakpoint hit. Use 'thread "
875 "info -s' to get extended information about the "
876 "report.\n");
877
878 return true; // Return true to stop the target
879 }
880 return false; // Let target run
881}
882
883const RegularExpression &
885 static RegularExpression regex(llvm::StringRef("libclang_rt.tsan_"));
886 return regex;
887}
888
890 const lldb::ModuleSP module_sp) {
891 static ConstString g_tsan_get_current_report("__tsan_get_current_report");
892 const Symbol *symbol = module_sp->FindFirstSymbolWithNameAndType(
893 g_tsan_get_current_report, lldb::eSymbolTypeAny);
894 return symbol != nullptr;
895}
896
898 if (IsActive())
899 return;
900
901 ProcessSP process_sp = GetProcessSP();
902 if (!process_sp)
903 return;
904
905 ConstString symbol_name("__tsan_on_report");
906 const Symbol *symbol = GetRuntimeModuleSP()->FindFirstSymbolWithNameAndType(
907 symbol_name, eSymbolTypeCode);
908
909 if (symbol == nullptr)
910 return;
911
912 if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
913 return;
914
915 Target &target = process_sp->GetTarget();
916 addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
917
918 if (symbol_address == LLDB_INVALID_ADDRESS)
919 return;
920
921 const bool internal = true;
922 const bool hardware = false;
923 const bool sync = false;
924 Breakpoint *breakpoint =
925 process_sp->GetTarget()
926 .CreateBreakpoint(symbol_address, internal, hardware)
927 .get();
929 sync);
930 breakpoint->SetBreakpointKind("thread-sanitizer-report");
931 SetBreakpointID(breakpoint->GetID());
932
933 SetActive(true);
934}
935
938 ProcessSP process_sp = GetProcessSP();
939 if (process_sp) {
940 process_sp->GetTarget().RemoveBreakpointByID(GetBreakpointID());
942 }
943 }
944 SetActive(false);
945}
946static std::string GenerateThreadName(const std::string &path,
948 StructuredData::ObjectSP main_info) {
949 std::string result = "additional information";
950
951 if (path == "mops") {
952 size_t size =
953 o->GetObjectForDotSeparatedPath("size")->GetUnsignedIntegerValue();
954 lldb::tid_t thread_id =
955 o->GetObjectForDotSeparatedPath("thread_id")->GetUnsignedIntegerValue();
956 bool is_write =
957 o->GetObjectForDotSeparatedPath("is_write")->GetBooleanValue();
958 bool is_atomic =
959 o->GetObjectForDotSeparatedPath("is_atomic")->GetBooleanValue();
960 addr_t addr =
961 o->GetObjectForDotSeparatedPath("address")->GetUnsignedIntegerValue();
962
963 std::string addr_string = Sprintf(" at 0x%llx", addr);
964
965 if (main_info->GetObjectForDotSeparatedPath("all_addresses_are_same")
966 ->GetBooleanValue()) {
967 addr_string = "";
968 }
969
970 if (main_info->GetObjectForDotSeparatedPath("issue_type")
971 ->GetStringValue() == "external-race") {
972 result = Sprintf("%s access by thread %d",
973 is_write ? "mutating" : "read-only", thread_id);
974 } else if (main_info->GetObjectForDotSeparatedPath("issue_type")
975 ->GetStringValue() == "swift-access-race") {
976 result = Sprintf("modifying access by thread %d", thread_id);
977 } else {
978 result = Sprintf("%s%s of size %zu%s by thread %" PRIu64,
979 is_atomic ? "atomic " : "", is_write ? "write" : "read",
980 size, addr_string.c_str(), thread_id);
981 }
982 }
983
984 if (path == "threads") {
985 lldb::tid_t thread_id =
986 o->GetObjectForDotSeparatedPath("thread_id")->GetUnsignedIntegerValue();
987 result = Sprintf("Thread %zu created", thread_id);
988 }
989
990 if (path == "locs") {
991 std::string type = std::string(
992 o->GetAsDictionary()->GetValueForKey("type")->GetStringValue());
993 lldb::tid_t thread_id =
994 o->GetObjectForDotSeparatedPath("thread_id")->GetUnsignedIntegerValue();
995 int fd = o->GetObjectForDotSeparatedPath("file_descriptor")
996 ->GetSignedIntegerValue();
997 if (type == "heap") {
998 result = Sprintf("Heap block allocated by thread %" PRIu64, thread_id);
999 } else if (type == "fd") {
1000 result = Sprintf("File descriptor %d created by thread %" PRIu64, fd,
1001 thread_id);
1002 }
1003 }
1004
1005 if (path == "mutexes") {
1006 int mutex_id =
1007 o->GetObjectForDotSeparatedPath("mutex_id")->GetSignedIntegerValue();
1008
1009 result = Sprintf("Mutex M%d created", mutex_id);
1010 }
1011
1012 if (path == "stacks") {
1013 lldb::tid_t thread_id =
1014 o->GetObjectForDotSeparatedPath("thread_id")->GetUnsignedIntegerValue();
1015 result = Sprintf("Thread %" PRIu64, thread_id);
1016 }
1017
1018 result[0] = toupper(result[0]);
1019
1020 return result;
1021}
1022
1023static void AddThreadsForPath(const std::string &path,
1024 ThreadCollectionSP threads, ProcessSP process_sp,
1026 info->GetObjectForDotSeparatedPath(path)->GetAsArray()->ForEach(
1027 [process_sp, threads, path, info](StructuredData::Object *o) -> bool {
1028 std::vector<lldb::addr_t> pcs;
1029 o->GetObjectForDotSeparatedPath("trace")->GetAsArray()->ForEach(
1030 [&pcs](StructuredData::Object *pc) -> bool {
1031 pcs.push_back(pc->GetUnsignedIntegerValue());
1032 return true;
1033 });
1034
1035 if (pcs.size() == 0)
1036 return true;
1037
1038 StructuredData::ObjectSP thread_id_obj =
1039 o->GetObjectForDotSeparatedPath("thread_os_id");
1040 lldb::tid_t tid =
1041 thread_id_obj ? thread_id_obj->GetUnsignedIntegerValue() : 0;
1042
1043 ThreadSP new_thread_sp =
1044 std::make_shared<HistoryThread>(*process_sp, tid, pcs);
1045 new_thread_sp->SetName(GenerateThreadName(path, o, info).c_str());
1046
1047 // Save this in the Process' ExtendedThreadList so a strong pointer
1048 // retains the object
1049 process_sp->GetExtendedThreadList().AddThread(new_thread_sp);
1050 threads->AddThread(new_thread_sp);
1051
1052 return true;
1053 });
1054}
1055
1059
1060 ThreadCollectionSP threads = std::make_shared<ThreadCollection>();
1061
1062 if (info->GetObjectForDotSeparatedPath("instrumentation_class")
1063 ->GetStringValue() != "ThreadSanitizer")
1064 return threads;
1065
1066 ProcessSP process_sp = GetProcessSP();
1067
1068 AddThreadsForPath("stacks", threads, process_sp, info);
1069 AddThreadsForPath("mops", threads, process_sp, info);
1070 AddThreadsForPath("locs", threads, process_sp, info);
1071 AddThreadsForPath("mutexes", threads, process_sp, info);
1072 AddThreadsForPath("threads", threads, process_sp, info);
1073
1074 return threads;
1075}
static llvm::raw_ostream & error(Stream &strm)
static void GetRenumberedThreadIds(ProcessSP process_sp, ValueObjectSP data, std::map< uint64_t, user_id_t > &thread_id_map)
static StructuredData::ArraySP ConvertToStructuredArray(ValueObjectSP return_value_sp, const std::string &items_name, const std::string &count_name, std::function< void(const ValueObjectSP &o, const StructuredData::DictionarySP &dict)> const &callback)
const char * thread_sanitizer_retrieve_report_data_prefix
static void GetSymbolDeclarationFromAddress(ProcessSP process_sp, addr_t addr, Declaration &decl)
static user_id_t Renumber(uint64_t id, std::map< uint64_t, user_id_t > &thread_id_map)
static std::string GenerateThreadName(const std::string &path, StructuredData::Object *o, StructuredData::ObjectSP main_info)
static std::string GetSymbolNameFromAddress(ProcessSP process_sp, addr_t addr)
static std::string RetrieveString(ValueObjectSP return_value_sp, ProcessSP process_sp, const std::string &expression_path)
static std::string Sprintf(const char *format,...)
static StructuredData::ArraySP CreateStackTrace(ValueObjectSP o, const std::string &trace_item_name=".trace")
const char * thread_sanitizer_retrieve_report_data_command
static void AddThreadsForPath(const std::string &path, ThreadCollectionSP threads, ProcessSP process_sp, StructuredData::ObjectSP info)
#define LLDB_PLUGIN_DEFINE(PluginName)
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetOpcodeLoadAddress(Target *target, AddressClass addr_class=AddressClass::eInvalid) const
Get the load address as an opcode load address.
Definition Address.cpp:358
lldb::ModuleSP GetModule() const
Get accessor for the module for this address.
Definition Address.cpp:273
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
Symbol * CalculateSymbolContextSymbol() const
Definition Address.cpp:888
General Outline: A breakpoint has four main parts, a filter, a resolver, the list of breakpoint locat...
Definition Breakpoint.h:81
void SetBreakpointKind(const char *kind)
Set the "kind" description for a breakpoint.
Definition Breakpoint.h:482
void SetCallback(BreakpointHitCallback callback, void *baton, bool is_synchronous=false)
Set the callback action invoked when the breakpoint is hit.
A uniqued constant string class.
Definition ConstString.h:40
const char * GetCString() const
Get the string value as a C string.
static void ReportWarning(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report warning events.
A class that describes the declaration location of a lldb object.
Definition Declaration.h:24
uint32_t GetLine() const
Get accessor for the declaration line number.
FileSpec & GetFile()
Get accessor for file specification.
void SetUnwindOnError(bool unwind=false)
Definition Target.h:373
void SetLanguage(lldb::LanguageType language_type)
Definition Target.h:337
void SetPrefix(const char *prefix)
Definition Target.h:362
void SetTryAllThreads(bool try_others=true)
Definition Target.h:406
void SetTimeout(const Timeout< std::micro > &timeout)
Definition Target.h:394
void SetStopOthers(bool stop_others=true)
Definition Target.h:410
void SetIgnoreBreakpoints(bool ignore=false)
Definition Target.h:377
Execution context objects refer to objects in the execution of the program that is being debugged.
lldb::ThreadSP GetThreadSP() const
Get accessor that creates a strong reference from the weak thread reference contained in this object.
lldb::ProcessSP GetProcessSP() const
Get accessor that creates a strong reference from the weak process reference contained in this object...
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
StructuredData::ObjectSP RetrieveReportData(ExecutionContextRef exe_ctx_ref)
bool CheckIfRuntimeIsValid(const lldb::ModuleSP module_sp) override
Check whether module_sp corresponds to a valid runtime library.
std::string GetLocationDescription(StructuredData::ObjectSP report, lldb::addr_t &global_addr, std::string &global_name, std::string &filename, uint32_t &line)
const RegularExpression & GetPatternForRuntimeLibrary() override
Return a regular expression which can be used to identify a valid version of the runtime library.
lldb::addr_t GetMainRacyAddress(StructuredData::ObjectSP report)
static lldb::InstrumentationRuntimeSP CreateInstance(const lldb::ProcessSP &process_sp)
static lldb::InstrumentationRuntimeType GetTypeStatic()
void Activate() override
Register a breakpoint in the runtime library and perform any other necessary initialization.
static bool NotifyBreakpointHit(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
InstrumentationRuntimeTSan(const lldb::ProcessSP &process_sp)
lldb::addr_t GetFirstNonInternalFramePc(StructuredData::ObjectSP trace, bool skip_one_frame=false)
std::string GenerateSummary(StructuredData::ObjectSP report)
lldb::ThreadCollectionSP GetBacktracesFromExtendedStopInfo(StructuredData::ObjectSP info) override
std::string FormatDescription(StructuredData::ObjectSP report)
ConstString GetName(NamePreference preference=ePreferDemangled) const
Best name get accessor.
Definition Mangled.cpp:369
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
An error handling class.
Definition Status.h:118
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
lldb::break_id_t GetID() const
Definition Stoppoint.cpp:22
llvm::StringRef GetString() const
size_t size_t PrintfVarArg(const char *format, va_list args)
Definition Stream.cpp:143
std::optional< IntType > GetItemAtIndexAsInteger(size_t idx) const
ObjectSP GetValueForKey(llvm::StringRef key) const
ObjectSP GetObjectForDotSeparatedPath(llvm::StringRef path)
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
std::shared_ptr< Array > ArraySP
bool ValueIsAddress() const
Definition Symbol.cpp:165
lldb::ModuleSP CalculateSymbolContextModule() override
Definition Symbol.cpp:408
Mangled & GetMangled()
Definition Symbol.h:147
Address & GetAddressRef()
Definition Symbol.h:73
ConstString GetName() const
Definition Symbol.cpp:511
static lldb::ExpressionResults Evaluate(ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, llvm::StringRef expr_cstr, llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp, std::string *fixed_expression=nullptr, ValueObject *ctx_obj=nullptr)
Evaluate one expression in the scratch context of the target passed in the exe_ctx and return its res...
lldb::VariableSP GetVariableAtIndex(size_t idx) const
#define LLDB_INVALID_BREAK_ID
#define LLDB_INVALID_ADDRESS
@ DoNoSelectMostRelevantFrame
A class that represents a running process on the host machine.
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
@ eLanguageTypeC
Non-standardized C, such as K&R.
std::shared_ptr< lldb_private::Stream > StreamSP
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
std::shared_ptr< lldb_private::Process > ProcessSP
InstrumentationRuntimeType
@ eInstrumentationRuntimeTypeThreadSanitizer
std::shared_ptr< lldb_private::Variable > VariableSP
uint64_t user_id_t
Definition lldb-types.h:82
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::InstrumentationRuntime > InstrumentationRuntimeSP
uint64_t tid_t
Definition lldb-types.h:84
std::shared_ptr< lldb_private::Module > ModuleSP
std::shared_ptr< lldb_private::ThreadCollection > ThreadCollectionSP