1//===-- tsan_rtl_report.cpp -----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file is a part of ThreadSanitizer (TSan), a race detector.
10//
11//===----------------------------------------------------------------------===//
12
13#include "sanitizer_common/sanitizer_common.h"
14#include "sanitizer_common/sanitizer_internal_defs.h"
15#include "sanitizer_common/sanitizer_libc.h"
16#include "sanitizer_common/sanitizer_placement_new.h"
17#include "sanitizer_common/sanitizer_stackdepot.h"
18#include "sanitizer_common/sanitizer_stacktrace.h"
19#include "tsan_defs.h"
20#include "tsan_fd.h"
21#include "tsan_flags.h"
22#include "tsan_mman.h"
23#include "tsan_platform.h"
24#include "tsan_report.h"
25#include "tsan_rtl.h"
26#include "tsan_suppressions.h"
27#include "tsan_symbolize.h"
28#include "tsan_sync.h"
29
30namespace __tsan {
31
32using namespace __sanitizer;
33
34static ReportStack *SymbolizeStack(StackTrace trace);
35
36// Can be overriden by an application/test to intercept reports.
37#ifdef TSAN_EXTERNAL_HOOKS
38bool OnReport(const ReportDesc *rep, bool suppressed);
39#else
40SANITIZER_WEAK_CXX_DEFAULT_IMPL
41bool OnReport(const ReportDesc *rep, bool suppressed) {
42 (void)rep;
43 return suppressed;
44}
45#endif
46
47SANITIZER_WEAK_DEFAULT_IMPL
48void __tsan_on_report(const ReportDesc *rep) {
49 (void)rep;
50}
51
52static void StackStripMain(SymbolizedStack *frames) {
53 SymbolizedStack *last_frame = nullptr;
54 SymbolizedStack *last_frame2 = nullptr;
55 for (SymbolizedStack *cur = frames; cur; cur = cur->next) {
56 last_frame2 = last_frame;
57 last_frame = cur;
58 }
59
60 if (last_frame2 == 0)
61 return;
62#if !SANITIZER_GO
63 const char *last = last_frame->info.function;
64 const char *last2 = last_frame2->info.function;
65 // Strip frame above 'main'
66 if (last2 && 0 == internal_strcmp(s1: last2, s2: "main")) {
67 last_frame->ClearAll();
68 last_frame2->next = nullptr;
69 // Strip our internal thread start routine.
70 } else if (last && 0 == internal_strcmp(s1: last, s2: "__tsan_thread_start_func")) {
71 last_frame->ClearAll();
72 last_frame2->next = nullptr;
73 // Strip global ctors init, .preinit_array and main caller.
74 } else if (last && (0 == internal_strcmp(s1: last, s2: "__do_global_ctors_aux") ||
75 0 == internal_strcmp(s1: last, s2: "__libc_csu_init") ||
76 0 == internal_strcmp(s1: last, s2: "__libc_start_main"))) {
77 last_frame->ClearAll();
78 last_frame2->next = nullptr;
79 // If both are 0, then we probably just failed to symbolize.
80 } else if (last || last2) {
81 // Ensure that we recovered stack completely. Trimmed stack
82 // can actually happen if we do not instrument some code,
83 // so it's only a debug print. However we must try hard to not miss it
84 // due to our fault.
85 DPrintf("Bottom stack frame is missed\n");
86 }
87#else
88 // The last frame always point into runtime (gosched0, goexit0, runtime.main).
89 last_frame->ClearAll();
90 last_frame2->next = nullptr;
91#endif
92}
93
94ReportStack *SymbolizeStackId(u32 stack_id) {
95 if (stack_id == 0)
96 return 0;
97 StackTrace stack = StackDepotGet(id: stack_id);
98 if (stack.trace == nullptr)
99 return nullptr;
100 return SymbolizeStack(trace: stack);
101}
102
103static ReportStack *SymbolizeStack(StackTrace trace) {
104 if (trace.size == 0)
105 return 0;
106 SymbolizedStack *top = nullptr;
107 for (uptr si = 0; si < trace.size; si++) {
108 const uptr pc = trace.trace[si];
109 uptr pc1 = pc;
110 // We obtain the return address, but we're interested in the previous
111 // instruction.
112 if ((pc & kExternalPCBit) == 0)
113 pc1 = StackTrace::GetPreviousInstructionPc(pc);
114 SymbolizedStack* ent = SymbolizeCode(addr: pc1, leaf: si == trace.size - 1);
115#if SANITIZER_GO
116 if (ent == nullptr) {
117 // Go might have 0 frames for this PC (wrapper frames aren't reported).
118 continue;
119 }
120#endif
121 CHECK_NE(ent, 0);
122 SymbolizedStack *last = ent;
123 while (last->next) {
124 last->info.address = pc; // restore original pc for report
125 last = last->next;
126 }
127 last->info.address = pc; // restore original pc for report
128 last->next = top;
129 top = ent;
130 }
131 StackStripMain(frames: top);
132
133 auto *stack = New<ReportStack>();
134 stack->frames = top;
135 return stack;
136}
137
138bool ShouldReport(ThreadState *thr, ReportType typ) {
139 // We set thr->suppress_reports in the fork context.
140 // Taking any locking in the fork context can lead to deadlocks.
141 // If any locks are already taken, it's too late to do this check.
142 CheckedMutex::CheckNoLocks();
143 if (!flags()->report_bugs || thr->suppress_reports)
144 return false;
145 switch (typ) {
146 case ReportTypeSignalUnsafe:
147 return flags()->report_signal_unsafe;
148 case ReportTypeThreadLeak:
149#if !SANITIZER_GO
150 // It's impossible to join phantom threads
151 // in the child after fork.
152 if (ctx->after_multithreaded_fork)
153 return false;
154#endif
155 return flags()->report_thread_leaks;
156 case ReportTypeMutexDestroyLocked:
157 return flags()->report_destroy_locked;
158 default:
159 return true;
160 }
161}
162
163ScopedReport::ScopedReport(ReportType typ, uptr tag) {
164 CheckedMutex::CheckNoLocks();
165 rep_ = New<ReportDesc>();
166 rep_->typ = typ;
167 rep_->tag = tag;
168}
169
170ScopedReport::~ScopedReport() { DestroyAndFree(p&: rep_); }
171
172void ScopedReport::AddStack(StackTrace stack, bool suppressable) {
173 rep_->added_stacks.PushBack(v: {.stack_trace: stack, .suppressable: suppressable});
174}
175
176void ScopedReport::AddMemoryAccess(uptr addr, uptr external_tag, Shadow s,
177 Tid tid, StackTrace stack,
178 const MutexSet* mset) {
179 uptr addr0, size;
180 AccessType typ;
181 s.GetAccess(addr: &addr0, size: &size, typ: &typ);
182 auto *mop = New<ReportMop>();
183 rep_->mops.PushBack(v: mop);
184 mop->tid = tid;
185 mop->addr = addr + addr0;
186 mop->size = size;
187 mop->write = !(typ & kAccessRead);
188 mop->atomic = typ & kAccessAtomic;
189 mop->external_tag = external_tag;
190 mop->stack_trace = stack;
191 for (uptr i = 0; i < mset->Size(); i++) {
192 MutexSet::Desc d = mset->Get(i);
193 int id = this->AddMutex(addr: d.addr, creation_stack_id: d.stack_id);
194 ReportMopMutex mtx = {.id: id, .write: d.write};
195 mop->mset.PushBack(v: mtx);
196 }
197}
198
199void ScopedReport::SymbolizeStackElems() {
200 // symbolize stacks
201 for (usize i = 0, size = rep_->added_stacks.Size(); i < size; i++) {
202 AddedStack& as = rep_->added_stacks[i];
203 ReportStack* rs = SymbolizeStack(trace: as.stack_trace);
204 if (rs)
205 rs->suppressable = as.suppressable;
206 rep_->stacks.PushBack(v: rs);
207 }
208
209 // symbolize memory ops
210 for (usize i = 0, size = rep_->mops.Size(); i < size; i++) {
211 ReportMop *mop = rep_->mops[i];
212 mop->stack = SymbolizeStack(trace: mop->stack_trace);
213 if (mop->stack)
214 mop->stack->suppressable = true;
215 }
216
217 // symbolize locations
218 for (usize i = 0, size = rep_->locs.Size(); i < size; i++)
219 rep_->locs[i]->stack = SymbolizeStackId(stack_id: rep_->locs[i]->stack_id);
220
221 // symbolize any added locations
222 for (usize i = 0, size = rep_->loc_addrs.Size(); i < size; i++) {
223 if (ReportLocation* loc = SymbolizeData(addr: rep_->loc_addrs[i])) {
224 loc->suppressable = true;
225 rep_->locs.PushBack(v: loc);
226 }
227 }
228
229 // symbolize threads
230 for (usize i = 0, size = rep_->threads.Size(); i < size; i++) {
231 ReportThread *rt = rep_->threads[i];
232 rt->stack = SymbolizeStackId(stack_id: rt->stack_id);
233 if (rt->stack)
234 rt->stack->suppressable = rt->suppressable;
235 }
236
237 // symbolize mutexes
238 for (usize i = 0, size = rep_->mutexes.Size(); i < size; i++) {
239 ReportMutex *rm = rep_->mutexes[i];
240 rm->stack = SymbolizeStackId(stack_id: rm->stack_id);
241 }
242
243#if !SANITIZER_GO
244 rep_->sleep = SymbolizeStackId(stack_id: rep_->sleep_stack_id);
245#endif
246}
247
248void ScopedReport::AddUniqueTid(Tid unique_tid) {
249 rep_->unique_tids.PushBack(v: unique_tid);
250}
251
252void ScopedReport::AddThread(const ThreadContext* tctx, bool suppressable) {
253 ThreadRegistryLock l(&ctx->thread_registry);
254 AddThreadLocked(tctx, suppressable);
255}
256
257void ScopedReport::AddThreadLocked(const ThreadContext* tctx,
258 bool suppressable) {
259 ctx->thread_registry.CheckLocked();
260 for (uptr i = 0; i < rep_->threads.Size(); i++) {
261 if ((u32)rep_->threads[i]->id == tctx->tid)
262 return;
263 }
264 auto *rt = New<ReportThread>();
265 rep_->threads.PushBack(v: rt);
266 rt->id = tctx->tid;
267 rt->os_id = tctx->os_id;
268 rt->running = (tctx->status == ThreadStatusRunning);
269 rt->name = internal_strdup(s: tctx->name);
270 rt->parent_tid = tctx->parent_tid;
271 rt->thread_type = tctx->thread_type;
272 rt->stack_id = tctx->creation_stack_id;
273 rt->suppressable = suppressable;
274}
275
276#if !SANITIZER_GO
277static bool IsInStackOrTls(ThreadContextBase *tctx_base, void *arg) {
278 uptr addr = (uptr)arg;
279 ThreadContext *tctx = static_cast<ThreadContext*>(tctx_base);
280 if (tctx->status != ThreadStatusRunning)
281 return false;
282 ThreadState *thr = tctx->thr;
283 CHECK(thr);
284 return ((addr >= thr->stk_addr && addr < thr->stk_addr + thr->stk_size) ||
285 (addr >= thr->tls_addr && addr < thr->tls_addr + thr->tls_size));
286}
287
288ThreadContext *IsThreadStackOrTls(uptr addr, bool *is_stack) {
289 ctx->thread_registry.CheckLocked();
290 ThreadContext *tctx =
291 static_cast<ThreadContext *>(ctx->thread_registry.FindThreadContextLocked(
292 cb: IsInStackOrTls, arg: (void *)addr));
293 if (!tctx)
294 return 0;
295 ThreadState *thr = tctx->thr;
296 CHECK(thr);
297 *is_stack = (addr >= thr->stk_addr && addr < thr->stk_addr + thr->stk_size);
298 return tctx;
299}
300#endif
301
302void ScopedReport::AddThread(Tid tid, bool suppressable) {
303 ThreadRegistryLock l(&ctx->thread_registry);
304 if (const auto* tctx = static_cast<ThreadContext*>(
305 ctx->thread_registry.GetThreadLocked(tid)))
306 AddThreadLocked(tctx, suppressable);
307}
308
309int ScopedReport::AddMutex(uptr addr, StackID creation_stack_id) {
310 for (uptr i = 0; i < rep_->mutexes.Size(); i++) {
311 if (rep_->mutexes[i]->addr == addr)
312 return rep_->mutexes[i]->id;
313 }
314 auto *rm = New<ReportMutex>();
315 rep_->mutexes.PushBack(v: rm);
316 rm->id = rep_->mutexes.Size() - 1;
317 rm->addr = addr;
318 rm->stack_id = creation_stack_id;
319 return rm->id;
320}
321
322void ScopedReport::AddLocation(uptr addr, uptr size) {
323 if (addr == 0)
324 return;
325#if !SANITIZER_GO
326 int fd = -1;
327 Tid creat_tid = kInvalidTid;
328 StackID creat_stack = 0;
329 bool closed = false;
330 if (FdLocation(addr, fd: &fd, tid: &creat_tid, stack: &creat_stack, closed: &closed)) {
331 auto *loc = New<ReportLocation>();
332 loc->type = ReportLocationFD;
333 loc->fd_closed = closed;
334 loc->fd = fd;
335 loc->tid = creat_tid;
336 loc->stack_id = creat_stack;
337 rep_->locs.PushBack(v: loc);
338 AddThread(tid: creat_tid);
339 return;
340 }
341 MBlock *b = 0;
342 uptr block_begin = 0;
343 Allocator *a = allocator();
344 if (a->PointerIsMine(p: (void*)addr)) {
345 block_begin = (uptr)a->GetBlockBegin(p: (void *)addr);
346 if (block_begin)
347 b = ctx->metamap.GetBlock(p: block_begin);
348 }
349 if (!b)
350 b = JavaHeapBlock(addr, start: &block_begin);
351 if (b != 0) {
352 auto *loc = New<ReportLocation>();
353 loc->type = ReportLocationHeap;
354 loc->heap_chunk_start = block_begin;
355 loc->heap_chunk_size = b->siz;
356 loc->external_tag = b->tag;
357 loc->tid = b->tid;
358 loc->stack_id = b->stk;
359 rep_->locs.PushBack(v: loc);
360 AddThread(tid: b->tid);
361 return;
362 }
363 bool is_stack = false;
364 {
365 ThreadRegistryLock l(&ctx->thread_registry);
366 if (ThreadContext* tctx = IsThreadStackOrTls(addr, is_stack: &is_stack)) {
367 auto* loc = New<ReportLocation>();
368 loc->type = is_stack ? ReportLocationStack : ReportLocationTLS;
369 loc->tid = tctx->tid;
370 rep_->locs.PushBack(v: loc);
371 AddThreadLocked(tctx);
372 }
373 }
374#endif
375 rep_->loc_addrs.PushBack(v: addr);
376}
377
378#if !SANITIZER_GO
379void ScopedReport::AddSleep(StackID stack_id) {
380 rep_->sleep_stack_id = stack_id;
381}
382#endif
383
384void ScopedReport::SetCount(int count) { rep_->count = count; }
385
386void ScopedReport::SetSigNum(int sig) { rep_->signum = sig; }
387
388const ReportDesc* ScopedReport::GetReport() const { return rep_; }
389
390// Replays the trace up to last_pos position in the last part
391// or up to the provided epoch/sid (whichever is earlier)
392// and calls the provided function f for each event.
393template <typename Func>
394void TraceReplay(Trace *trace, TracePart *last, Event *last_pos, Sid sid,
395 Epoch epoch, Func f) {
396 TracePart *part = trace->parts.Front();
397 Sid ev_sid = kFreeSid;
398 Epoch ev_epoch = kEpochOver;
399 for (;;) {
400 DCHECK_EQ(part->trace, trace);
401 // Note: an event can't start in the last element.
402 // Since an event can take up to 2 elements,
403 // we ensure we have at least 2 before adding an event.
404 Event *end = &part->events[TracePart::kSize - 1];
405 if (part == last)
406 end = last_pos;
407 f(kFreeSid, kEpochOver, nullptr); // notify about part start
408 for (Event *evp = &part->events[0]; evp < end; evp++) {
409 Event *evp0 = evp;
410 if (!evp->is_access && !evp->is_func) {
411 switch (evp->type) {
412 case EventType::kTime: {
413 auto *ev = reinterpret_cast<EventTime *>(evp);
414 ev_sid = static_cast<Sid>(ev->sid);
415 ev_epoch = static_cast<Epoch>(ev->epoch);
416 if (ev_sid == sid && ev_epoch > epoch)
417 return;
418 break;
419 }
420 case EventType::kAccessExt:
421 FALLTHROUGH;
422 case EventType::kAccessRange:
423 FALLTHROUGH;
424 case EventType::kLock:
425 FALLTHROUGH;
426 case EventType::kRLock:
427 // These take 2 Event elements.
428 evp++;
429 break;
430 case EventType::kUnlock:
431 // This takes 1 Event element.
432 break;
433 }
434 }
435 CHECK_NE(ev_sid, kFreeSid);
436 CHECK_NE(ev_epoch, kEpochOver);
437 f(ev_sid, ev_epoch, evp0);
438 }
439 if (part == last)
440 return;
441 part = trace->parts.Next(e: part);
442 CHECK(part);
443 }
444 CHECK(0);
445}
446
447static void RestoreStackMatch(VarSizeStackTrace *pstk, MutexSet *pmset,
448 Vector<uptr> *stack, MutexSet *mset, uptr pc,
449 bool *found) {
450 DPrintf2(" MATCHED\n");
451 *pmset = *mset;
452 stack->PushBack(v: pc);
453 pstk->Init(pcs: &(*stack)[0], cnt: stack->Size());
454 stack->PopBack();
455 *found = true;
456}
457
458// Checks if addr1|size1 is fully contained in addr2|size2.
459// We check for fully contained instread of just overlapping
460// because a memory access is always traced once, but can be
461// split into multiple accesses in the shadow.
462static constexpr bool IsWithinAccess(uptr addr1, uptr size1, uptr addr2,
463 uptr size2) {
464 return addr1 >= addr2 && addr1 + size1 <= addr2 + size2;
465}
466
467// Replays the trace of slot sid up to the target event identified
468// by epoch/addr/size/typ and restores and returns tid, stack, mutex set
469// and tag for that event. If there are multiple such events, it returns
470// the last one. Returns false if the event is not present in the trace.
471bool RestoreStack(EventType type, Sid sid, Epoch epoch, uptr addr, uptr size,
472 AccessType typ, Tid *ptid, VarSizeStackTrace *pstk,
473 MutexSet *pmset, uptr *ptag) {
474 // This function restores stack trace and mutex set for the thread/epoch.
475 // It does so by getting stack trace and mutex set at the beginning of
476 // trace part, and then replaying the trace till the given epoch.
477 DPrintf2("RestoreStack: sid=%u@%u addr=0x%zx/%zu typ=%x\n",
478 static_cast<int>(sid), static_cast<int>(epoch), addr, size,
479 static_cast<int>(typ));
480 ctx->slot_mtx.CheckLocked(); // needed to prevent trace part recycling
481 ctx->thread_registry.CheckLocked();
482 TidSlot *slot = &ctx->slots[static_cast<uptr>(sid)];
483 Tid tid = kInvalidTid;
484 // Need to lock the slot mutex as it protects slot->journal.
485 slot->mtx.CheckLocked();
486 for (uptr i = 0; i < slot->journal.Size(); i++) {
487 DPrintf2(" journal: epoch=%d tid=%d\n",
488 static_cast<int>(slot->journal[i].epoch), slot->journal[i].tid);
489 if (i == slot->journal.Size() - 1 || slot->journal[i + 1].epoch > epoch) {
490 tid = slot->journal[i].tid;
491 break;
492 }
493 }
494 if (tid == kInvalidTid)
495 return false;
496 *ptid = tid;
497 ThreadContext *tctx =
498 static_cast<ThreadContext *>(ctx->thread_registry.GetThreadLocked(tid));
499 Trace *trace = &tctx->trace;
500 // Snapshot first/last parts and the current position in the last part.
501 TracePart *first_part;
502 TracePart *last_part;
503 Event *last_pos;
504 {
505 Lock lock(&trace->mtx);
506 first_part = trace->parts.Front();
507 if (!first_part) {
508 DPrintf2("RestoreStack: tid=%d trace=%p no trace parts\n", tid, trace);
509 return false;
510 }
511 last_part = trace->parts.Back();
512 last_pos = trace->final_pos;
513 if (tctx->thr)
514 last_pos = (Event *)atomic_load_relaxed(a: &tctx->thr->trace_pos);
515 }
516 DynamicMutexSet mset;
517 Vector<uptr> stack;
518 uptr prev_pc = 0;
519 bool found = false;
520 bool is_read = typ & kAccessRead;
521 bool is_atomic = typ & kAccessAtomic;
522 bool is_free = typ & kAccessFree;
523 DPrintf2("RestoreStack: tid=%d parts=[%p-%p] last_pos=%p\n", tid,
524 trace->parts.Front(), last_part, last_pos);
525 TraceReplay(
526 trace, last: last_part, last_pos, sid, epoch,
527 f: [&](Sid ev_sid, Epoch ev_epoch, Event *evp) {
528 if (evp == nullptr) {
529 // Each trace part is self-consistent, so we reset state.
530 stack.Resize(size: 0);
531 mset->Reset();
532 prev_pc = 0;
533 return;
534 }
535 bool match = ev_sid == sid && ev_epoch == epoch;
536 if (evp->is_access) {
537 if (evp->is_func == 0 && evp->type == EventType::kAccessExt &&
538 evp->_ == 0) // NopEvent
539 return;
540 auto *ev = reinterpret_cast<EventAccess *>(evp);
541 uptr ev_addr = RestoreAddr(addr: ev->addr);
542 uptr ev_size = 1 << ev->size_log;
543 uptr ev_pc =
544 prev_pc + ev->pc_delta - (1 << (EventAccess::kPCBits - 1));
545 prev_pc = ev_pc;
546 DPrintf2(" Access: pc=0x%zx addr=0x%zx/%zu type=%u/%u\n", ev_pc,
547 ev_addr, ev_size, ev->is_read, ev->is_atomic);
548 if (match && type == EventType::kAccessExt &&
549 IsWithinAccess(addr1: addr, size1: size, addr2: ev_addr, size2: ev_size) &&
550 is_read == ev->is_read && is_atomic == ev->is_atomic && !is_free)
551 RestoreStackMatch(pstk, pmset, stack: &stack, mset, pc: ev_pc, found: &found);
552 return;
553 }
554 if (evp->is_func) {
555 auto *ev = reinterpret_cast<EventFunc *>(evp);
556 if (ev->pc) {
557 DPrintf2(" FuncEnter: pc=0x%llx\n", ev->pc);
558 stack.PushBack(v: ev->pc);
559 } else {
560 DPrintf2(" FuncExit\n");
561 // We don't log pathologically large stacks in each part,
562 // if the stack was truncated we can have more func exits than
563 // entries.
564 if (stack.Size())
565 stack.PopBack();
566 }
567 return;
568 }
569 switch (evp->type) {
570 case EventType::kAccessExt: {
571 auto *ev = reinterpret_cast<EventAccessExt *>(evp);
572 uptr ev_addr = RestoreAddr(addr: ev->addr);
573 uptr ev_size = 1 << ev->size_log;
574 prev_pc = ev->pc;
575 DPrintf2(" AccessExt: pc=0x%llx addr=0x%zx/%zu type=%u/%u\n",
576 ev->pc, ev_addr, ev_size, ev->is_read, ev->is_atomic);
577 if (match && type == EventType::kAccessExt &&
578 IsWithinAccess(addr1: addr, size1: size, addr2: ev_addr, size2: ev_size) &&
579 is_read == ev->is_read && is_atomic == ev->is_atomic &&
580 !is_free)
581 RestoreStackMatch(pstk, pmset, stack: &stack, mset, pc: ev->pc, found: &found);
582 break;
583 }
584 case EventType::kAccessRange: {
585 auto *ev = reinterpret_cast<EventAccessRange *>(evp);
586 uptr ev_addr = RestoreAddr(addr: ev->addr);
587 uptr ev_size =
588 (ev->size_hi << EventAccessRange::kSizeLoBits) + ev->size_lo;
589 uptr ev_pc = RestoreAddr(addr: ev->pc);
590 prev_pc = ev_pc;
591 DPrintf2(" Range: pc=0x%zx addr=0x%zx/%zu type=%u/%u\n", ev_pc,
592 ev_addr, ev_size, ev->is_read, ev->is_free);
593 if (match && type == EventType::kAccessExt &&
594 IsWithinAccess(addr1: addr, size1: size, addr2: ev_addr, size2: ev_size) &&
595 is_read == ev->is_read && !is_atomic && is_free == ev->is_free)
596 RestoreStackMatch(pstk, pmset, stack: &stack, mset, pc: ev_pc, found: &found);
597 break;
598 }
599 case EventType::kLock:
600 FALLTHROUGH;
601 case EventType::kRLock: {
602 auto *ev = reinterpret_cast<EventLock *>(evp);
603 bool is_write = ev->type == EventType::kLock;
604 uptr ev_addr = RestoreAddr(addr: ev->addr);
605 uptr ev_pc = RestoreAddr(addr: ev->pc);
606 StackID stack_id =
607 (ev->stack_hi << EventLock::kStackIDLoBits) + ev->stack_lo;
608 DPrintf2(" Lock: pc=0x%zx addr=0x%zx stack=%u write=%d\n", ev_pc,
609 ev_addr, stack_id, is_write);
610 mset->AddAddr(addr: ev_addr, stack_id, write: is_write);
611 // Events with ev_pc == 0 are written to the beginning of trace
612 // part as initial mutex set (are not real).
613 if (match && type == EventType::kLock && addr == ev_addr && ev_pc)
614 RestoreStackMatch(pstk, pmset, stack: &stack, mset, pc: ev_pc, found: &found);
615 break;
616 }
617 case EventType::kUnlock: {
618 auto *ev = reinterpret_cast<EventUnlock *>(evp);
619 uptr ev_addr = RestoreAddr(addr: ev->addr);
620 DPrintf2(" Unlock: addr=0x%zx\n", ev_addr);
621 mset->DelAddr(addr: ev_addr);
622 break;
623 }
624 case EventType::kTime:
625 // TraceReplay already extracted sid/epoch from it,
626 // nothing else to do here.
627 break;
628 }
629 });
630 ExtractTagFromStack(stack: pstk, tag: ptag);
631 return found;
632}
633
634bool RacyStacks::operator==(const RacyStacks &other) const {
635 if (hash[0] == other.hash[0] && hash[1] == other.hash[1])
636 return true;
637 if (hash[0] == other.hash[1] && hash[1] == other.hash[0])
638 return true;
639 return false;
640}
641
642static bool FindRacyStacks(const RacyStacks &hash) {
643 for (uptr i = 0; i < ctx->racy_stacks.Size(); i++) {
644 if (hash == ctx->racy_stacks[i]) {
645 VPrintf(2, "ThreadSanitizer: suppressing report as doubled (stack)\n");
646 return true;
647 }
648 }
649 return false;
650}
651
652static bool HandleRacyStacks(ThreadState *thr, VarSizeStackTrace traces[2]) {
653 if (!flags()->suppress_equal_stacks)
654 return false;
655 RacyStacks hash;
656 hash.hash[0] = md5_hash(data: traces[0].trace, size: traces[0].size * sizeof(uptr));
657 hash.hash[1] = md5_hash(data: traces[1].trace, size: traces[1].size * sizeof(uptr));
658 {
659 ReadLock lock(&ctx->racy_mtx);
660 if (FindRacyStacks(hash))
661 return true;
662 }
663 Lock lock(&ctx->racy_mtx);
664 if (FindRacyStacks(hash))
665 return true;
666 ctx->racy_stacks.PushBack(v: hash);
667 return false;
668}
669
670bool OutputReport(ThreadState *thr, ScopedReport &srep) {
671 CheckedMutex::CheckNoLocks();
672 // These should have been checked in ShouldReport.
673 // It's too late to check them here, we have already taken locks.
674 CHECK(flags()->report_bugs);
675 CHECK(!thr->suppress_reports);
676 srep.SymbolizeStackElems();
677 atomic_store_relaxed(a: &ctx->last_symbolize_time_ns, v: NanoTime());
678 const ReportDesc *rep = srep.GetReport();
679 CHECK_EQ(thr->current_report, nullptr);
680 thr->current_report = rep;
681 Suppression *supp = 0;
682 uptr pc_or_addr = 0;
683 for (uptr i = 0; pc_or_addr == 0 && i < rep->mops.Size(); i++)
684 pc_or_addr = IsSuppressed(typ: rep->typ, stack: rep->mops[i]->stack, sp: &supp);
685 for (uptr i = 0; pc_or_addr == 0 && i < rep->stacks.Size(); i++)
686 pc_or_addr = IsSuppressed(typ: rep->typ, stack: rep->stacks[i], sp: &supp);
687 for (uptr i = 0; pc_or_addr == 0 && i < rep->threads.Size(); i++)
688 pc_or_addr = IsSuppressed(typ: rep->typ, stack: rep->threads[i]->stack, sp: &supp);
689 for (uptr i = 0; pc_or_addr == 0 && i < rep->locs.Size(); i++)
690 pc_or_addr = IsSuppressed(typ: rep->typ, loc: rep->locs[i], sp: &supp);
691 if (pc_or_addr != 0) {
692 Lock lock(&ctx->fired_suppressions_mtx);
693 FiredSuppression s = {.type: srep.GetReport()->typ, .pc_or_addr: pc_or_addr, .supp: supp};
694 ctx->fired_suppressions.push_back(element: s);
695 }
696 {
697 bool suppressed = OnReport(rep, suppressed: pc_or_addr != 0);
698 if (suppressed) {
699 thr->current_report = nullptr;
700 return false;
701 }
702 }
703 PrintReport(rep);
704 __tsan_on_report(rep);
705 atomic_fetch_add(a: &ctx->nreported, v: 1, mo: memory_order_relaxed);
706 if (flags()->halt_on_error)
707 Die();
708 thr->current_report = nullptr;
709 return true;
710}
711
712bool IsFiredSuppression(Context *ctx, ReportType type, StackTrace trace) {
713 ReadLock lock(&ctx->fired_suppressions_mtx);
714 for (uptr k = 0; k < ctx->fired_suppressions.size(); k++) {
715 if (ctx->fired_suppressions[k].type != type)
716 continue;
717 for (uptr j = 0; j < trace.size; j++) {
718 FiredSuppression *s = &ctx->fired_suppressions[k];
719 if (trace.trace[j] == s->pc_or_addr) {
720 if (s->supp)
721 atomic_fetch_add(a: &s->supp->hit_count, v: 1, mo: memory_order_relaxed);
722 return true;
723 }
724 }
725 }
726 return false;
727}
728
729static bool IsFiredSuppression(Context *ctx, ReportType type, uptr addr) {
730 ReadLock lock(&ctx->fired_suppressions_mtx);
731 for (uptr k = 0; k < ctx->fired_suppressions.size(); k++) {
732 if (ctx->fired_suppressions[k].type != type)
733 continue;
734 FiredSuppression *s = &ctx->fired_suppressions[k];
735 if (addr == s->pc_or_addr) {
736 if (s->supp)
737 atomic_fetch_add(a: &s->supp->hit_count, v: 1, mo: memory_order_relaxed);
738 return true;
739 }
740 }
741 return false;
742}
743
744static bool SpuriousRace(Shadow old) {
745 Shadow last(LoadShadow(p: &ctx->last_spurious_race));
746 return last.sid() == old.sid() && last.epoch() == old.epoch();
747}
748
749void ReportRace(ThreadState *thr, RawShadow *shadow_mem, Shadow cur, Shadow old,
750 AccessType typ0) {
751 CheckedMutex::CheckNoLocks();
752
753 // Symbolizer makes lots of intercepted calls. If we try to process them,
754 // at best it will cause deadlocks on internal mutexes.
755 ScopedIgnoreInterceptors ignore;
756
757 uptr addr = ShadowToMem(s: shadow_mem);
758 DPrintf("#%d: ReportRace %p\n", thr->tid, (void *)addr);
759 if (!ShouldReport(thr, typ: ReportTypeRace))
760 return;
761 uptr addr_off0, size0;
762 cur.GetAccess(addr: &addr_off0, size: &size0, typ: nullptr);
763 uptr addr_off1, size1, typ1;
764 old.GetAccess(addr: &addr_off1, size: &size1, typ: &typ1);
765 if (!flags()->report_atomic_races &&
766 ((typ0 & kAccessAtomic) || (typ1 & kAccessAtomic)) &&
767 !(typ0 & kAccessFree) && !(typ1 & kAccessFree))
768 return;
769 if (SpuriousRace(old))
770 return;
771
772 const uptr kMop = 2;
773 Shadow s[kMop] = {cur, old};
774 uptr addr0 = addr + addr_off0;
775 uptr addr1 = addr + addr_off1;
776 uptr end0 = addr0 + size0;
777 uptr end1 = addr1 + size1;
778 uptr addr_min = min(a: addr0, b: addr1);
779 uptr addr_max = max(a: end0, b: end1);
780 if (IsExpectedReport(addr: addr_min, size: addr_max - addr_min))
781 return;
782
783 ReportType rep_typ = ReportTypeRace;
784 if ((typ0 & kAccessVptr) && (typ1 & kAccessFree))
785 rep_typ = ReportTypeVptrUseAfterFree;
786 else if (typ0 & kAccessVptr)
787 rep_typ = ReportTypeVptrRace;
788 else if (typ1 & kAccessFree)
789 rep_typ = ReportTypeUseAfterFree;
790
791 if (IsFiredSuppression(ctx, type: rep_typ, addr))
792 return;
793
794 VarSizeStackTrace traces[kMop];
795 Tid tids[kMop] = {thr->tid, kInvalidTid};
796 uptr tags[kMop] = {kExternalTagNone, kExternalTagNone};
797
798 ObtainCurrentStack(thr, toppc: thr->trace_prev_pc, stack: &traces[0], tag: &tags[0]);
799 if (IsFiredSuppression(ctx, type: rep_typ, trace: traces[0]))
800 return;
801
802 DynamicMutexSet mset1;
803 MutexSet *mset[kMop] = {&thr->mset, mset1};
804
805 {
806 // We need to lock the slot during RestoreStack because it protects
807 // the slot journal.
808 Lock slot_lock(&ctx->slots[static_cast<uptr>(s[1].sid())].mtx);
809 ThreadRegistryLock l0(&ctx->thread_registry);
810 Lock slots_lock(&ctx->slot_mtx);
811 if (SpuriousRace(old))
812 return;
813 if (!RestoreStack(type: EventType::kAccessExt, sid: s[1].sid(), epoch: s[1].epoch(), addr: addr1,
814 size: size1, typ: typ1, ptid: &tids[1], pstk: &traces[1], pmset: mset[1], ptag: &tags[1])) {
815 StoreShadow(sp: &ctx->last_spurious_race, s: old.raw());
816 return;
817 }
818 }
819
820 if (IsFiredSuppression(ctx, type: rep_typ, trace: traces[1]))
821 return;
822
823 if (HandleRacyStacks(thr, traces))
824 return;
825
826 // If any of the accesses has a tag, treat this as an "external" race.
827 uptr tag = kExternalTagNone;
828 for (uptr i = 0; i < kMop; i++) {
829 if (tags[i] != kExternalTagNone) {
830 rep_typ = ReportTypeExternalRace;
831 tag = tags[i];
832 break;
833 }
834 }
835
836 ScopedReport rep(rep_typ, tag);
837 for (uptr i = 0; i < kMop; i++)
838 rep.AddMemoryAccess(addr, external_tag: tags[i], s: s[i], tid: tids[i], stack: traces[i], mset: mset[i]);
839
840 for (uptr i = 0; i < kMop; i++) rep.AddThread(tid: tids[i]);
841
842 rep.AddLocation(addr: addr_min, size: addr_max - addr_min);
843
844 if (flags()->print_full_thread_history) {
845 const ReportDesc* rep_desc = rep.GetReport();
846 for (uptr i = 0; i < rep_desc->threads.Size(); i++) {
847 Tid parent_tid = rep_desc->threads[i]->parent_tid;
848 if (parent_tid == kMainTid || parent_tid == kInvalidTid)
849 continue;
850 rep.AddThread(tid: parent_tid);
851 }
852 }
853
854#if !SANITIZER_GO
855 if (!((typ0 | typ1) & kAccessFree) &&
856 s[1].epoch() <= thr->last_sleep_clock.Get(sid: s[1].sid()))
857 rep.AddSleep(stack_id: thr->last_sleep_stack_id);
858#endif
859 OutputReport(thr, srep&: rep);
860}
861
862void PrintCurrentStack(ThreadState *thr, uptr pc) {
863 VarSizeStackTrace trace;
864 ObtainCurrentStack(thr, toppc: pc, stack: &trace);
865 PrintStack(stack: SymbolizeStack(trace));
866}
867
868// Always inlining PrintCurrentStack, because LocatePcInTrace assumes
869// __sanitizer_print_stack_trace exists in the actual unwinded stack, but
870// tail-call to PrintCurrentStack breaks this assumption because
871// __sanitizer_print_stack_trace disappears after tail-call.
872// However, this solution is not reliable enough, please see dvyukov's comment
873// http://reviews.llvm.org/D19148#406208
874// Also see PR27280 comment 2 and 3 for breaking examples and analysis.
875ALWAYS_INLINE USED void PrintCurrentStack(uptr pc, bool fast) {
876#if !SANITIZER_GO
877 uptr bp = GET_CURRENT_FRAME();
878 auto *ptrace = New<BufferedStackTrace>();
879 ptrace->Unwind(pc, bp, context: nullptr, request_fast: fast);
880
881 for (uptr i = 0; i < ptrace->size / 2; i++) {
882 uptr tmp = ptrace->trace_buffer[i];
883 ptrace->trace_buffer[i] = ptrace->trace_buffer[ptrace->size - i - 1];
884 ptrace->trace_buffer[ptrace->size - i - 1] = tmp;
885 }
886
887 if (ready_to_symbolize) {
888 PrintStack(stack: SymbolizeStack(trace: *ptrace));
889 } else {
890 Printf(
891 format: "WARNING: PrintCurrentStack() has been called too early, before "
892 "symbolization is possible. Printing unsymbolized stack trace:\n");
893 for (unsigned int i = 0; i < ptrace->size; i++)
894 Printf(format: " #%u: 0x%zx\n", i, ptrace->trace[i]);
895 }
896#endif
897}
898
899} // namespace __tsan
900
901using namespace __tsan;
902
903extern "C" {
904SANITIZER_INTERFACE_ATTRIBUTE
905void __sanitizer_print_stack_trace() {
906 PrintCurrentStack(pc: StackTrace::GetCurrentPc(), fast: false);
907}
908} // extern "C"
909