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