xref: /freebsd/contrib/llvm-project/compiler-rt/lib/tsan/rtl/tsan_report.cpp (revision 59c8e88e72633afbc47a4ace0d2170d00d51f7dc)
1 //===-- tsan_report.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 // This file is a part of ThreadSanitizer (TSan), a race detector.
10 //
11 //===----------------------------------------------------------------------===//
12 #include "tsan_report.h"
13 #include "tsan_platform.h"
14 #include "tsan_rtl.h"
15 #include "sanitizer_common/sanitizer_file.h"
16 #include "sanitizer_common/sanitizer_placement_new.h"
17 #include "sanitizer_common/sanitizer_report_decorator.h"
18 #include "sanitizer_common/sanitizer_stacktrace_printer.h"
19 
20 namespace __tsan {
21 
22 class Decorator: public __sanitizer::SanitizerCommonDecorator {
23  public:
24   Decorator() : SanitizerCommonDecorator() { }
25   const char *Access()     { return Blue(); }
26   const char *ThreadDescription()    { return Cyan(); }
27   const char *Location()   { return Green(); }
28   const char *Sleep()   { return Yellow(); }
29   const char *Mutex()   { return Magenta(); }
30 };
31 
32 ReportDesc::ReportDesc()
33     : tag(kExternalTagNone)
34     , stacks()
35     , mops()
36     , locs()
37     , mutexes()
38     , threads()
39     , unique_tids()
40     , sleep()
41     , count() {
42 }
43 
44 ReportMop::ReportMop()
45     : mset() {
46 }
47 
48 ReportDesc::~ReportDesc() {
49   // FIXME(dvyukov): it must be leaking a lot of memory.
50 }
51 
52 #if !SANITIZER_GO
53 
54 const int kThreadBufSize = 32;
55 const char *thread_name(char *buf, Tid tid) {
56   if (tid == kMainTid)
57     return "main thread";
58   internal_snprintf(buf, kThreadBufSize, "thread T%d", tid);
59   return buf;
60 }
61 
62 static const char *ReportTypeString(ReportType typ, uptr tag) {
63   switch (typ) {
64     case ReportTypeRace:
65       return "data race";
66     case ReportTypeVptrRace:
67       return "data race on vptr (ctor/dtor vs virtual call)";
68     case ReportTypeUseAfterFree:
69       return "heap-use-after-free";
70     case ReportTypeVptrUseAfterFree:
71       return "heap-use-after-free (virtual call vs free)";
72     case ReportTypeExternalRace: {
73       const char *str = GetReportHeaderFromTag(tag);
74       return str ? str : "race on external object";
75     }
76     case ReportTypeThreadLeak:
77       return "thread leak";
78     case ReportTypeMutexDestroyLocked:
79       return "destroy of a locked mutex";
80     case ReportTypeMutexDoubleLock:
81       return "double lock of a mutex";
82     case ReportTypeMutexInvalidAccess:
83       return "use of an invalid mutex (e.g. uninitialized or destroyed)";
84     case ReportTypeMutexBadUnlock:
85       return "unlock of an unlocked mutex (or by a wrong thread)";
86     case ReportTypeMutexBadReadLock:
87       return "read lock of a write locked mutex";
88     case ReportTypeMutexBadReadUnlock:
89       return "read unlock of a write locked mutex";
90     case ReportTypeSignalUnsafe:
91       return "signal-unsafe call inside of a signal";
92     case ReportTypeErrnoInSignal:
93       return "signal handler spoils errno";
94     case ReportTypeDeadlock:
95       return "lock-order-inversion (potential deadlock)";
96     // No default case so compiler warns us if we miss one
97   }
98   UNREACHABLE("missing case");
99 }
100 
101 void PrintStack(const ReportStack *ent) {
102   if (ent == 0 || ent->frames == 0) {
103     Printf("    [failed to restore the stack]\n\n");
104     return;
105   }
106   SymbolizedStack *frame = ent->frames;
107   for (int i = 0; frame && frame->info.address; frame = frame->next, i++) {
108     InternalScopedString res;
109     RenderFrame(&res, common_flags()->stack_trace_format, i,
110                 frame->info.address, &frame->info,
111                 common_flags()->symbolize_vs_style,
112                 common_flags()->strip_path_prefix);
113     Printf("%s\n", res.data());
114   }
115   Printf("\n");
116 }
117 
118 static void PrintMutexSet(Vector<ReportMopMutex> const& mset) {
119   for (uptr i = 0; i < mset.Size(); i++) {
120     if (i == 0)
121       Printf(" (mutexes:");
122     const ReportMopMutex m = mset[i];
123     Printf(" %s M%u", m.write ? "write" : "read", m.id);
124     Printf(i == mset.Size() - 1 ? ")" : ",");
125   }
126 }
127 
128 static const char *MopDesc(bool first, bool write, bool atomic) {
129   return atomic ? (first ? (write ? "Atomic write" : "Atomic read")
130                 : (write ? "Previous atomic write" : "Previous atomic read"))
131                 : (first ? (write ? "Write" : "Read")
132                 : (write ? "Previous write" : "Previous read"));
133 }
134 
135 static const char *ExternalMopDesc(bool first, bool write) {
136   return first ? (write ? "Modifying" : "Read-only")
137                : (write ? "Previous modifying" : "Previous read-only");
138 }
139 
140 static void PrintMop(const ReportMop *mop, bool first) {
141   Decorator d;
142   char thrbuf[kThreadBufSize];
143   Printf("%s", d.Access());
144   if (mop->external_tag == kExternalTagNone) {
145     Printf("  %s of size %d at %p by %s",
146            MopDesc(first, mop->write, mop->atomic), mop->size,
147            (void *)mop->addr, thread_name(thrbuf, mop->tid));
148   } else {
149     const char *object_type = GetObjectTypeFromTag(mop->external_tag);
150     if (object_type == nullptr)
151         object_type = "external object";
152     Printf("  %s access of %s at %p by %s",
153            ExternalMopDesc(first, mop->write), object_type,
154            (void *)mop->addr, thread_name(thrbuf, mop->tid));
155   }
156   PrintMutexSet(mop->mset);
157   Printf(":\n");
158   Printf("%s", d.Default());
159   PrintStack(mop->stack);
160 }
161 
162 static void PrintLocation(const ReportLocation *loc) {
163   Decorator d;
164   char thrbuf[kThreadBufSize];
165   bool print_stack = false;
166   Printf("%s", d.Location());
167   if (loc->type == ReportLocationGlobal) {
168     const DataInfo &global = loc->global;
169     if (global.size != 0)
170       Printf("  Location is global '%s' of size %zu at %p (%s+0x%zx)\n\n",
171              global.name, global.size, reinterpret_cast<void *>(global.start),
172              StripModuleName(global.module), global.module_offset);
173     else
174       Printf("  Location is global '%s' at %p (%s+0x%zx)\n\n", global.name,
175              reinterpret_cast<void *>(global.start),
176              StripModuleName(global.module), global.module_offset);
177   } else if (loc->type == ReportLocationHeap) {
178     char thrbuf[kThreadBufSize];
179     const char *object_type = GetObjectTypeFromTag(loc->external_tag);
180     if (!object_type) {
181       Printf("  Location is heap block of size %zu at %p allocated by %s:\n",
182              loc->heap_chunk_size,
183              reinterpret_cast<void *>(loc->heap_chunk_start),
184              thread_name(thrbuf, loc->tid));
185     } else {
186       Printf("  Location is %s of size %zu at %p allocated by %s:\n",
187              object_type, loc->heap_chunk_size,
188              reinterpret_cast<void *>(loc->heap_chunk_start),
189              thread_name(thrbuf, loc->tid));
190     }
191     print_stack = true;
192   } else if (loc->type == ReportLocationStack) {
193     Printf("  Location is stack of %s.\n\n", thread_name(thrbuf, loc->tid));
194   } else if (loc->type == ReportLocationTLS) {
195     Printf("  Location is TLS of %s.\n\n", thread_name(thrbuf, loc->tid));
196   } else if (loc->type == ReportLocationFD) {
197     Printf("  Location is file descriptor %d %s by %s at:\n", loc->fd,
198            loc->fd_closed ? "destroyed" : "created",
199            thread_name(thrbuf, loc->tid));
200     print_stack = true;
201   }
202   Printf("%s", d.Default());
203   if (print_stack)
204     PrintStack(loc->stack);
205 }
206 
207 static void PrintMutexShort(const ReportMutex *rm, const char *after) {
208   Decorator d;
209   Printf("%sM%d%s%s", d.Mutex(), rm->id, d.Default(), after);
210 }
211 
212 static void PrintMutexShortWithAddress(const ReportMutex *rm,
213                                        const char *after) {
214   Decorator d;
215   Printf("%sM%d (%p)%s%s", d.Mutex(), rm->id,
216          reinterpret_cast<void *>(rm->addr), d.Default(), after);
217 }
218 
219 static void PrintMutex(const ReportMutex *rm) {
220   Decorator d;
221   Printf("%s", d.Mutex());
222   Printf("  Mutex M%u (%p) created at:\n", rm->id,
223          reinterpret_cast<void *>(rm->addr));
224   Printf("%s", d.Default());
225   PrintStack(rm->stack);
226 }
227 
228 static void PrintThread(const ReportThread *rt) {
229   Decorator d;
230   if (rt->id == kMainTid)  // Little sense in describing the main thread.
231     return;
232   Printf("%s", d.ThreadDescription());
233   Printf("  Thread T%d", rt->id);
234   if (rt->name && rt->name[0] != '\0')
235     Printf(" '%s'", rt->name);
236   char thrbuf[kThreadBufSize];
237   const char *thread_status = rt->running ? "running" : "finished";
238   if (rt->thread_type == ThreadType::Worker) {
239     Printf(" (tid=%llu, %s) is a GCD worker thread\n", rt->os_id,
240            thread_status);
241     Printf("\n");
242     Printf("%s", d.Default());
243     return;
244   }
245   Printf(" (tid=%llu, %s) created by %s", rt->os_id, thread_status,
246          thread_name(thrbuf, rt->parent_tid));
247   if (rt->stack)
248     Printf(" at:");
249   Printf("\n");
250   Printf("%s", d.Default());
251   PrintStack(rt->stack);
252 }
253 
254 static void PrintSleep(const ReportStack *s) {
255   Decorator d;
256   Printf("%s", d.Sleep());
257   Printf("  As if synchronized via sleep:\n");
258   Printf("%s", d.Default());
259   PrintStack(s);
260 }
261 
262 static ReportStack *ChooseSummaryStack(const ReportDesc *rep) {
263   if (rep->mops.Size())
264     return rep->mops[0]->stack;
265   if (rep->stacks.Size())
266     return rep->stacks[0];
267   if (rep->mutexes.Size())
268     return rep->mutexes[0]->stack;
269   if (rep->threads.Size())
270     return rep->threads[0]->stack;
271   return 0;
272 }
273 
274 static bool FrameIsInternal(const SymbolizedStack *frame) {
275   if (frame == 0)
276     return false;
277   const char *file = frame->info.file;
278   const char *module = frame->info.module;
279   if (file != 0 &&
280       (internal_strstr(file, "tsan_interceptors_posix.cpp") ||
281        internal_strstr(file, "tsan_interceptors_memintrinsics.cpp") ||
282        internal_strstr(file, "sanitizer_common_interceptors.inc") ||
283        internal_strstr(file, "tsan_interface_")))
284     return true;
285   if (module != 0 && (internal_strstr(module, "libclang_rt.tsan_")))
286     return true;
287   return false;
288 }
289 
290 static SymbolizedStack *SkipTsanInternalFrames(SymbolizedStack *frames) {
291   while (FrameIsInternal(frames) && frames->next)
292     frames = frames->next;
293   return frames;
294 }
295 
296 void PrintReport(const ReportDesc *rep) {
297   Decorator d;
298   Printf("==================\n");
299   const char *rep_typ_str = ReportTypeString(rep->typ, rep->tag);
300   Printf("%s", d.Warning());
301   Printf("WARNING: ThreadSanitizer: %s (pid=%d)\n", rep_typ_str,
302          (int)internal_getpid());
303   Printf("%s", d.Default());
304 
305   if (rep->typ == ReportTypeErrnoInSignal)
306     Printf("  Signal %u handler invoked at:\n", rep->signum);
307 
308   if (rep->typ == ReportTypeDeadlock) {
309     char thrbuf[kThreadBufSize];
310     Printf("  Cycle in lock order graph: ");
311     for (uptr i = 0; i < rep->mutexes.Size(); i++)
312       PrintMutexShortWithAddress(rep->mutexes[i], " => ");
313     PrintMutexShort(rep->mutexes[0], "\n\n");
314     CHECK_GT(rep->mutexes.Size(), 0U);
315     CHECK_EQ(rep->mutexes.Size() * (flags()->second_deadlock_stack ? 2 : 1),
316              rep->stacks.Size());
317     for (uptr i = 0; i < rep->mutexes.Size(); i++) {
318       Printf("  Mutex ");
319       PrintMutexShort(rep->mutexes[(i + 1) % rep->mutexes.Size()],
320                       " acquired here while holding mutex ");
321       PrintMutexShort(rep->mutexes[i], " in ");
322       Printf("%s", d.ThreadDescription());
323       Printf("%s:\n", thread_name(thrbuf, rep->unique_tids[i]));
324       Printf("%s", d.Default());
325       if (flags()->second_deadlock_stack) {
326         PrintStack(rep->stacks[2*i]);
327         Printf("  Mutex ");
328         PrintMutexShort(rep->mutexes[i],
329                         " previously acquired by the same thread here:\n");
330         PrintStack(rep->stacks[2*i+1]);
331       } else {
332         PrintStack(rep->stacks[i]);
333         if (i == 0)
334           Printf("    Hint: use TSAN_OPTIONS=second_deadlock_stack=1 "
335                  "to get more informative warning message\n\n");
336       }
337     }
338   } else {
339     for (uptr i = 0; i < rep->stacks.Size(); i++) {
340       if (i)
341         Printf("  and:\n");
342       PrintStack(rep->stacks[i]);
343     }
344   }
345 
346   for (uptr i = 0; i < rep->mops.Size(); i++)
347     PrintMop(rep->mops[i], i == 0);
348 
349   if (rep->sleep)
350     PrintSleep(rep->sleep);
351 
352   for (uptr i = 0; i < rep->locs.Size(); i++)
353     PrintLocation(rep->locs[i]);
354 
355   if (rep->typ != ReportTypeDeadlock) {
356     for (uptr i = 0; i < rep->mutexes.Size(); i++)
357       PrintMutex(rep->mutexes[i]);
358   }
359 
360   for (uptr i = 0; i < rep->threads.Size(); i++)
361     PrintThread(rep->threads[i]);
362 
363   if (rep->typ == ReportTypeThreadLeak && rep->count > 1)
364     Printf("  And %d more similar thread leaks.\n\n", rep->count - 1);
365 
366   if (ReportStack *stack = ChooseSummaryStack(rep)) {
367     if (SymbolizedStack *frame = SkipTsanInternalFrames(stack->frames))
368       ReportErrorSummary(rep_typ_str, frame->info);
369   }
370 
371   if (common_flags()->print_module_map == 2)
372     DumpProcessMap();
373 
374   Printf("==================\n");
375 }
376 
377 #else  // #if !SANITIZER_GO
378 
379 const Tid kMainGoroutineId = 1;
380 
381 void PrintStack(const ReportStack *ent) {
382   if (ent == 0 || ent->frames == 0) {
383     Printf("  [failed to restore the stack]\n");
384     return;
385   }
386   SymbolizedStack *frame = ent->frames;
387   for (int i = 0; frame; frame = frame->next, i++) {
388     const AddressInfo &info = frame->info;
389     Printf("  %s()\n      %s:%d +0x%zx\n", info.function,
390            StripPathPrefix(info.file, common_flags()->strip_path_prefix),
391            info.line, info.module_offset);
392   }
393 }
394 
395 static void PrintMop(const ReportMop *mop, bool first) {
396   Printf("\n");
397   Printf("%s at %p by ",
398          (first ? (mop->write ? "Write" : "Read")
399                 : (mop->write ? "Previous write" : "Previous read")),
400          reinterpret_cast<void *>(mop->addr));
401   if (mop->tid == kMainGoroutineId)
402     Printf("main goroutine:\n");
403   else
404     Printf("goroutine %d:\n", mop->tid);
405   PrintStack(mop->stack);
406 }
407 
408 static void PrintLocation(const ReportLocation *loc) {
409   switch (loc->type) {
410   case ReportLocationHeap: {
411     Printf("\n");
412     Printf("Heap block of size %zu at %p allocated by ", loc->heap_chunk_size,
413            reinterpret_cast<void *>(loc->heap_chunk_start));
414     if (loc->tid == kMainGoroutineId)
415       Printf("main goroutine:\n");
416     else
417       Printf("goroutine %d:\n", loc->tid);
418     PrintStack(loc->stack);
419     break;
420   }
421   case ReportLocationGlobal: {
422     Printf("\n");
423     Printf("Global var %s of size %zu at %p declared at %s:%zu\n",
424            loc->global.name, loc->global.size,
425            reinterpret_cast<void *>(loc->global.start), loc->global.file,
426            loc->global.line);
427     break;
428   }
429   default:
430     break;
431   }
432 }
433 
434 static void PrintThread(const ReportThread *rt) {
435   if (rt->id == kMainGoroutineId)
436     return;
437   Printf("\n");
438   Printf("Goroutine %d (%s) created at:\n",
439     rt->id, rt->running ? "running" : "finished");
440   PrintStack(rt->stack);
441 }
442 
443 void PrintReport(const ReportDesc *rep) {
444   Printf("==================\n");
445   if (rep->typ == ReportTypeRace) {
446     Printf("WARNING: DATA RACE");
447     for (uptr i = 0; i < rep->mops.Size(); i++)
448       PrintMop(rep->mops[i], i == 0);
449     for (uptr i = 0; i < rep->locs.Size(); i++)
450       PrintLocation(rep->locs[i]);
451     for (uptr i = 0; i < rep->threads.Size(); i++)
452       PrintThread(rep->threads[i]);
453   } else if (rep->typ == ReportTypeDeadlock) {
454     Printf("WARNING: DEADLOCK\n");
455     for (uptr i = 0; i < rep->mutexes.Size(); i++) {
456       Printf("Goroutine %d lock mutex %u while holding mutex %u:\n", 999,
457              rep->mutexes[i]->id,
458              rep->mutexes[(i + 1) % rep->mutexes.Size()]->id);
459       PrintStack(rep->stacks[2*i]);
460       Printf("\n");
461       Printf("Mutex %u was previously locked here:\n",
462              rep->mutexes[(i + 1) % rep->mutexes.Size()]->id);
463       PrintStack(rep->stacks[2*i + 1]);
464       Printf("\n");
465     }
466   }
467   Printf("==================\n");
468 }
469 
470 #endif
471 
472 }  // namespace __tsan
473