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