1 //===-- tsan_rtl_report.cc ------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of ThreadSanitizer (TSan), a race detector.
12 //===----------------------------------------------------------------------===//
14 #include "sanitizer_common/sanitizer_libc.h"
15 #include "sanitizer_common/sanitizer_placement_new.h"
16 #include "sanitizer_common/sanitizer_stackdepot.h"
17 #include "sanitizer_common/sanitizer_common.h"
18 #include "sanitizer_common/sanitizer_stacktrace.h"
19 #include "tsan_platform.h"
21 #include "tsan_suppressions.h"
22 #include "tsan_symbolize.h"
23 #include "tsan_report.h"
24 #include "tsan_sync.h"
25 #include "tsan_mman.h"
26 #include "tsan_flags.h"
31 using namespace __sanitizer; // NOLINT
33 static ReportStack *SymbolizeStack(StackTrace trace);
35 void TsanCheckFailed(const char *file, int line, const char *cond,
37 // There is high probability that interceptors will check-fail as well,
38 // on the other hand there is no sense in processing interceptors
39 // since we are going to die soon.
40 ScopedIgnoreInterceptors ignore;
42 cur_thread()->ignore_sync++;
43 cur_thread()->ignore_reads_and_writes++;
45 Printf("FATAL: ThreadSanitizer CHECK failed: "
46 "%s:%d \"%s\" (0x%zx, 0x%zx)\n",
47 file, line, cond, (uptr)v1, (uptr)v2);
48 PrintCurrentStackSlow(StackTrace::GetCurrentPc());
52 // Can be overriden by an application/test to intercept reports.
53 #ifdef TSAN_EXTERNAL_HOOKS
54 bool OnReport(const ReportDesc *rep, bool suppressed);
56 SANITIZER_WEAK_CXX_DEFAULT_IMPL
57 bool OnReport(const ReportDesc *rep, bool suppressed) {
63 SANITIZER_WEAK_DEFAULT_IMPL
64 void __tsan_on_report(const ReportDesc *rep) {
68 static void StackStripMain(SymbolizedStack *frames) {
69 SymbolizedStack *last_frame = nullptr;
70 SymbolizedStack *last_frame2 = nullptr;
71 for (SymbolizedStack *cur = frames; cur; cur = cur->next) {
72 last_frame2 = last_frame;
79 const char *last = last_frame->info.function;
80 const char *last2 = last_frame2->info.function;
81 // Strip frame above 'main'
82 if (last2 && 0 == internal_strcmp(last2, "main")) {
83 last_frame->ClearAll();
84 last_frame2->next = nullptr;
85 // Strip our internal thread start routine.
86 } else if (last && 0 == internal_strcmp(last, "__tsan_thread_start_func")) {
87 last_frame->ClearAll();
88 last_frame2->next = nullptr;
89 // Strip global ctors init.
90 } else if (last && 0 == internal_strcmp(last, "__do_global_ctors_aux")) {
91 last_frame->ClearAll();
92 last_frame2->next = nullptr;
93 // If both are 0, then we probably just failed to symbolize.
94 } else if (last || last2) {
95 // Ensure that we recovered stack completely. Trimmed stack
96 // can actually happen if we do not instrument some code,
97 // so it's only a debug print. However we must try hard to not miss it
99 DPrintf("Bottom stack frame is missed\n");
102 // The last frame always point into runtime (gosched0, goexit0, runtime.main).
103 last_frame->ClearAll();
104 last_frame2->next = nullptr;
108 ReportStack *SymbolizeStackId(u32 stack_id) {
111 StackTrace stack = StackDepotGet(stack_id);
112 if (stack.trace == nullptr)
114 return SymbolizeStack(stack);
117 static ReportStack *SymbolizeStack(StackTrace trace) {
120 SymbolizedStack *top = nullptr;
121 for (uptr si = 0; si < trace.size; si++) {
122 const uptr pc = trace.trace[si];
124 // We obtain the return address, but we're interested in the previous
126 if ((pc & kExternalPCBit) == 0)
127 pc1 = StackTrace::GetPreviousInstructionPc(pc);
128 SymbolizedStack *ent = SymbolizeCode(pc1);
130 SymbolizedStack *last = ent;
132 last->info.address = pc; // restore original pc for report
135 last->info.address = pc; // restore original pc for report
141 ReportStack *stack = ReportStack::New();
146 ScopedReport::ScopedReport(ReportType typ) {
147 ctx->thread_registry->CheckLocked();
148 void *mem = internal_alloc(MBlockReport, sizeof(ReportDesc));
149 rep_ = new(mem) ReportDesc;
151 ctx->report_mtx.Lock();
152 CommonSanitizerReportMutex.Lock();
155 ScopedReport::~ScopedReport() {
156 CommonSanitizerReportMutex.Unlock();
157 ctx->report_mtx.Unlock();
158 DestroyAndFree(rep_);
161 void ScopedReport::AddStack(StackTrace stack, bool suppressable) {
162 ReportStack **rs = rep_->stacks.PushBack();
163 *rs = SymbolizeStack(stack);
164 (*rs)->suppressable = suppressable;
167 void ScopedReport::AddMemoryAccess(uptr addr, Shadow s, StackTrace stack,
168 const MutexSet *mset) {
169 void *mem = internal_alloc(MBlockReportMop, sizeof(ReportMop));
170 ReportMop *mop = new(mem) ReportMop;
171 rep_->mops.PushBack(mop);
173 mop->addr = addr + s.addr0();
174 mop->size = s.size();
175 mop->write = s.IsWrite();
176 mop->atomic = s.IsAtomic();
177 mop->stack = SymbolizeStack(stack);
179 mop->stack->suppressable = true;
180 for (uptr i = 0; i < mset->Size(); i++) {
181 MutexSet::Desc d = mset->Get(i);
182 u64 mid = this->AddMutex(d.id);
183 ReportMopMutex mtx = {mid, d.write};
184 mop->mset.PushBack(mtx);
188 void ScopedReport::AddUniqueTid(int unique_tid) {
189 rep_->unique_tids.PushBack(unique_tid);
192 void ScopedReport::AddThread(const ThreadContext *tctx, bool suppressable) {
193 for (uptr i = 0; i < rep_->threads.Size(); i++) {
194 if ((u32)rep_->threads[i]->id == tctx->tid)
197 void *mem = internal_alloc(MBlockReportThread, sizeof(ReportThread));
198 ReportThread *rt = new(mem) ReportThread;
199 rep_->threads.PushBack(rt);
201 rt->os_id = tctx->os_id;
202 rt->running = (tctx->status == ThreadStatusRunning);
203 rt->name = internal_strdup(tctx->name);
204 rt->parent_tid = tctx->parent_tid;
206 rt->stack = SymbolizeStackId(tctx->creation_stack_id);
208 rt->stack->suppressable = suppressable;
212 static bool FindThreadByUidLockedCallback(ThreadContextBase *tctx, void *arg) {
213 int unique_id = *(int *)arg;
214 return tctx->unique_id == (u32)unique_id;
217 static ThreadContext *FindThreadByUidLocked(int unique_id) {
218 ctx->thread_registry->CheckLocked();
219 return static_cast<ThreadContext *>(
220 ctx->thread_registry->FindThreadContextLocked(
221 FindThreadByUidLockedCallback, &unique_id));
224 static ThreadContext *FindThreadByTidLocked(int tid) {
225 ctx->thread_registry->CheckLocked();
226 return static_cast<ThreadContext*>(
227 ctx->thread_registry->GetThreadLocked(tid));
230 static bool IsInStackOrTls(ThreadContextBase *tctx_base, void *arg) {
231 uptr addr = (uptr)arg;
232 ThreadContext *tctx = static_cast<ThreadContext*>(tctx_base);
233 if (tctx->status != ThreadStatusRunning)
235 ThreadState *thr = tctx->thr;
237 return ((addr >= thr->stk_addr && addr < thr->stk_addr + thr->stk_size) ||
238 (addr >= thr->tls_addr && addr < thr->tls_addr + thr->tls_size));
241 ThreadContext *IsThreadStackOrTls(uptr addr, bool *is_stack) {
242 ctx->thread_registry->CheckLocked();
243 ThreadContext *tctx = static_cast<ThreadContext*>(
244 ctx->thread_registry->FindThreadContextLocked(IsInStackOrTls,
248 ThreadState *thr = tctx->thr;
250 *is_stack = (addr >= thr->stk_addr && addr < thr->stk_addr + thr->stk_size);
255 void ScopedReport::AddThread(int unique_tid, bool suppressable) {
257 if (const ThreadContext *tctx = FindThreadByUidLocked(unique_tid))
258 AddThread(tctx, suppressable);
262 void ScopedReport::AddMutex(const SyncVar *s) {
263 for (uptr i = 0; i < rep_->mutexes.Size(); i++) {
264 if (rep_->mutexes[i]->id == s->uid)
267 void *mem = internal_alloc(MBlockReportMutex, sizeof(ReportMutex));
268 ReportMutex *rm = new(mem) ReportMutex;
269 rep_->mutexes.PushBack(rm);
272 rm->destroyed = false;
273 rm->stack = SymbolizeStackId(s->creation_stack_id);
276 u64 ScopedReport::AddMutex(u64 id) {
279 uptr addr = SyncVar::SplitId(id, &uid);
280 SyncVar *s = ctx->metamap.GetIfExistsAndLock(addr, true);
281 // Check that the mutex is still alive.
282 // Another mutex can be created at the same address,
283 // so check uid as well.
284 if (s && s->CheckId(uid)) {
295 void ScopedReport::AddDeadMutex(u64 id) {
296 for (uptr i = 0; i < rep_->mutexes.Size(); i++) {
297 if (rep_->mutexes[i]->id == id)
300 void *mem = internal_alloc(MBlockReportMutex, sizeof(ReportMutex));
301 ReportMutex *rm = new(mem) ReportMutex;
302 rep_->mutexes.PushBack(rm);
305 rm->destroyed = true;
309 void ScopedReport::AddLocation(uptr addr, uptr size) {
316 if (FdLocation(addr, &fd, &creat_tid, &creat_stack)) {
317 ReportLocation *loc = ReportLocation::New(ReportLocationFD);
319 loc->tid = creat_tid;
320 loc->stack = SymbolizeStackId(creat_stack);
321 rep_->locs.PushBack(loc);
322 ThreadContext *tctx = FindThreadByUidLocked(creat_tid);
328 Allocator *a = allocator();
329 if (a->PointerIsMine((void*)addr)) {
330 void *block_begin = a->GetBlockBegin((void*)addr);
332 b = ctx->metamap.GetBlock((uptr)block_begin);
335 ThreadContext *tctx = FindThreadByTidLocked(b->tid);
336 ReportLocation *loc = ReportLocation::New(ReportLocationHeap);
337 loc->heap_chunk_start = (uptr)allocator()->GetBlockBegin((void *)addr);
338 loc->heap_chunk_size = b->siz;
339 loc->tid = tctx ? tctx->tid : b->tid;
340 loc->stack = SymbolizeStackId(b->stk);
341 rep_->locs.PushBack(loc);
346 bool is_stack = false;
347 if (ThreadContext *tctx = IsThreadStackOrTls(addr, &is_stack)) {
348 ReportLocation *loc =
349 ReportLocation::New(is_stack ? ReportLocationStack : ReportLocationTLS);
350 loc->tid = tctx->tid;
351 rep_->locs.PushBack(loc);
355 if (ReportLocation *loc = SymbolizeData(addr)) {
356 loc->suppressable = true;
357 rep_->locs.PushBack(loc);
363 void ScopedReport::AddSleep(u32 stack_id) {
364 rep_->sleep = SymbolizeStackId(stack_id);
368 void ScopedReport::SetCount(int count) {
372 const ReportDesc *ScopedReport::GetReport() const {
376 void RestoreStack(int tid, const u64 epoch, VarSizeStackTrace *stk,
378 // This function restores stack trace and mutex set for the thread/epoch.
379 // It does so by getting stack trace and mutex set at the beginning of
380 // trace part, and then replaying the trace till the given epoch.
381 Trace* trace = ThreadTrace(tid);
382 ReadLock l(&trace->mtx);
383 const int partidx = (epoch / kTracePartSize) % TraceParts();
384 TraceHeader* hdr = &trace->headers[partidx];
385 if (epoch < hdr->epoch0 || epoch >= hdr->epoch0 + kTracePartSize)
387 CHECK_EQ(RoundDown(epoch, kTracePartSize), hdr->epoch0);
388 const u64 epoch0 = RoundDown(epoch, TraceSize());
389 const u64 eend = epoch % TraceSize();
390 const u64 ebegin = RoundDown(eend, kTracePartSize);
391 DPrintf("#%d: RestoreStack epoch=%zu ebegin=%zu eend=%zu partidx=%d\n",
392 tid, (uptr)epoch, (uptr)ebegin, (uptr)eend, partidx);
393 Vector<uptr> stack(MBlockReportStack);
394 stack.Resize(hdr->stack0.size + 64);
395 for (uptr i = 0; i < hdr->stack0.size; i++) {
396 stack[i] = hdr->stack0.trace[i];
397 DPrintf2(" #%02zu: pc=%zx\n", i, stack[i]);
401 uptr pos = hdr->stack0.size;
402 Event *events = (Event*)GetThreadTrace(tid);
403 for (uptr i = ebegin; i <= eend; i++) {
404 Event ev = events[i];
405 EventType typ = (EventType)(ev >> 61);
406 uptr pc = (uptr)(ev & ((1ull << 61) - 1));
407 DPrintf2(" %zu typ=%d pc=%zx\n", i, typ, pc);
408 if (typ == EventTypeMop) {
410 } else if (typ == EventTypeFuncEnter) {
411 if (stack.Size() < pos + 2)
412 stack.Resize(pos + 2);
414 } else if (typ == EventTypeFuncExit) {
419 if (typ == EventTypeLock) {
420 mset->Add(pc, true, epoch0 + i);
421 } else if (typ == EventTypeUnlock) {
423 } else if (typ == EventTypeRLock) {
424 mset->Add(pc, false, epoch0 + i);
425 } else if (typ == EventTypeRUnlock) {
426 mset->Del(pc, false);
429 for (uptr j = 0; j <= pos; j++)
430 DPrintf2(" #%zu: %zx\n", j, stack[j]);
432 if (pos == 0 && stack[0] == 0)
435 stk->Init(&stack[0], pos);
438 static bool HandleRacyStacks(ThreadState *thr, VarSizeStackTrace traces[2],
439 uptr addr_min, uptr addr_max) {
440 bool equal_stack = false;
442 bool equal_address = false;
443 RacyAddress ra0 = {addr_min, addr_max};
445 ReadLock lock(&ctx->racy_mtx);
446 if (flags()->suppress_equal_stacks) {
447 hash.hash[0] = md5_hash(traces[0].trace, traces[0].size * sizeof(uptr));
448 hash.hash[1] = md5_hash(traces[1].trace, traces[1].size * sizeof(uptr));
449 for (uptr i = 0; i < ctx->racy_stacks.Size(); i++) {
450 if (hash == ctx->racy_stacks[i]) {
452 "ThreadSanitizer: suppressing report as doubled (stack)\n");
458 if (flags()->suppress_equal_addresses) {
459 for (uptr i = 0; i < ctx->racy_addresses.Size(); i++) {
460 RacyAddress ra2 = ctx->racy_addresses[i];
461 uptr maxbeg = max(ra0.addr_min, ra2.addr_min);
462 uptr minend = min(ra0.addr_max, ra2.addr_max);
463 if (maxbeg < minend) {
464 VPrintf(2, "ThreadSanitizer: suppressing report as doubled (addr)\n");
465 equal_address = true;
471 if (!equal_stack && !equal_address)
474 Lock lock(&ctx->racy_mtx);
475 ctx->racy_stacks.PushBack(hash);
477 if (!equal_address) {
478 Lock lock(&ctx->racy_mtx);
479 ctx->racy_addresses.PushBack(ra0);
484 static void AddRacyStacks(ThreadState *thr, VarSizeStackTrace traces[2],
485 uptr addr_min, uptr addr_max) {
486 Lock lock(&ctx->racy_mtx);
487 if (flags()->suppress_equal_stacks) {
489 hash.hash[0] = md5_hash(traces[0].trace, traces[0].size * sizeof(uptr));
490 hash.hash[1] = md5_hash(traces[1].trace, traces[1].size * sizeof(uptr));
491 ctx->racy_stacks.PushBack(hash);
493 if (flags()->suppress_equal_addresses) {
494 RacyAddress ra0 = {addr_min, addr_max};
495 ctx->racy_addresses.PushBack(ra0);
499 bool OutputReport(ThreadState *thr, const ScopedReport &srep) {
500 if (!flags()->report_bugs)
502 atomic_store_relaxed(&ctx->last_symbolize_time_ns, NanoTime());
503 const ReportDesc *rep = srep.GetReport();
504 CHECK_EQ(thr->current_report, nullptr);
505 thr->current_report = rep;
506 Suppression *supp = 0;
508 for (uptr i = 0; pc_or_addr == 0 && i < rep->mops.Size(); i++)
509 pc_or_addr = IsSuppressed(rep->typ, rep->mops[i]->stack, &supp);
510 for (uptr i = 0; pc_or_addr == 0 && i < rep->stacks.Size(); i++)
511 pc_or_addr = IsSuppressed(rep->typ, rep->stacks[i], &supp);
512 for (uptr i = 0; pc_or_addr == 0 && i < rep->threads.Size(); i++)
513 pc_or_addr = IsSuppressed(rep->typ, rep->threads[i]->stack, &supp);
514 for (uptr i = 0; pc_or_addr == 0 && i < rep->locs.Size(); i++)
515 pc_or_addr = IsSuppressed(rep->typ, rep->locs[i], &supp);
516 if (pc_or_addr != 0) {
517 Lock lock(&ctx->fired_suppressions_mtx);
518 FiredSuppression s = {srep.GetReport()->typ, pc_or_addr, supp};
519 ctx->fired_suppressions.push_back(s);
522 bool old_is_freeing = thr->is_freeing;
523 thr->is_freeing = false;
524 bool suppressed = OnReport(rep, pc_or_addr != 0);
525 thr->is_freeing = old_is_freeing;
527 thr->current_report = nullptr;
532 __tsan_on_report(rep);
534 if (flags()->halt_on_error)
536 thr->current_report = nullptr;
540 bool IsFiredSuppression(Context *ctx, ReportType type, StackTrace trace) {
541 ReadLock lock(&ctx->fired_suppressions_mtx);
542 for (uptr k = 0; k < ctx->fired_suppressions.size(); k++) {
543 if (ctx->fired_suppressions[k].type != type)
545 for (uptr j = 0; j < trace.size; j++) {
546 FiredSuppression *s = &ctx->fired_suppressions[k];
547 if (trace.trace[j] == s->pc_or_addr) {
549 atomic_fetch_add(&s->supp->hit_count, 1, memory_order_relaxed);
557 static bool IsFiredSuppression(Context *ctx, ReportType type, uptr addr) {
558 ReadLock lock(&ctx->fired_suppressions_mtx);
559 for (uptr k = 0; k < ctx->fired_suppressions.size(); k++) {
560 if (ctx->fired_suppressions[k].type != type)
562 FiredSuppression *s = &ctx->fired_suppressions[k];
563 if (addr == s->pc_or_addr) {
565 atomic_fetch_add(&s->supp->hit_count, 1, memory_order_relaxed);
572 static bool RaceBetweenAtomicAndFree(ThreadState *thr) {
573 Shadow s0(thr->racy_state[0]);
574 Shadow s1(thr->racy_state[1]);
575 CHECK(!(s0.IsAtomic() && s1.IsAtomic()));
576 if (!s0.IsAtomic() && !s1.IsAtomic())
578 if (s0.IsAtomic() && s1.IsFreed())
580 if (s1.IsAtomic() && thr->is_freeing)
585 void ReportRace(ThreadState *thr) {
588 // Symbolizer makes lots of intercepted calls. If we try to process them,
589 // at best it will cause deadlocks on internal mutexes.
590 ScopedIgnoreInterceptors ignore;
592 if (!flags()->report_bugs)
594 if (!flags()->report_atomic_races && !RaceBetweenAtomicAndFree(thr))
599 Shadow s(thr->racy_state[1]);
600 freed = s.GetFreedAndReset();
601 thr->racy_state[1] = s.raw();
604 uptr addr = ShadowToMem((uptr)thr->racy_shadow_addr);
608 uptr a0 = addr + Shadow(thr->racy_state[0]).addr0();
609 uptr a1 = addr + Shadow(thr->racy_state[1]).addr0();
610 uptr e0 = a0 + Shadow(thr->racy_state[0]).size();
611 uptr e1 = a1 + Shadow(thr->racy_state[1]).size();
612 addr_min = min(a0, a1);
613 addr_max = max(e0, e1);
614 if (IsExpectedReport(addr_min, addr_max - addr_min))
618 ReportType typ = ReportTypeRace;
619 if (thr->is_vptr_access && freed)
620 typ = ReportTypeVptrUseAfterFree;
621 else if (thr->is_vptr_access)
622 typ = ReportTypeVptrRace;
624 typ = ReportTypeUseAfterFree;
626 if (IsFiredSuppression(ctx, typ, addr))
630 VarSizeStackTrace traces[kMop];
631 const uptr toppc = TraceTopPC(thr);
632 ObtainCurrentStack(thr, toppc, &traces[0]);
633 if (IsFiredSuppression(ctx, typ, traces[0]))
636 // MutexSet is too large to live on stack.
637 Vector<u64> mset_buffer(MBlockScopedBuf);
638 mset_buffer.Resize(sizeof(MutexSet) / sizeof(u64) + 1);
639 MutexSet *mset2 = new(&mset_buffer[0]) MutexSet();
641 Shadow s2(thr->racy_state[1]);
642 RestoreStack(s2.tid(), s2.epoch(), &traces[1], mset2);
643 if (IsFiredSuppression(ctx, typ, traces[1]))
646 if (HandleRacyStacks(thr, traces, addr_min, addr_max))
649 ThreadRegistryLock l0(ctx->thread_registry);
650 ScopedReport rep(typ);
651 for (uptr i = 0; i < kMop; i++) {
652 Shadow s(thr->racy_state[i]);
653 rep.AddMemoryAccess(addr, s, traces[i], i == 0 ? &thr->mset : mset2);
656 for (uptr i = 0; i < kMop; i++) {
657 FastState s(thr->racy_state[i]);
658 ThreadContext *tctx = static_cast<ThreadContext*>(
659 ctx->thread_registry->GetThreadLocked(s.tid()));
660 if (s.epoch() < tctx->epoch0 || s.epoch() > tctx->epoch1)
665 rep.AddLocation(addr_min, addr_max - addr_min);
669 Shadow s(thr->racy_state[1]);
670 if (s.epoch() <= thr->last_sleep_clock.get(s.tid()))
671 rep.AddSleep(thr->last_sleep_stack_id);
675 if (!OutputReport(thr, rep))
678 AddRacyStacks(thr, traces, addr_min, addr_max);
681 void PrintCurrentStack(ThreadState *thr, uptr pc) {
682 VarSizeStackTrace trace;
683 ObtainCurrentStack(thr, pc, &trace);
684 PrintStack(SymbolizeStack(trace));
687 // Always inlining PrintCurrentStackSlow, because LocatePcInTrace assumes
688 // __sanitizer_print_stack_trace exists in the actual unwinded stack, but
689 // tail-call to PrintCurrentStackSlow breaks this assumption because
690 // __sanitizer_print_stack_trace disappears after tail-call.
691 // However, this solution is not reliable enough, please see dvyukov's comment
692 // http://reviews.llvm.org/D19148#406208
693 // Also see PR27280 comment 2 and 3 for breaking examples and analysis.
695 void PrintCurrentStackSlow(uptr pc) {
697 BufferedStackTrace *ptrace =
698 new(internal_alloc(MBlockStackTrace, sizeof(BufferedStackTrace)))
699 BufferedStackTrace();
700 ptrace->Unwind(kStackTraceMax, pc, 0, 0, 0, 0, false);
701 for (uptr i = 0; i < ptrace->size / 2; i++) {
702 uptr tmp = ptrace->trace_buffer[i];
703 ptrace->trace_buffer[i] = ptrace->trace_buffer[ptrace->size - i - 1];
704 ptrace->trace_buffer[ptrace->size - i - 1] = tmp;
706 PrintStack(SymbolizeStack(*ptrace));
710 } // namespace __tsan
712 using namespace __tsan;
715 SANITIZER_INTERFACE_ATTRIBUTE
716 void __sanitizer_print_stack_trace() {
717 PrintCurrentStackSlow(StackTrace::GetCurrentPc());