]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/tsan/rtl/tsan_rtl_report.cc
Merge ^/head r314270 through r314419.
[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) {
147   ctx->thread_registry->CheckLocked();
148   void *mem = internal_alloc(MBlockReport, sizeof(ReportDesc));
149   rep_ = new(mem) ReportDesc;
150   rep_->typ = typ;
151   ctx->report_mtx.Lock();
152   CommonSanitizerReportMutex.Lock();
153 }
154
155 ScopedReport::~ScopedReport() {
156   CommonSanitizerReportMutex.Unlock();
157   ctx->report_mtx.Unlock();
158   DestroyAndFree(rep_);
159 }
160
161 void ScopedReport::AddStack(StackTrace stack, bool suppressable) {
162   ReportStack **rs = rep_->stacks.PushBack();
163   *rs = SymbolizeStack(stack);
164   (*rs)->suppressable = suppressable;
165 }
166
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);
172   mop->tid = s.tid();
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);
178   if (mop->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);
185   }
186 }
187
188 void ScopedReport::AddUniqueTid(int unique_tid) {
189   rep_->unique_tids.PushBack(unique_tid);
190 }
191
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)
195       return;
196   }
197   void *mem = internal_alloc(MBlockReportThread, sizeof(ReportThread));
198   ReportThread *rt = new(mem) ReportThread;
199   rep_->threads.PushBack(rt);
200   rt->id = tctx->tid;
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;
205   rt->stack = 0;
206   rt->stack = SymbolizeStackId(tctx->creation_stack_id);
207   if (rt->stack)
208     rt->stack->suppressable = suppressable;
209 }
210
211 #if !SANITIZER_GO
212 static bool FindThreadByUidLockedCallback(ThreadContextBase *tctx, void *arg) {
213   int unique_id = *(int *)arg;
214   return tctx->unique_id == (u32)unique_id;
215 }
216
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));
222 }
223
224 static ThreadContext *FindThreadByTidLocked(int tid) {
225   ctx->thread_registry->CheckLocked();
226   return static_cast<ThreadContext*>(
227       ctx->thread_registry->GetThreadLocked(tid));
228 }
229
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)
234     return false;
235   ThreadState *thr = tctx->thr;
236   CHECK(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));
239 }
240
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,
245                                                     (void*)addr));
246   if (!tctx)
247     return 0;
248   ThreadState *thr = tctx->thr;
249   CHECK(thr);
250   *is_stack = (addr >= thr->stk_addr && addr < thr->stk_addr + thr->stk_size);
251   return tctx;
252 }
253 #endif
254
255 void ScopedReport::AddThread(int unique_tid, bool suppressable) {
256 #if !SANITIZER_GO
257   if (const ThreadContext *tctx = FindThreadByUidLocked(unique_tid))
258     AddThread(tctx, suppressable);
259 #endif
260 }
261
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)
265       return;
266   }
267   void *mem = internal_alloc(MBlockReportMutex, sizeof(ReportMutex));
268   ReportMutex *rm = new(mem) ReportMutex;
269   rep_->mutexes.PushBack(rm);
270   rm->id = s->uid;
271   rm->addr = s->addr;
272   rm->destroyed = false;
273   rm->stack = SymbolizeStackId(s->creation_stack_id);
274 }
275
276 u64 ScopedReport::AddMutex(u64 id) {
277   u64 uid = 0;
278   u64 mid = 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)) {
285     mid = s->uid;
286     AddMutex(s);
287   } else {
288     AddDeadMutex(id);
289   }
290   if (s)
291     s->mtx.Unlock();
292   return mid;
293 }
294
295 void ScopedReport::AddDeadMutex(u64 id) {
296   for (uptr i = 0; i < rep_->mutexes.Size(); i++) {
297     if (rep_->mutexes[i]->id == id)
298       return;
299   }
300   void *mem = internal_alloc(MBlockReportMutex, sizeof(ReportMutex));
301   ReportMutex *rm = new(mem) ReportMutex;
302   rep_->mutexes.PushBack(rm);
303   rm->id = id;
304   rm->addr = 0;
305   rm->destroyed = true;
306   rm->stack = 0;
307 }
308
309 void ScopedReport::AddLocation(uptr addr, uptr size) {
310   if (addr == 0)
311     return;
312 #if !SANITIZER_GO
313   int fd = -1;
314   int creat_tid = -1;
315   u32 creat_stack = 0;
316   if (FdLocation(addr, &fd, &creat_tid, &creat_stack)) {
317     ReportLocation *loc = ReportLocation::New(ReportLocationFD);
318     loc->fd = fd;
319     loc->tid = creat_tid;
320     loc->stack = SymbolizeStackId(creat_stack);
321     rep_->locs.PushBack(loc);
322     ThreadContext *tctx = FindThreadByUidLocked(creat_tid);
323     if (tctx)
324       AddThread(tctx);
325     return;
326   }
327   MBlock *b = 0;
328   Allocator *a = allocator();
329   if (a->PointerIsMine((void*)addr)) {
330     void *block_begin = a->GetBlockBegin((void*)addr);
331     if (block_begin)
332       b = ctx->metamap.GetBlock((uptr)block_begin);
333   }
334   if (b != 0) {
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);
342     if (tctx)
343       AddThread(tctx);
344     return;
345   }
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);
352     AddThread(tctx);
353   }
354 #endif
355   if (ReportLocation *loc = SymbolizeData(addr)) {
356     loc->suppressable = true;
357     rep_->locs.PushBack(loc);
358     return;
359   }
360 }
361
362 #if !SANITIZER_GO
363 void ScopedReport::AddSleep(u32 stack_id) {
364   rep_->sleep = SymbolizeStackId(stack_id);
365 }
366 #endif
367
368 void ScopedReport::SetCount(int count) {
369   rep_->count = count;
370 }
371
372 const ReportDesc *ScopedReport::GetReport() const {
373   return rep_;
374 }
375
376 void RestoreStack(int tid, const u64 epoch, VarSizeStackTrace *stk,
377                   MutexSet *mset) {
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)
386     return;
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]);
398   }
399   if (mset)
400     *mset = hdr->mset0;
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) {
409       stack[pos] = pc;
410     } else if (typ == EventTypeFuncEnter) {
411       if (stack.Size() < pos + 2)
412         stack.Resize(pos + 2);
413       stack[pos++] = pc;
414     } else if (typ == EventTypeFuncExit) {
415       if (pos > 0)
416         pos--;
417     }
418     if (mset) {
419       if (typ == EventTypeLock) {
420         mset->Add(pc, true, epoch0 + i);
421       } else if (typ == EventTypeUnlock) {
422         mset->Del(pc, true);
423       } else if (typ == EventTypeRLock) {
424         mset->Add(pc, false, epoch0 + i);
425       } else if (typ == EventTypeRUnlock) {
426         mset->Del(pc, false);
427       }
428     }
429     for (uptr j = 0; j <= pos; j++)
430       DPrintf2("      #%zu: %zx\n", j, stack[j]);
431   }
432   if (pos == 0 && stack[0] == 0)
433     return;
434   pos++;
435   stk->Init(&stack[0], pos);
436 }
437
438 static bool HandleRacyStacks(ThreadState *thr, VarSizeStackTrace traces[2],
439                              uptr addr_min, uptr addr_max) {
440   bool equal_stack = false;
441   RacyStacks hash;
442   bool equal_address = false;
443   RacyAddress ra0 = {addr_min, addr_max};
444   {
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]) {
451           VPrintf(2,
452               "ThreadSanitizer: suppressing report as doubled (stack)\n");
453           equal_stack = true;
454           break;
455         }
456       }
457     }
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;
466           break;
467         }
468       }
469     }
470   }
471   if (!equal_stack && !equal_address)
472     return false;
473   if (!equal_stack) {
474     Lock lock(&ctx->racy_mtx);
475     ctx->racy_stacks.PushBack(hash);
476   }
477   if (!equal_address) {
478     Lock lock(&ctx->racy_mtx);
479     ctx->racy_addresses.PushBack(ra0);
480   }
481   return true;
482 }
483
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) {
488     RacyStacks hash;
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);
492   }
493   if (flags()->suppress_equal_addresses) {
494     RacyAddress ra0 = {addr_min, addr_max};
495     ctx->racy_addresses.PushBack(ra0);
496   }
497 }
498
499 bool OutputReport(ThreadState *thr, const ScopedReport &srep) {
500   if (!flags()->report_bugs)
501     return false;
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;
507   uptr pc_or_addr = 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);
520   }
521   {
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;
526     if (suppressed) {
527       thr->current_report = nullptr;
528       return false;
529     }
530   }
531   PrintReport(rep);
532   __tsan_on_report(rep);
533   ctx->nreported++;
534   if (flags()->halt_on_error)
535     Die();
536   thr->current_report = nullptr;
537   return true;
538 }
539
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)
544       continue;
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) {
548         if (s->supp)
549           atomic_fetch_add(&s->supp->hit_count, 1, memory_order_relaxed);
550         return true;
551       }
552     }
553   }
554   return false;
555 }
556
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)
561       continue;
562     FiredSuppression *s = &ctx->fired_suppressions[k];
563     if (addr == s->pc_or_addr) {
564       if (s->supp)
565         atomic_fetch_add(&s->supp->hit_count, 1, memory_order_relaxed);
566       return true;
567     }
568   }
569   return false;
570 }
571
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())
577     return true;
578   if (s0.IsAtomic() && s1.IsFreed())
579     return true;
580   if (s1.IsAtomic() && thr->is_freeing)
581     return true;
582   return false;
583 }
584
585 void ReportRace(ThreadState *thr) {
586   CheckNoLocks(thr);
587
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;
591
592   if (!flags()->report_bugs)
593     return;
594   if (!flags()->report_atomic_races && !RaceBetweenAtomicAndFree(thr))
595     return;
596
597   bool freed = false;
598   {
599     Shadow s(thr->racy_state[1]);
600     freed = s.GetFreedAndReset();
601     thr->racy_state[1] = s.raw();
602   }
603
604   uptr addr = ShadowToMem((uptr)thr->racy_shadow_addr);
605   uptr addr_min = 0;
606   uptr addr_max = 0;
607   {
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))
615       return;
616   }
617
618   ReportType typ = ReportTypeRace;
619   if (thr->is_vptr_access && freed)
620     typ = ReportTypeVptrUseAfterFree;
621   else if (thr->is_vptr_access)
622     typ = ReportTypeVptrRace;
623   else if (freed)
624     typ = ReportTypeUseAfterFree;
625
626   if (IsFiredSuppression(ctx, typ, addr))
627     return;
628
629   const uptr kMop = 2;
630   VarSizeStackTrace traces[kMop];
631   const uptr toppc = TraceTopPC(thr);
632   ObtainCurrentStack(thr, toppc, &traces[0]);
633   if (IsFiredSuppression(ctx, typ, traces[0]))
634     return;
635
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();
640
641   Shadow s2(thr->racy_state[1]);
642   RestoreStack(s2.tid(), s2.epoch(), &traces[1], mset2);
643   if (IsFiredSuppression(ctx, typ, traces[1]))
644     return;
645
646   if (HandleRacyStacks(thr, traces, addr_min, addr_max))
647     return;
648
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);
654   }
655
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)
661       continue;
662     rep.AddThread(tctx);
663   }
664
665   rep.AddLocation(addr_min, addr_max - addr_min);
666
667 #if !SANITIZER_GO
668   {  // NOLINT
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);
672   }
673 #endif
674
675   if (!OutputReport(thr, rep))
676     return;
677
678   AddRacyStacks(thr, traces, addr_min, addr_max);
679 }
680
681 void PrintCurrentStack(ThreadState *thr, uptr pc) {
682   VarSizeStackTrace trace;
683   ObtainCurrentStack(thr, pc, &trace);
684   PrintStack(SymbolizeStack(trace));
685 }
686
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.
694 ALWAYS_INLINE
695 void PrintCurrentStackSlow(uptr pc) {
696 #if !SANITIZER_GO
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;
705   }
706   PrintStack(SymbolizeStack(*ptrace));
707 #endif
708 }
709
710 }  // namespace __tsan
711
712 using namespace __tsan;
713
714 extern "C" {
715 SANITIZER_INTERFACE_ATTRIBUTE
716 void __sanitizer_print_stack_trace() {
717   PrintCurrentStackSlow(StackTrace::GetCurrentPc());
718 }
719 }  // extern "C"