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