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