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