Bug Summary

File:tools/lldb/source/Plugins/InstrumentationRuntime/ThreadSanitizer/ThreadSanitizerRuntime.cpp
Warning:line 293, column 1
Potential memory leak

Annotated Source Code

1//===-- ThreadSanitizerRuntime.cpp ------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ThreadSanitizerRuntime.h"
11
12#include "Plugins/Process/Utility/HistoryThread.h"
13#include "lldb/Breakpoint/StoppointCallbackContext.h"
14#include "lldb/Core/Debugger.h"
15#include "lldb/Core/Module.h"
16#include "lldb/Core/PluginInterface.h"
17#include "lldb/Core/PluginManager.h"
18#include "lldb/Core/StreamFile.h"
19#include "lldb/Core/ValueObject.h"
20#include "lldb/Expression/UserExpression.h"
21#include "lldb/Interpreter/CommandReturnObject.h"
22#include "lldb/Symbol/Symbol.h"
23#include "lldb/Symbol/SymbolContext.h"
24#include "lldb/Symbol/Variable.h"
25#include "lldb/Symbol/VariableList.h"
26#include "lldb/Target/InstrumentationRuntimeStopInfo.h"
27#include "lldb/Target/SectionLoadList.h"
28#include "lldb/Target/StopInfo.h"
29#include "lldb/Target/Target.h"
30#include "lldb/Target/Thread.h"
31#include "lldb/Utility/RegularExpression.h"
32#include "lldb/Utility/Stream.h"
33
34using namespace lldb;
35using namespace lldb_private;
36
37lldb::InstrumentationRuntimeSP
38ThreadSanitizerRuntime::CreateInstance(const lldb::ProcessSP &process_sp) {
39 return InstrumentationRuntimeSP(new ThreadSanitizerRuntime(process_sp));
40}
41
42void ThreadSanitizerRuntime::Initialize() {
43 PluginManager::RegisterPlugin(
44 GetPluginNameStatic(), "ThreadSanitizer instrumentation runtime plugin.",
45 CreateInstance, GetTypeStatic);
46}
47
48void ThreadSanitizerRuntime::Terminate() {
49 PluginManager::UnregisterPlugin(CreateInstance);
50}
51
52lldb_private::ConstString ThreadSanitizerRuntime::GetPluginNameStatic() {
53 return ConstString("ThreadSanitizer");
54}
55
56lldb::InstrumentationRuntimeType ThreadSanitizerRuntime::GetTypeStatic() {
57 return eInstrumentationRuntimeTypeThreadSanitizer;
58}
59
60ThreadSanitizerRuntime::~ThreadSanitizerRuntime() { Deactivate(); }
61
62static constexpr std::chrono::seconds g_retrieve_data_function_timeout(2);
63
64const char *thread_sanitizer_retrieve_report_data_prefix = R"(
65extern "C"
66{
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);
88
89 // TODO: dlsym won't work on Windows.
90 void *dlsym(void* handle, const char* symbol);
91 int (*ptr__tsan_get_report_loc_object_type)(void *report, unsigned long idx, const char **object_type);
92}
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};
161)";
162
163const char *thread_sanitizer_retrieve_report_data_command = R"(
164data t = {0};
165
166ptr__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");
167
168t.report = __tsan_get_current_report();
169__tsan_get_report_data(t.report, &t.description, &t.report_count, &t.stack_count, &t.mop_count, &t.loc_count, &t.mutex_count, &t.thread_count, &t.unique_tid_count, t.sleep_trace, REPORT_TRACE_SIZE);
170
171if (t.stack_count > REPORT_ARRAY_SIZE) t.stack_count = REPORT_ARRAY_SIZE;
172for (int i = 0; i < t.stack_count; i++) {
173 t.stacks[i].idx = i;
174 __tsan_get_report_stack(t.report, i, t.stacks[i].trace, REPORT_TRACE_SIZE);
175}
176
177if (t.mop_count > REPORT_ARRAY_SIZE) t.mop_count = REPORT_ARRAY_SIZE;
178for (int i = 0; i < t.mop_count; i++) {
179 t.mops[i].idx = i;
180 __tsan_get_report_mop(t.report, i, &t.mops[i].tid, &t.mops[i].addr, &t.mops[i].size, &t.mops[i].write, &t.mops[i].atomic, t.mops[i].trace, REPORT_TRACE_SIZE);
181}
182
183if (t.loc_count > REPORT_ARRAY_SIZE) t.loc_count = REPORT_ARRAY_SIZE;
184for (int i = 0; i < t.loc_count; i++) {
185 t.locs[i].idx = i;
186 __tsan_get_report_loc(t.report, i, &t.locs[i].type, &t.locs[i].addr, &t.locs[i].start, &t.locs[i].size, &t.locs[i].tid, &t.locs[i].fd, &t.locs[i].suppressable, t.locs[i].trace, REPORT_TRACE_SIZE);
187 if (ptr__tsan_get_report_loc_object_type)
188 ptr__tsan_get_report_loc_object_type(t.report, i, &t.locs[i].object_type);
189}
190
191if (t.mutex_count > REPORT_ARRAY_SIZE) t.mutex_count = REPORT_ARRAY_SIZE;
192for (int i = 0; i < t.mutex_count; i++) {
193 t.mutexes[i].idx = i;
194 __tsan_get_report_mutex(t.report, i, &t.mutexes[i].mutex_id, &t.mutexes[i].addr, &t.mutexes[i].destroyed, t.mutexes[i].trace, REPORT_TRACE_SIZE);
195}
196
197if (t.thread_count > REPORT_ARRAY_SIZE) t.thread_count = REPORT_ARRAY_SIZE;
198for (int i = 0; i < t.thread_count; i++) {
199 t.threads[i].idx = i;
200 __tsan_get_report_thread(t.report, i, &t.threads[i].tid, &t.threads[i].os_id, &t.threads[i].running, &t.threads[i].name, &t.threads[i].parent_tid, t.threads[i].trace, REPORT_TRACE_SIZE);
201}
202
203if (t.unique_tid_count > REPORT_ARRAY_SIZE) t.unique_tid_count = REPORT_ARRAY_SIZE;
204for (int i = 0; i < t.unique_tid_count; i++) {
205 t.unique_tids[i].idx = i;
206 __tsan_get_report_unique_tid(t.report, i, &t.unique_tids[i].tid);
207}
208
209t;
210)";
211
212static StructuredData::Array *
213CreateStackTrace(ValueObjectSP o,
214 const std::string &trace_item_name = ".trace") {
215 StructuredData::Array *trace = new StructuredData::Array();
216 ValueObjectSP trace_value_object =
217 o->GetValueForExpressionPath(trace_item_name.c_str());
218 size_t count = trace_value_object->GetNumChildren();
219 for (size_t j = 0; j < count; j++) {
220 addr_t trace_addr =
221 trace_value_object->GetChildAtIndex(j, true)->GetValueAsUnsigned(0);
222 if (trace_addr == 0)
223 break;
224 trace->AddItem(
225 StructuredData::ObjectSP(new StructuredData::Integer(trace_addr)));
226 }
227 return trace;
228}
229
230static StructuredData::Array *ConvertToStructuredArray(
231 ValueObjectSP return_value_sp, const std::string &items_name,
232 const std::string &count_name,
233 std::function<void(ValueObjectSP o, StructuredData::Dictionary *dict)> const
234 &callback) {
235 StructuredData::Array *array = new StructuredData::Array();
9
Memory is allocated
236 unsigned int count =
237 return_value_sp->GetValueForExpressionPath(count_name.c_str())
238 ->GetValueAsUnsigned(0);
239 ValueObjectSP objects =
240 return_value_sp->GetValueForExpressionPath(items_name.c_str());
241 for (unsigned int i = 0; i < count; i++) {
10
Assuming 'i' is >= 'count'
11
Loop condition is false. Execution continues on line 249
242 ValueObjectSP o = objects->GetChildAtIndex(i, true);
243 StructuredData::Dictionary *dict = new StructuredData::Dictionary();
244
245 callback(o, dict);
246
247 array->AddItem(StructuredData::ObjectSP(dict));
248 }
249 return array;
250}
251
252static std::string RetrieveString(ValueObjectSP return_value_sp,
253 ProcessSP process_sp,
254 const std::string &expression_path) {
255 addr_t ptr =
256 return_value_sp->GetValueForExpressionPath(expression_path.c_str())
257 ->GetValueAsUnsigned(0);
258 std::string str;
259 Error error;
260 process_sp->ReadCStringFromMemory(ptr, str, error);
261 return str;
262}
263
264static void
265GetRenumberedThreadIds(ProcessSP process_sp, ValueObjectSP data,
266 std::map<uint64_t, user_id_t> &thread_id_map) {
267 ConvertToStructuredArray(
8
Calling 'ConvertToStructuredArray'
12
Returned allocated memory
268 data, ".threads", ".thread_count",
269 [process_sp, &thread_id_map](ValueObjectSP o,
270 StructuredData::Dictionary *dict) {
271 uint64_t thread_id =
272 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0);
273 uint64_t thread_os_id =
274 o->GetValueForExpressionPath(".os_id")->GetValueAsUnsigned(0);
275 user_id_t lldb_user_id = 0;
276
277 bool can_update = true;
278 ThreadSP lldb_thread = process_sp->GetThreadList().FindThreadByID(
279 thread_os_id, can_update);
280 if (lldb_thread) {
281 lldb_user_id = lldb_thread->GetIndexID();
282 } else {
283 // This isn't a live thread anymore. Ask process to assign a new
284 // Index ID (or return an old one if we've already seen this
285 // thread_os_id).
286 // It will also make sure that no new threads are assigned this Index
287 // ID.
288 lldb_user_id = process_sp->AssignIndexIDToThread(thread_os_id);
289 }
290
291 thread_id_map[thread_id] = lldb_user_id;
292 });
293}
13
Potential memory leak
294
295static user_id_t Renumber(uint64_t id,
296 std::map<uint64_t, user_id_t> &thread_id_map) {
297 auto IT = thread_id_map.find(id);
298 if (IT == thread_id_map.end())
299 return 0;
300
301 return IT->second;
302}
303
304StructuredData::ObjectSP
305ThreadSanitizerRuntime::RetrieveReportData(ExecutionContextRef exe_ctx_ref) {
306 ProcessSP process_sp = GetProcessSP();
307 if (!process_sp)
3
Taking false branch
308 return StructuredData::ObjectSP();
309
310 ThreadSP thread_sp = exe_ctx_ref.GetThreadSP();
311 StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
312
313 if (!frame_sp)
4
Taking false branch
314 return StructuredData::ObjectSP();
315
316 EvaluateExpressionOptions options;
317 options.SetUnwindOnError(true);
318 options.SetTryAllThreads(true);
319 options.SetStopOthers(true);
320 options.SetIgnoreBreakpoints(true);
321 options.SetTimeout(g_retrieve_data_function_timeout);
322 options.SetPrefix(thread_sanitizer_retrieve_report_data_prefix);
323 options.SetAutoApplyFixIts(false);
324 options.SetLanguage(eLanguageTypeObjC_plus_plus);
325
326 ValueObjectSP main_value;
327 ExecutionContext exe_ctx;
328 Error eval_error;
329 frame_sp->CalculateExecutionContext(exe_ctx);
330 ExpressionResults result = UserExpression::Evaluate(
331 exe_ctx, options, thread_sanitizer_retrieve_report_data_command, "",
332 main_value, eval_error);
333 if (result != eExpressionCompleted) {
5
Assuming 'result' is equal to eExpressionCompleted
6
Taking false branch
334 process_sp->GetTarget().GetDebugger().GetAsyncOutputStream()->Printf(
335 "Warning: Cannot evaluate ThreadSanitizer expression:\n%s\n",
336 eval_error.AsCString());
337 return StructuredData::ObjectSP();
338 }
339
340 std::map<uint64_t, user_id_t> thread_id_map;
341 GetRenumberedThreadIds(process_sp, main_value, thread_id_map);
7
Calling 'GetRenumberedThreadIds'
342
343 StructuredData::Dictionary *dict = new StructuredData::Dictionary();
344 dict->AddStringItem("instrumentation_class", "ThreadSanitizer");
345 dict->AddStringItem("issue_type",
346 RetrieveString(main_value, process_sp, ".description"));
347 dict->AddIntegerItem("report_count",
348 main_value->GetValueForExpressionPath(".report_count")
349 ->GetValueAsUnsigned(0));
350 dict->AddItem("sleep_trace", StructuredData::ObjectSP(CreateStackTrace(
351 main_value, ".sleep_trace")));
352
353 StructuredData::Array *stacks = ConvertToStructuredArray(
354 main_value, ".stacks", ".stack_count",
355 [thread_sp](ValueObjectSP o, StructuredData::Dictionary *dict) {
356 dict->AddIntegerItem(
357 "index",
358 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
359 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
360 // "stacks" happen on the current thread
361 dict->AddIntegerItem("thread_id", thread_sp->GetIndexID());
362 });
363 dict->AddItem("stacks", StructuredData::ObjectSP(stacks));
364
365 StructuredData::Array *mops = ConvertToStructuredArray(
366 main_value, ".mops", ".mop_count",
367 [&thread_id_map](ValueObjectSP o, StructuredData::Dictionary *dict) {
368 dict->AddIntegerItem(
369 "index",
370 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
371 dict->AddIntegerItem(
372 "thread_id",
373 Renumber(
374 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0),
375 thread_id_map));
376 dict->AddIntegerItem(
377 "size",
378 o->GetValueForExpressionPath(".size")->GetValueAsUnsigned(0));
379 dict->AddBooleanItem(
380 "is_write",
381 o->GetValueForExpressionPath(".write")->GetValueAsUnsigned(0));
382 dict->AddBooleanItem(
383 "is_atomic",
384 o->GetValueForExpressionPath(".atomic")->GetValueAsUnsigned(0));
385 dict->AddIntegerItem(
386 "address",
387 o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
388 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
389 });
390 dict->AddItem("mops", StructuredData::ObjectSP(mops));
391
392 StructuredData::Array *locs = ConvertToStructuredArray(
393 main_value, ".locs", ".loc_count",
394 [process_sp, &thread_id_map](ValueObjectSP o,
395 StructuredData::Dictionary *dict) {
396 dict->AddIntegerItem(
397 "index",
398 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
399 dict->AddStringItem("type", RetrieveString(o, process_sp, ".type"));
400 dict->AddIntegerItem(
401 "address",
402 o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
403 dict->AddIntegerItem(
404 "start",
405 o->GetValueForExpressionPath(".start")->GetValueAsUnsigned(0));
406 dict->AddIntegerItem(
407 "size",
408 o->GetValueForExpressionPath(".size")->GetValueAsUnsigned(0));
409 dict->AddIntegerItem(
410 "thread_id",
411 Renumber(
412 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0),
413 thread_id_map));
414 dict->AddIntegerItem(
415 "file_descriptor",
416 o->GetValueForExpressionPath(".fd")->GetValueAsUnsigned(0));
417 dict->AddIntegerItem("suppressable",
418 o->GetValueForExpressionPath(".suppressable")
419 ->GetValueAsUnsigned(0));
420 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
421 dict->AddStringItem("object_type",
422 RetrieveString(o, process_sp, ".object_type"));
423 });
424 dict->AddItem("locs", StructuredData::ObjectSP(locs));
425
426 StructuredData::Array *mutexes = ConvertToStructuredArray(
427 main_value, ".mutexes", ".mutex_count",
428 [](ValueObjectSP o, StructuredData::Dictionary *dict) {
429 dict->AddIntegerItem(
430 "index",
431 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
432 dict->AddIntegerItem(
433 "mutex_id",
434 o->GetValueForExpressionPath(".mutex_id")->GetValueAsUnsigned(0));
435 dict->AddIntegerItem(
436 "address",
437 o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0));
438 dict->AddIntegerItem(
439 "destroyed",
440 o->GetValueForExpressionPath(".destroyed")->GetValueAsUnsigned(0));
441 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
442 });
443 dict->AddItem("mutexes", StructuredData::ObjectSP(mutexes));
444
445 StructuredData::Array *threads = ConvertToStructuredArray(
446 main_value, ".threads", ".thread_count",
447 [process_sp, &thread_id_map](ValueObjectSP o,
448 StructuredData::Dictionary *dict) {
449 dict->AddIntegerItem(
450 "index",
451 o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0));
452 dict->AddIntegerItem(
453 "thread_id",
454 Renumber(
455 o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0),
456 thread_id_map));
457 dict->AddIntegerItem(
458 "thread_os_id",
459 o->GetValueForExpressionPath(".os_id")->GetValueAsUnsigned(0));
460 dict->AddIntegerItem(
461 "running",
462 o->GetValueForExpressionPath(".running")->GetValueAsUnsigned(0));
463 dict->AddStringItem("name", RetrieveString(o, process_sp, ".name"));
464 dict->AddIntegerItem(
465 "parent_thread_id",
466 Renumber(o->GetValueForExpressionPath(".parent_tid")
467 ->GetValueAsUnsigned(0),
468 thread_id_map));
469 dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o)));
470 });
471 dict->AddItem("threads", StructuredData::ObjectSP(threads));
472
473 StructuredData::Array *unique_tids = ConvertToStructuredArray(
474 main_value, ".unique_tids", ".unique_tid_count",
475 [&thread_id_map](ValueObjectSP o, StructuredData::Dictionary *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", StructuredData::ObjectSP(unique_tids));
486
487 return StructuredData::ObjectSP(dict);
488}
489
490std::string
491ThreadSanitizerRuntime::FormatDescription(StructuredData::ObjectSP report) {
492 std::string description = 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 }
528
529 // for unknown report codes just show the code
530 return description;
531}
532
533static std::string Sprintf(const char *format, ...) {
534 StreamString s;
535 va_list args;
536 va_start(args, format)__builtin_va_start(args, format);
537 s.PrintfVarArg(format, args);
538 va_end(args)__builtin_va_end(args);
539 return s.GetString();
540}
541
542static std::string GetSymbolNameFromAddress(ProcessSP process_sp, addr_t addr) {
543 lldb_private::Address so_addr;
544 if (!process_sp->GetTarget().GetSectionLoadList().ResolveLoadAddress(addr,
545 so_addr))
546 return "";
547
548 lldb_private::Symbol *symbol = so_addr.CalculateSymbolContextSymbol();
549 if (!symbol)
550 return "";
551
552 std::string sym_name = symbol->GetName().GetCString();
553 return sym_name;
554}
555
556static void GetSymbolDeclarationFromAddress(ProcessSP process_sp, addr_t addr,
557 Declaration &decl) {
558 lldb_private::Address so_addr;
559 if (!process_sp->GetTarget().GetSectionLoadList().ResolveLoadAddress(addr,
560 so_addr))
561 return;
562
563 lldb_private::Symbol *symbol = so_addr.CalculateSymbolContextSymbol();
564 if (!symbol)
565 return;
566
567 ConstString sym_name = symbol->GetMangled().GetName(
568 lldb::eLanguageTypeUnknown, Mangled::ePreferMangled);
569
570 ModuleSP module = symbol->CalculateSymbolContextModule();
571 if (!module)
572 return;
573
574 VariableList var_list;
575 module->FindGlobalVariables(sym_name, nullptr, true, 1U, var_list);
576 if (var_list.GetSize() < 1)
577 return;
578
579 VariableSP var = var_list.GetVariableAtIndex(0);
580 decl = var->GetDeclaration();
581}
582
583addr_t ThreadSanitizerRuntime::GetFirstNonInternalFramePc(
584 StructuredData::ObjectSP trace) {
585 ProcessSP process_sp = GetProcessSP();
586 ModuleSP runtime_module_sp = GetRuntimeModuleSP();
587
588 addr_t result = 0;
589 trace->GetAsArray()->ForEach([process_sp, runtime_module_sp,
590 &result](StructuredData::Object *o) -> bool {
591 addr_t addr = o->GetIntegerValue();
592 lldb_private::Address so_addr;
593 if (!process_sp->GetTarget().GetSectionLoadList().ResolveLoadAddress(
594 addr, so_addr))
595 return true;
596
597 if (so_addr.GetModule() == runtime_module_sp)
598 return true;
599
600 result = addr;
601 return false;
602 });
603
604 return result;
605}
606
607std::string
608ThreadSanitizerRuntime::GenerateSummary(StructuredData::ObjectSP report) {
609 ProcessSP process_sp = GetProcessSP();
610
611 std::string summary = report->GetAsDictionary()
612 ->GetValueForKey("description")
613 ->GetAsString()
614 ->GetValue();
615 addr_t pc = 0;
616 if (report->GetAsDictionary()
617 ->GetValueForKey("mops")
618 ->GetAsArray()
619 ->GetSize() > 0)
620 pc = GetFirstNonInternalFramePc(report->GetAsDictionary()
621 ->GetValueForKey("mops")
622 ->GetAsArray()
623 ->GetItemAtIndex(0)
624 ->GetAsDictionary()
625 ->GetValueForKey("trace"));
626
627 if (report->GetAsDictionary()
628 ->GetValueForKey("stacks")
629 ->GetAsArray()
630 ->GetSize() > 0)
631 pc = GetFirstNonInternalFramePc(report->GetAsDictionary()
632 ->GetValueForKey("stacks")
633 ->GetAsArray()
634 ->GetItemAtIndex(0)
635 ->GetAsDictionary()
636 ->GetValueForKey("trace"));
637
638 if (pc != 0) {
639 summary = summary + " in " + GetSymbolNameFromAddress(process_sp, pc);
640 }
641
642 if (report->GetAsDictionary()
643 ->GetValueForKey("locs")
644 ->GetAsArray()
645 ->GetSize() > 0) {
646 StructuredData::ObjectSP loc = report->GetAsDictionary()
647 ->GetValueForKey("locs")
648 ->GetAsArray()
649 ->GetItemAtIndex(0);
650 std::string object_type = loc->GetAsDictionary()
651 ->GetValueForKey("object_type")
652 ->GetAsString()
653 ->GetValue();
654 if (!object_type.empty()) {
655 summary = "Race on " + object_type + " object";
656 }
657 addr_t addr = loc->GetAsDictionary()
658 ->GetValueForKey("address")
659 ->GetAsInteger()
660 ->GetValue();
661 if (addr == 0)
662 addr = loc->GetAsDictionary()
663 ->GetValueForKey("start")
664 ->GetAsInteger()
665 ->GetValue();
666
667 if (addr != 0) {
668 std::string global_name = GetSymbolNameFromAddress(process_sp, addr);
669 if (!global_name.empty()) {
670 summary = summary + " at " + global_name;
671 } else {
672 summary = summary + " at " + Sprintf("0x%llx", addr);
673 }
674 } else {
675 int fd = loc->GetAsDictionary()
676 ->GetValueForKey("file_descriptor")
677 ->GetAsInteger()
678 ->GetValue();
679 if (fd != 0) {
680 summary = summary + " on file descriptor " + Sprintf("%d", fd);
681 }
682 }
683 }
684
685 return summary;
686}
687
688addr_t
689ThreadSanitizerRuntime::GetMainRacyAddress(StructuredData::ObjectSP report) {
690 addr_t result = (addr_t)-1;
691
692 report->GetObjectForDotSeparatedPath("mops")->GetAsArray()->ForEach(
693 [&result](StructuredData::Object *o) -> bool {
694 addr_t addr =
695 o->GetObjectForDotSeparatedPath("address")->GetIntegerValue();
696 if (addr < result)
697 result = addr;
698 return true;
699 });
700
701 return (result == (addr_t)-1) ? 0 : result;
702}
703
704std::string ThreadSanitizerRuntime::GetLocationDescription(
705 StructuredData::ObjectSP report, addr_t &global_addr,
706 std::string &global_name, std::string &filename, uint32_t &line) {
707 std::string result = "";
708
709 ProcessSP process_sp = GetProcessSP();
710
711 if (report->GetAsDictionary()
712 ->GetValueForKey("locs")
713 ->GetAsArray()
714 ->GetSize() > 0) {
715 StructuredData::ObjectSP loc = report->GetAsDictionary()
716 ->GetValueForKey("locs")
717 ->GetAsArray()
718 ->GetItemAtIndex(0);
719 std::string type =
720 loc->GetAsDictionary()->GetValueForKey("type")->GetStringValue();
721 if (type == "global") {
722 global_addr = loc->GetAsDictionary()
723 ->GetValueForKey("address")
724 ->GetAsInteger()
725 ->GetValue();
726 global_name = GetSymbolNameFromAddress(process_sp, global_addr);
727 if (!global_name.empty()) {
728 result = Sprintf("'%s' is a global variable (0x%llx)",
729 global_name.c_str(), global_addr);
730 } else {
731 result = Sprintf("0x%llx is a global variable", global_addr);
732 }
733
734 Declaration decl;
735 GetSymbolDeclarationFromAddress(process_sp, global_addr, decl);
736 if (decl.GetFile()) {
737 filename = decl.GetFile().GetPath();
738 line = decl.GetLine();
739 }
740 } else if (type == "heap") {
741 addr_t addr = loc->GetAsDictionary()
742 ->GetValueForKey("start")
743 ->GetAsInteger()
744 ->GetValue();
745 long size = loc->GetAsDictionary()
746 ->GetValueForKey("size")
747 ->GetAsInteger()
748 ->GetValue();
749 std::string object_type = loc->GetAsDictionary()
750 ->GetValueForKey("object_type")
751 ->GetAsString()
752 ->GetValue();
753 if (!object_type.empty()) {
754 result = Sprintf("Location is a %ld-byte %s object at 0x%llx", size,
755 object_type.c_str(), addr);
756 } else {
757 result =
758 Sprintf("Location is a %ld-byte heap object at 0x%llx", size, addr);
759 }
760 } else if (type == "stack") {
761 int tid = loc->GetAsDictionary()
762 ->GetValueForKey("thread_id")
763 ->GetAsInteger()
764 ->GetValue();
765 result = Sprintf("Location is stack of thread %d", tid);
766 } else if (type == "tls") {
767 int tid = loc->GetAsDictionary()
768 ->GetValueForKey("thread_id")
769 ->GetAsInteger()
770 ->GetValue();
771 result = Sprintf("Location is TLS of thread %d", tid);
772 } else if (type == "fd") {
773 int fd = loc->GetAsDictionary()
774 ->GetValueForKey("file_descriptor")
775 ->GetAsInteger()
776 ->GetValue();
777 result = Sprintf("Location is file descriptor %d", fd);
778 }
779 }
780
781 return result;
782}
783
784bool ThreadSanitizerRuntime::NotifyBreakpointHit(
785 void *baton, StoppointCallbackContext *context, user_id_t break_id,
786 user_id_t break_loc_id) {
787 assert(baton && "null baton")((baton && "null baton") ? static_cast<void> (0
) : __assert_fail ("baton && \"null baton\"", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/lldb/source/Plugins/InstrumentationRuntime/ThreadSanitizer/ThreadSanitizerRuntime.cpp"
, 787, __PRETTY_FUNCTION__))
;
788 if (!baton)
1
Taking false branch
789 return false;
790
791 ThreadSanitizerRuntime *const instance =
792 static_cast<ThreadSanitizerRuntime *>(baton);
793
794 StructuredData::ObjectSP report =
795 instance->RetrieveReportData(context->exe_ctx_ref);
2
Calling 'ThreadSanitizerRuntime::RetrieveReportData'
796 std::string stop_reason_description;
797 if (report) {
798 std::string issue_description = instance->FormatDescription(report);
799 report->GetAsDictionary()->AddStringItem("description", issue_description);
800 stop_reason_description = issue_description + " detected";
801 report->GetAsDictionary()->AddStringItem("stop_description",
802 stop_reason_description);
803 std::string summary = instance->GenerateSummary(report);
804 report->GetAsDictionary()->AddStringItem("summary", summary);
805 addr_t main_address = instance->GetMainRacyAddress(report);
806 report->GetAsDictionary()->AddIntegerItem("memory_address", main_address);
807
808 addr_t global_addr = 0;
809 std::string global_name = "";
810 std::string location_filename = "";
811 uint32_t location_line = 0;
812 std::string location_description = instance->GetLocationDescription(
813 report, global_addr, global_name, location_filename, location_line);
814 report->GetAsDictionary()->AddStringItem("location_description",
815 location_description);
816 if (global_addr != 0) {
817 report->GetAsDictionary()->AddIntegerItem("global_address", global_addr);
818 }
819 if (!global_name.empty()) {
820 report->GetAsDictionary()->AddStringItem("global_name", global_name);
821 }
822 if (location_filename != "") {
823 report->GetAsDictionary()->AddStringItem("location_filename",
824 location_filename);
825 report->GetAsDictionary()->AddIntegerItem("location_line", location_line);
826 }
827
828 bool all_addresses_are_same = true;
829 report->GetObjectForDotSeparatedPath("mops")->GetAsArray()->ForEach(
830 [&all_addresses_are_same,
831 main_address](StructuredData::Object *o) -> bool {
832 addr_t addr =
833 o->GetObjectForDotSeparatedPath("address")->GetIntegerValue();
834 if (main_address != addr)
835 all_addresses_are_same = false;
836 return true;
837 });
838 report->GetAsDictionary()->AddBooleanItem("all_addresses_are_same",
839 all_addresses_are_same);
840 }
841
842 ProcessSP process_sp = instance->GetProcessSP();
843 // Make sure this is the right process
844 if (process_sp && process_sp == context->exe_ctx_ref.GetProcessSP()) {
845 ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
846 if (thread_sp)
847 thread_sp->SetStopInfo(
848 InstrumentationRuntimeStopInfo::
849 CreateStopReasonWithInstrumentationData(
850 *thread_sp, stop_reason_description, report));
851
852 StreamFileSP stream_sp(
853 process_sp->GetTarget().GetDebugger().GetOutputFile());
854 if (stream_sp) {
855 stream_sp->Printf("ThreadSanitizer report breakpoint hit. Use 'thread "
856 "info -s' to get extended information about the "
857 "report.\n");
858 }
859 return true; // Return true to stop the target
860 } else
861 return false; // Let target run
862}
863
864const RegularExpression &ThreadSanitizerRuntime::GetPatternForRuntimeLibrary() {
865 static RegularExpression regex(llvm::StringRef("libclang_rt.tsan_"));
866 return regex;
867}
868
869bool ThreadSanitizerRuntime::CheckIfRuntimeIsValid(
870 const lldb::ModuleSP module_sp) {
871 static ConstString g_tsan_get_current_report("__tsan_get_current_report");
872 const Symbol *symbol = module_sp->FindFirstSymbolWithNameAndType(
873 g_tsan_get_current_report, lldb::eSymbolTypeAny);
874 return symbol != nullptr;
875}
876
877void ThreadSanitizerRuntime::Activate() {
878 if (IsActive())
879 return;
880
881 ProcessSP process_sp = GetProcessSP();
882 if (!process_sp)
883 return;
884
885 ConstString symbol_name("__tsan_on_report");
886 const Symbol *symbol = GetRuntimeModuleSP()->FindFirstSymbolWithNameAndType(
887 symbol_name, eSymbolTypeCode);
888
889 if (symbol == NULL__null)
890 return;
891
892 if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
893 return;
894
895 Target &target = process_sp->GetTarget();
896 addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
897
898 if (symbol_address == LLDB_INVALID_ADDRESS(18446744073709551615UL))
899 return;
900
901 bool internal = true;
902 bool hardware = false;
903 Breakpoint *breakpoint =
904 process_sp->GetTarget()
905 .CreateBreakpoint(symbol_address, internal, hardware)
906 .get();
907 breakpoint->SetCallback(ThreadSanitizerRuntime::NotifyBreakpointHit, this,
908 true);
909 breakpoint->SetBreakpointKind("thread-sanitizer-report");
910 SetBreakpointID(breakpoint->GetID());
911
912 StreamFileSP stream_sp(process_sp->GetTarget().GetDebugger().GetOutputFile());
913 if (stream_sp) {
914 stream_sp->Printf("ThreadSanitizer debugger support is active.\n");
915 }
916
917 SetActive(true);
918}
919
920void ThreadSanitizerRuntime::Deactivate() {
921 if (GetBreakpointID() != LLDB_INVALID_BREAK_ID0) {
922 ProcessSP process_sp = GetProcessSP();
923 if (process_sp) {
924 process_sp->GetTarget().RemoveBreakpointByID(GetBreakpointID());
925 SetBreakpointID(LLDB_INVALID_BREAK_ID0);
926 }
927 }
928 SetActive(false);
929}
930static std::string GenerateThreadName(const std::string &path,
931 StructuredData::Object *o,
932 StructuredData::ObjectSP main_info) {
933 std::string result = "additional information";
934
935 if (path == "mops") {
936 int size = o->GetObjectForDotSeparatedPath("size")->GetIntegerValue();
937 int thread_id =
938 o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
939 bool is_write =
940 o->GetObjectForDotSeparatedPath("is_write")->GetBooleanValue();
941 bool is_atomic =
942 o->GetObjectForDotSeparatedPath("is_atomic")->GetBooleanValue();
943 addr_t addr = o->GetObjectForDotSeparatedPath("address")->GetIntegerValue();
944
945 std::string addr_string = Sprintf(" at 0x%llx", addr);
946
947 if (main_info->GetObjectForDotSeparatedPath("all_addresses_are_same")
948 ->GetBooleanValue()) {
949 addr_string = "";
950 }
951
952 result = Sprintf("%s%s of size %d%s by thread %d",
953 is_atomic ? "atomic " : "", is_write ? "write" : "read",
954 size, addr_string.c_str(), thread_id);
955 }
956
957 if (path == "threads") {
958 int thread_id =
959 o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
960 result = Sprintf("Thread %d created", thread_id);
961 }
962
963 if (path == "locs") {
964 std::string type =
965 o->GetAsDictionary()->GetValueForKey("type")->GetStringValue();
966 int thread_id =
967 o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
968 int fd =
969 o->GetObjectForDotSeparatedPath("file_descriptor")->GetIntegerValue();
970 if (type == "heap") {
971 result = Sprintf("Heap block allocated by thread %d", thread_id);
972 } else if (type == "fd") {
973 result =
974 Sprintf("File descriptor %d created by thread %t", fd, thread_id);
975 }
976 }
977
978 if (path == "mutexes") {
979 int mutex_id =
980 o->GetObjectForDotSeparatedPath("mutex_id")->GetIntegerValue();
981
982 result = Sprintf("Mutex M%d created", mutex_id);
983 }
984
985 if (path == "stacks") {
986 int thread_id =
987 o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue();
988 result = Sprintf("Thread %d", thread_id);
989 }
990
991 result[0] = toupper(result[0]);
992
993 return result;
994}
995
996static void AddThreadsForPath(const std::string &path,
997 ThreadCollectionSP threads, ProcessSP process_sp,
998 StructuredData::ObjectSP info) {
999 info->GetObjectForDotSeparatedPath(path)->GetAsArray()->ForEach(
1000 [process_sp, threads, path, info](StructuredData::Object *o) -> bool {
1001 std::vector<lldb::addr_t> pcs;
1002 o->GetObjectForDotSeparatedPath("trace")->GetAsArray()->ForEach(
1003 [&pcs](StructuredData::Object *pc) -> bool {
1004 pcs.push_back(pc->GetAsInteger()->GetValue());
1005 return true;
1006 });
1007
1008 if (pcs.size() == 0)
1009 return true;
1010
1011 StructuredData::ObjectSP thread_id_obj =
1012 o->GetObjectForDotSeparatedPath("thread_os_id");
1013 tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0;
1014
1015 uint32_t stop_id = 0;
1016 bool stop_id_is_valid = false;
1017 HistoryThread *history_thread =
1018 new HistoryThread(*process_sp, tid, pcs, stop_id, stop_id_is_valid);
1019 ThreadSP new_thread_sp(history_thread);
1020 new_thread_sp->SetName(GenerateThreadName(path, o, info).c_str());
1021
1022 // Save this in the Process' ExtendedThreadList so a strong pointer
1023 // retains the object
1024 process_sp->GetExtendedThreadList().AddThread(new_thread_sp);
1025 threads->AddThread(new_thread_sp);
1026
1027 return true;
1028 });
1029}
1030
1031lldb::ThreadCollectionSP
1032ThreadSanitizerRuntime::GetBacktracesFromExtendedStopInfo(
1033 StructuredData::ObjectSP info) {
1034 ThreadCollectionSP threads;
1035 threads.reset(new ThreadCollection());
1036
1037 if (info->GetObjectForDotSeparatedPath("instrumentation_class")
1038 ->GetStringValue() != "ThreadSanitizer")
1039 return threads;
1040
1041 ProcessSP process_sp = GetProcessSP();
1042
1043 AddThreadsForPath("stacks", threads, process_sp, info);
1044 AddThreadsForPath("mops", threads, process_sp, info);
1045 AddThreadsForPath("locs", threads, process_sp, info);
1046 AddThreadsForPath("mutexes", threads, process_sp, info);
1047 AddThreadsForPath("threads", threads, process_sp, info);
1048
1049 return threads;
1050}