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