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