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 "sanitizer_common/sanitizer_atomic.h" 15 #include "sanitizer_common/sanitizer_common.h" 16 #include "sanitizer_common/sanitizer_file.h" 17 #include "sanitizer_common/sanitizer_libc.h" 18 #include "sanitizer_common/sanitizer_stackdepot.h" 19 #include "sanitizer_common/sanitizer_placement_new.h" 20 #include "sanitizer_common/sanitizer_symbolizer.h" 21 #include "tsan_defs.h" 22 #include "tsan_platform.h" 23 #include "tsan_rtl.h" 24 #include "tsan_mman.h" 25 #include "tsan_suppressions.h" 26 #include "tsan_symbolize.h" 27 #include "ubsan/ubsan_init.h" 28 29 #ifdef __SSE3__ 30 // <emmintrin.h> transitively includes <stdlib.h>, 31 // and it's prohibited to include std headers into tsan runtime. 32 // So we do this dirty trick. 33 #define _MM_MALLOC_H_INCLUDED 34 #define __MM_MALLOC_H 35 #include <emmintrin.h> 36 typedef __m128i m128; 37 #endif 38 39 volatile int __tsan_resumed = 0; 40 41 extern "C" void __tsan_resume() { 42 __tsan_resumed = 1; 43 } 44 45 namespace __tsan { 46 47 #if !SANITIZER_GO && !SANITIZER_MAC 48 __attribute__((tls_model("initial-exec"))) 49 THREADLOCAL char cur_thread_placeholder[sizeof(ThreadState)] ALIGNED(64); 50 #endif 51 static char ctx_placeholder[sizeof(Context)] ALIGNED(64); 52 Context *ctx; 53 54 // Can be overriden by a front-end. 55 #ifdef TSAN_EXTERNAL_HOOKS 56 bool OnFinalize(bool failed); 57 void OnInitialize(); 58 #else 59 SANITIZER_WEAK_CXX_DEFAULT_IMPL 60 bool OnFinalize(bool failed) { 61 return failed; 62 } 63 SANITIZER_WEAK_CXX_DEFAULT_IMPL 64 void OnInitialize() {} 65 #endif 66 67 static char thread_registry_placeholder[sizeof(ThreadRegistry)]; 68 69 static ThreadContextBase *CreateThreadContext(u32 tid) { 70 // Map thread trace when context is created. 71 char name[50]; 72 internal_snprintf(name, sizeof(name), "trace %u", tid); 73 MapThreadTrace(GetThreadTrace(tid), TraceSize() * sizeof(Event), name); 74 const uptr hdr = GetThreadTraceHeader(tid); 75 internal_snprintf(name, sizeof(name), "trace header %u", tid); 76 MapThreadTrace(hdr, sizeof(Trace), name); 77 new((void*)hdr) Trace(); 78 // We are going to use only a small part of the trace with the default 79 // value of history_size. However, the constructor writes to the whole trace. 80 // Release the unused part. 81 uptr hdr_end = hdr + sizeof(Trace); 82 hdr_end -= sizeof(TraceHeader) * (kTraceParts - TraceParts()); 83 hdr_end = RoundUp(hdr_end, GetPageSizeCached()); 84 if (hdr_end < hdr + sizeof(Trace)) { 85 ReleaseMemoryPagesToOS(hdr_end, hdr + sizeof(Trace)); 86 uptr unused = hdr + sizeof(Trace) - hdr_end; 87 if (hdr_end != (uptr)MmapFixedNoAccess(hdr_end, unused)) { 88 Report("ThreadSanitizer: failed to mprotect(%p, %p)\n", 89 hdr_end, unused); 90 CHECK("unable to mprotect" && 0); 91 } 92 } 93 void *mem = internal_alloc(MBlockThreadContex, sizeof(ThreadContext)); 94 return new(mem) ThreadContext(tid); 95 } 96 97 #if !SANITIZER_GO 98 static const u32 kThreadQuarantineSize = 16; 99 #else 100 static const u32 kThreadQuarantineSize = 64; 101 #endif 102 103 Context::Context() 104 : initialized() 105 , report_mtx(MutexTypeReport, StatMtxReport) 106 , nreported() 107 , nmissed_expected() 108 , thread_registry(new(thread_registry_placeholder) ThreadRegistry( 109 CreateThreadContext, kMaxTid, kThreadQuarantineSize, kMaxTidReuse)) 110 , racy_mtx(MutexTypeRacy, StatMtxRacy) 111 , racy_stacks() 112 , racy_addresses() 113 , fired_suppressions_mtx(MutexTypeFired, StatMtxFired) 114 , clock_alloc("clock allocator") { 115 fired_suppressions.reserve(8); 116 } 117 118 // The objects are allocated in TLS, so one may rely on zero-initialization. 119 ThreadState::ThreadState(Context *ctx, int tid, int unique_id, u64 epoch, 120 unsigned reuse_count, 121 uptr stk_addr, uptr stk_size, 122 uptr tls_addr, uptr tls_size) 123 : fast_state(tid, epoch) 124 // Do not touch these, rely on zero initialization, 125 // they may be accessed before the ctor. 126 // , ignore_reads_and_writes() 127 // , ignore_interceptors() 128 , clock(tid, reuse_count) 129 #if !SANITIZER_GO 130 , jmp_bufs() 131 #endif 132 , tid(tid) 133 , unique_id(unique_id) 134 , stk_addr(stk_addr) 135 , stk_size(stk_size) 136 , tls_addr(tls_addr) 137 , tls_size(tls_size) 138 #if !SANITIZER_GO 139 , last_sleep_clock(tid) 140 #endif 141 { 142 } 143 144 #if !SANITIZER_GO 145 static void MemoryProfiler(Context *ctx, fd_t fd, int i) { 146 uptr n_threads; 147 uptr n_running_threads; 148 ctx->thread_registry->GetNumberOfThreads(&n_threads, &n_running_threads); 149 InternalMmapVector<char> buf(4096); 150 WriteMemoryProfile(buf.data(), buf.size(), n_threads, n_running_threads); 151 WriteToFile(fd, buf.data(), internal_strlen(buf.data())); 152 } 153 154 static void *BackgroundThread(void *arg) { 155 // This is a non-initialized non-user thread, nothing to see here. 156 // We don't use ScopedIgnoreInterceptors, because we want ignores to be 157 // enabled even when the thread function exits (e.g. during pthread thread 158 // shutdown code). 159 cur_thread_init(); 160 cur_thread()->ignore_interceptors++; 161 const u64 kMs2Ns = 1000 * 1000; 162 163 fd_t mprof_fd = kInvalidFd; 164 if (flags()->profile_memory && flags()->profile_memory[0]) { 165 if (internal_strcmp(flags()->profile_memory, "stdout") == 0) { 166 mprof_fd = 1; 167 } else if (internal_strcmp(flags()->profile_memory, "stderr") == 0) { 168 mprof_fd = 2; 169 } else { 170 InternalScopedString filename; 171 filename.append("%s.%d", flags()->profile_memory, (int)internal_getpid()); 172 fd_t fd = OpenFile(filename.data(), WrOnly); 173 if (fd == kInvalidFd) { 174 Printf("ThreadSanitizer: failed to open memory profile file '%s'\n", 175 filename.data()); 176 } else { 177 mprof_fd = fd; 178 } 179 } 180 } 181 182 u64 last_flush = NanoTime(); 183 uptr last_rss = 0; 184 for (int i = 0; 185 atomic_load(&ctx->stop_background_thread, memory_order_relaxed) == 0; 186 i++) { 187 SleepForMillis(100); 188 u64 now = NanoTime(); 189 190 // Flush memory if requested. 191 if (flags()->flush_memory_ms > 0) { 192 if (last_flush + flags()->flush_memory_ms * kMs2Ns < now) { 193 VPrintf(1, "ThreadSanitizer: periodic memory flush\n"); 194 FlushShadowMemory(); 195 last_flush = NanoTime(); 196 } 197 } 198 // GetRSS can be expensive on huge programs, so don't do it every 100ms. 199 if (flags()->memory_limit_mb > 0) { 200 uptr rss = GetRSS(); 201 uptr limit = uptr(flags()->memory_limit_mb) << 20; 202 VPrintf(1, "ThreadSanitizer: memory flush check" 203 " RSS=%llu LAST=%llu LIMIT=%llu\n", 204 (u64)rss >> 20, (u64)last_rss >> 20, (u64)limit >> 20); 205 if (2 * rss > limit + last_rss) { 206 VPrintf(1, "ThreadSanitizer: flushing memory due to RSS\n"); 207 FlushShadowMemory(); 208 rss = GetRSS(); 209 VPrintf(1, "ThreadSanitizer: memory flushed RSS=%llu\n", (u64)rss>>20); 210 } 211 last_rss = rss; 212 } 213 214 // Write memory profile if requested. 215 if (mprof_fd != kInvalidFd) 216 MemoryProfiler(ctx, mprof_fd, i); 217 218 // Flush symbolizer cache if requested. 219 if (flags()->flush_symbolizer_ms > 0) { 220 u64 last = atomic_load(&ctx->last_symbolize_time_ns, 221 memory_order_relaxed); 222 if (last != 0 && last + flags()->flush_symbolizer_ms * kMs2Ns < now) { 223 Lock l(&ctx->report_mtx); 224 ScopedErrorReportLock l2; 225 SymbolizeFlush(); 226 atomic_store(&ctx->last_symbolize_time_ns, 0, memory_order_relaxed); 227 } 228 } 229 } 230 return nullptr; 231 } 232 233 static void StartBackgroundThread() { 234 ctx->background_thread = internal_start_thread(&BackgroundThread, 0); 235 } 236 237 #ifndef __mips__ 238 static void StopBackgroundThread() { 239 atomic_store(&ctx->stop_background_thread, 1, memory_order_relaxed); 240 internal_join_thread(ctx->background_thread); 241 ctx->background_thread = 0; 242 } 243 #endif 244 #endif 245 246 void DontNeedShadowFor(uptr addr, uptr size) { 247 ReleaseMemoryPagesToOS(MemToShadow(addr), MemToShadow(addr + size)); 248 } 249 250 #if !SANITIZER_GO 251 void UnmapShadow(ThreadState *thr, uptr addr, uptr size) { 252 if (size == 0) return; 253 DontNeedShadowFor(addr, size); 254 ScopedGlobalProcessor sgp; 255 ctx->metamap.ResetRange(thr->proc(), addr, size); 256 } 257 #endif 258 259 void MapShadow(uptr addr, uptr size) { 260 // Global data is not 64K aligned, but there are no adjacent mappings, 261 // so we can get away with unaligned mapping. 262 // CHECK_EQ(addr, addr & ~((64 << 10) - 1)); // windows wants 64K alignment 263 const uptr kPageSize = GetPageSizeCached(); 264 uptr shadow_begin = RoundDownTo((uptr)MemToShadow(addr), kPageSize); 265 uptr shadow_end = RoundUpTo((uptr)MemToShadow(addr + size), kPageSize); 266 if (!MmapFixedSuperNoReserve(shadow_begin, shadow_end - shadow_begin, 267 "shadow")) 268 Die(); 269 270 // Meta shadow is 2:1, so tread carefully. 271 static bool data_mapped = false; 272 static uptr mapped_meta_end = 0; 273 uptr meta_begin = (uptr)MemToMeta(addr); 274 uptr meta_end = (uptr)MemToMeta(addr + size); 275 meta_begin = RoundDownTo(meta_begin, 64 << 10); 276 meta_end = RoundUpTo(meta_end, 64 << 10); 277 if (!data_mapped) { 278 // First call maps data+bss. 279 data_mapped = true; 280 if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin, 281 "meta shadow")) 282 Die(); 283 } else { 284 // Mapping continous heap. 285 // Windows wants 64K alignment. 286 meta_begin = RoundDownTo(meta_begin, 64 << 10); 287 meta_end = RoundUpTo(meta_end, 64 << 10); 288 if (meta_end <= mapped_meta_end) 289 return; 290 if (meta_begin < mapped_meta_end) 291 meta_begin = mapped_meta_end; 292 if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin, 293 "meta shadow")) 294 Die(); 295 mapped_meta_end = meta_end; 296 } 297 VPrintf(2, "mapped meta shadow for (%p-%p) at (%p-%p)\n", 298 addr, addr+size, meta_begin, meta_end); 299 } 300 301 void MapThreadTrace(uptr addr, uptr size, const char *name) { 302 DPrintf("#0: Mapping trace at %p-%p(0x%zx)\n", addr, addr + size, size); 303 CHECK_GE(addr, TraceMemBeg()); 304 CHECK_LE(addr + size, TraceMemEnd()); 305 CHECK_EQ(addr, addr & ~((64 << 10) - 1)); // windows wants 64K alignment 306 if (!MmapFixedSuperNoReserve(addr, size, name)) { 307 Printf("FATAL: ThreadSanitizer can not mmap thread trace (%p/%p)\n", 308 addr, size); 309 Die(); 310 } 311 } 312 313 static void CheckShadowMapping() { 314 uptr beg, end; 315 for (int i = 0; GetUserRegion(i, &beg, &end); i++) { 316 // Skip cases for empty regions (heap definition for architectures that 317 // do not use 64-bit allocator). 318 if (beg == end) 319 continue; 320 VPrintf(3, "checking shadow region %p-%p\n", beg, end); 321 uptr prev = 0; 322 for (uptr p0 = beg; p0 <= end; p0 += (end - beg) / 4) { 323 for (int x = -(int)kShadowCell; x <= (int)kShadowCell; x += kShadowCell) { 324 const uptr p = RoundDown(p0 + x, kShadowCell); 325 if (p < beg || p >= end) 326 continue; 327 const uptr s = MemToShadow(p); 328 const uptr m = (uptr)MemToMeta(p); 329 VPrintf(3, " checking pointer %p: shadow=%p meta=%p\n", p, s, m); 330 CHECK(IsAppMem(p)); 331 CHECK(IsShadowMem(s)); 332 CHECK_EQ(p, ShadowToMem(s)); 333 CHECK(IsMetaMem(m)); 334 if (prev) { 335 // Ensure that shadow and meta mappings are linear within a single 336 // user range. Lots of code that processes memory ranges assumes it. 337 const uptr prev_s = MemToShadow(prev); 338 const uptr prev_m = (uptr)MemToMeta(prev); 339 CHECK_EQ(s - prev_s, (p - prev) * kShadowMultiplier); 340 CHECK_EQ((m - prev_m) / kMetaShadowSize, 341 (p - prev) / kMetaShadowCell); 342 } 343 prev = p; 344 } 345 } 346 } 347 } 348 349 #if !SANITIZER_GO 350 static void OnStackUnwind(const SignalContext &sig, const void *, 351 BufferedStackTrace *stack) { 352 stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context, 353 common_flags()->fast_unwind_on_fatal); 354 } 355 356 static void TsanOnDeadlySignal(int signo, void *siginfo, void *context) { 357 HandleDeadlySignal(siginfo, context, GetTid(), &OnStackUnwind, nullptr); 358 } 359 #endif 360 361 void Initialize(ThreadState *thr) { 362 // Thread safe because done before all threads exist. 363 static bool is_initialized = false; 364 if (is_initialized) 365 return; 366 is_initialized = true; 367 // We are not ready to handle interceptors yet. 368 ScopedIgnoreInterceptors ignore; 369 SanitizerToolName = "ThreadSanitizer"; 370 // Install tool-specific callbacks in sanitizer_common. 371 SetCheckFailedCallback(TsanCheckFailed); 372 373 ctx = new(ctx_placeholder) Context; 374 const char *env_name = SANITIZER_GO ? "GORACE" : "TSAN_OPTIONS"; 375 const char *options = GetEnv(env_name); 376 CacheBinaryName(); 377 CheckASLR(); 378 InitializeFlags(&ctx->flags, options, env_name); 379 AvoidCVE_2016_2143(); 380 __sanitizer::InitializePlatformEarly(); 381 __tsan::InitializePlatformEarly(); 382 383 #if !SANITIZER_GO 384 // Re-exec ourselves if we need to set additional env or command line args. 385 MaybeReexec(); 386 387 InitializeAllocator(); 388 ReplaceSystemMalloc(); 389 #endif 390 if (common_flags()->detect_deadlocks) 391 ctx->dd = DDetector::Create(flags()); 392 Processor *proc = ProcCreate(); 393 ProcWire(proc, thr); 394 InitializeInterceptors(); 395 CheckShadowMapping(); 396 InitializePlatform(); 397 InitializeMutex(); 398 InitializeDynamicAnnotations(); 399 #if !SANITIZER_GO 400 InitializeShadowMemory(); 401 InitializeAllocatorLate(); 402 InstallDeadlySignalHandlers(TsanOnDeadlySignal); 403 #endif 404 // Setup correct file descriptor for error reports. 405 __sanitizer_set_report_path(common_flags()->log_path); 406 InitializeSuppressions(); 407 #if !SANITIZER_GO 408 InitializeLibIgnore(); 409 Symbolizer::GetOrInit()->AddHooks(EnterSymbolizer, ExitSymbolizer); 410 #endif 411 412 VPrintf(1, "***** Running under ThreadSanitizer v2 (pid %d) *****\n", 413 (int)internal_getpid()); 414 415 // Initialize thread 0. 416 int tid = ThreadCreate(thr, 0, 0, true); 417 CHECK_EQ(tid, 0); 418 ThreadStart(thr, tid, GetTid(), ThreadType::Regular); 419 #if TSAN_CONTAINS_UBSAN 420 __ubsan::InitAsPlugin(); 421 #endif 422 ctx->initialized = true; 423 424 #if !SANITIZER_GO 425 Symbolizer::LateInitialize(); 426 #endif 427 428 if (flags()->stop_on_start) { 429 Printf("ThreadSanitizer is suspended at startup (pid %d)." 430 " Call __tsan_resume().\n", 431 (int)internal_getpid()); 432 while (__tsan_resumed == 0) {} 433 } 434 435 OnInitialize(); 436 } 437 438 void MaybeSpawnBackgroundThread() { 439 // On MIPS, TSan initialization is run before 440 // __pthread_initialize_minimal_internal() is finished, so we can not spawn 441 // new threads. 442 #if !SANITIZER_GO && !defined(__mips__) 443 static atomic_uint32_t bg_thread = {}; 444 if (atomic_load(&bg_thread, memory_order_relaxed) == 0 && 445 atomic_exchange(&bg_thread, 1, memory_order_relaxed) == 0) { 446 StartBackgroundThread(); 447 SetSandboxingCallback(StopBackgroundThread); 448 } 449 #endif 450 } 451 452 453 int Finalize(ThreadState *thr) { 454 bool failed = false; 455 456 if (common_flags()->print_module_map == 1) 457 DumpProcessMap(); 458 459 if (flags()->atexit_sleep_ms > 0 && ThreadCount(thr) > 1) 460 SleepForMillis(flags()->atexit_sleep_ms); 461 462 // Wait for pending reports. 463 ctx->report_mtx.Lock(); 464 { ScopedErrorReportLock l; } 465 ctx->report_mtx.Unlock(); 466 467 #if !SANITIZER_GO 468 if (Verbosity()) AllocatorPrintStats(); 469 #endif 470 471 ThreadFinalize(thr); 472 473 if (ctx->nreported) { 474 failed = true; 475 #if !SANITIZER_GO 476 Printf("ThreadSanitizer: reported %d warnings\n", ctx->nreported); 477 #else 478 Printf("Found %d data race(s)\n", ctx->nreported); 479 #endif 480 } 481 482 if (ctx->nmissed_expected) { 483 failed = true; 484 Printf("ThreadSanitizer: missed %d expected races\n", 485 ctx->nmissed_expected); 486 } 487 488 if (common_flags()->print_suppressions) 489 PrintMatchedSuppressions(); 490 #if !SANITIZER_GO 491 if (flags()->print_benign) 492 PrintMatchedBenignRaces(); 493 #endif 494 495 failed = OnFinalize(failed); 496 497 #if TSAN_COLLECT_STATS 498 StatAggregate(ctx->stat, thr->stat); 499 StatOutput(ctx->stat); 500 #endif 501 502 return failed ? common_flags()->exitcode : 0; 503 } 504 505 #if !SANITIZER_GO 506 void ForkBefore(ThreadState *thr, uptr pc) { 507 ctx->thread_registry->Lock(); 508 ctx->report_mtx.Lock(); 509 // Ignore memory accesses in the pthread_atfork callbacks. 510 // If any of them triggers a data race we will deadlock 511 // on the report_mtx. 512 // We could ignore interceptors and sync operations as well, 513 // but so far it's unclear if it will do more good or harm. 514 // Unnecessarily ignoring things can lead to false positives later. 515 ThreadIgnoreBegin(thr, pc); 516 } 517 518 void ForkParentAfter(ThreadState *thr, uptr pc) { 519 ThreadIgnoreEnd(thr, pc); // Begin is in ForkBefore. 520 ctx->report_mtx.Unlock(); 521 ctx->thread_registry->Unlock(); 522 } 523 524 void ForkChildAfter(ThreadState *thr, uptr pc) { 525 ThreadIgnoreEnd(thr, pc); // Begin is in ForkBefore. 526 ctx->report_mtx.Unlock(); 527 ctx->thread_registry->Unlock(); 528 529 uptr nthread = 0; 530 ctx->thread_registry->GetNumberOfThreads(0, 0, &nthread /* alive threads */); 531 VPrintf(1, "ThreadSanitizer: forked new process with pid %d," 532 " parent had %d threads\n", (int)internal_getpid(), (int)nthread); 533 if (nthread == 1) { 534 StartBackgroundThread(); 535 } else { 536 // We've just forked a multi-threaded process. We cannot reasonably function 537 // after that (some mutexes may be locked before fork). So just enable 538 // ignores for everything in the hope that we will exec soon. 539 ctx->after_multithreaded_fork = true; 540 thr->ignore_interceptors++; 541 ThreadIgnoreBegin(thr, pc); 542 ThreadIgnoreSyncBegin(thr, pc); 543 } 544 } 545 #endif 546 547 #if SANITIZER_GO 548 NOINLINE 549 void GrowShadowStack(ThreadState *thr) { 550 const int sz = thr->shadow_stack_end - thr->shadow_stack; 551 const int newsz = 2 * sz; 552 uptr *newstack = (uptr*)internal_alloc(MBlockShadowStack, 553 newsz * sizeof(uptr)); 554 internal_memcpy(newstack, thr->shadow_stack, sz * sizeof(uptr)); 555 internal_free(thr->shadow_stack); 556 thr->shadow_stack = newstack; 557 thr->shadow_stack_pos = newstack + sz; 558 thr->shadow_stack_end = newstack + newsz; 559 } 560 #endif 561 562 u32 CurrentStackId(ThreadState *thr, uptr pc) { 563 if (!thr->is_inited) // May happen during bootstrap. 564 return 0; 565 if (pc != 0) { 566 #if !SANITIZER_GO 567 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end); 568 #else 569 if (thr->shadow_stack_pos == thr->shadow_stack_end) 570 GrowShadowStack(thr); 571 #endif 572 thr->shadow_stack_pos[0] = pc; 573 thr->shadow_stack_pos++; 574 } 575 u32 id = StackDepotPut( 576 StackTrace(thr->shadow_stack, thr->shadow_stack_pos - thr->shadow_stack)); 577 if (pc != 0) 578 thr->shadow_stack_pos--; 579 return id; 580 } 581 582 void TraceSwitch(ThreadState *thr) { 583 #if !SANITIZER_GO 584 if (ctx->after_multithreaded_fork) 585 return; 586 #endif 587 thr->nomalloc++; 588 Trace *thr_trace = ThreadTrace(thr->tid); 589 Lock l(&thr_trace->mtx); 590 unsigned trace = (thr->fast_state.epoch() / kTracePartSize) % TraceParts(); 591 TraceHeader *hdr = &thr_trace->headers[trace]; 592 hdr->epoch0 = thr->fast_state.epoch(); 593 ObtainCurrentStack(thr, 0, &hdr->stack0); 594 hdr->mset0 = thr->mset; 595 thr->nomalloc--; 596 } 597 598 Trace *ThreadTrace(int tid) { 599 return (Trace*)GetThreadTraceHeader(tid); 600 } 601 602 uptr TraceTopPC(ThreadState *thr) { 603 Event *events = (Event*)GetThreadTrace(thr->tid); 604 uptr pc = events[thr->fast_state.GetTracePos()]; 605 return pc; 606 } 607 608 uptr TraceSize() { 609 return (uptr)(1ull << (kTracePartSizeBits + flags()->history_size + 1)); 610 } 611 612 uptr TraceParts() { 613 return TraceSize() / kTracePartSize; 614 } 615 616 #if !SANITIZER_GO 617 extern "C" void __tsan_trace_switch() { 618 TraceSwitch(cur_thread()); 619 } 620 621 extern "C" void __tsan_report_race() { 622 ReportRace(cur_thread()); 623 } 624 #endif 625 626 ALWAYS_INLINE 627 Shadow LoadShadow(u64 *p) { 628 u64 raw = atomic_load((atomic_uint64_t*)p, memory_order_relaxed); 629 return Shadow(raw); 630 } 631 632 ALWAYS_INLINE 633 void StoreShadow(u64 *sp, u64 s) { 634 atomic_store((atomic_uint64_t*)sp, s, memory_order_relaxed); 635 } 636 637 ALWAYS_INLINE 638 void StoreIfNotYetStored(u64 *sp, u64 *s) { 639 StoreShadow(sp, *s); 640 *s = 0; 641 } 642 643 ALWAYS_INLINE 644 void HandleRace(ThreadState *thr, u64 *shadow_mem, 645 Shadow cur, Shadow old) { 646 thr->racy_state[0] = cur.raw(); 647 thr->racy_state[1] = old.raw(); 648 thr->racy_shadow_addr = shadow_mem; 649 #if !SANITIZER_GO 650 HACKY_CALL(__tsan_report_race); 651 #else 652 ReportRace(thr); 653 #endif 654 } 655 656 static inline bool HappensBefore(Shadow old, ThreadState *thr) { 657 return thr->clock.get(old.TidWithIgnore()) >= old.epoch(); 658 } 659 660 ALWAYS_INLINE 661 void MemoryAccessImpl1(ThreadState *thr, uptr addr, 662 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic, 663 u64 *shadow_mem, Shadow cur) { 664 StatInc(thr, StatMop); 665 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead); 666 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog)); 667 668 // This potentially can live in an MMX/SSE scratch register. 669 // The required intrinsics are: 670 // __m128i _mm_move_epi64(__m128i*); 671 // _mm_storel_epi64(u64*, __m128i); 672 u64 store_word = cur.raw(); 673 bool stored = false; 674 675 // scan all the shadow values and dispatch to 4 categories: 676 // same, replace, candidate and race (see comments below). 677 // we consider only 3 cases regarding access sizes: 678 // equal, intersect and not intersect. initially I considered 679 // larger and smaller as well, it allowed to replace some 680 // 'candidates' with 'same' or 'replace', but I think 681 // it's just not worth it (performance- and complexity-wise). 682 683 Shadow old(0); 684 685 // It release mode we manually unroll the loop, 686 // because empirically gcc generates better code this way. 687 // However, we can't afford unrolling in debug mode, because the function 688 // consumes almost 4K of stack. Gtest gives only 4K of stack to death test 689 // threads, which is not enough for the unrolled loop. 690 #if SANITIZER_DEBUG 691 for (int idx = 0; idx < 4; idx++) { 692 #include "tsan_update_shadow_word_inl.h" 693 } 694 #else 695 int idx = 0; 696 #include "tsan_update_shadow_word_inl.h" 697 idx = 1; 698 if (stored) { 699 #include "tsan_update_shadow_word_inl.h" 700 } else { 701 #include "tsan_update_shadow_word_inl.h" 702 } 703 idx = 2; 704 if (stored) { 705 #include "tsan_update_shadow_word_inl.h" 706 } else { 707 #include "tsan_update_shadow_word_inl.h" 708 } 709 idx = 3; 710 if (stored) { 711 #include "tsan_update_shadow_word_inl.h" 712 } else { 713 #include "tsan_update_shadow_word_inl.h" 714 } 715 #endif 716 717 // we did not find any races and had already stored 718 // the current access info, so we are done 719 if (LIKELY(stored)) 720 return; 721 // choose a random candidate slot and replace it 722 StoreShadow(shadow_mem + (cur.epoch() % kShadowCnt), store_word); 723 StatInc(thr, StatShadowReplace); 724 return; 725 RACE: 726 HandleRace(thr, shadow_mem, cur, old); 727 return; 728 } 729 730 void UnalignedMemoryAccess(ThreadState *thr, uptr pc, uptr addr, 731 int size, bool kAccessIsWrite, bool kIsAtomic) { 732 while (size) { 733 int size1 = 1; 734 int kAccessSizeLog = kSizeLog1; 735 if (size >= 8 && (addr & ~7) == ((addr + 7) & ~7)) { 736 size1 = 8; 737 kAccessSizeLog = kSizeLog8; 738 } else if (size >= 4 && (addr & ~7) == ((addr + 3) & ~7)) { 739 size1 = 4; 740 kAccessSizeLog = kSizeLog4; 741 } else if (size >= 2 && (addr & ~7) == ((addr + 1) & ~7)) { 742 size1 = 2; 743 kAccessSizeLog = kSizeLog2; 744 } 745 MemoryAccess(thr, pc, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic); 746 addr += size1; 747 size -= size1; 748 } 749 } 750 751 ALWAYS_INLINE 752 bool ContainsSameAccessSlow(u64 *s, u64 a, u64 sync_epoch, bool is_write) { 753 Shadow cur(a); 754 for (uptr i = 0; i < kShadowCnt; i++) { 755 Shadow old(LoadShadow(&s[i])); 756 if (Shadow::Addr0AndSizeAreEqual(cur, old) && 757 old.TidWithIgnore() == cur.TidWithIgnore() && 758 old.epoch() > sync_epoch && 759 old.IsAtomic() == cur.IsAtomic() && 760 old.IsRead() <= cur.IsRead()) 761 return true; 762 } 763 return false; 764 } 765 766 #if defined(__SSE3__) 767 #define SHUF(v0, v1, i0, i1, i2, i3) _mm_castps_si128(_mm_shuffle_ps( \ 768 _mm_castsi128_ps(v0), _mm_castsi128_ps(v1), \ 769 (i0)*1 + (i1)*4 + (i2)*16 + (i3)*64)) 770 ALWAYS_INLINE 771 bool ContainsSameAccessFast(u64 *s, u64 a, u64 sync_epoch, bool is_write) { 772 // This is an optimized version of ContainsSameAccessSlow. 773 // load current access into access[0:63] 774 const m128 access = _mm_cvtsi64_si128(a); 775 // duplicate high part of access in addr0: 776 // addr0[0:31] = access[32:63] 777 // addr0[32:63] = access[32:63] 778 // addr0[64:95] = access[32:63] 779 // addr0[96:127] = access[32:63] 780 const m128 addr0 = SHUF(access, access, 1, 1, 1, 1); 781 // load 4 shadow slots 782 const m128 shadow0 = _mm_load_si128((__m128i*)s); 783 const m128 shadow1 = _mm_load_si128((__m128i*)s + 1); 784 // load high parts of 4 shadow slots into addr_vect: 785 // addr_vect[0:31] = shadow0[32:63] 786 // addr_vect[32:63] = shadow0[96:127] 787 // addr_vect[64:95] = shadow1[32:63] 788 // addr_vect[96:127] = shadow1[96:127] 789 m128 addr_vect = SHUF(shadow0, shadow1, 1, 3, 1, 3); 790 if (!is_write) { 791 // set IsRead bit in addr_vect 792 const m128 rw_mask1 = _mm_cvtsi64_si128(1<<15); 793 const m128 rw_mask = SHUF(rw_mask1, rw_mask1, 0, 0, 0, 0); 794 addr_vect = _mm_or_si128(addr_vect, rw_mask); 795 } 796 // addr0 == addr_vect? 797 const m128 addr_res = _mm_cmpeq_epi32(addr0, addr_vect); 798 // epoch1[0:63] = sync_epoch 799 const m128 epoch1 = _mm_cvtsi64_si128(sync_epoch); 800 // epoch[0:31] = sync_epoch[0:31] 801 // epoch[32:63] = sync_epoch[0:31] 802 // epoch[64:95] = sync_epoch[0:31] 803 // epoch[96:127] = sync_epoch[0:31] 804 const m128 epoch = SHUF(epoch1, epoch1, 0, 0, 0, 0); 805 // load low parts of shadow cell epochs into epoch_vect: 806 // epoch_vect[0:31] = shadow0[0:31] 807 // epoch_vect[32:63] = shadow0[64:95] 808 // epoch_vect[64:95] = shadow1[0:31] 809 // epoch_vect[96:127] = shadow1[64:95] 810 const m128 epoch_vect = SHUF(shadow0, shadow1, 0, 2, 0, 2); 811 // epoch_vect >= sync_epoch? 812 const m128 epoch_res = _mm_cmpgt_epi32(epoch_vect, epoch); 813 // addr_res & epoch_res 814 const m128 res = _mm_and_si128(addr_res, epoch_res); 815 // mask[0] = res[7] 816 // mask[1] = res[15] 817 // ... 818 // mask[15] = res[127] 819 const int mask = _mm_movemask_epi8(res); 820 return mask != 0; 821 } 822 #endif 823 824 ALWAYS_INLINE 825 bool ContainsSameAccess(u64 *s, u64 a, u64 sync_epoch, bool is_write) { 826 #if defined(__SSE3__) 827 bool res = ContainsSameAccessFast(s, a, sync_epoch, is_write); 828 // NOTE: this check can fail if the shadow is concurrently mutated 829 // by other threads. But it still can be useful if you modify 830 // ContainsSameAccessFast and want to ensure that it's not completely broken. 831 // DCHECK_EQ(res, ContainsSameAccessSlow(s, a, sync_epoch, is_write)); 832 return res; 833 #else 834 return ContainsSameAccessSlow(s, a, sync_epoch, is_write); 835 #endif 836 } 837 838 ALWAYS_INLINE USED 839 void MemoryAccess(ThreadState *thr, uptr pc, uptr addr, 840 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic) { 841 u64 *shadow_mem = (u64*)MemToShadow(addr); 842 DPrintf2("#%d: MemoryAccess: @%p %p size=%d" 843 " is_write=%d shadow_mem=%p {%zx, %zx, %zx, %zx}\n", 844 (int)thr->fast_state.tid(), (void*)pc, (void*)addr, 845 (int)(1 << kAccessSizeLog), kAccessIsWrite, shadow_mem, 846 (uptr)shadow_mem[0], (uptr)shadow_mem[1], 847 (uptr)shadow_mem[2], (uptr)shadow_mem[3]); 848 #if SANITIZER_DEBUG 849 if (!IsAppMem(addr)) { 850 Printf("Access to non app mem %zx\n", addr); 851 DCHECK(IsAppMem(addr)); 852 } 853 if (!IsShadowMem((uptr)shadow_mem)) { 854 Printf("Bad shadow addr %p (%zx)\n", shadow_mem, addr); 855 DCHECK(IsShadowMem((uptr)shadow_mem)); 856 } 857 #endif 858 859 if (!SANITIZER_GO && !kAccessIsWrite && *shadow_mem == kShadowRodata) { 860 // Access to .rodata section, no races here. 861 // Measurements show that it can be 10-20% of all memory accesses. 862 StatInc(thr, StatMop); 863 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead); 864 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog)); 865 StatInc(thr, StatMopRodata); 866 return; 867 } 868 869 FastState fast_state = thr->fast_state; 870 if (UNLIKELY(fast_state.GetIgnoreBit())) { 871 StatInc(thr, StatMop); 872 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead); 873 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog)); 874 StatInc(thr, StatMopIgnored); 875 return; 876 } 877 878 Shadow cur(fast_state); 879 cur.SetAddr0AndSizeLog(addr & 7, kAccessSizeLog); 880 cur.SetWrite(kAccessIsWrite); 881 cur.SetAtomic(kIsAtomic); 882 883 if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(), 884 thr->fast_synch_epoch, kAccessIsWrite))) { 885 StatInc(thr, StatMop); 886 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead); 887 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog)); 888 StatInc(thr, StatMopSame); 889 return; 890 } 891 892 if (kCollectHistory) { 893 fast_state.IncrementEpoch(); 894 thr->fast_state = fast_state; 895 TraceAddEvent(thr, fast_state, EventTypeMop, pc); 896 cur.IncrementEpoch(); 897 } 898 899 MemoryAccessImpl1(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic, 900 shadow_mem, cur); 901 } 902 903 // Called by MemoryAccessRange in tsan_rtl_thread.cpp 904 ALWAYS_INLINE USED 905 void MemoryAccessImpl(ThreadState *thr, uptr addr, 906 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic, 907 u64 *shadow_mem, Shadow cur) { 908 if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(), 909 thr->fast_synch_epoch, kAccessIsWrite))) { 910 StatInc(thr, StatMop); 911 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead); 912 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog)); 913 StatInc(thr, StatMopSame); 914 return; 915 } 916 917 MemoryAccessImpl1(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic, 918 shadow_mem, cur); 919 } 920 921 static void MemoryRangeSet(ThreadState *thr, uptr pc, uptr addr, uptr size, 922 u64 val) { 923 (void)thr; 924 (void)pc; 925 if (size == 0) 926 return; 927 // FIXME: fix me. 928 uptr offset = addr % kShadowCell; 929 if (offset) { 930 offset = kShadowCell - offset; 931 if (size <= offset) 932 return; 933 addr += offset; 934 size -= offset; 935 } 936 DCHECK_EQ(addr % 8, 0); 937 // If a user passes some insane arguments (memset(0)), 938 // let it just crash as usual. 939 if (!IsAppMem(addr) || !IsAppMem(addr + size - 1)) 940 return; 941 // Don't want to touch lots of shadow memory. 942 // If a program maps 10MB stack, there is no need reset the whole range. 943 size = (size + (kShadowCell - 1)) & ~(kShadowCell - 1); 944 // UnmapOrDie/MmapFixedNoReserve does not work on Windows. 945 if (SANITIZER_WINDOWS || size < common_flags()->clear_shadow_mmap_threshold) { 946 u64 *p = (u64*)MemToShadow(addr); 947 CHECK(IsShadowMem((uptr)p)); 948 CHECK(IsShadowMem((uptr)(p + size * kShadowCnt / kShadowCell - 1))); 949 // FIXME: may overwrite a part outside the region 950 for (uptr i = 0; i < size / kShadowCell * kShadowCnt;) { 951 p[i++] = val; 952 for (uptr j = 1; j < kShadowCnt; j++) 953 p[i++] = 0; 954 } 955 } else { 956 // The region is big, reset only beginning and end. 957 const uptr kPageSize = GetPageSizeCached(); 958 u64 *begin = (u64*)MemToShadow(addr); 959 u64 *end = begin + size / kShadowCell * kShadowCnt; 960 u64 *p = begin; 961 // Set at least first kPageSize/2 to page boundary. 962 while ((p < begin + kPageSize / kShadowSize / 2) || ((uptr)p % kPageSize)) { 963 *p++ = val; 964 for (uptr j = 1; j < kShadowCnt; j++) 965 *p++ = 0; 966 } 967 // Reset middle part. 968 u64 *p1 = p; 969 p = RoundDown(end, kPageSize); 970 UnmapOrDie((void*)p1, (uptr)p - (uptr)p1); 971 if (!MmapFixedSuperNoReserve((uptr)p1, (uptr)p - (uptr)p1)) 972 Die(); 973 // Set the ending. 974 while (p < end) { 975 *p++ = val; 976 for (uptr j = 1; j < kShadowCnt; j++) 977 *p++ = 0; 978 } 979 } 980 } 981 982 void MemoryResetRange(ThreadState *thr, uptr pc, uptr addr, uptr size) { 983 MemoryRangeSet(thr, pc, addr, size, 0); 984 } 985 986 void MemoryRangeFreed(ThreadState *thr, uptr pc, uptr addr, uptr size) { 987 // Processing more than 1k (4k of shadow) is expensive, 988 // can cause excessive memory consumption (user does not necessary touch 989 // the whole range) and most likely unnecessary. 990 if (size > 1024) 991 size = 1024; 992 CHECK_EQ(thr->is_freeing, false); 993 thr->is_freeing = true; 994 MemoryAccessRange(thr, pc, addr, size, true); 995 thr->is_freeing = false; 996 if (kCollectHistory) { 997 thr->fast_state.IncrementEpoch(); 998 TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc); 999 } 1000 Shadow s(thr->fast_state); 1001 s.ClearIgnoreBit(); 1002 s.MarkAsFreed(); 1003 s.SetWrite(true); 1004 s.SetAddr0AndSizeLog(0, 3); 1005 MemoryRangeSet(thr, pc, addr, size, s.raw()); 1006 } 1007 1008 void MemoryRangeImitateWrite(ThreadState *thr, uptr pc, uptr addr, uptr size) { 1009 if (kCollectHistory) { 1010 thr->fast_state.IncrementEpoch(); 1011 TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc); 1012 } 1013 Shadow s(thr->fast_state); 1014 s.ClearIgnoreBit(); 1015 s.SetWrite(true); 1016 s.SetAddr0AndSizeLog(0, 3); 1017 MemoryRangeSet(thr, pc, addr, size, s.raw()); 1018 } 1019 1020 void MemoryRangeImitateWriteOrResetRange(ThreadState *thr, uptr pc, uptr addr, 1021 uptr size) { 1022 if (thr->ignore_reads_and_writes == 0) 1023 MemoryRangeImitateWrite(thr, pc, addr, size); 1024 else 1025 MemoryResetRange(thr, pc, addr, size); 1026 } 1027 1028 ALWAYS_INLINE USED 1029 void FuncEntry(ThreadState *thr, uptr pc) { 1030 StatInc(thr, StatFuncEnter); 1031 DPrintf2("#%d: FuncEntry %p\n", (int)thr->fast_state.tid(), (void*)pc); 1032 if (kCollectHistory) { 1033 thr->fast_state.IncrementEpoch(); 1034 TraceAddEvent(thr, thr->fast_state, EventTypeFuncEnter, pc); 1035 } 1036 1037 // Shadow stack maintenance can be replaced with 1038 // stack unwinding during trace switch (which presumably must be faster). 1039 DCHECK_GE(thr->shadow_stack_pos, thr->shadow_stack); 1040 #if !SANITIZER_GO 1041 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end); 1042 #else 1043 if (thr->shadow_stack_pos == thr->shadow_stack_end) 1044 GrowShadowStack(thr); 1045 #endif 1046 thr->shadow_stack_pos[0] = pc; 1047 thr->shadow_stack_pos++; 1048 } 1049 1050 ALWAYS_INLINE USED 1051 void FuncExit(ThreadState *thr) { 1052 StatInc(thr, StatFuncExit); 1053 DPrintf2("#%d: FuncExit\n", (int)thr->fast_state.tid()); 1054 if (kCollectHistory) { 1055 thr->fast_state.IncrementEpoch(); 1056 TraceAddEvent(thr, thr->fast_state, EventTypeFuncExit, 0); 1057 } 1058 1059 DCHECK_GT(thr->shadow_stack_pos, thr->shadow_stack); 1060 #if !SANITIZER_GO 1061 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end); 1062 #endif 1063 thr->shadow_stack_pos--; 1064 } 1065 1066 void ThreadIgnoreBegin(ThreadState *thr, uptr pc, bool save_stack) { 1067 DPrintf("#%d: ThreadIgnoreBegin\n", thr->tid); 1068 thr->ignore_reads_and_writes++; 1069 CHECK_GT(thr->ignore_reads_and_writes, 0); 1070 thr->fast_state.SetIgnoreBit(); 1071 #if !SANITIZER_GO 1072 if (save_stack && !ctx->after_multithreaded_fork) 1073 thr->mop_ignore_set.Add(CurrentStackId(thr, pc)); 1074 #endif 1075 } 1076 1077 void ThreadIgnoreEnd(ThreadState *thr, uptr pc) { 1078 DPrintf("#%d: ThreadIgnoreEnd\n", thr->tid); 1079 CHECK_GT(thr->ignore_reads_and_writes, 0); 1080 thr->ignore_reads_and_writes--; 1081 if (thr->ignore_reads_and_writes == 0) { 1082 thr->fast_state.ClearIgnoreBit(); 1083 #if !SANITIZER_GO 1084 thr->mop_ignore_set.Reset(); 1085 #endif 1086 } 1087 } 1088 1089 #if !SANITIZER_GO 1090 extern "C" SANITIZER_INTERFACE_ATTRIBUTE 1091 uptr __tsan_testonly_shadow_stack_current_size() { 1092 ThreadState *thr = cur_thread(); 1093 return thr->shadow_stack_pos - thr->shadow_stack; 1094 } 1095 #endif 1096 1097 void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc, bool save_stack) { 1098 DPrintf("#%d: ThreadIgnoreSyncBegin\n", thr->tid); 1099 thr->ignore_sync++; 1100 CHECK_GT(thr->ignore_sync, 0); 1101 #if !SANITIZER_GO 1102 if (save_stack && !ctx->after_multithreaded_fork) 1103 thr->sync_ignore_set.Add(CurrentStackId(thr, pc)); 1104 #endif 1105 } 1106 1107 void ThreadIgnoreSyncEnd(ThreadState *thr, uptr pc) { 1108 DPrintf("#%d: ThreadIgnoreSyncEnd\n", thr->tid); 1109 CHECK_GT(thr->ignore_sync, 0); 1110 thr->ignore_sync--; 1111 #if !SANITIZER_GO 1112 if (thr->ignore_sync == 0) 1113 thr->sync_ignore_set.Reset(); 1114 #endif 1115 } 1116 1117 bool MD5Hash::operator==(const MD5Hash &other) const { 1118 return hash[0] == other.hash[0] && hash[1] == other.hash[1]; 1119 } 1120 1121 #if SANITIZER_DEBUG 1122 void build_consistency_debug() {} 1123 #else 1124 void build_consistency_release() {} 1125 #endif 1126 1127 #if TSAN_COLLECT_STATS 1128 void build_consistency_stats() {} 1129 #else 1130 void build_consistency_nostats() {} 1131 #endif 1132 1133 } // namespace __tsan 1134 1135 #if !SANITIZER_GO 1136 // Must be included in this file to make sure everything is inlined. 1137 #include "tsan_interface_inl.h" 1138 #endif 1139