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 // Re-exec ourselves if we need to set additional env or command line args. 655 MaybeReexec(); 656 657 InitializeAllocator(); 658 ReplaceSystemMalloc(); 659 #endif 660 if (common_flags()->detect_deadlocks) 661 ctx->dd = DDetector::Create(flags()); 662 Processor *proc = ProcCreate(); 663 ProcWire(proc, thr); 664 InitializeInterceptors(); 665 InitializePlatform(); 666 InitializeDynamicAnnotations(); 667 #if !SANITIZER_GO 668 InitializeShadowMemory(); 669 InitializeAllocatorLate(); 670 InstallDeadlySignalHandlers(TsanOnDeadlySignal); 671 #endif 672 // Setup correct file descriptor for error reports. 673 __sanitizer_set_report_path(common_flags()->log_path); 674 InitializeSuppressions(); 675 #if !SANITIZER_GO 676 InitializeLibIgnore(); 677 Symbolizer::GetOrInit()->AddHooks(EnterSymbolizer, ExitSymbolizer); 678 #endif 679 680 VPrintf(1, "***** Running under ThreadSanitizer v3 (pid %d) *****\n", 681 (int)internal_getpid()); 682 683 // Initialize thread 0. 684 Tid tid = ThreadCreate(nullptr, 0, 0, true); 685 CHECK_EQ(tid, kMainTid); 686 ThreadStart(thr, tid, GetTid(), ThreadType::Regular); 687 #if TSAN_CONTAINS_UBSAN 688 __ubsan::InitAsPlugin(); 689 #endif 690 691 #if !SANITIZER_GO 692 Symbolizer::LateInitialize(); 693 if (InitializeMemoryProfiler() || flags()->force_background_thread) 694 MaybeSpawnBackgroundThread(); 695 #endif 696 ctx->initialized = true; 697 698 if (flags()->stop_on_start) { 699 Printf("ThreadSanitizer is suspended at startup (pid %d)." 700 " Call __tsan_resume().\n", 701 (int)internal_getpid()); 702 while (__tsan_resumed == 0) {} 703 } 704 705 OnInitialize(); 706 } 707 708 void MaybeSpawnBackgroundThread() { 709 // On MIPS, TSan initialization is run before 710 // __pthread_initialize_minimal_internal() is finished, so we can not spawn 711 // new threads. 712 #if !SANITIZER_GO && !defined(__mips__) 713 static atomic_uint32_t bg_thread = {}; 714 if (atomic_load(&bg_thread, memory_order_relaxed) == 0 && 715 atomic_exchange(&bg_thread, 1, memory_order_relaxed) == 0) { 716 StartBackgroundThread(); 717 SetSandboxingCallback(StopBackgroundThread); 718 } 719 #endif 720 } 721 722 int Finalize(ThreadState *thr) { 723 bool failed = false; 724 725 #if !SANITIZER_GO 726 if (common_flags()->print_module_map == 1) 727 DumpProcessMap(); 728 #endif 729 730 if (flags()->atexit_sleep_ms > 0 && ThreadCount(thr) > 1) 731 internal_usleep(u64(flags()->atexit_sleep_ms) * 1000); 732 733 { 734 // Wait for pending reports. 735 ScopedErrorReportLock lock; 736 } 737 738 #if !SANITIZER_GO 739 if (Verbosity()) AllocatorPrintStats(); 740 #endif 741 742 ThreadFinalize(thr); 743 744 if (ctx->nreported) { 745 failed = true; 746 #if !SANITIZER_GO 747 Printf("ThreadSanitizer: reported %d warnings\n", ctx->nreported); 748 #else 749 Printf("Found %d data race(s)\n", ctx->nreported); 750 #endif 751 } 752 753 if (common_flags()->print_suppressions) 754 PrintMatchedSuppressions(); 755 756 failed = OnFinalize(failed); 757 758 return failed ? common_flags()->exitcode : 0; 759 } 760 761 #if !SANITIZER_GO 762 void ForkBefore(ThreadState* thr, uptr pc) SANITIZER_NO_THREAD_SAFETY_ANALYSIS { 763 GlobalProcessorLock(); 764 // Detaching from the slot makes OnUserFree skip writing to the shadow. 765 // The slot will be locked so any attempts to use it will deadlock anyway. 766 SlotDetach(thr); 767 for (auto& slot : ctx->slots) slot.mtx.Lock(); 768 ctx->thread_registry.Lock(); 769 ctx->slot_mtx.Lock(); 770 ScopedErrorReportLock::Lock(); 771 AllocatorLock(); 772 // Suppress all reports in the pthread_atfork callbacks. 773 // Reports will deadlock on the report_mtx. 774 // We could ignore sync operations as well, 775 // but so far it's unclear if it will do more good or harm. 776 // Unnecessarily ignoring things can lead to false positives later. 777 thr->suppress_reports++; 778 // On OS X, REAL(fork) can call intercepted functions (OSSpinLockLock), and 779 // we'll assert in CheckNoLocks() unless we ignore interceptors. 780 // On OS X libSystem_atfork_prepare/parent/child callbacks are called 781 // after/before our callbacks and they call free. 782 thr->ignore_interceptors++; 783 // Disables memory write in OnUserAlloc/Free. 784 thr->ignore_reads_and_writes++; 785 786 __tsan_test_only_on_fork(); 787 } 788 789 static void ForkAfter(ThreadState* thr) SANITIZER_NO_THREAD_SAFETY_ANALYSIS { 790 thr->suppress_reports--; // Enabled in ForkBefore. 791 thr->ignore_interceptors--; 792 thr->ignore_reads_and_writes--; 793 AllocatorUnlock(); 794 ScopedErrorReportLock::Unlock(); 795 ctx->slot_mtx.Unlock(); 796 ctx->thread_registry.Unlock(); 797 for (auto& slot : ctx->slots) slot.mtx.Unlock(); 798 SlotAttachAndLock(thr); 799 SlotUnlock(thr); 800 GlobalProcessorUnlock(); 801 } 802 803 void ForkParentAfter(ThreadState* thr, uptr pc) { ForkAfter(thr); } 804 805 void ForkChildAfter(ThreadState* thr, uptr pc, bool start_thread) { 806 ForkAfter(thr); 807 u32 nthread = ctx->thread_registry.OnFork(thr->tid); 808 VPrintf(1, 809 "ThreadSanitizer: forked new process with pid %d," 810 " parent had %d threads\n", 811 (int)internal_getpid(), (int)nthread); 812 if (nthread == 1) { 813 if (start_thread) 814 StartBackgroundThread(); 815 } else { 816 // We've just forked a multi-threaded process. We cannot reasonably function 817 // after that (some mutexes may be locked before fork). So just enable 818 // ignores for everything in the hope that we will exec soon. 819 ctx->after_multithreaded_fork = true; 820 thr->ignore_interceptors++; 821 thr->suppress_reports++; 822 ThreadIgnoreBegin(thr, pc); 823 ThreadIgnoreSyncBegin(thr, pc); 824 } 825 } 826 #endif 827 828 #if SANITIZER_GO 829 NOINLINE 830 void GrowShadowStack(ThreadState *thr) { 831 const int sz = thr->shadow_stack_end - thr->shadow_stack; 832 const int newsz = 2 * sz; 833 auto *newstack = (uptr *)Alloc(newsz * sizeof(uptr)); 834 internal_memcpy(newstack, thr->shadow_stack, sz * sizeof(uptr)); 835 Free(thr->shadow_stack); 836 thr->shadow_stack = newstack; 837 thr->shadow_stack_pos = newstack + sz; 838 thr->shadow_stack_end = newstack + newsz; 839 } 840 #endif 841 842 StackID CurrentStackId(ThreadState *thr, uptr pc) { 843 #if !SANITIZER_GO 844 if (!thr->is_inited) // May happen during bootstrap. 845 return kInvalidStackID; 846 #endif 847 if (pc != 0) { 848 #if !SANITIZER_GO 849 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end); 850 #else 851 if (thr->shadow_stack_pos == thr->shadow_stack_end) 852 GrowShadowStack(thr); 853 #endif 854 thr->shadow_stack_pos[0] = pc; 855 thr->shadow_stack_pos++; 856 } 857 StackID id = StackDepotPut( 858 StackTrace(thr->shadow_stack, thr->shadow_stack_pos - thr->shadow_stack)); 859 if (pc != 0) 860 thr->shadow_stack_pos--; 861 return id; 862 } 863 864 static bool TraceSkipGap(ThreadState* thr) { 865 Trace *trace = &thr->tctx->trace; 866 Event *pos = reinterpret_cast<Event *>(atomic_load_relaxed(&thr->trace_pos)); 867 DCHECK_EQ(reinterpret_cast<uptr>(pos + 1) & TracePart::kAlignment, 0); 868 auto *part = trace->parts.Back(); 869 DPrintf("#%d: TraceSwitchPart enter trace=%p parts=%p-%p pos=%p\n", thr->tid, 870 trace, trace->parts.Front(), part, pos); 871 if (!part) 872 return false; 873 // We can get here when we still have space in the current trace part. 874 // The fast-path check in TraceAcquire has false positives in the middle of 875 // the part. Check if we are indeed at the end of the current part or not, 876 // and fill any gaps with NopEvent's. 877 Event* end = &part->events[TracePart::kSize]; 878 DCHECK_GE(pos, &part->events[0]); 879 DCHECK_LE(pos, end); 880 if (pos + 1 < end) { 881 if ((reinterpret_cast<uptr>(pos) & TracePart::kAlignment) == 882 TracePart::kAlignment) 883 *pos++ = NopEvent; 884 *pos++ = NopEvent; 885 DCHECK_LE(pos + 2, end); 886 atomic_store_relaxed(&thr->trace_pos, reinterpret_cast<uptr>(pos)); 887 return true; 888 } 889 // We are indeed at the end. 890 for (; pos < end; pos++) *pos = NopEvent; 891 return false; 892 } 893 894 NOINLINE 895 void TraceSwitchPart(ThreadState* thr) { 896 if (TraceSkipGap(thr)) 897 return; 898 #if !SANITIZER_GO 899 if (ctx->after_multithreaded_fork) { 900 // We just need to survive till exec. 901 TracePart* part = thr->tctx->trace.parts.Back(); 902 if (part) { 903 atomic_store_relaxed(&thr->trace_pos, 904 reinterpret_cast<uptr>(&part->events[0])); 905 return; 906 } 907 } 908 #endif 909 TraceSwitchPartImpl(thr); 910 } 911 912 void TraceSwitchPartImpl(ThreadState* thr) { 913 SlotLocker locker(thr, true); 914 Trace* trace = &thr->tctx->trace; 915 TracePart* part = TracePartAlloc(thr); 916 part->trace = trace; 917 thr->trace_prev_pc = 0; 918 TracePart* recycle = nullptr; 919 // Keep roughly half of parts local to the thread 920 // (not queued into the recycle queue). 921 uptr local_parts = (Trace::kMinParts + flags()->history_size + 1) / 2; 922 { 923 Lock lock(&trace->mtx); 924 if (trace->parts.Empty()) 925 trace->local_head = part; 926 if (trace->parts.Size() >= local_parts) { 927 recycle = trace->local_head; 928 trace->local_head = trace->parts.Next(recycle); 929 } 930 trace->parts.PushBack(part); 931 atomic_store_relaxed(&thr->trace_pos, 932 reinterpret_cast<uptr>(&part->events[0])); 933 } 934 // Make this part self-sufficient by restoring the current stack 935 // and mutex set in the beginning of the trace. 936 TraceTime(thr); 937 { 938 // Pathologically large stacks may not fit into the part. 939 // In these cases we log only fixed number of top frames. 940 const uptr kMaxFrames = 1000; 941 // Check that kMaxFrames won't consume the whole part. 942 static_assert(kMaxFrames < TracePart::kSize / 2, "kMaxFrames is too big"); 943 uptr* pos = Max(&thr->shadow_stack[0], thr->shadow_stack_pos - kMaxFrames); 944 for (; pos < thr->shadow_stack_pos; pos++) { 945 if (TryTraceFunc(thr, *pos)) 946 continue; 947 CHECK(TraceSkipGap(thr)); 948 CHECK(TryTraceFunc(thr, *pos)); 949 } 950 } 951 for (uptr i = 0; i < thr->mset.Size(); i++) { 952 MutexSet::Desc d = thr->mset.Get(i); 953 for (uptr i = 0; i < d.count; i++) 954 TraceMutexLock(thr, d.write ? EventType::kLock : EventType::kRLock, 0, 955 d.addr, d.stack_id); 956 } 957 { 958 Lock lock(&ctx->slot_mtx); 959 // There is a small chance that the slot may be not queued at this point. 960 // This can happen if the slot has kEpochLast epoch and another thread 961 // in FindSlotAndLock discovered that it's exhausted and removed it from 962 // the slot queue. kEpochLast can happen in 2 cases: (1) if TraceSwitchPart 963 // was called with the slot locked and epoch already at kEpochLast, 964 // or (2) if we've acquired a new slot in SlotLock in the beginning 965 // of the function and the slot was at kEpochLast - 1, so after increment 966 // in SlotAttachAndLock it become kEpochLast. 967 if (ctx->slot_queue.Queued(thr->slot)) { 968 ctx->slot_queue.Remove(thr->slot); 969 ctx->slot_queue.PushBack(thr->slot); 970 } 971 if (recycle) 972 ctx->trace_part_recycle.PushBack(recycle); 973 } 974 DPrintf("#%d: TraceSwitchPart exit parts=%p-%p pos=0x%zx\n", thr->tid, 975 trace->parts.Front(), trace->parts.Back(), 976 atomic_load_relaxed(&thr->trace_pos)); 977 } 978 979 void ThreadIgnoreBegin(ThreadState* thr, uptr pc) { 980 DPrintf("#%d: ThreadIgnoreBegin\n", thr->tid); 981 thr->ignore_reads_and_writes++; 982 CHECK_GT(thr->ignore_reads_and_writes, 0); 983 thr->fast_state.SetIgnoreBit(); 984 #if !SANITIZER_GO 985 if (pc && !ctx->after_multithreaded_fork) 986 thr->mop_ignore_set.Add(CurrentStackId(thr, pc)); 987 #endif 988 } 989 990 void ThreadIgnoreEnd(ThreadState *thr) { 991 DPrintf("#%d: ThreadIgnoreEnd\n", thr->tid); 992 CHECK_GT(thr->ignore_reads_and_writes, 0); 993 thr->ignore_reads_and_writes--; 994 if (thr->ignore_reads_and_writes == 0) { 995 thr->fast_state.ClearIgnoreBit(); 996 #if !SANITIZER_GO 997 thr->mop_ignore_set.Reset(); 998 #endif 999 } 1000 } 1001 1002 #if !SANITIZER_GO 1003 extern "C" SANITIZER_INTERFACE_ATTRIBUTE 1004 uptr __tsan_testonly_shadow_stack_current_size() { 1005 ThreadState *thr = cur_thread(); 1006 return thr->shadow_stack_pos - thr->shadow_stack; 1007 } 1008 #endif 1009 1010 void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc) { 1011 DPrintf("#%d: ThreadIgnoreSyncBegin\n", thr->tid); 1012 thr->ignore_sync++; 1013 CHECK_GT(thr->ignore_sync, 0); 1014 #if !SANITIZER_GO 1015 if (pc && !ctx->after_multithreaded_fork) 1016 thr->sync_ignore_set.Add(CurrentStackId(thr, pc)); 1017 #endif 1018 } 1019 1020 void ThreadIgnoreSyncEnd(ThreadState *thr) { 1021 DPrintf("#%d: ThreadIgnoreSyncEnd\n", thr->tid); 1022 CHECK_GT(thr->ignore_sync, 0); 1023 thr->ignore_sync--; 1024 #if !SANITIZER_GO 1025 if (thr->ignore_sync == 0) 1026 thr->sync_ignore_set.Reset(); 1027 #endif 1028 } 1029 1030 bool MD5Hash::operator==(const MD5Hash &other) const { 1031 return hash[0] == other.hash[0] && hash[1] == other.hash[1]; 1032 } 1033 1034 #if SANITIZER_DEBUG 1035 void build_consistency_debug() {} 1036 #else 1037 void build_consistency_release() {} 1038 #endif 1039 } // namespace __tsan 1040 1041 #if SANITIZER_CHECK_DEADLOCKS 1042 namespace __sanitizer { 1043 using namespace __tsan; 1044 MutexMeta mutex_meta[] = { 1045 {MutexInvalid, "Invalid", {}}, 1046 {MutexThreadRegistry, 1047 "ThreadRegistry", 1048 {MutexTypeSlots, MutexTypeTrace, MutexTypeReport}}, 1049 {MutexTypeReport, "Report", {MutexTypeTrace}}, 1050 {MutexTypeSyncVar, "SyncVar", {MutexTypeReport, MutexTypeTrace}}, 1051 {MutexTypeAnnotations, "Annotations", {}}, 1052 {MutexTypeAtExit, "AtExit", {}}, 1053 {MutexTypeFired, "Fired", {MutexLeaf}}, 1054 {MutexTypeRacy, "Racy", {MutexLeaf}}, 1055 {MutexTypeGlobalProc, "GlobalProc", {MutexTypeSlot, MutexTypeSlots}}, 1056 {MutexTypeInternalAlloc, "InternalAlloc", {MutexLeaf}}, 1057 {MutexTypeTrace, "Trace", {}}, 1058 {MutexTypeSlot, 1059 "Slot", 1060 {MutexMulti, MutexTypeTrace, MutexTypeSyncVar, MutexThreadRegistry, 1061 MutexTypeSlots}}, 1062 {MutexTypeSlots, "Slots", {MutexTypeTrace, MutexTypeReport}}, 1063 {}, 1064 }; 1065 1066 void PrintMutexPC(uptr pc) { StackTrace(&pc, 1).Print(); } 1067 1068 } // namespace __sanitizer 1069 #endif 1070