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