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