]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/tsan/rtl/tsan_rtl_report.cc
Merge ^/head r317808 through r317970.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / tsan / rtl / tsan_rtl_report.cc
1 //===-- tsan_rtl_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
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"
20 #include "tsan_rtl.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"
27 #include "tsan_fd.h"
28
29 namespace __tsan {
30
31 using namespace __sanitizer;  // NOLINT
32
33 static ReportStack *SymbolizeStack(StackTrace trace);
34
35 void TsanCheckFailed(const char *file, int line, const char *cond,
36                      u64 v1, u64 v2) {
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 #if !SANITIZER_GO
42   cur_thread()->ignore_sync++;
43   cur_thread()->ignore_reads_and_writes++;
44 #endif
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());
49   Die();
50 }
51
52 // Can be overriden by an application/test to intercept reports.
53 #ifdef TSAN_EXTERNAL_HOOKS
54 bool OnReport(const ReportDesc *rep, bool suppressed);
55 #else
56 SANITIZER_WEAK_CXX_DEFAULT_IMPL
57 bool OnReport(const ReportDesc *rep, bool suppressed) {
58   (void)rep;
59   return suppressed;
60 }
61 #endif
62
63 SANITIZER_WEAK_DEFAULT_IMPL
64 void __tsan_on_report(const ReportDesc *rep) {
65   (void)rep;
66 }
67
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;
73     last_frame = cur;
74   }
75
76   if (last_frame2 == 0)
77     return;
78 #if !SANITIZER_GO
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
98     // due to our fault.
99     DPrintf("Bottom stack frame is missed\n");
100   }
101 #else
102   // The last frame always point into runtime (gosched0, goexit0, runtime.main).
103   last_frame->ClearAll();
104   last_frame2->next = nullptr;
105 #endif
106 }
107
108 ReportStack *SymbolizeStackId(u32 stack_id) {
109   if (stack_id == 0)
110     return 0;
111   StackTrace stack = StackDepotGet(stack_id);
112   if (stack.trace == nullptr)
113     return nullptr;
114   return SymbolizeStack(stack);
115 }
116
117 static ReportStack *SymbolizeStack(StackTrace trace) {
118   if (trace.size == 0)
119     return 0;
120   SymbolizedStack *top = nullptr;
121   for (uptr si = 0; si < trace.size; si++) {
122     const uptr pc = trace.trace[si];
123     uptr pc1 = pc;
124     // We obtain the return address, but we're interested in the previous
125     // instruction.
126     if ((pc & kExternalPCBit) == 0)
127       pc1 = StackTrace::GetPreviousInstructionPc(pc);
128     SymbolizedStack *ent = SymbolizeCode(pc1);
129     CHECK_NE(ent, 0);
130     SymbolizedStack *last = ent;
131     while (last->next) {
132       last->info.address = pc;  // restore original pc for report
133       last = last->next;
134     }
135     last->info.address = pc;  // restore original pc for report
136     last->next = top;
137     top = ent;
138   }
139   StackStripMain(top);
140
141   ReportStack *stack = ReportStack::New();
142   stack->frames = top;
143   return stack;
144 }
145
146 ScopedReport::ScopedReport(ReportType typ, uptr tag) {
147   ctx->thread_registry->CheckLocked();
148   void *mem = internal_alloc(MBlockReport, sizeof(ReportDesc));
149   rep_ = new(mem) ReportDesc;
150   rep_->typ = typ;
151   rep_->tag = tag;
152   ctx->report_mtx.Lock();
153   CommonSanitizerReportMutex.Lock();
154 }
155
156 ScopedReport::~ScopedReport() {
157   CommonSanitizerReportMutex.Unlock();
158   ctx->report_mtx.Unlock();
159   DestroyAndFree(rep_);
160 }
161
162 void ScopedReport::AddStack(StackTrace stack, bool suppressable) {
163   ReportStack **rs = rep_->stacks.PushBack();
164   *rs = SymbolizeStack(stack);
165   (*rs)->suppressable = suppressable;
166 }
167
168 void ScopedReport::AddMemoryAccess(uptr addr, uptr external_tag, Shadow s,
169                                    StackTrace stack, const MutexSet *mset) {
170   void *mem = internal_alloc(MBlockReportMop, sizeof(ReportMop));
171   ReportMop *mop = new(mem) ReportMop;
172   rep_->mops.PushBack(mop);
173   mop->tid = s.tid();
174   mop->addr = addr + s.addr0();
175   mop->size = s.size();
176   mop->write = s.IsWrite();
177   mop->atomic = s.IsAtomic();
178   mop->stack = SymbolizeStack(stack);
179   mop->external_tag = external_tag;
180   if (mop->stack)
181     mop->stack->suppressable = true;
182   for (uptr i = 0; i < mset->Size(); i++) {
183     MutexSet::Desc d = mset->Get(i);
184     u64 mid = this->AddMutex(d.id);
185     ReportMopMutex mtx = {mid, d.write};
186     mop->mset.PushBack(mtx);
187   }
188 }
189
190 void ScopedReport::AddUniqueTid(int unique_tid) {
191   rep_->unique_tids.PushBack(unique_tid);
192 }
193
194 void ScopedReport::AddThread(const ThreadContext *tctx, bool suppressable) {
195   for (uptr i = 0; i < rep_->threads.Size(); i++) {
196     if ((u32)rep_->threads[i]->id == tctx->tid)
197       return;
198   }
199   void *mem = internal_alloc(MBlockReportThread, sizeof(ReportThread));
200   ReportThread *rt = new(mem) ReportThread;
201   rep_->threads.PushBack(rt);
202   rt->id = tctx->tid;
203   rt->os_id = tctx->os_id;
204   rt->running = (tctx->status == ThreadStatusRunning);
205   rt->name = internal_strdup(tctx->name);
206   rt->parent_tid = tctx->parent_tid;
207   rt->workerthread = tctx->workerthread;
208   rt->stack = 0;
209   rt->stack = SymbolizeStackId(tctx->creation_stack_id);
210   if (rt->stack)
211     rt->stack->suppressable = suppressable;
212 }
213
214 #if !SANITIZER_GO
215 static bool FindThreadByUidLockedCallback(ThreadContextBase *tctx, void *arg) {
216   int unique_id = *(int *)arg;
217   return tctx->unique_id == (u32)unique_id;
218 }
219
220 static ThreadContext *FindThreadByUidLocked(int unique_id) {
221   ctx->thread_registry->CheckLocked();
222   return static_cast<ThreadContext *>(
223       ctx->thread_registry->FindThreadContextLocked(
224           FindThreadByUidLockedCallback, &unique_id));
225 }
226
227 static ThreadContext *FindThreadByTidLocked(int tid) {
228   ctx->thread_registry->CheckLocked();
229   return static_cast<ThreadContext*>(
230       ctx->thread_registry->GetThreadLocked(tid));
231 }
232
233 static bool IsInStackOrTls(ThreadContextBase *tctx_base, void *arg) {
234   uptr addr = (uptr)arg;
235   ThreadContext *tctx = static_cast<ThreadContext*>(tctx_base);
236   if (tctx->status != ThreadStatusRunning)
237     return false;
238   ThreadState *thr = tctx->thr;
239   CHECK(thr);
240   return ((addr >= thr->stk_addr && addr < thr->stk_addr + thr->stk_size) ||
241           (addr >= thr->tls_addr && addr < thr->tls_addr + thr->tls_size));
242 }
243
244 ThreadContext *IsThreadStackOrTls(uptr addr, bool *is_stack) {
245   ctx->thread_registry->CheckLocked();
246   ThreadContext *tctx = static_cast<ThreadContext*>(
247       ctx->thread_registry->FindThreadContextLocked(IsInStackOrTls,
248                                                     (void*)addr));
249   if (!tctx)
250     return 0;
251   ThreadState *thr = tctx->thr;
252   CHECK(thr);
253   *is_stack = (addr >= thr->stk_addr && addr < thr->stk_addr + thr->stk_size);
254   return tctx;
255 }
256 #endif
257
258 void ScopedReport::AddThread(int unique_tid, bool suppressable) {
259 #if !SANITIZER_GO
260   if (const ThreadContext *tctx = FindThreadByUidLocked(unique_tid))
261     AddThread(tctx, suppressable);
262 #endif
263 }
264
265 void ScopedReport::AddMutex(const SyncVar *s) {
266   for (uptr i = 0; i < rep_->mutexes.Size(); i++) {
267     if (rep_->mutexes[i]->id == s->uid)
268       return;
269   }
270   void *mem = internal_alloc(MBlockReportMutex, sizeof(ReportMutex));
271   ReportMutex *rm = new(mem) ReportMutex;
272   rep_->mutexes.PushBack(rm);
273   rm->id = s->uid;
274   rm->addr = s->addr;
275   rm->destroyed = false;
276   rm->stack = SymbolizeStackId(s->creation_stack_id);
277 }
278
279 u64 ScopedReport::AddMutex(u64 id) {
280   u64 uid = 0;
281   u64 mid = id;
282   uptr addr = SyncVar::SplitId(id, &uid);
283   SyncVar *s = ctx->metamap.GetIfExistsAndLock(addr, true);
284   // Check that the mutex is still alive.
285   // Another mutex can be created at the same address,
286   // so check uid as well.
287   if (s && s->CheckId(uid)) {
288     mid = s->uid;
289     AddMutex(s);
290   } else {
291     AddDeadMutex(id);
292   }
293   if (s)
294     s->mtx.Unlock();
295   return mid;
296 }
297
298 void ScopedReport::AddDeadMutex(u64 id) {
299   for (uptr i = 0; i < rep_->mutexes.Size(); i++) {
300     if (rep_->mutexes[i]->id == id)
301       return;
302   }
303   void *mem = internal_alloc(MBlockReportMutex, sizeof(ReportMutex));
304   ReportMutex *rm = new(mem) ReportMutex;
305   rep_->mutexes.PushBack(rm);
306   rm->id = id;
307   rm->addr = 0;
308   rm->destroyed = true;
309   rm->stack = 0;
310 }
311
312 void ScopedReport::AddLocation(uptr addr, uptr size) {
313   if (addr == 0)
314     return;
315 #if !SANITIZER_GO
316   int fd = -1;
317   int creat_tid = -1;
318   u32 creat_stack = 0;
319   if (FdLocation(addr, &fd, &creat_tid, &creat_stack)) {
320     ReportLocation *loc = ReportLocation::New(ReportLocationFD);
321     loc->fd = fd;
322     loc->tid = creat_tid;
323     loc->stack = SymbolizeStackId(creat_stack);
324     rep_->locs.PushBack(loc);
325     ThreadContext *tctx = FindThreadByUidLocked(creat_tid);
326     if (tctx)
327       AddThread(tctx);
328     return;
329   }
330   MBlock *b = 0;
331   Allocator *a = allocator();
332   if (a->PointerIsMine((void*)addr)) {
333     void *block_begin = a->GetBlockBegin((void*)addr);
334     if (block_begin)
335       b = ctx->metamap.GetBlock((uptr)block_begin);
336   }
337   if (b != 0) {
338     ThreadContext *tctx = FindThreadByTidLocked(b->tid);
339     ReportLocation *loc = ReportLocation::New(ReportLocationHeap);
340     loc->heap_chunk_start = (uptr)allocator()->GetBlockBegin((void *)addr);
341     loc->heap_chunk_size = b->siz;
342     loc->external_tag = b->tag;
343     loc->tid = tctx ? tctx->tid : b->tid;
344     loc->stack = SymbolizeStackId(b->stk);
345     rep_->locs.PushBack(loc);
346     if (tctx)
347       AddThread(tctx);
348     return;
349   }
350   bool is_stack = false;
351   if (ThreadContext *tctx = IsThreadStackOrTls(addr, &is_stack)) {
352     ReportLocation *loc =
353         ReportLocation::New(is_stack ? ReportLocationStack : ReportLocationTLS);
354     loc->tid = tctx->tid;
355     rep_->locs.PushBack(loc);
356     AddThread(tctx);
357   }
358 #endif
359   if (ReportLocation *loc = SymbolizeData(addr)) {
360     loc->suppressable = true;
361     rep_->locs.PushBack(loc);
362     return;
363   }
364 }
365
366 #if !SANITIZER_GO
367 void ScopedReport::AddSleep(u32 stack_id) {
368   rep_->sleep = SymbolizeStackId(stack_id);
369 }
370 #endif
371
372 void ScopedReport::SetCount(int count) {
373   rep_->count = count;
374 }
375
376 const ReportDesc *ScopedReport::GetReport() const {
377   return rep_;
378 }
379
380 void RestoreStack(int tid, const u64 epoch, VarSizeStackTrace *stk,
381                   MutexSet *mset, uptr *tag) {
382   // This function restores stack trace and mutex set for the thread/epoch.
383   // It does so by getting stack trace and mutex set at the beginning of
384   // trace part, and then replaying the trace till the given epoch.
385   Trace* trace = ThreadTrace(tid);
386   ReadLock l(&trace->mtx);
387   const int partidx = (epoch / kTracePartSize) % TraceParts();
388   TraceHeader* hdr = &trace->headers[partidx];
389   if (epoch < hdr->epoch0 || epoch >= hdr->epoch0 + kTracePartSize)
390     return;
391   CHECK_EQ(RoundDown(epoch, kTracePartSize), hdr->epoch0);
392   const u64 epoch0 = RoundDown(epoch, TraceSize());
393   const u64 eend = epoch % TraceSize();
394   const u64 ebegin = RoundDown(eend, kTracePartSize);
395   DPrintf("#%d: RestoreStack epoch=%zu ebegin=%zu eend=%zu partidx=%d\n",
396           tid, (uptr)epoch, (uptr)ebegin, (uptr)eend, partidx);
397   Vector<uptr> stack(MBlockReportStack);
398   stack.Resize(hdr->stack0.size + 64);
399   for (uptr i = 0; i < hdr->stack0.size; i++) {
400     stack[i] = hdr->stack0.trace[i];
401     DPrintf2("  #%02zu: pc=%zx\n", i, stack[i]);
402   }
403   if (mset)
404     *mset = hdr->mset0;
405   uptr pos = hdr->stack0.size;
406   Event *events = (Event*)GetThreadTrace(tid);
407   for (uptr i = ebegin; i <= eend; i++) {
408     Event ev = events[i];
409     EventType typ = (EventType)(ev >> 61);
410     uptr pc = (uptr)(ev & ((1ull << 61) - 1));
411     DPrintf2("  %zu typ=%d pc=%zx\n", i, typ, pc);
412     if (typ == EventTypeMop) {
413       stack[pos] = pc;
414     } else if (typ == EventTypeFuncEnter) {
415       if (stack.Size() < pos + 2)
416         stack.Resize(pos + 2);
417       stack[pos++] = pc;
418     } else if (typ == EventTypeFuncExit) {
419       if (pos > 0)
420         pos--;
421     }
422     if (mset) {
423       if (typ == EventTypeLock) {
424         mset->Add(pc, true, epoch0 + i);
425       } else if (typ == EventTypeUnlock) {
426         mset->Del(pc, true);
427       } else if (typ == EventTypeRLock) {
428         mset->Add(pc, false, epoch0 + i);
429       } else if (typ == EventTypeRUnlock) {
430         mset->Del(pc, false);
431       }
432     }
433     for (uptr j = 0; j <= pos; j++)
434       DPrintf2("      #%zu: %zx\n", j, stack[j]);
435   }
436   if (pos == 0 && stack[0] == 0)
437     return;
438   pos++;
439   stk->Init(&stack[0], pos);
440   ExtractTagFromStack(stk, tag);
441 }
442
443 static bool HandleRacyStacks(ThreadState *thr, VarSizeStackTrace traces[2],
444                              uptr addr_min, uptr addr_max) {
445   bool equal_stack = false;
446   RacyStacks hash;
447   bool equal_address = false;
448   RacyAddress ra0 = {addr_min, addr_max};
449   {
450     ReadLock lock(&ctx->racy_mtx);
451     if (flags()->suppress_equal_stacks) {
452       hash.hash[0] = md5_hash(traces[0].trace, traces[0].size * sizeof(uptr));
453       hash.hash[1] = md5_hash(traces[1].trace, traces[1].size * sizeof(uptr));
454       for (uptr i = 0; i < ctx->racy_stacks.Size(); i++) {
455         if (hash == ctx->racy_stacks[i]) {
456           VPrintf(2,
457               "ThreadSanitizer: suppressing report as doubled (stack)\n");
458           equal_stack = true;
459           break;
460         }
461       }
462     }
463     if (flags()->suppress_equal_addresses) {
464       for (uptr i = 0; i < ctx->racy_addresses.Size(); i++) {
465         RacyAddress ra2 = ctx->racy_addresses[i];
466         uptr maxbeg = max(ra0.addr_min, ra2.addr_min);
467         uptr minend = min(ra0.addr_max, ra2.addr_max);
468         if (maxbeg < minend) {
469           VPrintf(2, "ThreadSanitizer: suppressing report as doubled (addr)\n");
470           equal_address = true;
471           break;
472         }
473       }
474     }
475   }
476   if (!equal_stack && !equal_address)
477     return false;
478   if (!equal_stack) {
479     Lock lock(&ctx->racy_mtx);
480     ctx->racy_stacks.PushBack(hash);
481   }
482   if (!equal_address) {
483     Lock lock(&ctx->racy_mtx);
484     ctx->racy_addresses.PushBack(ra0);
485   }
486   return true;
487 }
488
489 static void AddRacyStacks(ThreadState *thr, VarSizeStackTrace traces[2],
490                           uptr addr_min, uptr addr_max) {
491   Lock lock(&ctx->racy_mtx);
492   if (flags()->suppress_equal_stacks) {
493     RacyStacks hash;
494     hash.hash[0] = md5_hash(traces[0].trace, traces[0].size * sizeof(uptr));
495     hash.hash[1] = md5_hash(traces[1].trace, traces[1].size * sizeof(uptr));
496     ctx->racy_stacks.PushBack(hash);
497   }
498   if (flags()->suppress_equal_addresses) {
499     RacyAddress ra0 = {addr_min, addr_max};
500     ctx->racy_addresses.PushBack(ra0);
501   }
502 }
503
504 bool OutputReport(ThreadState *thr, const ScopedReport &srep) {
505   if (!flags()->report_bugs || thr->suppress_reports)
506     return false;
507   atomic_store_relaxed(&ctx->last_symbolize_time_ns, NanoTime());
508   const ReportDesc *rep = srep.GetReport();
509   CHECK_EQ(thr->current_report, nullptr);
510   thr->current_report = rep;
511   Suppression *supp = 0;
512   uptr pc_or_addr = 0;
513   for (uptr i = 0; pc_or_addr == 0 && i < rep->mops.Size(); i++)
514     pc_or_addr = IsSuppressed(rep->typ, rep->mops[i]->stack, &supp);
515   for (uptr i = 0; pc_or_addr == 0 && i < rep->stacks.Size(); i++)
516     pc_or_addr = IsSuppressed(rep->typ, rep->stacks[i], &supp);
517   for (uptr i = 0; pc_or_addr == 0 && i < rep->threads.Size(); i++)
518     pc_or_addr = IsSuppressed(rep->typ, rep->threads[i]->stack, &supp);
519   for (uptr i = 0; pc_or_addr == 0 && i < rep->locs.Size(); i++)
520     pc_or_addr = IsSuppressed(rep->typ, rep->locs[i], &supp);
521   if (pc_or_addr != 0) {
522     Lock lock(&ctx->fired_suppressions_mtx);
523     FiredSuppression s = {srep.GetReport()->typ, pc_or_addr, supp};
524     ctx->fired_suppressions.push_back(s);
525   }
526   {
527     bool old_is_freeing = thr->is_freeing;
528     thr->is_freeing = false;
529     bool suppressed = OnReport(rep, pc_or_addr != 0);
530     thr->is_freeing = old_is_freeing;
531     if (suppressed) {
532       thr->current_report = nullptr;
533       return false;
534     }
535   }
536   PrintReport(rep);
537   __tsan_on_report(rep);
538   ctx->nreported++;
539   if (flags()->halt_on_error)
540     Die();
541   thr->current_report = nullptr;
542   return true;
543 }
544
545 bool IsFiredSuppression(Context *ctx, ReportType type, StackTrace trace) {
546   ReadLock lock(&ctx->fired_suppressions_mtx);
547   for (uptr k = 0; k < ctx->fired_suppressions.size(); k++) {
548     if (ctx->fired_suppressions[k].type != type)
549       continue;
550     for (uptr j = 0; j < trace.size; j++) {
551       FiredSuppression *s = &ctx->fired_suppressions[k];
552       if (trace.trace[j] == s->pc_or_addr) {
553         if (s->supp)
554           atomic_fetch_add(&s->supp->hit_count, 1, memory_order_relaxed);
555         return true;
556       }
557     }
558   }
559   return false;
560 }
561
562 static bool IsFiredSuppression(Context *ctx, ReportType type, uptr addr) {
563   ReadLock lock(&ctx->fired_suppressions_mtx);
564   for (uptr k = 0; k < ctx->fired_suppressions.size(); k++) {
565     if (ctx->fired_suppressions[k].type != type)
566       continue;
567     FiredSuppression *s = &ctx->fired_suppressions[k];
568     if (addr == s->pc_or_addr) {
569       if (s->supp)
570         atomic_fetch_add(&s->supp->hit_count, 1, memory_order_relaxed);
571       return true;
572     }
573   }
574   return false;
575 }
576
577 static bool RaceBetweenAtomicAndFree(ThreadState *thr) {
578   Shadow s0(thr->racy_state[0]);
579   Shadow s1(thr->racy_state[1]);
580   CHECK(!(s0.IsAtomic() && s1.IsAtomic()));
581   if (!s0.IsAtomic() && !s1.IsAtomic())
582     return true;
583   if (s0.IsAtomic() && s1.IsFreed())
584     return true;
585   if (s1.IsAtomic() && thr->is_freeing)
586     return true;
587   return false;
588 }
589
590 void ReportRace(ThreadState *thr) {
591   CheckNoLocks(thr);
592
593   // Symbolizer makes lots of intercepted calls. If we try to process them,
594   // at best it will cause deadlocks on internal mutexes.
595   ScopedIgnoreInterceptors ignore;
596
597   if (!flags()->report_bugs)
598     return;
599   if (!flags()->report_atomic_races && !RaceBetweenAtomicAndFree(thr))
600     return;
601
602   bool freed = false;
603   {
604     Shadow s(thr->racy_state[1]);
605     freed = s.GetFreedAndReset();
606     thr->racy_state[1] = s.raw();
607   }
608
609   uptr addr = ShadowToMem((uptr)thr->racy_shadow_addr);
610   uptr addr_min = 0;
611   uptr addr_max = 0;
612   {
613     uptr a0 = addr + Shadow(thr->racy_state[0]).addr0();
614     uptr a1 = addr + Shadow(thr->racy_state[1]).addr0();
615     uptr e0 = a0 + Shadow(thr->racy_state[0]).size();
616     uptr e1 = a1 + Shadow(thr->racy_state[1]).size();
617     addr_min = min(a0, a1);
618     addr_max = max(e0, e1);
619     if (IsExpectedReport(addr_min, addr_max - addr_min))
620       return;
621   }
622
623   ReportType typ = ReportTypeRace;
624   if (thr->is_vptr_access && freed)
625     typ = ReportTypeVptrUseAfterFree;
626   else if (thr->is_vptr_access)
627     typ = ReportTypeVptrRace;
628   else if (freed)
629     typ = ReportTypeUseAfterFree;
630
631   if (IsFiredSuppression(ctx, typ, addr))
632     return;
633
634   const uptr kMop = 2;
635   VarSizeStackTrace traces[kMop];
636   uptr tags[kMop] = {kExternalTagNone};
637   const uptr toppc = TraceTopPC(thr);
638   ObtainCurrentStack(thr, toppc, &traces[0], &tags[0]);
639   if (IsFiredSuppression(ctx, typ, traces[0]))
640     return;
641
642   // MutexSet is too large to live on stack.
643   Vector<u64> mset_buffer(MBlockScopedBuf);
644   mset_buffer.Resize(sizeof(MutexSet) / sizeof(u64) + 1);
645   MutexSet *mset2 = new(&mset_buffer[0]) MutexSet();
646
647   Shadow s2(thr->racy_state[1]);
648   RestoreStack(s2.tid(), s2.epoch(), &traces[1], mset2, &tags[1]);
649   if (IsFiredSuppression(ctx, typ, traces[1]))
650     return;
651
652   if (HandleRacyStacks(thr, traces, addr_min, addr_max))
653     return;
654
655   // If any of the accesses has a tag, treat this as an "external" race.
656   uptr tag = kExternalTagNone;
657   for (uptr i = 0; i < kMop; i++) {
658     if (tags[i] != kExternalTagNone) {
659       typ = ReportTypeExternalRace;
660       tag = tags[i];
661       break;
662     }
663   }
664
665   ThreadRegistryLock l0(ctx->thread_registry);
666   ScopedReport rep(typ, tag);
667   for (uptr i = 0; i < kMop; i++) {
668     Shadow s(thr->racy_state[i]);
669     rep.AddMemoryAccess(addr, tags[i], s, traces[i],
670                         i == 0 ? &thr->mset : mset2);
671   }
672
673   for (uptr i = 0; i < kMop; i++) {
674     FastState s(thr->racy_state[i]);
675     ThreadContext *tctx = static_cast<ThreadContext*>(
676         ctx->thread_registry->GetThreadLocked(s.tid()));
677     if (s.epoch() < tctx->epoch0 || s.epoch() > tctx->epoch1)
678       continue;
679     rep.AddThread(tctx);
680   }
681
682   rep.AddLocation(addr_min, addr_max - addr_min);
683
684 #if !SANITIZER_GO
685   {  // NOLINT
686     Shadow s(thr->racy_state[1]);
687     if (s.epoch() <= thr->last_sleep_clock.get(s.tid()))
688       rep.AddSleep(thr->last_sleep_stack_id);
689   }
690 #endif
691
692   if (!OutputReport(thr, rep))
693     return;
694
695   AddRacyStacks(thr, traces, addr_min, addr_max);
696 }
697
698 void PrintCurrentStack(ThreadState *thr, uptr pc) {
699   VarSizeStackTrace trace;
700   ObtainCurrentStack(thr, pc, &trace);
701   PrintStack(SymbolizeStack(trace));
702 }
703
704 // Always inlining PrintCurrentStackSlow, because LocatePcInTrace assumes
705 // __sanitizer_print_stack_trace exists in the actual unwinded stack, but
706 // tail-call to PrintCurrentStackSlow breaks this assumption because
707 // __sanitizer_print_stack_trace disappears after tail-call.
708 // However, this solution is not reliable enough, please see dvyukov's comment
709 // http://reviews.llvm.org/D19148#406208
710 // Also see PR27280 comment 2 and 3 for breaking examples and analysis.
711 ALWAYS_INLINE
712 void PrintCurrentStackSlow(uptr pc) {
713 #if !SANITIZER_GO
714   BufferedStackTrace *ptrace =
715       new(internal_alloc(MBlockStackTrace, sizeof(BufferedStackTrace)))
716           BufferedStackTrace();
717   ptrace->Unwind(kStackTraceMax, pc, 0, 0, 0, 0, false);
718   for (uptr i = 0; i < ptrace->size / 2; i++) {
719     uptr tmp = ptrace->trace_buffer[i];
720     ptrace->trace_buffer[i] = ptrace->trace_buffer[ptrace->size - i - 1];
721     ptrace->trace_buffer[ptrace->size - i - 1] = tmp;
722   }
723   PrintStack(SymbolizeStack(*ptrace));
724 #endif
725 }
726
727 }  // namespace __tsan
728
729 using namespace __tsan;
730
731 extern "C" {
732 SANITIZER_INTERFACE_ATTRIBUTE
733 void __sanitizer_print_stack_trace() {
734   PrintCurrentStackSlow(StackTrace::GetCurrentPc());
735 }
736 }  // extern "C"