1 //===-- tsan_rtl.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 // Main file (entry points) for the TSan run-time. 12 //===----------------------------------------------------------------------===// 13 14 #include "tsan_rtl.h" 15 16 #include "sanitizer_common/sanitizer_atomic.h" 17 #include "sanitizer_common/sanitizer_common.h" 18 #include "sanitizer_common/sanitizer_file.h" 19 #include "sanitizer_common/sanitizer_interface_internal.h" 20 #include "sanitizer_common/sanitizer_libc.h" 21 #include "sanitizer_common/sanitizer_placement_new.h" 22 #include "sanitizer_common/sanitizer_stackdepot.h" 23 #include "sanitizer_common/sanitizer_symbolizer.h" 24 #include "tsan_defs.h" 25 #include "tsan_interface.h" 26 #include "tsan_mman.h" 27 #include "tsan_platform.h" 28 #include "tsan_suppressions.h" 29 #include "tsan_symbolize.h" 30 #include "ubsan/ubsan_init.h" 31 32 volatile int __tsan_resumed = 0; 33 34 extern "C" void __tsan_resume() { 35 __tsan_resumed = 1; 36 } 37 38 SANITIZER_WEAK_DEFAULT_IMPL 39 void __tsan_test_only_on_fork() {} 40 41 namespace __tsan { 42 43 #if !SANITIZER_GO 44 void (*on_initialize)(void); 45 int (*on_finalize)(int); 46 #endif 47 48 #if !SANITIZER_GO && !SANITIZER_APPLE 49 __attribute__((tls_model("initial-exec"))) 50 THREADLOCAL char cur_thread_placeholder[sizeof(ThreadState)] ALIGNED( 51 SANITIZER_CACHE_LINE_SIZE); 52 #endif 53 static char ctx_placeholder[sizeof(Context)] ALIGNED(SANITIZER_CACHE_LINE_SIZE); 54 Context *ctx; 55 56 // Can be overriden by a front-end. 57 #ifdef TSAN_EXTERNAL_HOOKS 58 bool OnFinalize(bool failed); 59 void OnInitialize(); 60 #else 61 SANITIZER_WEAK_CXX_DEFAULT_IMPL 62 bool OnFinalize(bool failed) { 63 # if !SANITIZER_GO 64 if (on_finalize) 65 return on_finalize(failed); 66 # endif 67 return failed; 68 } 69 70 SANITIZER_WEAK_CXX_DEFAULT_IMPL 71 void OnInitialize() { 72 # if !SANITIZER_GO 73 if (on_initialize) 74 on_initialize(); 75 # endif 76 } 77 #endif 78 79 static TracePart* TracePartAlloc(ThreadState* thr) { 80 TracePart* part = nullptr; 81 { 82 Lock lock(&ctx->slot_mtx); 83 uptr max_parts = Trace::kMinParts + flags()->history_size; 84 Trace* trace = &thr->tctx->trace; 85 if (trace->parts_allocated == max_parts || 86 ctx->trace_part_finished_excess) { 87 part = ctx->trace_part_recycle.PopFront(); 88 DPrintf("#%d: TracePartAlloc: part=%p\n", thr->tid, part); 89 if (part && part->trace) { 90 Trace* trace1 = part->trace; 91 Lock trace_lock(&trace1->mtx); 92 part->trace = nullptr; 93 TracePart* part1 = trace1->parts.PopFront(); 94 CHECK_EQ(part, part1); 95 if (trace1->parts_allocated > trace1->parts.Size()) { 96 ctx->trace_part_finished_excess += 97 trace1->parts_allocated - trace1->parts.Size(); 98 trace1->parts_allocated = trace1->parts.Size(); 99 } 100 } 101 } 102 if (trace->parts_allocated < max_parts) { 103 trace->parts_allocated++; 104 if (ctx->trace_part_finished_excess) 105 ctx->trace_part_finished_excess--; 106 } 107 if (!part) 108 ctx->trace_part_total_allocated++; 109 else if (ctx->trace_part_recycle_finished) 110 ctx->trace_part_recycle_finished--; 111 } 112 if (!part) 113 part = new (MmapOrDie(sizeof(*part), "TracePart")) TracePart(); 114 return part; 115 } 116 117 static void TracePartFree(TracePart* part) SANITIZER_REQUIRES(ctx->slot_mtx) { 118 DCHECK(part->trace); 119 part->trace = nullptr; 120 ctx->trace_part_recycle.PushFront(part); 121 } 122 123 void TraceResetForTesting() { 124 Lock lock(&ctx->slot_mtx); 125 while (auto* part = ctx->trace_part_recycle.PopFront()) { 126 if (auto trace = part->trace) 127 CHECK_EQ(trace->parts.PopFront(), part); 128 UnmapOrDie(part, sizeof(*part)); 129 } 130 ctx->trace_part_total_allocated = 0; 131 ctx->trace_part_recycle_finished = 0; 132 ctx->trace_part_finished_excess = 0; 133 } 134 135 static void DoResetImpl(uptr epoch) { 136 ThreadRegistryLock lock0(&ctx->thread_registry); 137 Lock lock1(&ctx->slot_mtx); 138 CHECK_EQ(ctx->global_epoch, epoch); 139 ctx->global_epoch++; 140 CHECK(!ctx->resetting); 141 ctx->resetting = true; 142 for (u32 i = ctx->thread_registry.NumThreadsLocked(); i--;) { 143 ThreadContext* tctx = (ThreadContext*)ctx->thread_registry.GetThreadLocked( 144 static_cast<Tid>(i)); 145 // Potentially we could purge all ThreadStatusDead threads from the 146 // registry. Since we reset all shadow, they can't race with anything 147 // anymore. However, their tid's can still be stored in some aux places 148 // (e.g. tid of thread that created something). 149 auto trace = &tctx->trace; 150 Lock lock(&trace->mtx); 151 bool attached = tctx->thr && tctx->thr->slot; 152 auto parts = &trace->parts; 153 bool local = false; 154 while (!parts->Empty()) { 155 auto part = parts->Front(); 156 local = local || part == trace->local_head; 157 if (local) 158 CHECK(!ctx->trace_part_recycle.Queued(part)); 159 else 160 ctx->trace_part_recycle.Remove(part); 161 if (attached && parts->Size() == 1) { 162 // The thread is running and this is the last/current part. 163 // Set the trace position to the end of the current part 164 // to force the thread to call SwitchTracePart and re-attach 165 // to a new slot and allocate a new trace part. 166 // Note: the thread is concurrently modifying the position as well, 167 // so this is only best-effort. The thread can only modify position 168 // within this part, because switching parts is protected by 169 // slot/trace mutexes that we hold here. 170 atomic_store_relaxed( 171 &tctx->thr->trace_pos, 172 reinterpret_cast<uptr>(&part->events[TracePart::kSize])); 173 break; 174 } 175 parts->Remove(part); 176 TracePartFree(part); 177 } 178 CHECK_LE(parts->Size(), 1); 179 trace->local_head = parts->Front(); 180 if (tctx->thr && !tctx->thr->slot) { 181 atomic_store_relaxed(&tctx->thr->trace_pos, 0); 182 tctx->thr->trace_prev_pc = 0; 183 } 184 if (trace->parts_allocated > trace->parts.Size()) { 185 ctx->trace_part_finished_excess += 186 trace->parts_allocated - trace->parts.Size(); 187 trace->parts_allocated = trace->parts.Size(); 188 } 189 } 190 while (ctx->slot_queue.PopFront()) { 191 } 192 for (auto& slot : ctx->slots) { 193 slot.SetEpoch(kEpochZero); 194 slot.journal.Reset(); 195 slot.thr = nullptr; 196 ctx->slot_queue.PushBack(&slot); 197 } 198 199 DPrintf("Resetting shadow...\n"); 200 if (!MmapFixedSuperNoReserve(ShadowBeg(), ShadowEnd() - ShadowBeg(), 201 "shadow")) { 202 Printf("failed to reset shadow memory\n"); 203 Die(); 204 } 205 DPrintf("Resetting meta shadow...\n"); 206 ctx->metamap.ResetClocks(); 207 ctx->resetting = false; 208 } 209 210 // Clang does not understand locking all slots in the loop: 211 // error: expecting mutex 'slot.mtx' to be held at start of each loop 212 void DoReset(ThreadState* thr, uptr epoch) SANITIZER_NO_THREAD_SAFETY_ANALYSIS { 213 { 214 for (auto& slot : ctx->slots) { 215 slot.mtx.Lock(); 216 if (UNLIKELY(epoch == 0)) 217 epoch = ctx->global_epoch; 218 if (UNLIKELY(epoch != ctx->global_epoch)) { 219 // Epoch can't change once we've locked the first slot. 220 CHECK_EQ(slot.sid, 0); 221 slot.mtx.Unlock(); 222 return; 223 } 224 } 225 } 226 DPrintf("#%d: DoReset epoch=%lu\n", thr ? thr->tid : -1, epoch); 227 DoResetImpl(epoch); 228 for (auto& slot : ctx->slots) slot.mtx.Unlock(); 229 } 230 231 void FlushShadowMemory() { DoReset(nullptr, 0); } 232 233 static TidSlot* FindSlotAndLock(ThreadState* thr) 234 SANITIZER_ACQUIRE(thr->slot->mtx) SANITIZER_NO_THREAD_SAFETY_ANALYSIS { 235 CHECK(!thr->slot); 236 TidSlot* slot = nullptr; 237 for (;;) { 238 uptr epoch; 239 { 240 Lock lock(&ctx->slot_mtx); 241 epoch = ctx->global_epoch; 242 if (slot) { 243 // This is an exhausted slot from the previous iteration. 244 if (ctx->slot_queue.Queued(slot)) 245 ctx->slot_queue.Remove(slot); 246 thr->slot_locked = false; 247 slot->mtx.Unlock(); 248 } 249 for (;;) { 250 slot = ctx->slot_queue.PopFront(); 251 if (!slot) 252 break; 253 if (slot->epoch() != kEpochLast) { 254 ctx->slot_queue.PushBack(slot); 255 break; 256 } 257 } 258 } 259 if (!slot) { 260 DoReset(thr, epoch); 261 continue; 262 } 263 slot->mtx.Lock(); 264 CHECK(!thr->slot_locked); 265 thr->slot_locked = true; 266 if (slot->thr) { 267 DPrintf("#%d: preempting sid=%d tid=%d\n", thr->tid, (u32)slot->sid, 268 slot->thr->tid); 269 slot->SetEpoch(slot->thr->fast_state.epoch()); 270 slot->thr = nullptr; 271 } 272 if (slot->epoch() != kEpochLast) 273 return slot; 274 } 275 } 276 277 void SlotAttachAndLock(ThreadState* thr) { 278 TidSlot* slot = FindSlotAndLock(thr); 279 DPrintf("#%d: SlotAttach: slot=%u\n", thr->tid, static_cast<int>(slot->sid)); 280 CHECK(!slot->thr); 281 CHECK(!thr->slot); 282 slot->thr = thr; 283 thr->slot = slot; 284 Epoch epoch = EpochInc(slot->epoch()); 285 CHECK(!EpochOverflow(epoch)); 286 slot->SetEpoch(epoch); 287 thr->fast_state.SetSid(slot->sid); 288 thr->fast_state.SetEpoch(epoch); 289 if (thr->slot_epoch != ctx->global_epoch) { 290 thr->slot_epoch = ctx->global_epoch; 291 thr->clock.Reset(); 292 #if !SANITIZER_GO 293 thr->last_sleep_stack_id = kInvalidStackID; 294 thr->last_sleep_clock.Reset(); 295 #endif 296 } 297 thr->clock.Set(slot->sid, epoch); 298 slot->journal.PushBack({thr->tid, epoch}); 299 } 300 301 static void SlotDetachImpl(ThreadState* thr, bool exiting) { 302 TidSlot* slot = thr->slot; 303 thr->slot = nullptr; 304 if (thr != slot->thr) { 305 slot = nullptr; // we don't own the slot anymore 306 if (thr->slot_epoch != ctx->global_epoch) { 307 TracePart* part = nullptr; 308 auto* trace = &thr->tctx->trace; 309 { 310 Lock l(&trace->mtx); 311 auto* parts = &trace->parts; 312 // The trace can be completely empty in an unlikely event 313 // the thread is preempted right after it acquired the slot 314 // in ThreadStart and did not trace any events yet. 315 CHECK_LE(parts->Size(), 1); 316 part = parts->PopFront(); 317 thr->tctx->trace.local_head = nullptr; 318 atomic_store_relaxed(&thr->trace_pos, 0); 319 thr->trace_prev_pc = 0; 320 } 321 if (part) { 322 Lock l(&ctx->slot_mtx); 323 TracePartFree(part); 324 } 325 } 326 return; 327 } 328 CHECK(exiting || thr->fast_state.epoch() == kEpochLast); 329 slot->SetEpoch(thr->fast_state.epoch()); 330 slot->thr = nullptr; 331 } 332 333 void SlotDetach(ThreadState* thr) { 334 Lock lock(&thr->slot->mtx); 335 SlotDetachImpl(thr, true); 336 } 337 338 void SlotLock(ThreadState* thr) SANITIZER_NO_THREAD_SAFETY_ANALYSIS { 339 DCHECK(!thr->slot_locked); 340 #if SANITIZER_DEBUG 341 // Check these mutexes are not locked. 342 // We can call DoReset from SlotAttachAndLock, which will lock 343 // these mutexes, but it happens only every once in a while. 344 { ThreadRegistryLock lock(&ctx->thread_registry); } 345 { Lock lock(&ctx->slot_mtx); } 346 #endif 347 TidSlot* slot = thr->slot; 348 slot->mtx.Lock(); 349 thr->slot_locked = true; 350 if (LIKELY(thr == slot->thr && thr->fast_state.epoch() != kEpochLast)) 351 return; 352 SlotDetachImpl(thr, false); 353 thr->slot_locked = false; 354 slot->mtx.Unlock(); 355 SlotAttachAndLock(thr); 356 } 357 358 void SlotUnlock(ThreadState* thr) { 359 DCHECK(thr->slot_locked); 360 thr->slot_locked = false; 361 thr->slot->mtx.Unlock(); 362 } 363 364 Context::Context() 365 : initialized(), 366 report_mtx(MutexTypeReport), 367 nreported(), 368 thread_registry([](Tid tid) -> ThreadContextBase* { 369 return new (Alloc(sizeof(ThreadContext))) ThreadContext(tid); 370 }), 371 racy_mtx(MutexTypeRacy), 372 racy_stacks(), 373 racy_addresses(), 374 fired_suppressions_mtx(MutexTypeFired), 375 slot_mtx(MutexTypeSlots), 376 resetting() { 377 fired_suppressions.reserve(8); 378 for (uptr i = 0; i < ARRAY_SIZE(slots); i++) { 379 TidSlot* slot = &slots[i]; 380 slot->sid = static_cast<Sid>(i); 381 slot_queue.PushBack(slot); 382 } 383 global_epoch = 1; 384 } 385 386 TidSlot::TidSlot() : mtx(MutexTypeSlot) {} 387 388 // The objects are allocated in TLS, so one may rely on zero-initialization. 389 ThreadState::ThreadState(Tid tid) 390 // Do not touch these, rely on zero initialization, 391 // they may be accessed before the ctor. 392 // ignore_reads_and_writes() 393 // ignore_interceptors() 394 : tid(tid) { 395 CHECK_EQ(reinterpret_cast<uptr>(this) % SANITIZER_CACHE_LINE_SIZE, 0); 396 #if !SANITIZER_GO 397 // C/C++ uses fixed size shadow stack. 398 const int kInitStackSize = kShadowStackSize; 399 shadow_stack = static_cast<uptr*>( 400 MmapNoReserveOrDie(kInitStackSize * sizeof(uptr), "shadow stack")); 401 SetShadowRegionHugePageMode(reinterpret_cast<uptr>(shadow_stack), 402 kInitStackSize * sizeof(uptr)); 403 #else 404 // Go uses malloc-allocated shadow stack with dynamic size. 405 const int kInitStackSize = 8; 406 shadow_stack = static_cast<uptr*>(Alloc(kInitStackSize * sizeof(uptr))); 407 #endif 408 shadow_stack_pos = shadow_stack; 409 shadow_stack_end = shadow_stack + kInitStackSize; 410 } 411 412 #if !SANITIZER_GO 413 void MemoryProfiler(u64 uptime) { 414 if (ctx->memprof_fd == kInvalidFd) 415 return; 416 InternalMmapVector<char> buf(4096); 417 WriteMemoryProfile(buf.data(), buf.size(), uptime); 418 WriteToFile(ctx->memprof_fd, buf.data(), internal_strlen(buf.data())); 419 } 420 421 static bool InitializeMemoryProfiler() { 422 ctx->memprof_fd = kInvalidFd; 423 const char *fname = flags()->profile_memory; 424 if (!fname || !fname[0]) 425 return false; 426 if (internal_strcmp(fname, "stdout") == 0) { 427 ctx->memprof_fd = 1; 428 } else if (internal_strcmp(fname, "stderr") == 0) { 429 ctx->memprof_fd = 2; 430 } else { 431 InternalScopedString filename; 432 filename.append("%s.%d", fname, (int)internal_getpid()); 433 ctx->memprof_fd = OpenFile(filename.data(), WrOnly); 434 if (ctx->memprof_fd == kInvalidFd) { 435 Printf("ThreadSanitizer: failed to open memory profile file '%s'\n", 436 filename.data()); 437 return false; 438 } 439 } 440 MemoryProfiler(0); 441 return true; 442 } 443 444 static void *BackgroundThread(void *arg) { 445 // This is a non-initialized non-user thread, nothing to see here. 446 // We don't use ScopedIgnoreInterceptors, because we want ignores to be 447 // enabled even when the thread function exits (e.g. during pthread thread 448 // shutdown code). 449 cur_thread_init()->ignore_interceptors++; 450 const u64 kMs2Ns = 1000 * 1000; 451 const u64 start = NanoTime(); 452 453 u64 last_flush = start; 454 uptr last_rss = 0; 455 while (!atomic_load_relaxed(&ctx->stop_background_thread)) { 456 SleepForMillis(100); 457 u64 now = NanoTime(); 458 459 // Flush memory if requested. 460 if (flags()->flush_memory_ms > 0) { 461 if (last_flush + flags()->flush_memory_ms * kMs2Ns < now) { 462 VReport(1, "ThreadSanitizer: periodic memory flush\n"); 463 FlushShadowMemory(); 464 now = last_flush = NanoTime(); 465 } 466 } 467 if (flags()->memory_limit_mb > 0) { 468 uptr rss = GetRSS(); 469 uptr limit = uptr(flags()->memory_limit_mb) << 20; 470 VReport(1, 471 "ThreadSanitizer: memory flush check" 472 " RSS=%llu LAST=%llu LIMIT=%llu\n", 473 (u64)rss >> 20, (u64)last_rss >> 20, (u64)limit >> 20); 474 if (2 * rss > limit + last_rss) { 475 VReport(1, "ThreadSanitizer: flushing memory due to RSS\n"); 476 FlushShadowMemory(); 477 rss = GetRSS(); 478 now = NanoTime(); 479 VReport(1, "ThreadSanitizer: memory flushed RSS=%llu\n", 480 (u64)rss >> 20); 481 } 482 last_rss = rss; 483 } 484 485 MemoryProfiler(now - start); 486 487 // Flush symbolizer cache if requested. 488 if (flags()->flush_symbolizer_ms > 0) { 489 u64 last = atomic_load(&ctx->last_symbolize_time_ns, 490 memory_order_relaxed); 491 if (last != 0 && last + flags()->flush_symbolizer_ms * kMs2Ns < now) { 492 Lock l(&ctx->report_mtx); 493 ScopedErrorReportLock l2; 494 SymbolizeFlush(); 495 atomic_store(&ctx->last_symbolize_time_ns, 0, memory_order_relaxed); 496 } 497 } 498 } 499 return nullptr; 500 } 501 502 static void StartBackgroundThread() { 503 ctx->background_thread = internal_start_thread(&BackgroundThread, 0); 504 } 505 506 #ifndef __mips__ 507 static void StopBackgroundThread() { 508 atomic_store(&ctx->stop_background_thread, 1, memory_order_relaxed); 509 internal_join_thread(ctx->background_thread); 510 ctx->background_thread = 0; 511 } 512 #endif 513 #endif 514 515 void DontNeedShadowFor(uptr addr, uptr size) { 516 ReleaseMemoryPagesToOS(reinterpret_cast<uptr>(MemToShadow(addr)), 517 reinterpret_cast<uptr>(MemToShadow(addr + size))); 518 } 519 520 #if !SANITIZER_GO 521 // We call UnmapShadow before the actual munmap, at that point we don't yet 522 // know if the provided address/size are sane. We can't call UnmapShadow 523 // after the actual munmap becuase at that point the memory range can 524 // already be reused for something else, so we can't rely on the munmap 525 // return value to understand is the values are sane. 526 // While calling munmap with insane values (non-canonical address, negative 527 // size, etc) is an error, the kernel won't crash. We must also try to not 528 // crash as the failure mode is very confusing (paging fault inside of the 529 // runtime on some derived shadow address). 530 static bool IsValidMmapRange(uptr addr, uptr size) { 531 if (size == 0) 532 return true; 533 if (static_cast<sptr>(size) < 0) 534 return false; 535 if (!IsAppMem(addr) || !IsAppMem(addr + size - 1)) 536 return false; 537 // Check that if the start of the region belongs to one of app ranges, 538 // end of the region belongs to the same region. 539 const uptr ranges[][2] = { 540 {LoAppMemBeg(), LoAppMemEnd()}, 541 {MidAppMemBeg(), MidAppMemEnd()}, 542 {HiAppMemBeg(), HiAppMemEnd()}, 543 }; 544 for (auto range : ranges) { 545 if (addr >= range[0] && addr < range[1]) 546 return addr + size <= range[1]; 547 } 548 return false; 549 } 550 551 void UnmapShadow(ThreadState *thr, uptr addr, uptr size) { 552 if (size == 0 || !IsValidMmapRange(addr, size)) 553 return; 554 DontNeedShadowFor(addr, size); 555 ScopedGlobalProcessor sgp; 556 SlotLocker locker(thr, true); 557 ctx->metamap.ResetRange(thr->proc(), addr, size, true); 558 } 559 #endif 560 561 void MapShadow(uptr addr, uptr size) { 562 // Global data is not 64K aligned, but there are no adjacent mappings, 563 // so we can get away with unaligned mapping. 564 // CHECK_EQ(addr, addr & ~((64 << 10) - 1)); // windows wants 64K alignment 565 const uptr kPageSize = GetPageSizeCached(); 566 uptr shadow_begin = RoundDownTo((uptr)MemToShadow(addr), kPageSize); 567 uptr shadow_end = RoundUpTo((uptr)MemToShadow(addr + size), kPageSize); 568 if (!MmapFixedSuperNoReserve(shadow_begin, shadow_end - shadow_begin, 569 "shadow")) 570 Die(); 571 572 // Meta shadow is 2:1, so tread carefully. 573 static bool data_mapped = false; 574 static uptr mapped_meta_end = 0; 575 uptr meta_begin = (uptr)MemToMeta(addr); 576 uptr meta_end = (uptr)MemToMeta(addr + size); 577 meta_begin = RoundDownTo(meta_begin, 64 << 10); 578 meta_end = RoundUpTo(meta_end, 64 << 10); 579 if (!data_mapped) { 580 // First call maps data+bss. 581 data_mapped = true; 582 if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin, 583 "meta shadow")) 584 Die(); 585 } else { 586 // Mapping continuous heap. 587 // Windows wants 64K alignment. 588 meta_begin = RoundDownTo(meta_begin, 64 << 10); 589 meta_end = RoundUpTo(meta_end, 64 << 10); 590 if (meta_end <= mapped_meta_end) 591 return; 592 if (meta_begin < mapped_meta_end) 593 meta_begin = mapped_meta_end; 594 if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin, 595 "meta shadow")) 596 Die(); 597 mapped_meta_end = meta_end; 598 } 599 VPrintf(2, "mapped meta shadow for (0x%zx-0x%zx) at (0x%zx-0x%zx)\n", addr, 600 addr + size, meta_begin, meta_end); 601 } 602 603 #if !SANITIZER_GO 604 static void OnStackUnwind(const SignalContext &sig, const void *, 605 BufferedStackTrace *stack) { 606 stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context, 607 common_flags()->fast_unwind_on_fatal); 608 } 609 610 static void TsanOnDeadlySignal(int signo, void *siginfo, void *context) { 611 HandleDeadlySignal(siginfo, context, GetTid(), &OnStackUnwind, nullptr); 612 } 613 #endif 614 615 void CheckUnwind() { 616 // There is high probability that interceptors will check-fail as well, 617 // on the other hand there is no sense in processing interceptors 618 // since we are going to die soon. 619 ScopedIgnoreInterceptors ignore; 620 #if !SANITIZER_GO 621 ThreadState* thr = cur_thread(); 622 thr->nomalloc = false; 623 thr->ignore_sync++; 624 thr->ignore_reads_and_writes++; 625 atomic_store_relaxed(&thr->in_signal_handler, 0); 626 #endif 627 PrintCurrentStackSlow(StackTrace::GetCurrentPc()); 628 } 629 630 bool is_initialized; 631 632 void Initialize(ThreadState *thr) { 633 // Thread safe because done before all threads exist. 634 if (is_initialized) 635 return; 636 is_initialized = true; 637 // We are not ready to handle interceptors yet. 638 ScopedIgnoreInterceptors ignore; 639 SanitizerToolName = "ThreadSanitizer"; 640 // Install tool-specific callbacks in sanitizer_common. 641 SetCheckUnwindCallback(CheckUnwind); 642 643 ctx = new(ctx_placeholder) Context; 644 const char *env_name = SANITIZER_GO ? "GORACE" : "TSAN_OPTIONS"; 645 const char *options = GetEnv(env_name); 646 CacheBinaryName(); 647 CheckASLR(); 648 InitializeFlags(&ctx->flags, options, env_name); 649 AvoidCVE_2016_2143(); 650 __sanitizer::InitializePlatformEarly(); 651 __tsan::InitializePlatformEarly(); 652 653 #if !SANITIZER_GO 654 InitializeAllocator(); 655 ReplaceSystemMalloc(); 656 #endif 657 if (common_flags()->detect_deadlocks) 658 ctx->dd = DDetector::Create(flags()); 659 Processor *proc = ProcCreate(); 660 ProcWire(proc, thr); 661 InitializeInterceptors(); 662 InitializePlatform(); 663 InitializeDynamicAnnotations(); 664 #if !SANITIZER_GO 665 InitializeShadowMemory(); 666 InitializeAllocatorLate(); 667 InstallDeadlySignalHandlers(TsanOnDeadlySignal); 668 #endif 669 // Setup correct file descriptor for error reports. 670 __sanitizer_set_report_path(common_flags()->log_path); 671 InitializeSuppressions(); 672 #if !SANITIZER_GO 673 InitializeLibIgnore(); 674 Symbolizer::GetOrInit()->AddHooks(EnterSymbolizer, ExitSymbolizer); 675 #endif 676 677 VPrintf(1, "***** Running under ThreadSanitizer v3 (pid %d) *****\n", 678 (int)internal_getpid()); 679 680 // Initialize thread 0. 681 Tid tid = ThreadCreate(nullptr, 0, 0, true); 682 CHECK_EQ(tid, kMainTid); 683 ThreadStart(thr, tid, GetTid(), ThreadType::Regular); 684 #if TSAN_CONTAINS_UBSAN 685 __ubsan::InitAsPlugin(); 686 #endif 687 688 #if !SANITIZER_GO 689 Symbolizer::LateInitialize(); 690 if (InitializeMemoryProfiler() || flags()->force_background_thread) 691 MaybeSpawnBackgroundThread(); 692 #endif 693 ctx->initialized = true; 694 695 if (flags()->stop_on_start) { 696 Printf("ThreadSanitizer is suspended at startup (pid %d)." 697 " Call __tsan_resume().\n", 698 (int)internal_getpid()); 699 while (__tsan_resumed == 0) {} 700 } 701 702 OnInitialize(); 703 } 704 705 void MaybeSpawnBackgroundThread() { 706 // On MIPS, TSan initialization is run before 707 // __pthread_initialize_minimal_internal() is finished, so we can not spawn 708 // new threads. 709 #if !SANITIZER_GO && !defined(__mips__) 710 static atomic_uint32_t bg_thread = {}; 711 if (atomic_load(&bg_thread, memory_order_relaxed) == 0 && 712 atomic_exchange(&bg_thread, 1, memory_order_relaxed) == 0) { 713 StartBackgroundThread(); 714 SetSandboxingCallback(StopBackgroundThread); 715 } 716 #endif 717 } 718 719 int Finalize(ThreadState *thr) { 720 bool failed = false; 721 722 #if !SANITIZER_GO 723 if (common_flags()->print_module_map == 1) 724 DumpProcessMap(); 725 #endif 726 727 if (flags()->atexit_sleep_ms > 0 && ThreadCount(thr) > 1) 728 internal_usleep(u64(flags()->atexit_sleep_ms) * 1000); 729 730 { 731 // Wait for pending reports. 732 ScopedErrorReportLock lock; 733 } 734 735 #if !SANITIZER_GO 736 if (Verbosity()) AllocatorPrintStats(); 737 #endif 738 739 ThreadFinalize(thr); 740 741 if (ctx->nreported) { 742 failed = true; 743 #if !SANITIZER_GO 744 Printf("ThreadSanitizer: reported %d warnings\n", ctx->nreported); 745 #else 746 Printf("Found %d data race(s)\n", ctx->nreported); 747 #endif 748 } 749 750 if (common_flags()->print_suppressions) 751 PrintMatchedSuppressions(); 752 753 failed = OnFinalize(failed); 754 755 return failed ? common_flags()->exitcode : 0; 756 } 757 758 #if !SANITIZER_GO 759 void ForkBefore(ThreadState* thr, uptr pc) SANITIZER_NO_THREAD_SAFETY_ANALYSIS { 760 GlobalProcessorLock(); 761 // Detaching from the slot makes OnUserFree skip writing to the shadow. 762 // The slot will be locked so any attempts to use it will deadlock anyway. 763 SlotDetach(thr); 764 for (auto& slot : ctx->slots) slot.mtx.Lock(); 765 ctx->thread_registry.Lock(); 766 ctx->slot_mtx.Lock(); 767 ScopedErrorReportLock::Lock(); 768 AllocatorLock(); 769 // Suppress all reports in the pthread_atfork callbacks. 770 // Reports will deadlock on the report_mtx. 771 // We could ignore sync operations as well, 772 // but so far it's unclear if it will do more good or harm. 773 // Unnecessarily ignoring things can lead to false positives later. 774 thr->suppress_reports++; 775 // On OS X, REAL(fork) can call intercepted functions (OSSpinLockLock), and 776 // we'll assert in CheckNoLocks() unless we ignore interceptors. 777 // On OS X libSystem_atfork_prepare/parent/child callbacks are called 778 // after/before our callbacks and they call free. 779 thr->ignore_interceptors++; 780 // Disables memory write in OnUserAlloc/Free. 781 thr->ignore_reads_and_writes++; 782 783 __tsan_test_only_on_fork(); 784 } 785 786 static void ForkAfter(ThreadState* thr) SANITIZER_NO_THREAD_SAFETY_ANALYSIS { 787 thr->suppress_reports--; // Enabled in ForkBefore. 788 thr->ignore_interceptors--; 789 thr->ignore_reads_and_writes--; 790 AllocatorUnlock(); 791 ScopedErrorReportLock::Unlock(); 792 ctx->slot_mtx.Unlock(); 793 ctx->thread_registry.Unlock(); 794 for (auto& slot : ctx->slots) slot.mtx.Unlock(); 795 SlotAttachAndLock(thr); 796 SlotUnlock(thr); 797 GlobalProcessorUnlock(); 798 } 799 800 void ForkParentAfter(ThreadState* thr, uptr pc) { ForkAfter(thr); } 801 802 void ForkChildAfter(ThreadState* thr, uptr pc, bool start_thread) { 803 ForkAfter(thr); 804 u32 nthread = ctx->thread_registry.OnFork(thr->tid); 805 VPrintf(1, 806 "ThreadSanitizer: forked new process with pid %d," 807 " parent had %d threads\n", 808 (int)internal_getpid(), (int)nthread); 809 if (nthread == 1) { 810 if (start_thread) 811 StartBackgroundThread(); 812 } else { 813 // We've just forked a multi-threaded process. We cannot reasonably function 814 // after that (some mutexes may be locked before fork). So just enable 815 // ignores for everything in the hope that we will exec soon. 816 ctx->after_multithreaded_fork = true; 817 thr->ignore_interceptors++; 818 thr->suppress_reports++; 819 ThreadIgnoreBegin(thr, pc); 820 ThreadIgnoreSyncBegin(thr, pc); 821 } 822 } 823 #endif 824 825 #if SANITIZER_GO 826 NOINLINE 827 void GrowShadowStack(ThreadState *thr) { 828 const int sz = thr->shadow_stack_end - thr->shadow_stack; 829 const int newsz = 2 * sz; 830 auto *newstack = (uptr *)Alloc(newsz * sizeof(uptr)); 831 internal_memcpy(newstack, thr->shadow_stack, sz * sizeof(uptr)); 832 Free(thr->shadow_stack); 833 thr->shadow_stack = newstack; 834 thr->shadow_stack_pos = newstack + sz; 835 thr->shadow_stack_end = newstack + newsz; 836 } 837 #endif 838 839 StackID CurrentStackId(ThreadState *thr, uptr pc) { 840 #if !SANITIZER_GO 841 if (!thr->is_inited) // May happen during bootstrap. 842 return kInvalidStackID; 843 #endif 844 if (pc != 0) { 845 #if !SANITIZER_GO 846 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end); 847 #else 848 if (thr->shadow_stack_pos == thr->shadow_stack_end) 849 GrowShadowStack(thr); 850 #endif 851 thr->shadow_stack_pos[0] = pc; 852 thr->shadow_stack_pos++; 853 } 854 StackID id = StackDepotPut( 855 StackTrace(thr->shadow_stack, thr->shadow_stack_pos - thr->shadow_stack)); 856 if (pc != 0) 857 thr->shadow_stack_pos--; 858 return id; 859 } 860 861 static bool TraceSkipGap(ThreadState* thr) { 862 Trace *trace = &thr->tctx->trace; 863 Event *pos = reinterpret_cast<Event *>(atomic_load_relaxed(&thr->trace_pos)); 864 DCHECK_EQ(reinterpret_cast<uptr>(pos + 1) & TracePart::kAlignment, 0); 865 auto *part = trace->parts.Back(); 866 DPrintf("#%d: TraceSwitchPart enter trace=%p parts=%p-%p pos=%p\n", thr->tid, 867 trace, trace->parts.Front(), part, pos); 868 if (!part) 869 return false; 870 // We can get here when we still have space in the current trace part. 871 // The fast-path check in TraceAcquire has false positives in the middle of 872 // the part. Check if we are indeed at the end of the current part or not, 873 // and fill any gaps with NopEvent's. 874 Event* end = &part->events[TracePart::kSize]; 875 DCHECK_GE(pos, &part->events[0]); 876 DCHECK_LE(pos, end); 877 if (pos + 1 < end) { 878 if ((reinterpret_cast<uptr>(pos) & TracePart::kAlignment) == 879 TracePart::kAlignment) 880 *pos++ = NopEvent; 881 *pos++ = NopEvent; 882 DCHECK_LE(pos + 2, end); 883 atomic_store_relaxed(&thr->trace_pos, reinterpret_cast<uptr>(pos)); 884 return true; 885 } 886 // We are indeed at the end. 887 for (; pos < end; pos++) *pos = NopEvent; 888 return false; 889 } 890 891 NOINLINE 892 void TraceSwitchPart(ThreadState* thr) { 893 if (TraceSkipGap(thr)) 894 return; 895 #if !SANITIZER_GO 896 if (ctx->after_multithreaded_fork) { 897 // We just need to survive till exec. 898 TracePart* part = thr->tctx->trace.parts.Back(); 899 if (part) { 900 atomic_store_relaxed(&thr->trace_pos, 901 reinterpret_cast<uptr>(&part->events[0])); 902 return; 903 } 904 } 905 #endif 906 TraceSwitchPartImpl(thr); 907 } 908 909 void TraceSwitchPartImpl(ThreadState* thr) { 910 SlotLocker locker(thr, true); 911 Trace* trace = &thr->tctx->trace; 912 TracePart* part = TracePartAlloc(thr); 913 part->trace = trace; 914 thr->trace_prev_pc = 0; 915 TracePart* recycle = nullptr; 916 // Keep roughly half of parts local to the thread 917 // (not queued into the recycle queue). 918 uptr local_parts = (Trace::kMinParts + flags()->history_size + 1) / 2; 919 { 920 Lock lock(&trace->mtx); 921 if (trace->parts.Empty()) 922 trace->local_head = part; 923 if (trace->parts.Size() >= local_parts) { 924 recycle = trace->local_head; 925 trace->local_head = trace->parts.Next(recycle); 926 } 927 trace->parts.PushBack(part); 928 atomic_store_relaxed(&thr->trace_pos, 929 reinterpret_cast<uptr>(&part->events[0])); 930 } 931 // Make this part self-sufficient by restoring the current stack 932 // and mutex set in the beginning of the trace. 933 TraceTime(thr); 934 { 935 // Pathologically large stacks may not fit into the part. 936 // In these cases we log only fixed number of top frames. 937 const uptr kMaxFrames = 1000; 938 // Check that kMaxFrames won't consume the whole part. 939 static_assert(kMaxFrames < TracePart::kSize / 2, "kMaxFrames is too big"); 940 uptr* pos = Max(&thr->shadow_stack[0], thr->shadow_stack_pos - kMaxFrames); 941 for (; pos < thr->shadow_stack_pos; pos++) { 942 if (TryTraceFunc(thr, *pos)) 943 continue; 944 CHECK(TraceSkipGap(thr)); 945 CHECK(TryTraceFunc(thr, *pos)); 946 } 947 } 948 for (uptr i = 0; i < thr->mset.Size(); i++) { 949 MutexSet::Desc d = thr->mset.Get(i); 950 for (uptr i = 0; i < d.count; i++) 951 TraceMutexLock(thr, d.write ? EventType::kLock : EventType::kRLock, 0, 952 d.addr, d.stack_id); 953 } 954 { 955 Lock lock(&ctx->slot_mtx); 956 // There is a small chance that the slot may be not queued at this point. 957 // This can happen if the slot has kEpochLast epoch and another thread 958 // in FindSlotAndLock discovered that it's exhausted and removed it from 959 // the slot queue. kEpochLast can happen in 2 cases: (1) if TraceSwitchPart 960 // was called with the slot locked and epoch already at kEpochLast, 961 // or (2) if we've acquired a new slot in SlotLock in the beginning 962 // of the function and the slot was at kEpochLast - 1, so after increment 963 // in SlotAttachAndLock it become kEpochLast. 964 if (ctx->slot_queue.Queued(thr->slot)) { 965 ctx->slot_queue.Remove(thr->slot); 966 ctx->slot_queue.PushBack(thr->slot); 967 } 968 if (recycle) 969 ctx->trace_part_recycle.PushBack(recycle); 970 } 971 DPrintf("#%d: TraceSwitchPart exit parts=%p-%p pos=0x%zx\n", thr->tid, 972 trace->parts.Front(), trace->parts.Back(), 973 atomic_load_relaxed(&thr->trace_pos)); 974 } 975 976 void ThreadIgnoreBegin(ThreadState* thr, uptr pc) { 977 DPrintf("#%d: ThreadIgnoreBegin\n", thr->tid); 978 thr->ignore_reads_and_writes++; 979 CHECK_GT(thr->ignore_reads_and_writes, 0); 980 thr->fast_state.SetIgnoreBit(); 981 #if !SANITIZER_GO 982 if (pc && !ctx->after_multithreaded_fork) 983 thr->mop_ignore_set.Add(CurrentStackId(thr, pc)); 984 #endif 985 } 986 987 void ThreadIgnoreEnd(ThreadState *thr) { 988 DPrintf("#%d: ThreadIgnoreEnd\n", thr->tid); 989 CHECK_GT(thr->ignore_reads_and_writes, 0); 990 thr->ignore_reads_and_writes--; 991 if (thr->ignore_reads_and_writes == 0) { 992 thr->fast_state.ClearIgnoreBit(); 993 #if !SANITIZER_GO 994 thr->mop_ignore_set.Reset(); 995 #endif 996 } 997 } 998 999 #if !SANITIZER_GO 1000 extern "C" SANITIZER_INTERFACE_ATTRIBUTE 1001 uptr __tsan_testonly_shadow_stack_current_size() { 1002 ThreadState *thr = cur_thread(); 1003 return thr->shadow_stack_pos - thr->shadow_stack; 1004 } 1005 #endif 1006 1007 void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc) { 1008 DPrintf("#%d: ThreadIgnoreSyncBegin\n", thr->tid); 1009 thr->ignore_sync++; 1010 CHECK_GT(thr->ignore_sync, 0); 1011 #if !SANITIZER_GO 1012 if (pc && !ctx->after_multithreaded_fork) 1013 thr->sync_ignore_set.Add(CurrentStackId(thr, pc)); 1014 #endif 1015 } 1016 1017 void ThreadIgnoreSyncEnd(ThreadState *thr) { 1018 DPrintf("#%d: ThreadIgnoreSyncEnd\n", thr->tid); 1019 CHECK_GT(thr->ignore_sync, 0); 1020 thr->ignore_sync--; 1021 #if !SANITIZER_GO 1022 if (thr->ignore_sync == 0) 1023 thr->sync_ignore_set.Reset(); 1024 #endif 1025 } 1026 1027 bool MD5Hash::operator==(const MD5Hash &other) const { 1028 return hash[0] == other.hash[0] && hash[1] == other.hash[1]; 1029 } 1030 1031 #if SANITIZER_DEBUG 1032 void build_consistency_debug() {} 1033 #else 1034 void build_consistency_release() {} 1035 #endif 1036 } // namespace __tsan 1037 1038 #if SANITIZER_CHECK_DEADLOCKS 1039 namespace __sanitizer { 1040 using namespace __tsan; 1041 MutexMeta mutex_meta[] = { 1042 {MutexInvalid, "Invalid", {}}, 1043 {MutexThreadRegistry, 1044 "ThreadRegistry", 1045 {MutexTypeSlots, MutexTypeTrace, MutexTypeReport}}, 1046 {MutexTypeReport, "Report", {MutexTypeTrace}}, 1047 {MutexTypeSyncVar, "SyncVar", {MutexTypeReport, MutexTypeTrace}}, 1048 {MutexTypeAnnotations, "Annotations", {}}, 1049 {MutexTypeAtExit, "AtExit", {}}, 1050 {MutexTypeFired, "Fired", {MutexLeaf}}, 1051 {MutexTypeRacy, "Racy", {MutexLeaf}}, 1052 {MutexTypeGlobalProc, "GlobalProc", {MutexTypeSlot, MutexTypeSlots}}, 1053 {MutexTypeInternalAlloc, "InternalAlloc", {MutexLeaf}}, 1054 {MutexTypeTrace, "Trace", {}}, 1055 {MutexTypeSlot, 1056 "Slot", 1057 {MutexMulti, MutexTypeTrace, MutexTypeSyncVar, MutexThreadRegistry, 1058 MutexTypeSlots}}, 1059 {MutexTypeSlots, "Slots", {MutexTypeTrace, MutexTypeReport}}, 1060 {}, 1061 }; 1062 1063 void PrintMutexPC(uptr pc) { StackTrace(&pc, 1).Print(); } 1064 1065 } // namespace __sanitizer 1066 #endif 1067