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