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