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