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