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;
41 Printf("FATAL: ThreadSanitizer CHECK failed: "
42 "%s:%d \"%s\" (0x%zx, 0x%zx)\n",
43 file, line, cond, (uptr)v1, (uptr)v2);
44 PrintCurrentStackSlow(StackTrace::GetCurrentPc());
48 // Can be overriden by an application/test to intercept reports.
49 #ifdef TSAN_EXTERNAL_HOOKS
50 bool OnReport(const ReportDesc *rep, bool suppressed);
52 SANITIZER_INTERFACE_ATTRIBUTE
53 bool WEAK OnReport(const ReportDesc *rep, bool suppressed) {
59 static void StackStripMain(SymbolizedStack *frames) {
60 SymbolizedStack *last_frame = nullptr;
61 SymbolizedStack *last_frame2 = nullptr;
62 for (SymbolizedStack *cur = frames; cur; cur = cur->next) {
63 last_frame2 = last_frame;
70 const char *last = last_frame->info.function;
71 const char *last2 = last_frame2->info.function;
72 // Strip frame above 'main'
73 if (last2 && 0 == internal_strcmp(last2, "main")) {
74 last_frame->ClearAll();
75 last_frame2->next = nullptr;
76 // Strip our internal thread start routine.
77 } else if (last && 0 == internal_strcmp(last, "__tsan_thread_start_func")) {
78 last_frame->ClearAll();
79 last_frame2->next = nullptr;
80 // Strip global ctors init.
81 } else if (last && 0 == internal_strcmp(last, "__do_global_ctors_aux")) {
82 last_frame->ClearAll();
83 last_frame2->next = nullptr;
84 // If both are 0, then we probably just failed to symbolize.
85 } else if (last || last2) {
86 // Ensure that we recovered stack completely. Trimmed stack
87 // can actually happen if we do not instrument some code,
88 // so it's only a debug print. However we must try hard to not miss it
90 DPrintf("Bottom stack frame is missed\n");
93 // The last frame always point into runtime (gosched0, goexit0, runtime.main).
94 last_frame->ClearAll();
95 last_frame2->next = nullptr;
99 ReportStack *SymbolizeStackId(u32 stack_id) {
102 StackTrace stack = StackDepotGet(stack_id);
103 if (stack.trace == nullptr)
105 return SymbolizeStack(stack);
108 static ReportStack *SymbolizeStack(StackTrace trace) {
111 SymbolizedStack *top = nullptr;
112 for (uptr si = 0; si < trace.size; si++) {
113 const uptr pc = trace.trace[si];
115 // We obtain the return address, but we're interested in the previous
117 if ((pc & kExternalPCBit) == 0)
118 pc1 = StackTrace::GetPreviousInstructionPc(pc);
119 SymbolizedStack *ent = SymbolizeCode(pc1);
121 SymbolizedStack *last = ent;
123 last->info.address = pc; // restore original pc for report
126 last->info.address = pc; // restore original pc for report
132 ReportStack *stack = ReportStack::New();
137 ScopedReport::ScopedReport(ReportType typ) {
138 ctx->thread_registry->CheckLocked();
139 void *mem = internal_alloc(MBlockReport, sizeof(ReportDesc));
140 rep_ = new(mem) ReportDesc;
142 ctx->report_mtx.Lock();
143 CommonSanitizerReportMutex.Lock();
146 ScopedReport::~ScopedReport() {
147 CommonSanitizerReportMutex.Unlock();
148 ctx->report_mtx.Unlock();
149 DestroyAndFree(rep_);
152 void ScopedReport::AddStack(StackTrace stack, bool suppressable) {
153 ReportStack **rs = rep_->stacks.PushBack();
154 *rs = SymbolizeStack(stack);
155 (*rs)->suppressable = suppressable;
158 void ScopedReport::AddMemoryAccess(uptr addr, Shadow s, StackTrace stack,
159 const MutexSet *mset) {
160 void *mem = internal_alloc(MBlockReportMop, sizeof(ReportMop));
161 ReportMop *mop = new(mem) ReportMop;
162 rep_->mops.PushBack(mop);
164 mop->addr = addr + s.addr0();
165 mop->size = s.size();
166 mop->write = s.IsWrite();
167 mop->atomic = s.IsAtomic();
168 mop->stack = SymbolizeStack(stack);
170 mop->stack->suppressable = true;
171 for (uptr i = 0; i < mset->Size(); i++) {
172 MutexSet::Desc d = mset->Get(i);
173 u64 mid = this->AddMutex(d.id);
174 ReportMopMutex mtx = {mid, d.write};
175 mop->mset.PushBack(mtx);
179 void ScopedReport::AddUniqueTid(int unique_tid) {
180 rep_->unique_tids.PushBack(unique_tid);
183 void ScopedReport::AddThread(const ThreadContext *tctx, bool suppressable) {
184 for (uptr i = 0; i < rep_->threads.Size(); i++) {
185 if ((u32)rep_->threads[i]->id == tctx->tid)
188 void *mem = internal_alloc(MBlockReportThread, sizeof(ReportThread));
189 ReportThread *rt = new(mem) ReportThread();
190 rep_->threads.PushBack(rt);
192 rt->pid = tctx->os_id;
193 rt->running = (tctx->status == ThreadStatusRunning);
194 rt->name = internal_strdup(tctx->name);
195 rt->parent_tid = tctx->parent_tid;
197 rt->stack = SymbolizeStackId(tctx->creation_stack_id);
199 rt->stack->suppressable = suppressable;
203 static ThreadContext *FindThreadByUidLocked(int unique_id) {
204 ctx->thread_registry->CheckLocked();
205 for (unsigned i = 0; i < kMaxTid; i++) {
206 ThreadContext *tctx = static_cast<ThreadContext*>(
207 ctx->thread_registry->GetThreadLocked(i));
208 if (tctx && tctx->unique_id == (u32)unique_id) {
215 static ThreadContext *FindThreadByTidLocked(int tid) {
216 ctx->thread_registry->CheckLocked();
217 return static_cast<ThreadContext*>(
218 ctx->thread_registry->GetThreadLocked(tid));
221 static bool IsInStackOrTls(ThreadContextBase *tctx_base, void *arg) {
222 uptr addr = (uptr)arg;
223 ThreadContext *tctx = static_cast<ThreadContext*>(tctx_base);
224 if (tctx->status != ThreadStatusRunning)
226 ThreadState *thr = tctx->thr;
228 return ((addr >= thr->stk_addr && addr < thr->stk_addr + thr->stk_size) ||
229 (addr >= thr->tls_addr && addr < thr->tls_addr + thr->tls_size));
232 ThreadContext *IsThreadStackOrTls(uptr addr, bool *is_stack) {
233 ctx->thread_registry->CheckLocked();
234 ThreadContext *tctx = static_cast<ThreadContext*>(
235 ctx->thread_registry->FindThreadContextLocked(IsInStackOrTls,
239 ThreadState *thr = tctx->thr;
241 *is_stack = (addr >= thr->stk_addr && addr < thr->stk_addr + thr->stk_size);
246 void ScopedReport::AddThread(int unique_tid, bool suppressable) {
248 if (const ThreadContext *tctx = FindThreadByUidLocked(unique_tid))
249 AddThread(tctx, suppressable);
253 void ScopedReport::AddMutex(const SyncVar *s) {
254 for (uptr i = 0; i < rep_->mutexes.Size(); i++) {
255 if (rep_->mutexes[i]->id == s->uid)
258 void *mem = internal_alloc(MBlockReportMutex, sizeof(ReportMutex));
259 ReportMutex *rm = new(mem) ReportMutex();
260 rep_->mutexes.PushBack(rm);
263 rm->destroyed = false;
264 rm->stack = SymbolizeStackId(s->creation_stack_id);
267 u64 ScopedReport::AddMutex(u64 id) {
270 uptr addr = SyncVar::SplitId(id, &uid);
271 SyncVar *s = ctx->metamap.GetIfExistsAndLock(addr);
272 // Check that the mutex is still alive.
273 // Another mutex can be created at the same address,
274 // so check uid as well.
275 if (s && s->CheckId(uid)) {
286 void ScopedReport::AddDeadMutex(u64 id) {
287 for (uptr i = 0; i < rep_->mutexes.Size(); i++) {
288 if (rep_->mutexes[i]->id == id)
291 void *mem = internal_alloc(MBlockReportMutex, sizeof(ReportMutex));
292 ReportMutex *rm = new(mem) ReportMutex();
293 rep_->mutexes.PushBack(rm);
296 rm->destroyed = true;
300 void ScopedReport::AddLocation(uptr addr, uptr size) {
307 if (FdLocation(addr, &fd, &creat_tid, &creat_stack)) {
308 ReportLocation *loc = ReportLocation::New(ReportLocationFD);
310 loc->tid = creat_tid;
311 loc->stack = SymbolizeStackId(creat_stack);
312 rep_->locs.PushBack(loc);
313 ThreadContext *tctx = FindThreadByUidLocked(creat_tid);
319 Allocator *a = allocator();
320 if (a->PointerIsMine((void*)addr)) {
321 void *block_begin = a->GetBlockBegin((void*)addr);
323 b = ctx->metamap.GetBlock((uptr)block_begin);
326 ThreadContext *tctx = FindThreadByTidLocked(b->tid);
327 ReportLocation *loc = ReportLocation::New(ReportLocationHeap);
328 loc->heap_chunk_start = (uptr)allocator()->GetBlockBegin((void *)addr);
329 loc->heap_chunk_size = b->siz;
330 loc->tid = tctx ? tctx->tid : b->tid;
331 loc->stack = SymbolizeStackId(b->stk);
332 rep_->locs.PushBack(loc);
337 bool is_stack = false;
338 if (ThreadContext *tctx = IsThreadStackOrTls(addr, &is_stack)) {
339 ReportLocation *loc =
340 ReportLocation::New(is_stack ? ReportLocationStack : ReportLocationTLS);
341 loc->tid = tctx->tid;
342 rep_->locs.PushBack(loc);
345 if (ReportLocation *loc = SymbolizeData(addr)) {
346 loc->suppressable = true;
347 rep_->locs.PushBack(loc);
354 void ScopedReport::AddSleep(u32 stack_id) {
355 rep_->sleep = SymbolizeStackId(stack_id);
359 void ScopedReport::SetCount(int count) {
363 const ReportDesc *ScopedReport::GetReport() const {
367 void RestoreStack(int tid, const u64 epoch, VarSizeStackTrace *stk,
369 // This function restores stack trace and mutex set for the thread/epoch.
370 // It does so by getting stack trace and mutex set at the beginning of
371 // trace part, and then replaying the trace till the given epoch.
372 ctx->thread_registry->CheckLocked();
373 ThreadContext *tctx = static_cast<ThreadContext*>(
374 ctx->thread_registry->GetThreadLocked(tid));
377 if (tctx->status != ThreadStatusRunning
378 && tctx->status != ThreadStatusFinished
379 && tctx->status != ThreadStatusDead)
381 Trace* trace = ThreadTrace(tctx->tid);
383 const int partidx = (epoch / kTracePartSize) % TraceParts();
384 TraceHeader* hdr = &trace->headers[partidx];
385 if (epoch < hdr->epoch0)
387 const u64 epoch0 = RoundDown(epoch, TraceSize());
388 const u64 eend = epoch % TraceSize();
389 const u64 ebegin = RoundDown(eend, kTracePartSize);
390 DPrintf("#%d: RestoreStack epoch=%zu ebegin=%zu eend=%zu partidx=%d\n",
391 tid, (uptr)epoch, (uptr)ebegin, (uptr)eend, partidx);
392 InternalScopedBuffer<uptr> stack(kShadowStackSize);
393 for (uptr i = 0; i < hdr->stack0.size; i++) {
394 stack[i] = hdr->stack0.trace[i];
395 DPrintf2(" #%02zu: pc=%zx\n", i, stack[i]);
399 uptr pos = hdr->stack0.size;
400 Event *events = (Event*)GetThreadTrace(tid);
401 for (uptr i = ebegin; i <= eend; i++) {
402 Event ev = events[i];
403 EventType typ = (EventType)(ev >> 61);
404 uptr pc = (uptr)(ev & ((1ull << 61) - 1));
405 DPrintf2(" %zu typ=%d pc=%zx\n", i, typ, pc);
406 if (typ == EventTypeMop) {
408 } else if (typ == EventTypeFuncEnter) {
410 } else if (typ == EventTypeFuncExit) {
415 if (typ == EventTypeLock) {
416 mset->Add(pc, true, epoch0 + i);
417 } else if (typ == EventTypeUnlock) {
419 } else if (typ == EventTypeRLock) {
420 mset->Add(pc, false, epoch0 + i);
421 } else if (typ == EventTypeRUnlock) {
422 mset->Del(pc, false);
425 for (uptr j = 0; j <= pos; j++)
426 DPrintf2(" #%zu: %zx\n", j, stack[j]);
428 if (pos == 0 && stack[0] == 0)
431 stk->Init(stack.data(), pos);
434 static bool HandleRacyStacks(ThreadState *thr, VarSizeStackTrace traces[2],
435 uptr addr_min, uptr addr_max) {
436 bool equal_stack = false;
438 if (flags()->suppress_equal_stacks) {
439 hash.hash[0] = md5_hash(traces[0].trace, traces[0].size * sizeof(uptr));
440 hash.hash[1] = md5_hash(traces[1].trace, traces[1].size * sizeof(uptr));
441 for (uptr i = 0; i < ctx->racy_stacks.Size(); i++) {
442 if (hash == ctx->racy_stacks[i]) {
443 DPrintf("ThreadSanitizer: suppressing report as doubled (stack)\n");
449 bool equal_address = false;
450 RacyAddress ra0 = {addr_min, addr_max};
451 if (flags()->suppress_equal_addresses) {
452 for (uptr i = 0; i < ctx->racy_addresses.Size(); i++) {
453 RacyAddress ra2 = ctx->racy_addresses[i];
454 uptr maxbeg = max(ra0.addr_min, ra2.addr_min);
455 uptr minend = min(ra0.addr_max, ra2.addr_max);
456 if (maxbeg < minend) {
457 DPrintf("ThreadSanitizer: suppressing report as doubled (addr)\n");
458 equal_address = true;
463 if (equal_stack || equal_address) {
465 ctx->racy_stacks.PushBack(hash);
467 ctx->racy_addresses.PushBack(ra0);
473 static void AddRacyStacks(ThreadState *thr, VarSizeStackTrace traces[2],
474 uptr addr_min, uptr addr_max) {
475 if (flags()->suppress_equal_stacks) {
477 hash.hash[0] = md5_hash(traces[0].trace, traces[0].size * sizeof(uptr));
478 hash.hash[1] = md5_hash(traces[1].trace, traces[1].size * sizeof(uptr));
479 ctx->racy_stacks.PushBack(hash);
481 if (flags()->suppress_equal_addresses) {
482 RacyAddress ra0 = {addr_min, addr_max};
483 ctx->racy_addresses.PushBack(ra0);
487 bool OutputReport(ThreadState *thr, const ScopedReport &srep) {
488 atomic_store(&ctx->last_symbolize_time_ns, NanoTime(), memory_order_relaxed);
489 const ReportDesc *rep = srep.GetReport();
490 Suppression *supp = 0;
491 uptr suppress_pc = 0;
492 for (uptr i = 0; suppress_pc == 0 && i < rep->mops.Size(); i++)
493 suppress_pc = IsSuppressed(rep->typ, rep->mops[i]->stack, &supp);
494 for (uptr i = 0; suppress_pc == 0 && i < rep->stacks.Size(); i++)
495 suppress_pc = IsSuppressed(rep->typ, rep->stacks[i], &supp);
496 for (uptr i = 0; suppress_pc == 0 && i < rep->threads.Size(); i++)
497 suppress_pc = IsSuppressed(rep->typ, rep->threads[i]->stack, &supp);
498 for (uptr i = 0; suppress_pc == 0 && i < rep->locs.Size(); i++)
499 suppress_pc = IsSuppressed(rep->typ, rep->locs[i], &supp);
500 if (suppress_pc != 0) {
501 FiredSuppression s = {srep.GetReport()->typ, suppress_pc, supp};
502 ctx->fired_suppressions.push_back(s);
505 bool old_is_freeing = thr->is_freeing;
506 thr->is_freeing = false;
507 bool suppressed = OnReport(rep, suppress_pc != 0);
508 thr->is_freeing = old_is_freeing;
514 if (flags()->halt_on_error)
515 internal__exit(flags()->exitcode);
519 bool IsFiredSuppression(Context *ctx, const ScopedReport &srep,
521 for (uptr k = 0; k < ctx->fired_suppressions.size(); k++) {
522 if (ctx->fired_suppressions[k].type != srep.GetReport()->typ)
524 for (uptr j = 0; j < trace.size; j++) {
525 FiredSuppression *s = &ctx->fired_suppressions[k];
526 if (trace.trace[j] == s->pc) {
528 s->supp->hit_count++;
536 static bool IsFiredSuppression(Context *ctx,
537 const ScopedReport &srep,
539 for (uptr k = 0; k < ctx->fired_suppressions.size(); k++) {
540 if (ctx->fired_suppressions[k].type != srep.GetReport()->typ)
542 FiredSuppression *s = &ctx->fired_suppressions[k];
545 s->supp->hit_count++;
552 static bool RaceBetweenAtomicAndFree(ThreadState *thr) {
553 Shadow s0(thr->racy_state[0]);
554 Shadow s1(thr->racy_state[1]);
555 CHECK(!(s0.IsAtomic() && s1.IsAtomic()));
556 if (!s0.IsAtomic() && !s1.IsAtomic())
558 if (s0.IsAtomic() && s1.IsFreed())
560 if (s1.IsAtomic() && thr->is_freeing)
565 void ReportRace(ThreadState *thr) {
568 // Symbolizer makes lots of intercepted calls. If we try to process them,
569 // at best it will cause deadlocks on internal mutexes.
570 ScopedIgnoreInterceptors ignore;
572 if (!flags()->report_bugs)
574 if (!flags()->report_atomic_races && !RaceBetweenAtomicAndFree(thr))
579 Shadow s(thr->racy_state[1]);
580 freed = s.GetFreedAndReset();
581 thr->racy_state[1] = s.raw();
584 uptr addr = ShadowToMem((uptr)thr->racy_shadow_addr);
588 uptr a0 = addr + Shadow(thr->racy_state[0]).addr0();
589 uptr a1 = addr + Shadow(thr->racy_state[1]).addr0();
590 uptr e0 = a0 + Shadow(thr->racy_state[0]).size();
591 uptr e1 = a1 + Shadow(thr->racy_state[1]).size();
592 addr_min = min(a0, a1);
593 addr_max = max(e0, e1);
594 if (IsExpectedReport(addr_min, addr_max - addr_min))
598 ThreadRegistryLock l0(ctx->thread_registry);
600 ReportType typ = ReportTypeRace;
601 if (thr->is_vptr_access && freed)
602 typ = ReportTypeVptrUseAfterFree;
603 else if (thr->is_vptr_access)
604 typ = ReportTypeVptrRace;
606 typ = ReportTypeUseAfterFree;
607 ScopedReport rep(typ);
608 if (IsFiredSuppression(ctx, rep, addr))
611 VarSizeStackTrace traces[kMop];
612 const uptr toppc = TraceTopPC(thr);
613 ObtainCurrentStack(thr, toppc, &traces[0]);
614 if (IsFiredSuppression(ctx, rep, traces[0]))
616 InternalScopedBuffer<MutexSet> mset2(1);
617 new(mset2.data()) MutexSet();
618 Shadow s2(thr->racy_state[1]);
619 RestoreStack(s2.tid(), s2.epoch(), &traces[1], mset2.data());
620 if (IsFiredSuppression(ctx, rep, traces[1]))
623 if (HandleRacyStacks(thr, traces, addr_min, addr_max))
626 for (uptr i = 0; i < kMop; i++) {
627 Shadow s(thr->racy_state[i]);
628 rep.AddMemoryAccess(addr, s, traces[i],
629 i == 0 ? &thr->mset : mset2.data());
632 for (uptr i = 0; i < kMop; i++) {
633 FastState s(thr->racy_state[i]);
634 ThreadContext *tctx = static_cast<ThreadContext*>(
635 ctx->thread_registry->GetThreadLocked(s.tid()));
636 if (s.epoch() < tctx->epoch0 || s.epoch() > tctx->epoch1)
641 rep.AddLocation(addr_min, addr_max - addr_min);
645 Shadow s(thr->racy_state[1]);
646 if (s.epoch() <= thr->last_sleep_clock.get(s.tid()))
647 rep.AddSleep(thr->last_sleep_stack_id);
651 if (!OutputReport(thr, rep))
654 AddRacyStacks(thr, traces, addr_min, addr_max);
657 void PrintCurrentStack(ThreadState *thr, uptr pc) {
658 VarSizeStackTrace trace;
659 ObtainCurrentStack(thr, pc, &trace);
660 PrintStack(SymbolizeStack(trace));
663 void PrintCurrentStackSlow(uptr pc) {
665 BufferedStackTrace *ptrace =
666 new(internal_alloc(MBlockStackTrace, sizeof(BufferedStackTrace)))
667 BufferedStackTrace();
668 ptrace->Unwind(kStackTraceMax, pc, 0, 0, 0, 0, false);
669 for (uptr i = 0; i < ptrace->size / 2; i++) {
670 uptr tmp = ptrace->trace_buffer[i];
671 ptrace->trace_buffer[i] = ptrace->trace_buffer[ptrace->size - i - 1];
672 ptrace->trace_buffer[ptrace->size - i - 1] = tmp;
674 PrintStack(SymbolizeStack(*ptrace));
678 } // namespace __tsan
680 using namespace __tsan;
683 SANITIZER_INTERFACE_ATTRIBUTE
684 void __sanitizer_print_stack_trace() {
685 PrintCurrentStackSlow(StackTrace::GetCurrentPc());