1 //===-- tsan_interceptors_posix.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 // FIXME: move as many interceptors as possible into 12 // sanitizer_common/sanitizer_common_interceptors.inc 13 //===----------------------------------------------------------------------===// 14 15 #include "sanitizer_common/sanitizer_atomic.h" 16 #include "sanitizer_common/sanitizer_errno.h" 17 #include "sanitizer_common/sanitizer_libc.h" 18 #include "sanitizer_common/sanitizer_linux.h" 19 #include "sanitizer_common/sanitizer_platform_limits_netbsd.h" 20 #include "sanitizer_common/sanitizer_platform_limits_posix.h" 21 #include "sanitizer_common/sanitizer_placement_new.h" 22 #include "sanitizer_common/sanitizer_posix.h" 23 #include "sanitizer_common/sanitizer_stacktrace.h" 24 #include "sanitizer_common/sanitizer_tls_get_addr.h" 25 #include "interception/interception.h" 26 #include "tsan_interceptors.h" 27 #include "tsan_interface.h" 28 #include "tsan_platform.h" 29 #include "tsan_suppressions.h" 30 #include "tsan_rtl.h" 31 #include "tsan_mman.h" 32 #include "tsan_fd.h" 33 34 #include <stdarg.h> 35 36 using namespace __tsan; 37 38 #if SANITIZER_FREEBSD || SANITIZER_MAC 39 #define stdout __stdoutp 40 #define stderr __stderrp 41 #endif 42 43 #if SANITIZER_NETBSD 44 #define dirfd(dirp) (*(int *)(dirp)) 45 #define fileno_unlocked(fp) \ 46 (((__sanitizer_FILE *)fp)->_file == -1 \ 47 ? -1 \ 48 : (int)(unsigned short)(((__sanitizer_FILE *)fp)->_file)) 49 50 #define stdout ((__sanitizer_FILE*)&__sF[1]) 51 #define stderr ((__sanitizer_FILE*)&__sF[2]) 52 53 #define nanosleep __nanosleep50 54 #define vfork __vfork14 55 #endif 56 57 #ifdef __mips__ 58 const int kSigCount = 129; 59 #else 60 const int kSigCount = 65; 61 #endif 62 63 #ifdef __mips__ 64 struct ucontext_t { 65 u64 opaque[768 / sizeof(u64) + 1]; 66 }; 67 #else 68 struct ucontext_t { 69 // The size is determined by looking at sizeof of real ucontext_t on linux. 70 u64 opaque[936 / sizeof(u64) + 1]; 71 }; 72 #endif 73 74 #if defined(__x86_64__) || defined(__mips__) || SANITIZER_PPC64V1 75 #define PTHREAD_ABI_BASE "GLIBC_2.3.2" 76 #elif defined(__aarch64__) || SANITIZER_PPC64V2 77 #define PTHREAD_ABI_BASE "GLIBC_2.17" 78 #endif 79 80 extern "C" int pthread_attr_init(void *attr); 81 extern "C" int pthread_attr_destroy(void *attr); 82 DECLARE_REAL(int, pthread_attr_getdetachstate, void *, void *) 83 extern "C" int pthread_attr_setstacksize(void *attr, uptr stacksize); 84 extern "C" int pthread_key_create(unsigned *key, void (*destructor)(void* v)); 85 extern "C" int pthread_setspecific(unsigned key, const void *v); 86 DECLARE_REAL(int, pthread_mutexattr_gettype, void *, void *) 87 DECLARE_REAL(int, fflush, __sanitizer_FILE *fp) 88 DECLARE_REAL_AND_INTERCEPTOR(void *, malloc, uptr size) 89 DECLARE_REAL_AND_INTERCEPTOR(void, free, void *ptr) 90 extern "C" void *pthread_self(); 91 extern "C" void _exit(int status); 92 #if !SANITIZER_NETBSD 93 extern "C" int fileno_unlocked(void *stream); 94 extern "C" int dirfd(void *dirp); 95 #endif 96 #if SANITIZER_GLIBC 97 extern "C" int mallopt(int param, int value); 98 #endif 99 #if SANITIZER_NETBSD 100 extern __sanitizer_FILE __sF[]; 101 #else 102 extern __sanitizer_FILE *stdout, *stderr; 103 #endif 104 #if !SANITIZER_FREEBSD && !SANITIZER_MAC && !SANITIZER_NETBSD 105 const int PTHREAD_MUTEX_RECURSIVE = 1; 106 const int PTHREAD_MUTEX_RECURSIVE_NP = 1; 107 #else 108 const int PTHREAD_MUTEX_RECURSIVE = 2; 109 const int PTHREAD_MUTEX_RECURSIVE_NP = 2; 110 #endif 111 #if !SANITIZER_FREEBSD && !SANITIZER_MAC && !SANITIZER_NETBSD 112 const int EPOLL_CTL_ADD = 1; 113 #endif 114 const int SIGILL = 4; 115 const int SIGTRAP = 5; 116 const int SIGABRT = 6; 117 const int SIGFPE = 8; 118 const int SIGSEGV = 11; 119 const int SIGPIPE = 13; 120 const int SIGTERM = 15; 121 #if defined(__mips__) || SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_NETBSD 122 const int SIGBUS = 10; 123 const int SIGSYS = 12; 124 #else 125 const int SIGBUS = 7; 126 const int SIGSYS = 31; 127 #endif 128 void *const MAP_FAILED = (void*)-1; 129 #if SANITIZER_NETBSD 130 const int PTHREAD_BARRIER_SERIAL_THREAD = 1234567; 131 #elif !SANITIZER_MAC 132 const int PTHREAD_BARRIER_SERIAL_THREAD = -1; 133 #endif 134 const int MAP_FIXED = 0x10; 135 typedef long long_t; 136 typedef __sanitizer::u16 mode_t; 137 138 // From /usr/include/unistd.h 139 # define F_ULOCK 0 /* Unlock a previously locked region. */ 140 # define F_LOCK 1 /* Lock a region for exclusive use. */ 141 # define F_TLOCK 2 /* Test and lock a region for exclusive use. */ 142 # define F_TEST 3 /* Test a region for other processes locks. */ 143 144 #if SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_NETBSD 145 const int SA_SIGINFO = 0x40; 146 const int SIG_SETMASK = 3; 147 #elif defined(__mips__) 148 const int SA_SIGINFO = 8; 149 const int SIG_SETMASK = 3; 150 #else 151 const int SA_SIGINFO = 4; 152 const int SIG_SETMASK = 2; 153 #endif 154 155 #define COMMON_INTERCEPTOR_NOTHING_IS_INITIALIZED \ 156 (cur_thread_init(), !cur_thread()->is_inited) 157 158 namespace __tsan { 159 struct SignalDesc { 160 bool armed; 161 bool sigaction; 162 __sanitizer_siginfo siginfo; 163 ucontext_t ctx; 164 }; 165 166 struct ThreadSignalContext { 167 int int_signal_send; 168 atomic_uintptr_t in_blocking_func; 169 atomic_uintptr_t have_pending_signals; 170 SignalDesc pending_signals[kSigCount]; 171 // emptyset and oldset are too big for stack. 172 __sanitizer_sigset_t emptyset; 173 __sanitizer_sigset_t oldset; 174 }; 175 176 // The sole reason tsan wraps atexit callbacks is to establish synchronization 177 // between callback setup and callback execution. 178 struct AtExitCtx { 179 void (*f)(); 180 void *arg; 181 }; 182 183 // InterceptorContext holds all global data required for interceptors. 184 // It's explicitly constructed in InitializeInterceptors with placement new 185 // and is never destroyed. This allows usage of members with non-trivial 186 // constructors and destructors. 187 struct InterceptorContext { 188 // The object is 64-byte aligned, because we want hot data to be located 189 // in a single cache line if possible (it's accessed in every interceptor). 190 ALIGNED(64) LibIgnore libignore; 191 __sanitizer_sigaction sigactions[kSigCount]; 192 #if !SANITIZER_MAC && !SANITIZER_NETBSD 193 unsigned finalize_key; 194 #endif 195 196 BlockingMutex atexit_mu; 197 Vector<struct AtExitCtx *> AtExitStack; 198 199 InterceptorContext() 200 : libignore(LINKER_INITIALIZED), AtExitStack() { 201 } 202 }; 203 204 static ALIGNED(64) char interceptor_placeholder[sizeof(InterceptorContext)]; 205 InterceptorContext *interceptor_ctx() { 206 return reinterpret_cast<InterceptorContext*>(&interceptor_placeholder[0]); 207 } 208 209 LibIgnore *libignore() { 210 return &interceptor_ctx()->libignore; 211 } 212 213 void InitializeLibIgnore() { 214 const SuppressionContext &supp = *Suppressions(); 215 const uptr n = supp.SuppressionCount(); 216 for (uptr i = 0; i < n; i++) { 217 const Suppression *s = supp.SuppressionAt(i); 218 if (0 == internal_strcmp(s->type, kSuppressionLib)) 219 libignore()->AddIgnoredLibrary(s->templ); 220 } 221 if (flags()->ignore_noninstrumented_modules) 222 libignore()->IgnoreNoninstrumentedModules(true); 223 libignore()->OnLibraryLoaded(0); 224 } 225 226 // The following two hooks can be used by for cooperative scheduling when 227 // locking. 228 #ifdef TSAN_EXTERNAL_HOOKS 229 void OnPotentiallyBlockingRegionBegin(); 230 void OnPotentiallyBlockingRegionEnd(); 231 #else 232 SANITIZER_WEAK_CXX_DEFAULT_IMPL void OnPotentiallyBlockingRegionBegin() {} 233 SANITIZER_WEAK_CXX_DEFAULT_IMPL void OnPotentiallyBlockingRegionEnd() {} 234 #endif 235 236 } // namespace __tsan 237 238 static ThreadSignalContext *SigCtx(ThreadState *thr) { 239 ThreadSignalContext *ctx = (ThreadSignalContext*)thr->signal_ctx; 240 if (ctx == 0 && !thr->is_dead) { 241 ctx = (ThreadSignalContext*)MmapOrDie(sizeof(*ctx), "ThreadSignalContext"); 242 MemoryResetRange(thr, (uptr)&SigCtx, (uptr)ctx, sizeof(*ctx)); 243 thr->signal_ctx = ctx; 244 } 245 return ctx; 246 } 247 248 ScopedInterceptor::ScopedInterceptor(ThreadState *thr, const char *fname, 249 uptr pc) 250 : thr_(thr), pc_(pc), in_ignored_lib_(false), ignoring_(false) { 251 Initialize(thr); 252 if (!thr_->is_inited) return; 253 if (!thr_->ignore_interceptors) FuncEntry(thr, pc); 254 DPrintf("#%d: intercept %s()\n", thr_->tid, fname); 255 ignoring_ = 256 !thr_->in_ignored_lib && (flags()->ignore_interceptors_accesses || 257 libignore()->IsIgnored(pc, &in_ignored_lib_)); 258 EnableIgnores(); 259 } 260 261 ScopedInterceptor::~ScopedInterceptor() { 262 if (!thr_->is_inited) return; 263 DisableIgnores(); 264 if (!thr_->ignore_interceptors) { 265 ProcessPendingSignals(thr_); 266 FuncExit(thr_); 267 CheckNoLocks(thr_); 268 } 269 } 270 271 void ScopedInterceptor::EnableIgnores() { 272 if (ignoring_) { 273 ThreadIgnoreBegin(thr_, pc_, /*save_stack=*/false); 274 if (flags()->ignore_noninstrumented_modules) thr_->suppress_reports++; 275 if (in_ignored_lib_) { 276 DCHECK(!thr_->in_ignored_lib); 277 thr_->in_ignored_lib = true; 278 } 279 } 280 } 281 282 void ScopedInterceptor::DisableIgnores() { 283 if (ignoring_) { 284 ThreadIgnoreEnd(thr_, pc_); 285 if (flags()->ignore_noninstrumented_modules) thr_->suppress_reports--; 286 if (in_ignored_lib_) { 287 DCHECK(thr_->in_ignored_lib); 288 thr_->in_ignored_lib = false; 289 } 290 } 291 } 292 293 #define TSAN_INTERCEPT(func) INTERCEPT_FUNCTION(func) 294 #if SANITIZER_FREEBSD 295 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION(func) 296 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(func) 297 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(func) 298 #elif SANITIZER_NETBSD 299 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION(func) 300 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(func) \ 301 INTERCEPT_FUNCTION(__libc_##func) 302 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(func) \ 303 INTERCEPT_FUNCTION(__libc_thr_##func) 304 #else 305 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION_VER(func, ver) 306 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(func) 307 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(func) 308 #endif 309 310 #define READ_STRING_OF_LEN(thr, pc, s, len, n) \ 311 MemoryAccessRange((thr), (pc), (uptr)(s), \ 312 common_flags()->strict_string_checks ? (len) + 1 : (n), false) 313 314 #define READ_STRING(thr, pc, s, n) \ 315 READ_STRING_OF_LEN((thr), (pc), (s), internal_strlen(s), (n)) 316 317 #define BLOCK_REAL(name) (BlockingCall(thr), REAL(name)) 318 319 struct BlockingCall { 320 explicit BlockingCall(ThreadState *thr) 321 : thr(thr) 322 , ctx(SigCtx(thr)) { 323 for (;;) { 324 atomic_store(&ctx->in_blocking_func, 1, memory_order_relaxed); 325 if (atomic_load(&ctx->have_pending_signals, memory_order_relaxed) == 0) 326 break; 327 atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed); 328 ProcessPendingSignals(thr); 329 } 330 // When we are in a "blocking call", we process signals asynchronously 331 // (right when they arrive). In this context we do not expect to be 332 // executing any user/runtime code. The known interceptor sequence when 333 // this is not true is: pthread_join -> munmap(stack). It's fine 334 // to ignore munmap in this case -- we handle stack shadow separately. 335 thr->ignore_interceptors++; 336 } 337 338 ~BlockingCall() { 339 thr->ignore_interceptors--; 340 atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed); 341 } 342 343 ThreadState *thr; 344 ThreadSignalContext *ctx; 345 }; 346 347 TSAN_INTERCEPTOR(unsigned, sleep, unsigned sec) { 348 SCOPED_TSAN_INTERCEPTOR(sleep, sec); 349 unsigned res = BLOCK_REAL(sleep)(sec); 350 AfterSleep(thr, pc); 351 return res; 352 } 353 354 TSAN_INTERCEPTOR(int, usleep, long_t usec) { 355 SCOPED_TSAN_INTERCEPTOR(usleep, usec); 356 int res = BLOCK_REAL(usleep)(usec); 357 AfterSleep(thr, pc); 358 return res; 359 } 360 361 TSAN_INTERCEPTOR(int, nanosleep, void *req, void *rem) { 362 SCOPED_TSAN_INTERCEPTOR(nanosleep, req, rem); 363 int res = BLOCK_REAL(nanosleep)(req, rem); 364 AfterSleep(thr, pc); 365 return res; 366 } 367 368 TSAN_INTERCEPTOR(int, pause, int fake) { 369 SCOPED_TSAN_INTERCEPTOR(pause, fake); 370 return BLOCK_REAL(pause)(fake); 371 } 372 373 static void at_exit_wrapper() { 374 AtExitCtx *ctx; 375 { 376 // Ensure thread-safety. 377 BlockingMutexLock l(&interceptor_ctx()->atexit_mu); 378 379 // Pop AtExitCtx from the top of the stack of callback functions 380 uptr element = interceptor_ctx()->AtExitStack.Size() - 1; 381 ctx = interceptor_ctx()->AtExitStack[element]; 382 interceptor_ctx()->AtExitStack.PopBack(); 383 } 384 385 Acquire(cur_thread(), (uptr)0, (uptr)ctx); 386 ((void(*)())ctx->f)(); 387 InternalFree(ctx); 388 } 389 390 static void cxa_at_exit_wrapper(void *arg) { 391 Acquire(cur_thread(), 0, (uptr)arg); 392 AtExitCtx *ctx = (AtExitCtx*)arg; 393 ((void(*)(void *arg))ctx->f)(ctx->arg); 394 InternalFree(ctx); 395 } 396 397 static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(), 398 void *arg, void *dso); 399 400 #if !SANITIZER_ANDROID 401 TSAN_INTERCEPTOR(int, atexit, void (*f)()) { 402 if (in_symbolizer()) 403 return 0; 404 // We want to setup the atexit callback even if we are in ignored lib 405 // or after fork. 406 SCOPED_INTERCEPTOR_RAW(atexit, f); 407 return setup_at_exit_wrapper(thr, pc, (void(*)())f, 0, 0); 408 } 409 #endif 410 411 TSAN_INTERCEPTOR(int, __cxa_atexit, void (*f)(void *a), void *arg, void *dso) { 412 if (in_symbolizer()) 413 return 0; 414 SCOPED_TSAN_INTERCEPTOR(__cxa_atexit, f, arg, dso); 415 return setup_at_exit_wrapper(thr, pc, (void(*)())f, arg, dso); 416 } 417 418 static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(), 419 void *arg, void *dso) { 420 AtExitCtx *ctx = (AtExitCtx*)InternalAlloc(sizeof(AtExitCtx)); 421 ctx->f = f; 422 ctx->arg = arg; 423 Release(thr, pc, (uptr)ctx); 424 // Memory allocation in __cxa_atexit will race with free during exit, 425 // because we do not see synchronization around atexit callback list. 426 ThreadIgnoreBegin(thr, pc); 427 int res; 428 if (!dso) { 429 // NetBSD does not preserve the 2nd argument if dso is equal to 0 430 // Store ctx in a local stack-like structure 431 432 // Ensure thread-safety. 433 BlockingMutexLock l(&interceptor_ctx()->atexit_mu); 434 435 res = REAL(__cxa_atexit)((void (*)(void *a))at_exit_wrapper, 0, 0); 436 // Push AtExitCtx on the top of the stack of callback functions 437 if (!res) { 438 interceptor_ctx()->AtExitStack.PushBack(ctx); 439 } 440 } else { 441 res = REAL(__cxa_atexit)(cxa_at_exit_wrapper, ctx, dso); 442 } 443 ThreadIgnoreEnd(thr, pc); 444 return res; 445 } 446 447 #if !SANITIZER_MAC && !SANITIZER_NETBSD 448 static void on_exit_wrapper(int status, void *arg) { 449 ThreadState *thr = cur_thread(); 450 uptr pc = 0; 451 Acquire(thr, pc, (uptr)arg); 452 AtExitCtx *ctx = (AtExitCtx*)arg; 453 ((void(*)(int status, void *arg))ctx->f)(status, ctx->arg); 454 InternalFree(ctx); 455 } 456 457 TSAN_INTERCEPTOR(int, on_exit, void(*f)(int, void*), void *arg) { 458 if (in_symbolizer()) 459 return 0; 460 SCOPED_TSAN_INTERCEPTOR(on_exit, f, arg); 461 AtExitCtx *ctx = (AtExitCtx*)InternalAlloc(sizeof(AtExitCtx)); 462 ctx->f = (void(*)())f; 463 ctx->arg = arg; 464 Release(thr, pc, (uptr)ctx); 465 // Memory allocation in __cxa_atexit will race with free during exit, 466 // because we do not see synchronization around atexit callback list. 467 ThreadIgnoreBegin(thr, pc); 468 int res = REAL(on_exit)(on_exit_wrapper, ctx); 469 ThreadIgnoreEnd(thr, pc); 470 return res; 471 } 472 #define TSAN_MAYBE_INTERCEPT_ON_EXIT TSAN_INTERCEPT(on_exit) 473 #else 474 #define TSAN_MAYBE_INTERCEPT_ON_EXIT 475 #endif 476 477 // Cleanup old bufs. 478 static void JmpBufGarbageCollect(ThreadState *thr, uptr sp) { 479 for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) { 480 JmpBuf *buf = &thr->jmp_bufs[i]; 481 if (buf->sp <= sp) { 482 uptr sz = thr->jmp_bufs.Size(); 483 internal_memcpy(buf, &thr->jmp_bufs[sz - 1], sizeof(*buf)); 484 thr->jmp_bufs.PopBack(); 485 i--; 486 } 487 } 488 } 489 490 static void SetJmp(ThreadState *thr, uptr sp) { 491 if (!thr->is_inited) // called from libc guts during bootstrap 492 return; 493 // Cleanup old bufs. 494 JmpBufGarbageCollect(thr, sp); 495 // Remember the buf. 496 JmpBuf *buf = thr->jmp_bufs.PushBack(); 497 buf->sp = sp; 498 buf->shadow_stack_pos = thr->shadow_stack_pos; 499 ThreadSignalContext *sctx = SigCtx(thr); 500 buf->int_signal_send = sctx ? sctx->int_signal_send : 0; 501 buf->in_blocking_func = sctx ? 502 atomic_load(&sctx->in_blocking_func, memory_order_relaxed) : 503 false; 504 buf->in_signal_handler = atomic_load(&thr->in_signal_handler, 505 memory_order_relaxed); 506 } 507 508 static void LongJmp(ThreadState *thr, uptr *env) { 509 uptr sp = ExtractLongJmpSp(env); 510 // Find the saved buf with matching sp. 511 for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) { 512 JmpBuf *buf = &thr->jmp_bufs[i]; 513 if (buf->sp == sp) { 514 CHECK_GE(thr->shadow_stack_pos, buf->shadow_stack_pos); 515 // Unwind the stack. 516 while (thr->shadow_stack_pos > buf->shadow_stack_pos) 517 FuncExit(thr); 518 ThreadSignalContext *sctx = SigCtx(thr); 519 if (sctx) { 520 sctx->int_signal_send = buf->int_signal_send; 521 atomic_store(&sctx->in_blocking_func, buf->in_blocking_func, 522 memory_order_relaxed); 523 } 524 atomic_store(&thr->in_signal_handler, buf->in_signal_handler, 525 memory_order_relaxed); 526 JmpBufGarbageCollect(thr, buf->sp - 1); // do not collect buf->sp 527 return; 528 } 529 } 530 Printf("ThreadSanitizer: can't find longjmp buf\n"); 531 CHECK(0); 532 } 533 534 // FIXME: put everything below into a common extern "C" block? 535 extern "C" void __tsan_setjmp(uptr sp) { 536 cur_thread_init(); 537 SetJmp(cur_thread(), sp); 538 } 539 540 #if SANITIZER_MAC 541 TSAN_INTERCEPTOR(int, setjmp, void *env); 542 TSAN_INTERCEPTOR(int, _setjmp, void *env); 543 TSAN_INTERCEPTOR(int, sigsetjmp, void *env); 544 #else // SANITIZER_MAC 545 546 #if SANITIZER_NETBSD 547 #define setjmp_symname __setjmp14 548 #define sigsetjmp_symname __sigsetjmp14 549 #else 550 #define setjmp_symname setjmp 551 #define sigsetjmp_symname sigsetjmp 552 #endif 553 554 #define TSAN_INTERCEPTOR_SETJMP_(x) __interceptor_ ## x 555 #define TSAN_INTERCEPTOR_SETJMP__(x) TSAN_INTERCEPTOR_SETJMP_(x) 556 #define TSAN_INTERCEPTOR_SETJMP TSAN_INTERCEPTOR_SETJMP__(setjmp_symname) 557 #define TSAN_INTERCEPTOR_SIGSETJMP TSAN_INTERCEPTOR_SETJMP__(sigsetjmp_symname) 558 559 #define TSAN_STRING_SETJMP SANITIZER_STRINGIFY(setjmp_symname) 560 #define TSAN_STRING_SIGSETJMP SANITIZER_STRINGIFY(sigsetjmp_symname) 561 562 // Not called. Merely to satisfy TSAN_INTERCEPT(). 563 extern "C" SANITIZER_INTERFACE_ATTRIBUTE 564 int TSAN_INTERCEPTOR_SETJMP(void *env); 565 extern "C" int TSAN_INTERCEPTOR_SETJMP(void *env) { 566 CHECK(0); 567 return 0; 568 } 569 570 // FIXME: any reason to have a separate declaration? 571 extern "C" SANITIZER_INTERFACE_ATTRIBUTE 572 int __interceptor__setjmp(void *env); 573 extern "C" int __interceptor__setjmp(void *env) { 574 CHECK(0); 575 return 0; 576 } 577 578 extern "C" SANITIZER_INTERFACE_ATTRIBUTE 579 int TSAN_INTERCEPTOR_SIGSETJMP(void *env); 580 extern "C" int TSAN_INTERCEPTOR_SIGSETJMP(void *env) { 581 CHECK(0); 582 return 0; 583 } 584 585 #if !SANITIZER_NETBSD 586 extern "C" SANITIZER_INTERFACE_ATTRIBUTE 587 int __interceptor___sigsetjmp(void *env); 588 extern "C" int __interceptor___sigsetjmp(void *env) { 589 CHECK(0); 590 return 0; 591 } 592 #endif 593 594 extern "C" int setjmp_symname(void *env); 595 extern "C" int _setjmp(void *env); 596 extern "C" int sigsetjmp_symname(void *env); 597 #if !SANITIZER_NETBSD 598 extern "C" int __sigsetjmp(void *env); 599 #endif 600 DEFINE_REAL(int, setjmp_symname, void *env) 601 DEFINE_REAL(int, _setjmp, void *env) 602 DEFINE_REAL(int, sigsetjmp_symname, void *env) 603 #if !SANITIZER_NETBSD 604 DEFINE_REAL(int, __sigsetjmp, void *env) 605 #endif 606 #endif // SANITIZER_MAC 607 608 #if SANITIZER_NETBSD 609 #define longjmp_symname __longjmp14 610 #define siglongjmp_symname __siglongjmp14 611 #else 612 #define longjmp_symname longjmp 613 #define siglongjmp_symname siglongjmp 614 #endif 615 616 TSAN_INTERCEPTOR(void, longjmp_symname, uptr *env, int val) { 617 // Note: if we call REAL(longjmp) in the context of ScopedInterceptor, 618 // bad things will happen. We will jump over ScopedInterceptor dtor and can 619 // leave thr->in_ignored_lib set. 620 { 621 SCOPED_INTERCEPTOR_RAW(longjmp_symname, env, val); 622 } 623 LongJmp(cur_thread(), env); 624 REAL(longjmp_symname)(env, val); 625 } 626 627 TSAN_INTERCEPTOR(void, siglongjmp_symname, uptr *env, int val) { 628 { 629 SCOPED_INTERCEPTOR_RAW(siglongjmp_symname, env, val); 630 } 631 LongJmp(cur_thread(), env); 632 REAL(siglongjmp_symname)(env, val); 633 } 634 635 #if SANITIZER_NETBSD 636 TSAN_INTERCEPTOR(void, _longjmp, uptr *env, int val) { 637 { 638 SCOPED_INTERCEPTOR_RAW(_longjmp, env, val); 639 } 640 LongJmp(cur_thread(), env); 641 REAL(_longjmp)(env, val); 642 } 643 #endif 644 645 #if !SANITIZER_MAC 646 TSAN_INTERCEPTOR(void*, malloc, uptr size) { 647 if (in_symbolizer()) 648 return InternalAlloc(size); 649 void *p = 0; 650 { 651 SCOPED_INTERCEPTOR_RAW(malloc, size); 652 p = user_alloc(thr, pc, size); 653 } 654 invoke_malloc_hook(p, size); 655 return p; 656 } 657 658 TSAN_INTERCEPTOR(void*, __libc_memalign, uptr align, uptr sz) { 659 SCOPED_TSAN_INTERCEPTOR(__libc_memalign, align, sz); 660 return user_memalign(thr, pc, align, sz); 661 } 662 663 TSAN_INTERCEPTOR(void*, calloc, uptr size, uptr n) { 664 if (in_symbolizer()) 665 return InternalCalloc(size, n); 666 void *p = 0; 667 { 668 SCOPED_INTERCEPTOR_RAW(calloc, size, n); 669 p = user_calloc(thr, pc, size, n); 670 } 671 invoke_malloc_hook(p, n * size); 672 return p; 673 } 674 675 TSAN_INTERCEPTOR(void*, realloc, void *p, uptr size) { 676 if (in_symbolizer()) 677 return InternalRealloc(p, size); 678 if (p) 679 invoke_free_hook(p); 680 { 681 SCOPED_INTERCEPTOR_RAW(realloc, p, size); 682 p = user_realloc(thr, pc, p, size); 683 } 684 invoke_malloc_hook(p, size); 685 return p; 686 } 687 688 TSAN_INTERCEPTOR(void*, reallocarray, void *p, uptr size, uptr n) { 689 if (in_symbolizer()) 690 return InternalReallocArray(p, size, n); 691 if (p) 692 invoke_free_hook(p); 693 { 694 SCOPED_INTERCEPTOR_RAW(reallocarray, p, size, n); 695 p = user_reallocarray(thr, pc, p, size, n); 696 } 697 invoke_malloc_hook(p, size); 698 return p; 699 } 700 701 TSAN_INTERCEPTOR(void, free, void *p) { 702 if (p == 0) 703 return; 704 if (in_symbolizer()) 705 return InternalFree(p); 706 invoke_free_hook(p); 707 SCOPED_INTERCEPTOR_RAW(free, p); 708 user_free(thr, pc, p); 709 } 710 711 TSAN_INTERCEPTOR(void, cfree, void *p) { 712 if (p == 0) 713 return; 714 if (in_symbolizer()) 715 return InternalFree(p); 716 invoke_free_hook(p); 717 SCOPED_INTERCEPTOR_RAW(cfree, p); 718 user_free(thr, pc, p); 719 } 720 721 TSAN_INTERCEPTOR(uptr, malloc_usable_size, void *p) { 722 SCOPED_INTERCEPTOR_RAW(malloc_usable_size, p); 723 return user_alloc_usable_size(p); 724 } 725 #endif 726 727 TSAN_INTERCEPTOR(char *, strcpy, char *dst, const char *src) { 728 SCOPED_TSAN_INTERCEPTOR(strcpy, dst, src); 729 uptr srclen = internal_strlen(src); 730 MemoryAccessRange(thr, pc, (uptr)dst, srclen + 1, true); 731 MemoryAccessRange(thr, pc, (uptr)src, srclen + 1, false); 732 return REAL(strcpy)(dst, src); 733 } 734 735 TSAN_INTERCEPTOR(char*, strncpy, char *dst, char *src, uptr n) { 736 SCOPED_TSAN_INTERCEPTOR(strncpy, dst, src, n); 737 uptr srclen = internal_strnlen(src, n); 738 MemoryAccessRange(thr, pc, (uptr)dst, n, true); 739 MemoryAccessRange(thr, pc, (uptr)src, min(srclen + 1, n), false); 740 return REAL(strncpy)(dst, src, n); 741 } 742 743 TSAN_INTERCEPTOR(char*, strdup, const char *str) { 744 SCOPED_TSAN_INTERCEPTOR(strdup, str); 745 // strdup will call malloc, so no instrumentation is required here. 746 return REAL(strdup)(str); 747 } 748 749 // Zero out addr if it points into shadow memory and was provided as a hint 750 // only, i.e., MAP_FIXED is not set. 751 static bool fix_mmap_addr(void **addr, long_t sz, int flags) { 752 if (*addr) { 753 if (!IsAppMem((uptr)*addr) || !IsAppMem((uptr)*addr + sz - 1)) { 754 if (flags & MAP_FIXED) { 755 errno = errno_EINVAL; 756 return false; 757 } else { 758 *addr = 0; 759 } 760 } 761 } 762 return true; 763 } 764 765 template <class Mmap> 766 static void *mmap_interceptor(ThreadState *thr, uptr pc, Mmap real_mmap, 767 void *addr, SIZE_T sz, int prot, int flags, 768 int fd, OFF64_T off) { 769 if (!fix_mmap_addr(&addr, sz, flags)) return MAP_FAILED; 770 void *res = real_mmap(addr, sz, prot, flags, fd, off); 771 if (res != MAP_FAILED) { 772 if (fd > 0) FdAccess(thr, pc, fd); 773 MemoryRangeImitateWriteOrResetRange(thr, pc, (uptr)res, sz); 774 } 775 return res; 776 } 777 778 TSAN_INTERCEPTOR(int, munmap, void *addr, long_t sz) { 779 SCOPED_TSAN_INTERCEPTOR(munmap, addr, sz); 780 UnmapShadow(thr, (uptr)addr, sz); 781 int res = REAL(munmap)(addr, sz); 782 return res; 783 } 784 785 #if SANITIZER_LINUX 786 TSAN_INTERCEPTOR(void*, memalign, uptr align, uptr sz) { 787 SCOPED_INTERCEPTOR_RAW(memalign, align, sz); 788 return user_memalign(thr, pc, align, sz); 789 } 790 #define TSAN_MAYBE_INTERCEPT_MEMALIGN TSAN_INTERCEPT(memalign) 791 #else 792 #define TSAN_MAYBE_INTERCEPT_MEMALIGN 793 #endif 794 795 #if !SANITIZER_MAC 796 TSAN_INTERCEPTOR(void*, aligned_alloc, uptr align, uptr sz) { 797 if (in_symbolizer()) 798 return InternalAlloc(sz, nullptr, align); 799 SCOPED_INTERCEPTOR_RAW(aligned_alloc, align, sz); 800 return user_aligned_alloc(thr, pc, align, sz); 801 } 802 803 TSAN_INTERCEPTOR(void*, valloc, uptr sz) { 804 if (in_symbolizer()) 805 return InternalAlloc(sz, nullptr, GetPageSizeCached()); 806 SCOPED_INTERCEPTOR_RAW(valloc, sz); 807 return user_valloc(thr, pc, sz); 808 } 809 #endif 810 811 #if SANITIZER_LINUX 812 TSAN_INTERCEPTOR(void*, pvalloc, uptr sz) { 813 if (in_symbolizer()) { 814 uptr PageSize = GetPageSizeCached(); 815 sz = sz ? RoundUpTo(sz, PageSize) : PageSize; 816 return InternalAlloc(sz, nullptr, PageSize); 817 } 818 SCOPED_INTERCEPTOR_RAW(pvalloc, sz); 819 return user_pvalloc(thr, pc, sz); 820 } 821 #define TSAN_MAYBE_INTERCEPT_PVALLOC TSAN_INTERCEPT(pvalloc) 822 #else 823 #define TSAN_MAYBE_INTERCEPT_PVALLOC 824 #endif 825 826 #if !SANITIZER_MAC 827 TSAN_INTERCEPTOR(int, posix_memalign, void **memptr, uptr align, uptr sz) { 828 if (in_symbolizer()) { 829 void *p = InternalAlloc(sz, nullptr, align); 830 if (!p) 831 return errno_ENOMEM; 832 *memptr = p; 833 return 0; 834 } 835 SCOPED_INTERCEPTOR_RAW(posix_memalign, memptr, align, sz); 836 return user_posix_memalign(thr, pc, memptr, align, sz); 837 } 838 #endif 839 840 // __cxa_guard_acquire and friends need to be intercepted in a special way - 841 // regular interceptors will break statically-linked libstdc++. Linux 842 // interceptors are especially defined as weak functions (so that they don't 843 // cause link errors when user defines them as well). So they silently 844 // auto-disable themselves when such symbol is already present in the binary. If 845 // we link libstdc++ statically, it will bring own __cxa_guard_acquire which 846 // will silently replace our interceptor. That's why on Linux we simply export 847 // these interceptors with INTERFACE_ATTRIBUTE. 848 // On OS X, we don't support statically linking, so we just use a regular 849 // interceptor. 850 #if SANITIZER_MAC 851 #define STDCXX_INTERCEPTOR TSAN_INTERCEPTOR 852 #else 853 #define STDCXX_INTERCEPTOR(rettype, name, ...) \ 854 extern "C" rettype INTERFACE_ATTRIBUTE name(__VA_ARGS__) 855 #endif 856 857 // Used in thread-safe function static initialization. 858 STDCXX_INTERCEPTOR(int, __cxa_guard_acquire, atomic_uint32_t *g) { 859 SCOPED_INTERCEPTOR_RAW(__cxa_guard_acquire, g); 860 OnPotentiallyBlockingRegionBegin(); 861 auto on_exit = at_scope_exit(&OnPotentiallyBlockingRegionEnd); 862 for (;;) { 863 u32 cmp = atomic_load(g, memory_order_acquire); 864 if (cmp == 0) { 865 if (atomic_compare_exchange_strong(g, &cmp, 1<<16, memory_order_relaxed)) 866 return 1; 867 } else if (cmp == 1) { 868 Acquire(thr, pc, (uptr)g); 869 return 0; 870 } else { 871 internal_sched_yield(); 872 } 873 } 874 } 875 876 STDCXX_INTERCEPTOR(void, __cxa_guard_release, atomic_uint32_t *g) { 877 SCOPED_INTERCEPTOR_RAW(__cxa_guard_release, g); 878 Release(thr, pc, (uptr)g); 879 atomic_store(g, 1, memory_order_release); 880 } 881 882 STDCXX_INTERCEPTOR(void, __cxa_guard_abort, atomic_uint32_t *g) { 883 SCOPED_INTERCEPTOR_RAW(__cxa_guard_abort, g); 884 atomic_store(g, 0, memory_order_relaxed); 885 } 886 887 namespace __tsan { 888 void DestroyThreadState() { 889 ThreadState *thr = cur_thread(); 890 Processor *proc = thr->proc(); 891 ThreadFinish(thr); 892 ProcUnwire(proc, thr); 893 ProcDestroy(proc); 894 DTLS_Destroy(); 895 cur_thread_finalize(); 896 } 897 898 void PlatformCleanUpThreadState(ThreadState *thr) { 899 ThreadSignalContext *sctx = thr->signal_ctx; 900 if (sctx) { 901 thr->signal_ctx = 0; 902 UnmapOrDie(sctx, sizeof(*sctx)); 903 } 904 } 905 } // namespace __tsan 906 907 #if !SANITIZER_MAC && !SANITIZER_NETBSD && !SANITIZER_FREEBSD 908 static void thread_finalize(void *v) { 909 uptr iter = (uptr)v; 910 if (iter > 1) { 911 if (pthread_setspecific(interceptor_ctx()->finalize_key, 912 (void*)(iter - 1))) { 913 Printf("ThreadSanitizer: failed to set thread key\n"); 914 Die(); 915 } 916 return; 917 } 918 DestroyThreadState(); 919 } 920 #endif 921 922 923 struct ThreadParam { 924 void* (*callback)(void *arg); 925 void *param; 926 atomic_uintptr_t tid; 927 }; 928 929 extern "C" void *__tsan_thread_start_func(void *arg) { 930 ThreadParam *p = (ThreadParam*)arg; 931 void* (*callback)(void *arg) = p->callback; 932 void *param = p->param; 933 int tid = 0; 934 { 935 cur_thread_init(); 936 ThreadState *thr = cur_thread(); 937 // Thread-local state is not initialized yet. 938 ScopedIgnoreInterceptors ignore; 939 #if !SANITIZER_MAC && !SANITIZER_NETBSD && !SANITIZER_FREEBSD 940 ThreadIgnoreBegin(thr, 0); 941 if (pthread_setspecific(interceptor_ctx()->finalize_key, 942 (void *)GetPthreadDestructorIterations())) { 943 Printf("ThreadSanitizer: failed to set thread key\n"); 944 Die(); 945 } 946 ThreadIgnoreEnd(thr, 0); 947 #endif 948 while ((tid = atomic_load(&p->tid, memory_order_acquire)) == 0) 949 internal_sched_yield(); 950 Processor *proc = ProcCreate(); 951 ProcWire(proc, thr); 952 ThreadStart(thr, tid, GetTid(), ThreadType::Regular); 953 atomic_store(&p->tid, 0, memory_order_release); 954 } 955 void *res = callback(param); 956 // Prevent the callback from being tail called, 957 // it mixes up stack traces. 958 volatile int foo = 42; 959 foo++; 960 return res; 961 } 962 963 TSAN_INTERCEPTOR(int, pthread_create, 964 void *th, void *attr, void *(*callback)(void*), void * param) { 965 SCOPED_INTERCEPTOR_RAW(pthread_create, th, attr, callback, param); 966 967 MaybeSpawnBackgroundThread(); 968 969 if (ctx->after_multithreaded_fork) { 970 if (flags()->die_after_fork) { 971 Report("ThreadSanitizer: starting new threads after multi-threaded " 972 "fork is not supported. Dying (set die_after_fork=0 to override)\n"); 973 Die(); 974 } else { 975 VPrintf(1, "ThreadSanitizer: starting new threads after multi-threaded " 976 "fork is not supported (pid %d). Continuing because of " 977 "die_after_fork=0, but you are on your own\n", internal_getpid()); 978 } 979 } 980 __sanitizer_pthread_attr_t myattr; 981 if (attr == 0) { 982 pthread_attr_init(&myattr); 983 attr = &myattr; 984 } 985 int detached = 0; 986 REAL(pthread_attr_getdetachstate)(attr, &detached); 987 AdjustStackSize(attr); 988 989 ThreadParam p; 990 p.callback = callback; 991 p.param = param; 992 atomic_store(&p.tid, 0, memory_order_relaxed); 993 int res = -1; 994 { 995 // Otherwise we see false positives in pthread stack manipulation. 996 ScopedIgnoreInterceptors ignore; 997 ThreadIgnoreBegin(thr, pc); 998 res = REAL(pthread_create)(th, attr, __tsan_thread_start_func, &p); 999 ThreadIgnoreEnd(thr, pc); 1000 } 1001 if (res == 0) { 1002 int tid = ThreadCreate(thr, pc, *(uptr*)th, IsStateDetached(detached)); 1003 CHECK_NE(tid, 0); 1004 // Synchronization on p.tid serves two purposes: 1005 // 1. ThreadCreate must finish before the new thread starts. 1006 // Otherwise the new thread can call pthread_detach, but the pthread_t 1007 // identifier is not yet registered in ThreadRegistry by ThreadCreate. 1008 // 2. ThreadStart must finish before this thread continues. 1009 // Otherwise, this thread can call pthread_detach and reset thr->sync 1010 // before the new thread got a chance to acquire from it in ThreadStart. 1011 atomic_store(&p.tid, tid, memory_order_release); 1012 while (atomic_load(&p.tid, memory_order_acquire) != 0) 1013 internal_sched_yield(); 1014 } 1015 if (attr == &myattr) 1016 pthread_attr_destroy(&myattr); 1017 return res; 1018 } 1019 1020 TSAN_INTERCEPTOR(int, pthread_join, void *th, void **ret) { 1021 SCOPED_INTERCEPTOR_RAW(pthread_join, th, ret); 1022 int tid = ThreadConsumeTid(thr, pc, (uptr)th); 1023 ThreadIgnoreBegin(thr, pc); 1024 int res = BLOCK_REAL(pthread_join)(th, ret); 1025 ThreadIgnoreEnd(thr, pc); 1026 if (res == 0) { 1027 ThreadJoin(thr, pc, tid); 1028 } 1029 return res; 1030 } 1031 1032 DEFINE_REAL_PTHREAD_FUNCTIONS 1033 1034 TSAN_INTERCEPTOR(int, pthread_detach, void *th) { 1035 SCOPED_INTERCEPTOR_RAW(pthread_detach, th); 1036 int tid = ThreadConsumeTid(thr, pc, (uptr)th); 1037 int res = REAL(pthread_detach)(th); 1038 if (res == 0) { 1039 ThreadDetach(thr, pc, tid); 1040 } 1041 return res; 1042 } 1043 1044 TSAN_INTERCEPTOR(void, pthread_exit, void *retval) { 1045 { 1046 SCOPED_INTERCEPTOR_RAW(pthread_exit, retval); 1047 #if !SANITIZER_MAC && !SANITIZER_ANDROID 1048 CHECK_EQ(thr, &cur_thread_placeholder); 1049 #endif 1050 } 1051 REAL(pthread_exit)(retval); 1052 } 1053 1054 #if SANITIZER_LINUX 1055 TSAN_INTERCEPTOR(int, pthread_tryjoin_np, void *th, void **ret) { 1056 SCOPED_INTERCEPTOR_RAW(pthread_tryjoin_np, th, ret); 1057 int tid = ThreadConsumeTid(thr, pc, (uptr)th); 1058 ThreadIgnoreBegin(thr, pc); 1059 int res = REAL(pthread_tryjoin_np)(th, ret); 1060 ThreadIgnoreEnd(thr, pc); 1061 if (res == 0) 1062 ThreadJoin(thr, pc, tid); 1063 else 1064 ThreadNotJoined(thr, pc, tid, (uptr)th); 1065 return res; 1066 } 1067 1068 TSAN_INTERCEPTOR(int, pthread_timedjoin_np, void *th, void **ret, 1069 const struct timespec *abstime) { 1070 SCOPED_INTERCEPTOR_RAW(pthread_timedjoin_np, th, ret, abstime); 1071 int tid = ThreadConsumeTid(thr, pc, (uptr)th); 1072 ThreadIgnoreBegin(thr, pc); 1073 int res = BLOCK_REAL(pthread_timedjoin_np)(th, ret, abstime); 1074 ThreadIgnoreEnd(thr, pc); 1075 if (res == 0) 1076 ThreadJoin(thr, pc, tid); 1077 else 1078 ThreadNotJoined(thr, pc, tid, (uptr)th); 1079 return res; 1080 } 1081 #endif 1082 1083 // Problem: 1084 // NPTL implementation of pthread_cond has 2 versions (2.2.5 and 2.3.2). 1085 // pthread_cond_t has different size in the different versions. 1086 // If call new REAL functions for old pthread_cond_t, they will corrupt memory 1087 // after pthread_cond_t (old cond is smaller). 1088 // If we call old REAL functions for new pthread_cond_t, we will lose some 1089 // functionality (e.g. old functions do not support waiting against 1090 // CLOCK_REALTIME). 1091 // Proper handling would require to have 2 versions of interceptors as well. 1092 // But this is messy, in particular requires linker scripts when sanitizer 1093 // runtime is linked into a shared library. 1094 // Instead we assume we don't have dynamic libraries built against old 1095 // pthread (2.2.5 is dated by 2002). And provide legacy_pthread_cond flag 1096 // that allows to work with old libraries (but this mode does not support 1097 // some features, e.g. pthread_condattr_getpshared). 1098 static void *init_cond(void *c, bool force = false) { 1099 // sizeof(pthread_cond_t) >= sizeof(uptr) in both versions. 1100 // So we allocate additional memory on the side large enough to hold 1101 // any pthread_cond_t object. Always call new REAL functions, but pass 1102 // the aux object to them. 1103 // Note: the code assumes that PTHREAD_COND_INITIALIZER initializes 1104 // first word of pthread_cond_t to zero. 1105 // It's all relevant only for linux. 1106 if (!common_flags()->legacy_pthread_cond) 1107 return c; 1108 atomic_uintptr_t *p = (atomic_uintptr_t*)c; 1109 uptr cond = atomic_load(p, memory_order_acquire); 1110 if (!force && cond != 0) 1111 return (void*)cond; 1112 void *newcond = WRAP(malloc)(pthread_cond_t_sz); 1113 internal_memset(newcond, 0, pthread_cond_t_sz); 1114 if (atomic_compare_exchange_strong(p, &cond, (uptr)newcond, 1115 memory_order_acq_rel)) 1116 return newcond; 1117 WRAP(free)(newcond); 1118 return (void*)cond; 1119 } 1120 1121 namespace { 1122 1123 template <class Fn> 1124 struct CondMutexUnlockCtx { 1125 ScopedInterceptor *si; 1126 ThreadState *thr; 1127 uptr pc; 1128 void *m; 1129 void *c; 1130 const Fn &fn; 1131 1132 int Cancel() const { return fn(); } 1133 void Unlock() const; 1134 }; 1135 1136 template <class Fn> 1137 void CondMutexUnlockCtx<Fn>::Unlock() const { 1138 // pthread_cond_wait interceptor has enabled async signal delivery 1139 // (see BlockingCall below). Disable async signals since we are running 1140 // tsan code. Also ScopedInterceptor and BlockingCall destructors won't run 1141 // since the thread is cancelled, so we have to manually execute them 1142 // (the thread still can run some user code due to pthread_cleanup_push). 1143 ThreadSignalContext *ctx = SigCtx(thr); 1144 CHECK_EQ(atomic_load(&ctx->in_blocking_func, memory_order_relaxed), 1); 1145 atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed); 1146 MutexPostLock(thr, pc, (uptr)m, MutexFlagDoPreLockOnPostLock); 1147 // Undo BlockingCall ctor effects. 1148 thr->ignore_interceptors--; 1149 si->~ScopedInterceptor(); 1150 } 1151 } // namespace 1152 1153 INTERCEPTOR(int, pthread_cond_init, void *c, void *a) { 1154 void *cond = init_cond(c, true); 1155 SCOPED_TSAN_INTERCEPTOR(pthread_cond_init, cond, a); 1156 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true); 1157 return REAL(pthread_cond_init)(cond, a); 1158 } 1159 1160 template <class Fn> 1161 int cond_wait(ThreadState *thr, uptr pc, ScopedInterceptor *si, const Fn &fn, 1162 void *c, void *m) { 1163 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false); 1164 MutexUnlock(thr, pc, (uptr)m); 1165 int res = 0; 1166 // This ensures that we handle mutex lock even in case of pthread_cancel. 1167 // See test/tsan/cond_cancel.cpp. 1168 { 1169 // Enable signal delivery while the thread is blocked. 1170 BlockingCall bc(thr); 1171 CondMutexUnlockCtx<Fn> arg = {si, thr, pc, m, c, fn}; 1172 res = call_pthread_cancel_with_cleanup( 1173 [](void *arg) -> int { 1174 return ((const CondMutexUnlockCtx<Fn> *)arg)->Cancel(); 1175 }, 1176 [](void *arg) { ((const CondMutexUnlockCtx<Fn> *)arg)->Unlock(); }, 1177 &arg); 1178 } 1179 if (res == errno_EOWNERDEAD) MutexRepair(thr, pc, (uptr)m); 1180 MutexPostLock(thr, pc, (uptr)m, MutexFlagDoPreLockOnPostLock); 1181 return res; 1182 } 1183 1184 INTERCEPTOR(int, pthread_cond_wait, void *c, void *m) { 1185 void *cond = init_cond(c); 1186 SCOPED_TSAN_INTERCEPTOR(pthread_cond_wait, cond, m); 1187 return cond_wait( 1188 thr, pc, &si, [=]() { return REAL(pthread_cond_wait)(cond, m); }, cond, 1189 m); 1190 } 1191 1192 INTERCEPTOR(int, pthread_cond_timedwait, void *c, void *m, void *abstime) { 1193 void *cond = init_cond(c); 1194 SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait, cond, m, abstime); 1195 return cond_wait( 1196 thr, pc, &si, 1197 [=]() { return REAL(pthread_cond_timedwait)(cond, m, abstime); }, cond, 1198 m); 1199 } 1200 1201 #if SANITIZER_LINUX 1202 INTERCEPTOR(int, pthread_cond_clockwait, void *c, void *m, 1203 __sanitizer_clockid_t clock, void *abstime) { 1204 void *cond = init_cond(c); 1205 SCOPED_TSAN_INTERCEPTOR(pthread_cond_clockwait, cond, m, clock, abstime); 1206 return cond_wait( 1207 thr, pc, &si, 1208 [=]() { return REAL(pthread_cond_clockwait)(cond, m, clock, abstime); }, 1209 cond, m); 1210 } 1211 #define TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT TSAN_INTERCEPT(pthread_cond_clockwait) 1212 #else 1213 #define TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT 1214 #endif 1215 1216 #if SANITIZER_MAC 1217 INTERCEPTOR(int, pthread_cond_timedwait_relative_np, void *c, void *m, 1218 void *reltime) { 1219 void *cond = init_cond(c); 1220 SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait_relative_np, cond, m, reltime); 1221 return cond_wait( 1222 thr, pc, &si, 1223 [=]() { 1224 return REAL(pthread_cond_timedwait_relative_np)(cond, m, reltime); 1225 }, 1226 cond, m); 1227 } 1228 #endif 1229 1230 INTERCEPTOR(int, pthread_cond_signal, void *c) { 1231 void *cond = init_cond(c); 1232 SCOPED_TSAN_INTERCEPTOR(pthread_cond_signal, cond); 1233 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false); 1234 return REAL(pthread_cond_signal)(cond); 1235 } 1236 1237 INTERCEPTOR(int, pthread_cond_broadcast, void *c) { 1238 void *cond = init_cond(c); 1239 SCOPED_TSAN_INTERCEPTOR(pthread_cond_broadcast, cond); 1240 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false); 1241 return REAL(pthread_cond_broadcast)(cond); 1242 } 1243 1244 INTERCEPTOR(int, pthread_cond_destroy, void *c) { 1245 void *cond = init_cond(c); 1246 SCOPED_TSAN_INTERCEPTOR(pthread_cond_destroy, cond); 1247 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true); 1248 int res = REAL(pthread_cond_destroy)(cond); 1249 if (common_flags()->legacy_pthread_cond) { 1250 // Free our aux cond and zero the pointer to not leave dangling pointers. 1251 WRAP(free)(cond); 1252 atomic_store((atomic_uintptr_t*)c, 0, memory_order_relaxed); 1253 } 1254 return res; 1255 } 1256 1257 TSAN_INTERCEPTOR(int, pthread_mutex_init, void *m, void *a) { 1258 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_init, m, a); 1259 int res = REAL(pthread_mutex_init)(m, a); 1260 if (res == 0) { 1261 u32 flagz = 0; 1262 if (a) { 1263 int type = 0; 1264 if (REAL(pthread_mutexattr_gettype)(a, &type) == 0) 1265 if (type == PTHREAD_MUTEX_RECURSIVE || 1266 type == PTHREAD_MUTEX_RECURSIVE_NP) 1267 flagz |= MutexFlagWriteReentrant; 1268 } 1269 MutexCreate(thr, pc, (uptr)m, flagz); 1270 } 1271 return res; 1272 } 1273 1274 TSAN_INTERCEPTOR(int, pthread_mutex_destroy, void *m) { 1275 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_destroy, m); 1276 int res = REAL(pthread_mutex_destroy)(m); 1277 if (res == 0 || res == errno_EBUSY) { 1278 MutexDestroy(thr, pc, (uptr)m); 1279 } 1280 return res; 1281 } 1282 1283 TSAN_INTERCEPTOR(int, pthread_mutex_trylock, void *m) { 1284 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_trylock, m); 1285 int res = REAL(pthread_mutex_trylock)(m); 1286 if (res == errno_EOWNERDEAD) 1287 MutexRepair(thr, pc, (uptr)m); 1288 if (res == 0 || res == errno_EOWNERDEAD) 1289 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock); 1290 return res; 1291 } 1292 1293 #if !SANITIZER_MAC 1294 TSAN_INTERCEPTOR(int, pthread_mutex_timedlock, void *m, void *abstime) { 1295 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_timedlock, m, abstime); 1296 int res = REAL(pthread_mutex_timedlock)(m, abstime); 1297 if (res == 0) { 1298 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock); 1299 } 1300 return res; 1301 } 1302 #endif 1303 1304 #if !SANITIZER_MAC 1305 TSAN_INTERCEPTOR(int, pthread_spin_init, void *m, int pshared) { 1306 SCOPED_TSAN_INTERCEPTOR(pthread_spin_init, m, pshared); 1307 int res = REAL(pthread_spin_init)(m, pshared); 1308 if (res == 0) { 1309 MutexCreate(thr, pc, (uptr)m); 1310 } 1311 return res; 1312 } 1313 1314 TSAN_INTERCEPTOR(int, pthread_spin_destroy, void *m) { 1315 SCOPED_TSAN_INTERCEPTOR(pthread_spin_destroy, m); 1316 int res = REAL(pthread_spin_destroy)(m); 1317 if (res == 0) { 1318 MutexDestroy(thr, pc, (uptr)m); 1319 } 1320 return res; 1321 } 1322 1323 TSAN_INTERCEPTOR(int, pthread_spin_lock, void *m) { 1324 SCOPED_TSAN_INTERCEPTOR(pthread_spin_lock, m); 1325 MutexPreLock(thr, pc, (uptr)m); 1326 int res = REAL(pthread_spin_lock)(m); 1327 if (res == 0) { 1328 MutexPostLock(thr, pc, (uptr)m); 1329 } 1330 return res; 1331 } 1332 1333 TSAN_INTERCEPTOR(int, pthread_spin_trylock, void *m) { 1334 SCOPED_TSAN_INTERCEPTOR(pthread_spin_trylock, m); 1335 int res = REAL(pthread_spin_trylock)(m); 1336 if (res == 0) { 1337 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock); 1338 } 1339 return res; 1340 } 1341 1342 TSAN_INTERCEPTOR(int, pthread_spin_unlock, void *m) { 1343 SCOPED_TSAN_INTERCEPTOR(pthread_spin_unlock, m); 1344 MutexUnlock(thr, pc, (uptr)m); 1345 int res = REAL(pthread_spin_unlock)(m); 1346 return res; 1347 } 1348 #endif 1349 1350 TSAN_INTERCEPTOR(int, pthread_rwlock_init, void *m, void *a) { 1351 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_init, m, a); 1352 int res = REAL(pthread_rwlock_init)(m, a); 1353 if (res == 0) { 1354 MutexCreate(thr, pc, (uptr)m); 1355 } 1356 return res; 1357 } 1358 1359 TSAN_INTERCEPTOR(int, pthread_rwlock_destroy, void *m) { 1360 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_destroy, m); 1361 int res = REAL(pthread_rwlock_destroy)(m); 1362 if (res == 0) { 1363 MutexDestroy(thr, pc, (uptr)m); 1364 } 1365 return res; 1366 } 1367 1368 TSAN_INTERCEPTOR(int, pthread_rwlock_rdlock, void *m) { 1369 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_rdlock, m); 1370 MutexPreReadLock(thr, pc, (uptr)m); 1371 int res = REAL(pthread_rwlock_rdlock)(m); 1372 if (res == 0) { 1373 MutexPostReadLock(thr, pc, (uptr)m); 1374 } 1375 return res; 1376 } 1377 1378 TSAN_INTERCEPTOR(int, pthread_rwlock_tryrdlock, void *m) { 1379 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_tryrdlock, m); 1380 int res = REAL(pthread_rwlock_tryrdlock)(m); 1381 if (res == 0) { 1382 MutexPostReadLock(thr, pc, (uptr)m, MutexFlagTryLock); 1383 } 1384 return res; 1385 } 1386 1387 #if !SANITIZER_MAC 1388 TSAN_INTERCEPTOR(int, pthread_rwlock_timedrdlock, void *m, void *abstime) { 1389 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedrdlock, m, abstime); 1390 int res = REAL(pthread_rwlock_timedrdlock)(m, abstime); 1391 if (res == 0) { 1392 MutexPostReadLock(thr, pc, (uptr)m); 1393 } 1394 return res; 1395 } 1396 #endif 1397 1398 TSAN_INTERCEPTOR(int, pthread_rwlock_wrlock, void *m) { 1399 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_wrlock, m); 1400 MutexPreLock(thr, pc, (uptr)m); 1401 int res = REAL(pthread_rwlock_wrlock)(m); 1402 if (res == 0) { 1403 MutexPostLock(thr, pc, (uptr)m); 1404 } 1405 return res; 1406 } 1407 1408 TSAN_INTERCEPTOR(int, pthread_rwlock_trywrlock, void *m) { 1409 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_trywrlock, m); 1410 int res = REAL(pthread_rwlock_trywrlock)(m); 1411 if (res == 0) { 1412 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock); 1413 } 1414 return res; 1415 } 1416 1417 #if !SANITIZER_MAC 1418 TSAN_INTERCEPTOR(int, pthread_rwlock_timedwrlock, void *m, void *abstime) { 1419 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedwrlock, m, abstime); 1420 int res = REAL(pthread_rwlock_timedwrlock)(m, abstime); 1421 if (res == 0) { 1422 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock); 1423 } 1424 return res; 1425 } 1426 #endif 1427 1428 TSAN_INTERCEPTOR(int, pthread_rwlock_unlock, void *m) { 1429 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_unlock, m); 1430 MutexReadOrWriteUnlock(thr, pc, (uptr)m); 1431 int res = REAL(pthread_rwlock_unlock)(m); 1432 return res; 1433 } 1434 1435 #if !SANITIZER_MAC 1436 TSAN_INTERCEPTOR(int, pthread_barrier_init, void *b, void *a, unsigned count) { 1437 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_init, b, a, count); 1438 MemoryWrite(thr, pc, (uptr)b, kSizeLog1); 1439 int res = REAL(pthread_barrier_init)(b, a, count); 1440 return res; 1441 } 1442 1443 TSAN_INTERCEPTOR(int, pthread_barrier_destroy, void *b) { 1444 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_destroy, b); 1445 MemoryWrite(thr, pc, (uptr)b, kSizeLog1); 1446 int res = REAL(pthread_barrier_destroy)(b); 1447 return res; 1448 } 1449 1450 TSAN_INTERCEPTOR(int, pthread_barrier_wait, void *b) { 1451 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_wait, b); 1452 Release(thr, pc, (uptr)b); 1453 MemoryRead(thr, pc, (uptr)b, kSizeLog1); 1454 int res = REAL(pthread_barrier_wait)(b); 1455 MemoryRead(thr, pc, (uptr)b, kSizeLog1); 1456 if (res == 0 || res == PTHREAD_BARRIER_SERIAL_THREAD) { 1457 Acquire(thr, pc, (uptr)b); 1458 } 1459 return res; 1460 } 1461 #endif 1462 1463 TSAN_INTERCEPTOR(int, pthread_once, void *o, void (*f)()) { 1464 SCOPED_INTERCEPTOR_RAW(pthread_once, o, f); 1465 if (o == 0 || f == 0) 1466 return errno_EINVAL; 1467 atomic_uint32_t *a; 1468 1469 if (SANITIZER_MAC) 1470 a = static_cast<atomic_uint32_t*>((void *)((char *)o + sizeof(long_t))); 1471 else if (SANITIZER_NETBSD) 1472 a = static_cast<atomic_uint32_t*> 1473 ((void *)((char *)o + __sanitizer::pthread_mutex_t_sz)); 1474 else 1475 a = static_cast<atomic_uint32_t*>(o); 1476 1477 u32 v = atomic_load(a, memory_order_acquire); 1478 if (v == 0 && atomic_compare_exchange_strong(a, &v, 1, 1479 memory_order_relaxed)) { 1480 (*f)(); 1481 if (!thr->in_ignored_lib) 1482 Release(thr, pc, (uptr)o); 1483 atomic_store(a, 2, memory_order_release); 1484 } else { 1485 while (v != 2) { 1486 internal_sched_yield(); 1487 v = atomic_load(a, memory_order_acquire); 1488 } 1489 if (!thr->in_ignored_lib) 1490 Acquire(thr, pc, (uptr)o); 1491 } 1492 return 0; 1493 } 1494 1495 #if SANITIZER_LINUX && !SANITIZER_ANDROID 1496 TSAN_INTERCEPTOR(int, __fxstat, int version, int fd, void *buf) { 1497 SCOPED_TSAN_INTERCEPTOR(__fxstat, version, fd, buf); 1498 if (fd > 0) 1499 FdAccess(thr, pc, fd); 1500 return REAL(__fxstat)(version, fd, buf); 1501 } 1502 #define TSAN_MAYBE_INTERCEPT___FXSTAT TSAN_INTERCEPT(__fxstat) 1503 #else 1504 #define TSAN_MAYBE_INTERCEPT___FXSTAT 1505 #endif 1506 1507 TSAN_INTERCEPTOR(int, fstat, int fd, void *buf) { 1508 #if SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_ANDROID || SANITIZER_NETBSD 1509 SCOPED_TSAN_INTERCEPTOR(fstat, fd, buf); 1510 if (fd > 0) 1511 FdAccess(thr, pc, fd); 1512 return REAL(fstat)(fd, buf); 1513 #else 1514 SCOPED_TSAN_INTERCEPTOR(__fxstat, 0, fd, buf); 1515 if (fd > 0) 1516 FdAccess(thr, pc, fd); 1517 return REAL(__fxstat)(0, fd, buf); 1518 #endif 1519 } 1520 1521 #if SANITIZER_LINUX && !SANITIZER_ANDROID 1522 TSAN_INTERCEPTOR(int, __fxstat64, int version, int fd, void *buf) { 1523 SCOPED_TSAN_INTERCEPTOR(__fxstat64, version, fd, buf); 1524 if (fd > 0) 1525 FdAccess(thr, pc, fd); 1526 return REAL(__fxstat64)(version, fd, buf); 1527 } 1528 #define TSAN_MAYBE_INTERCEPT___FXSTAT64 TSAN_INTERCEPT(__fxstat64) 1529 #else 1530 #define TSAN_MAYBE_INTERCEPT___FXSTAT64 1531 #endif 1532 1533 #if SANITIZER_LINUX && !SANITIZER_ANDROID 1534 TSAN_INTERCEPTOR(int, fstat64, int fd, void *buf) { 1535 SCOPED_TSAN_INTERCEPTOR(__fxstat64, 0, fd, buf); 1536 if (fd > 0) 1537 FdAccess(thr, pc, fd); 1538 return REAL(__fxstat64)(0, fd, buf); 1539 } 1540 #define TSAN_MAYBE_INTERCEPT_FSTAT64 TSAN_INTERCEPT(fstat64) 1541 #else 1542 #define TSAN_MAYBE_INTERCEPT_FSTAT64 1543 #endif 1544 1545 TSAN_INTERCEPTOR(int, open, const char *name, int oflag, ...) { 1546 va_list ap; 1547 va_start(ap, oflag); 1548 mode_t mode = va_arg(ap, int); 1549 va_end(ap); 1550 SCOPED_TSAN_INTERCEPTOR(open, name, oflag, mode); 1551 READ_STRING(thr, pc, name, 0); 1552 int fd = REAL(open)(name, oflag, mode); 1553 if (fd >= 0) 1554 FdFileCreate(thr, pc, fd); 1555 return fd; 1556 } 1557 1558 #if SANITIZER_LINUX 1559 TSAN_INTERCEPTOR(int, open64, const char *name, int oflag, ...) { 1560 va_list ap; 1561 va_start(ap, oflag); 1562 mode_t mode = va_arg(ap, int); 1563 va_end(ap); 1564 SCOPED_TSAN_INTERCEPTOR(open64, name, oflag, mode); 1565 READ_STRING(thr, pc, name, 0); 1566 int fd = REAL(open64)(name, oflag, mode); 1567 if (fd >= 0) 1568 FdFileCreate(thr, pc, fd); 1569 return fd; 1570 } 1571 #define TSAN_MAYBE_INTERCEPT_OPEN64 TSAN_INTERCEPT(open64) 1572 #else 1573 #define TSAN_MAYBE_INTERCEPT_OPEN64 1574 #endif 1575 1576 TSAN_INTERCEPTOR(int, creat, const char *name, int mode) { 1577 SCOPED_TSAN_INTERCEPTOR(creat, name, mode); 1578 READ_STRING(thr, pc, name, 0); 1579 int fd = REAL(creat)(name, mode); 1580 if (fd >= 0) 1581 FdFileCreate(thr, pc, fd); 1582 return fd; 1583 } 1584 1585 #if SANITIZER_LINUX 1586 TSAN_INTERCEPTOR(int, creat64, const char *name, int mode) { 1587 SCOPED_TSAN_INTERCEPTOR(creat64, name, mode); 1588 READ_STRING(thr, pc, name, 0); 1589 int fd = REAL(creat64)(name, mode); 1590 if (fd >= 0) 1591 FdFileCreate(thr, pc, fd); 1592 return fd; 1593 } 1594 #define TSAN_MAYBE_INTERCEPT_CREAT64 TSAN_INTERCEPT(creat64) 1595 #else 1596 #define TSAN_MAYBE_INTERCEPT_CREAT64 1597 #endif 1598 1599 TSAN_INTERCEPTOR(int, dup, int oldfd) { 1600 SCOPED_TSAN_INTERCEPTOR(dup, oldfd); 1601 int newfd = REAL(dup)(oldfd); 1602 if (oldfd >= 0 && newfd >= 0 && newfd != oldfd) 1603 FdDup(thr, pc, oldfd, newfd, true); 1604 return newfd; 1605 } 1606 1607 TSAN_INTERCEPTOR(int, dup2, int oldfd, int newfd) { 1608 SCOPED_TSAN_INTERCEPTOR(dup2, oldfd, newfd); 1609 int newfd2 = REAL(dup2)(oldfd, newfd); 1610 if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd) 1611 FdDup(thr, pc, oldfd, newfd2, false); 1612 return newfd2; 1613 } 1614 1615 #if !SANITIZER_MAC 1616 TSAN_INTERCEPTOR(int, dup3, int oldfd, int newfd, int flags) { 1617 SCOPED_TSAN_INTERCEPTOR(dup3, oldfd, newfd, flags); 1618 int newfd2 = REAL(dup3)(oldfd, newfd, flags); 1619 if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd) 1620 FdDup(thr, pc, oldfd, newfd2, false); 1621 return newfd2; 1622 } 1623 #endif 1624 1625 #if SANITIZER_LINUX 1626 TSAN_INTERCEPTOR(int, eventfd, unsigned initval, int flags) { 1627 SCOPED_TSAN_INTERCEPTOR(eventfd, initval, flags); 1628 int fd = REAL(eventfd)(initval, flags); 1629 if (fd >= 0) 1630 FdEventCreate(thr, pc, fd); 1631 return fd; 1632 } 1633 #define TSAN_MAYBE_INTERCEPT_EVENTFD TSAN_INTERCEPT(eventfd) 1634 #else 1635 #define TSAN_MAYBE_INTERCEPT_EVENTFD 1636 #endif 1637 1638 #if SANITIZER_LINUX 1639 TSAN_INTERCEPTOR(int, signalfd, int fd, void *mask, int flags) { 1640 SCOPED_TSAN_INTERCEPTOR(signalfd, fd, mask, flags); 1641 if (fd >= 0) 1642 FdClose(thr, pc, fd); 1643 fd = REAL(signalfd)(fd, mask, flags); 1644 if (fd >= 0) 1645 FdSignalCreate(thr, pc, fd); 1646 return fd; 1647 } 1648 #define TSAN_MAYBE_INTERCEPT_SIGNALFD TSAN_INTERCEPT(signalfd) 1649 #else 1650 #define TSAN_MAYBE_INTERCEPT_SIGNALFD 1651 #endif 1652 1653 #if SANITIZER_LINUX 1654 TSAN_INTERCEPTOR(int, inotify_init, int fake) { 1655 SCOPED_TSAN_INTERCEPTOR(inotify_init, fake); 1656 int fd = REAL(inotify_init)(fake); 1657 if (fd >= 0) 1658 FdInotifyCreate(thr, pc, fd); 1659 return fd; 1660 } 1661 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT TSAN_INTERCEPT(inotify_init) 1662 #else 1663 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT 1664 #endif 1665 1666 #if SANITIZER_LINUX 1667 TSAN_INTERCEPTOR(int, inotify_init1, int flags) { 1668 SCOPED_TSAN_INTERCEPTOR(inotify_init1, flags); 1669 int fd = REAL(inotify_init1)(flags); 1670 if (fd >= 0) 1671 FdInotifyCreate(thr, pc, fd); 1672 return fd; 1673 } 1674 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1 TSAN_INTERCEPT(inotify_init1) 1675 #else 1676 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1 1677 #endif 1678 1679 TSAN_INTERCEPTOR(int, socket, int domain, int type, int protocol) { 1680 SCOPED_TSAN_INTERCEPTOR(socket, domain, type, protocol); 1681 int fd = REAL(socket)(domain, type, protocol); 1682 if (fd >= 0) 1683 FdSocketCreate(thr, pc, fd); 1684 return fd; 1685 } 1686 1687 TSAN_INTERCEPTOR(int, socketpair, int domain, int type, int protocol, int *fd) { 1688 SCOPED_TSAN_INTERCEPTOR(socketpair, domain, type, protocol, fd); 1689 int res = REAL(socketpair)(domain, type, protocol, fd); 1690 if (res == 0 && fd[0] >= 0 && fd[1] >= 0) 1691 FdPipeCreate(thr, pc, fd[0], fd[1]); 1692 return res; 1693 } 1694 1695 TSAN_INTERCEPTOR(int, connect, int fd, void *addr, unsigned addrlen) { 1696 SCOPED_TSAN_INTERCEPTOR(connect, fd, addr, addrlen); 1697 FdSocketConnecting(thr, pc, fd); 1698 int res = REAL(connect)(fd, addr, addrlen); 1699 if (res == 0 && fd >= 0) 1700 FdSocketConnect(thr, pc, fd); 1701 return res; 1702 } 1703 1704 TSAN_INTERCEPTOR(int, bind, int fd, void *addr, unsigned addrlen) { 1705 SCOPED_TSAN_INTERCEPTOR(bind, fd, addr, addrlen); 1706 int res = REAL(bind)(fd, addr, addrlen); 1707 if (fd > 0 && res == 0) 1708 FdAccess(thr, pc, fd); 1709 return res; 1710 } 1711 1712 TSAN_INTERCEPTOR(int, listen, int fd, int backlog) { 1713 SCOPED_TSAN_INTERCEPTOR(listen, fd, backlog); 1714 int res = REAL(listen)(fd, backlog); 1715 if (fd > 0 && res == 0) 1716 FdAccess(thr, pc, fd); 1717 return res; 1718 } 1719 1720 TSAN_INTERCEPTOR(int, close, int fd) { 1721 SCOPED_TSAN_INTERCEPTOR(close, fd); 1722 if (fd >= 0) 1723 FdClose(thr, pc, fd); 1724 return REAL(close)(fd); 1725 } 1726 1727 #if SANITIZER_LINUX 1728 TSAN_INTERCEPTOR(int, __close, int fd) { 1729 SCOPED_TSAN_INTERCEPTOR(__close, fd); 1730 if (fd >= 0) 1731 FdClose(thr, pc, fd); 1732 return REAL(__close)(fd); 1733 } 1734 #define TSAN_MAYBE_INTERCEPT___CLOSE TSAN_INTERCEPT(__close) 1735 #else 1736 #define TSAN_MAYBE_INTERCEPT___CLOSE 1737 #endif 1738 1739 // glibc guts 1740 #if SANITIZER_LINUX && !SANITIZER_ANDROID 1741 TSAN_INTERCEPTOR(void, __res_iclose, void *state, bool free_addr) { 1742 SCOPED_TSAN_INTERCEPTOR(__res_iclose, state, free_addr); 1743 int fds[64]; 1744 int cnt = ExtractResolvFDs(state, fds, ARRAY_SIZE(fds)); 1745 for (int i = 0; i < cnt; i++) { 1746 if (fds[i] > 0) 1747 FdClose(thr, pc, fds[i]); 1748 } 1749 REAL(__res_iclose)(state, free_addr); 1750 } 1751 #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE TSAN_INTERCEPT(__res_iclose) 1752 #else 1753 #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE 1754 #endif 1755 1756 TSAN_INTERCEPTOR(int, pipe, int *pipefd) { 1757 SCOPED_TSAN_INTERCEPTOR(pipe, pipefd); 1758 int res = REAL(pipe)(pipefd); 1759 if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0) 1760 FdPipeCreate(thr, pc, pipefd[0], pipefd[1]); 1761 return res; 1762 } 1763 1764 #if !SANITIZER_MAC 1765 TSAN_INTERCEPTOR(int, pipe2, int *pipefd, int flags) { 1766 SCOPED_TSAN_INTERCEPTOR(pipe2, pipefd, flags); 1767 int res = REAL(pipe2)(pipefd, flags); 1768 if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0) 1769 FdPipeCreate(thr, pc, pipefd[0], pipefd[1]); 1770 return res; 1771 } 1772 #endif 1773 1774 TSAN_INTERCEPTOR(int, unlink, char *path) { 1775 SCOPED_TSAN_INTERCEPTOR(unlink, path); 1776 Release(thr, pc, File2addr(path)); 1777 int res = REAL(unlink)(path); 1778 return res; 1779 } 1780 1781 TSAN_INTERCEPTOR(void*, tmpfile, int fake) { 1782 SCOPED_TSAN_INTERCEPTOR(tmpfile, fake); 1783 void *res = REAL(tmpfile)(fake); 1784 if (res) { 1785 int fd = fileno_unlocked(res); 1786 if (fd >= 0) 1787 FdFileCreate(thr, pc, fd); 1788 } 1789 return res; 1790 } 1791 1792 #if SANITIZER_LINUX 1793 TSAN_INTERCEPTOR(void*, tmpfile64, int fake) { 1794 SCOPED_TSAN_INTERCEPTOR(tmpfile64, fake); 1795 void *res = REAL(tmpfile64)(fake); 1796 if (res) { 1797 int fd = fileno_unlocked(res); 1798 if (fd >= 0) 1799 FdFileCreate(thr, pc, fd); 1800 } 1801 return res; 1802 } 1803 #define TSAN_MAYBE_INTERCEPT_TMPFILE64 TSAN_INTERCEPT(tmpfile64) 1804 #else 1805 #define TSAN_MAYBE_INTERCEPT_TMPFILE64 1806 #endif 1807 1808 static void FlushStreams() { 1809 // Flushing all the streams here may freeze the process if a child thread is 1810 // performing file stream operations at the same time. 1811 REAL(fflush)(stdout); 1812 REAL(fflush)(stderr); 1813 } 1814 1815 TSAN_INTERCEPTOR(void, abort, int fake) { 1816 SCOPED_TSAN_INTERCEPTOR(abort, fake); 1817 FlushStreams(); 1818 REAL(abort)(fake); 1819 } 1820 1821 TSAN_INTERCEPTOR(int, rmdir, char *path) { 1822 SCOPED_TSAN_INTERCEPTOR(rmdir, path); 1823 Release(thr, pc, Dir2addr(path)); 1824 int res = REAL(rmdir)(path); 1825 return res; 1826 } 1827 1828 TSAN_INTERCEPTOR(int, closedir, void *dirp) { 1829 SCOPED_TSAN_INTERCEPTOR(closedir, dirp); 1830 if (dirp) { 1831 int fd = dirfd(dirp); 1832 FdClose(thr, pc, fd); 1833 } 1834 return REAL(closedir)(dirp); 1835 } 1836 1837 #if SANITIZER_LINUX 1838 TSAN_INTERCEPTOR(int, epoll_create, int size) { 1839 SCOPED_TSAN_INTERCEPTOR(epoll_create, size); 1840 int fd = REAL(epoll_create)(size); 1841 if (fd >= 0) 1842 FdPollCreate(thr, pc, fd); 1843 return fd; 1844 } 1845 1846 TSAN_INTERCEPTOR(int, epoll_create1, int flags) { 1847 SCOPED_TSAN_INTERCEPTOR(epoll_create1, flags); 1848 int fd = REAL(epoll_create1)(flags); 1849 if (fd >= 0) 1850 FdPollCreate(thr, pc, fd); 1851 return fd; 1852 } 1853 1854 TSAN_INTERCEPTOR(int, epoll_ctl, int epfd, int op, int fd, void *ev) { 1855 SCOPED_TSAN_INTERCEPTOR(epoll_ctl, epfd, op, fd, ev); 1856 if (epfd >= 0) 1857 FdAccess(thr, pc, epfd); 1858 if (epfd >= 0 && fd >= 0) 1859 FdAccess(thr, pc, fd); 1860 if (op == EPOLL_CTL_ADD && epfd >= 0) 1861 FdRelease(thr, pc, epfd); 1862 int res = REAL(epoll_ctl)(epfd, op, fd, ev); 1863 return res; 1864 } 1865 1866 TSAN_INTERCEPTOR(int, epoll_wait, int epfd, void *ev, int cnt, int timeout) { 1867 SCOPED_TSAN_INTERCEPTOR(epoll_wait, epfd, ev, cnt, timeout); 1868 if (epfd >= 0) 1869 FdAccess(thr, pc, epfd); 1870 int res = BLOCK_REAL(epoll_wait)(epfd, ev, cnt, timeout); 1871 if (res > 0 && epfd >= 0) 1872 FdAcquire(thr, pc, epfd); 1873 return res; 1874 } 1875 1876 TSAN_INTERCEPTOR(int, epoll_pwait, int epfd, void *ev, int cnt, int timeout, 1877 void *sigmask) { 1878 SCOPED_TSAN_INTERCEPTOR(epoll_pwait, epfd, ev, cnt, timeout, sigmask); 1879 if (epfd >= 0) 1880 FdAccess(thr, pc, epfd); 1881 int res = BLOCK_REAL(epoll_pwait)(epfd, ev, cnt, timeout, sigmask); 1882 if (res > 0 && epfd >= 0) 1883 FdAcquire(thr, pc, epfd); 1884 return res; 1885 } 1886 1887 #define TSAN_MAYBE_INTERCEPT_EPOLL \ 1888 TSAN_INTERCEPT(epoll_create); \ 1889 TSAN_INTERCEPT(epoll_create1); \ 1890 TSAN_INTERCEPT(epoll_ctl); \ 1891 TSAN_INTERCEPT(epoll_wait); \ 1892 TSAN_INTERCEPT(epoll_pwait) 1893 #else 1894 #define TSAN_MAYBE_INTERCEPT_EPOLL 1895 #endif 1896 1897 // The following functions are intercepted merely to process pending signals. 1898 // If program blocks signal X, we must deliver the signal before the function 1899 // returns. Similarly, if program unblocks a signal (or returns from sigsuspend) 1900 // it's better to deliver the signal straight away. 1901 TSAN_INTERCEPTOR(int, sigsuspend, const __sanitizer_sigset_t *mask) { 1902 SCOPED_TSAN_INTERCEPTOR(sigsuspend, mask); 1903 return REAL(sigsuspend)(mask); 1904 } 1905 1906 TSAN_INTERCEPTOR(int, sigblock, int mask) { 1907 SCOPED_TSAN_INTERCEPTOR(sigblock, mask); 1908 return REAL(sigblock)(mask); 1909 } 1910 1911 TSAN_INTERCEPTOR(int, sigsetmask, int mask) { 1912 SCOPED_TSAN_INTERCEPTOR(sigsetmask, mask); 1913 return REAL(sigsetmask)(mask); 1914 } 1915 1916 TSAN_INTERCEPTOR(int, pthread_sigmask, int how, const __sanitizer_sigset_t *set, 1917 __sanitizer_sigset_t *oldset) { 1918 SCOPED_TSAN_INTERCEPTOR(pthread_sigmask, how, set, oldset); 1919 return REAL(pthread_sigmask)(how, set, oldset); 1920 } 1921 1922 namespace __tsan { 1923 1924 static void CallUserSignalHandler(ThreadState *thr, bool sync, bool acquire, 1925 bool sigact, int sig, 1926 __sanitizer_siginfo *info, void *uctx) { 1927 __sanitizer_sigaction *sigactions = interceptor_ctx()->sigactions; 1928 if (acquire) 1929 Acquire(thr, 0, (uptr)&sigactions[sig]); 1930 // Signals are generally asynchronous, so if we receive a signals when 1931 // ignores are enabled we should disable ignores. This is critical for sync 1932 // and interceptors, because otherwise we can miss syncronization and report 1933 // false races. 1934 int ignore_reads_and_writes = thr->ignore_reads_and_writes; 1935 int ignore_interceptors = thr->ignore_interceptors; 1936 int ignore_sync = thr->ignore_sync; 1937 if (!ctx->after_multithreaded_fork) { 1938 thr->ignore_reads_and_writes = 0; 1939 thr->fast_state.ClearIgnoreBit(); 1940 thr->ignore_interceptors = 0; 1941 thr->ignore_sync = 0; 1942 } 1943 // Ensure that the handler does not spoil errno. 1944 const int saved_errno = errno; 1945 errno = 99; 1946 // This code races with sigaction. Be careful to not read sa_sigaction twice. 1947 // Also need to remember pc for reporting before the call, 1948 // because the handler can reset it. 1949 volatile uptr pc = 1950 sigact ? (uptr)sigactions[sig].sigaction : (uptr)sigactions[sig].handler; 1951 if (pc != sig_dfl && pc != sig_ign) { 1952 if (sigact) 1953 ((__sanitizer_sigactionhandler_ptr)pc)(sig, info, uctx); 1954 else 1955 ((__sanitizer_sighandler_ptr)pc)(sig); 1956 } 1957 if (!ctx->after_multithreaded_fork) { 1958 thr->ignore_reads_and_writes = ignore_reads_and_writes; 1959 if (ignore_reads_and_writes) 1960 thr->fast_state.SetIgnoreBit(); 1961 thr->ignore_interceptors = ignore_interceptors; 1962 thr->ignore_sync = ignore_sync; 1963 } 1964 // We do not detect errno spoiling for SIGTERM, 1965 // because some SIGTERM handlers do spoil errno but reraise SIGTERM, 1966 // tsan reports false positive in such case. 1967 // It's difficult to properly detect this situation (reraise), 1968 // because in async signal processing case (when handler is called directly 1969 // from rtl_generic_sighandler) we have not yet received the reraised 1970 // signal; and it looks too fragile to intercept all ways to reraise a signal. 1971 if (flags()->report_bugs && !sync && sig != SIGTERM && errno != 99) { 1972 VarSizeStackTrace stack; 1973 // StackTrace::GetNestInstructionPc(pc) is used because return address is 1974 // expected, OutputReport() will undo this. 1975 ObtainCurrentStack(thr, StackTrace::GetNextInstructionPc(pc), &stack); 1976 ThreadRegistryLock l(ctx->thread_registry); 1977 ScopedReport rep(ReportTypeErrnoInSignal); 1978 if (!IsFiredSuppression(ctx, ReportTypeErrnoInSignal, stack)) { 1979 rep.AddStack(stack, true); 1980 OutputReport(thr, rep); 1981 } 1982 } 1983 errno = saved_errno; 1984 } 1985 1986 void ProcessPendingSignals(ThreadState *thr) { 1987 ThreadSignalContext *sctx = SigCtx(thr); 1988 if (sctx == 0 || 1989 atomic_load(&sctx->have_pending_signals, memory_order_relaxed) == 0) 1990 return; 1991 atomic_store(&sctx->have_pending_signals, 0, memory_order_relaxed); 1992 atomic_fetch_add(&thr->in_signal_handler, 1, memory_order_relaxed); 1993 internal_sigfillset(&sctx->emptyset); 1994 int res = REAL(pthread_sigmask)(SIG_SETMASK, &sctx->emptyset, &sctx->oldset); 1995 CHECK_EQ(res, 0); 1996 for (int sig = 0; sig < kSigCount; sig++) { 1997 SignalDesc *signal = &sctx->pending_signals[sig]; 1998 if (signal->armed) { 1999 signal->armed = false; 2000 CallUserSignalHandler(thr, false, true, signal->sigaction, sig, 2001 &signal->siginfo, &signal->ctx); 2002 } 2003 } 2004 res = REAL(pthread_sigmask)(SIG_SETMASK, &sctx->oldset, 0); 2005 CHECK_EQ(res, 0); 2006 atomic_fetch_add(&thr->in_signal_handler, -1, memory_order_relaxed); 2007 } 2008 2009 } // namespace __tsan 2010 2011 static bool is_sync_signal(ThreadSignalContext *sctx, int sig) { 2012 return sig == SIGSEGV || sig == SIGBUS || sig == SIGILL || sig == SIGTRAP || 2013 sig == SIGABRT || sig == SIGFPE || sig == SIGPIPE || sig == SIGSYS || 2014 // If we are sending signal to ourselves, we must process it now. 2015 (sctx && sig == sctx->int_signal_send); 2016 } 2017 2018 void ALWAYS_INLINE rtl_generic_sighandler(bool sigact, int sig, 2019 __sanitizer_siginfo *info, 2020 void *ctx) { 2021 cur_thread_init(); 2022 ThreadState *thr = cur_thread(); 2023 ThreadSignalContext *sctx = SigCtx(thr); 2024 if (sig < 0 || sig >= kSigCount) { 2025 VPrintf(1, "ThreadSanitizer: ignoring signal %d\n", sig); 2026 return; 2027 } 2028 // Don't mess with synchronous signals. 2029 const bool sync = is_sync_signal(sctx, sig); 2030 if (sync || 2031 // If we are in blocking function, we can safely process it now 2032 // (but check if we are in a recursive interceptor, 2033 // i.e. pthread_join()->munmap()). 2034 (sctx && atomic_load(&sctx->in_blocking_func, memory_order_relaxed))) { 2035 atomic_fetch_add(&thr->in_signal_handler, 1, memory_order_relaxed); 2036 if (sctx && atomic_load(&sctx->in_blocking_func, memory_order_relaxed)) { 2037 atomic_store(&sctx->in_blocking_func, 0, memory_order_relaxed); 2038 CallUserSignalHandler(thr, sync, true, sigact, sig, info, ctx); 2039 atomic_store(&sctx->in_blocking_func, 1, memory_order_relaxed); 2040 } else { 2041 // Be very conservative with when we do acquire in this case. 2042 // It's unsafe to do acquire in async handlers, because ThreadState 2043 // can be in inconsistent state. 2044 // SIGSYS looks relatively safe -- it's synchronous and can actually 2045 // need some global state. 2046 bool acq = (sig == SIGSYS); 2047 CallUserSignalHandler(thr, sync, acq, sigact, sig, info, ctx); 2048 } 2049 atomic_fetch_add(&thr->in_signal_handler, -1, memory_order_relaxed); 2050 return; 2051 } 2052 2053 if (sctx == 0) 2054 return; 2055 SignalDesc *signal = &sctx->pending_signals[sig]; 2056 if (signal->armed == false) { 2057 signal->armed = true; 2058 signal->sigaction = sigact; 2059 if (info) 2060 internal_memcpy(&signal->siginfo, info, sizeof(*info)); 2061 if (ctx) 2062 internal_memcpy(&signal->ctx, ctx, sizeof(signal->ctx)); 2063 atomic_store(&sctx->have_pending_signals, 1, memory_order_relaxed); 2064 } 2065 } 2066 2067 static void rtl_sighandler(int sig) { 2068 rtl_generic_sighandler(false, sig, 0, 0); 2069 } 2070 2071 static void rtl_sigaction(int sig, __sanitizer_siginfo *info, void *ctx) { 2072 rtl_generic_sighandler(true, sig, info, ctx); 2073 } 2074 2075 TSAN_INTERCEPTOR(int, raise, int sig) { 2076 SCOPED_TSAN_INTERCEPTOR(raise, sig); 2077 ThreadSignalContext *sctx = SigCtx(thr); 2078 CHECK_NE(sctx, 0); 2079 int prev = sctx->int_signal_send; 2080 sctx->int_signal_send = sig; 2081 int res = REAL(raise)(sig); 2082 CHECK_EQ(sctx->int_signal_send, sig); 2083 sctx->int_signal_send = prev; 2084 return res; 2085 } 2086 2087 TSAN_INTERCEPTOR(int, kill, int pid, int sig) { 2088 SCOPED_TSAN_INTERCEPTOR(kill, pid, sig); 2089 ThreadSignalContext *sctx = SigCtx(thr); 2090 CHECK_NE(sctx, 0); 2091 int prev = sctx->int_signal_send; 2092 if (pid == (int)internal_getpid()) { 2093 sctx->int_signal_send = sig; 2094 } 2095 int res = REAL(kill)(pid, sig); 2096 if (pid == (int)internal_getpid()) { 2097 CHECK_EQ(sctx->int_signal_send, sig); 2098 sctx->int_signal_send = prev; 2099 } 2100 return res; 2101 } 2102 2103 TSAN_INTERCEPTOR(int, pthread_kill, void *tid, int sig) { 2104 SCOPED_TSAN_INTERCEPTOR(pthread_kill, tid, sig); 2105 ThreadSignalContext *sctx = SigCtx(thr); 2106 CHECK_NE(sctx, 0); 2107 int prev = sctx->int_signal_send; 2108 if (tid == pthread_self()) { 2109 sctx->int_signal_send = sig; 2110 } 2111 int res = REAL(pthread_kill)(tid, sig); 2112 if (tid == pthread_self()) { 2113 CHECK_EQ(sctx->int_signal_send, sig); 2114 sctx->int_signal_send = prev; 2115 } 2116 return res; 2117 } 2118 2119 TSAN_INTERCEPTOR(int, gettimeofday, void *tv, void *tz) { 2120 SCOPED_TSAN_INTERCEPTOR(gettimeofday, tv, tz); 2121 // It's intercepted merely to process pending signals. 2122 return REAL(gettimeofday)(tv, tz); 2123 } 2124 2125 TSAN_INTERCEPTOR(int, getaddrinfo, void *node, void *service, 2126 void *hints, void *rv) { 2127 SCOPED_TSAN_INTERCEPTOR(getaddrinfo, node, service, hints, rv); 2128 // We miss atomic synchronization in getaddrinfo, 2129 // and can report false race between malloc and free 2130 // inside of getaddrinfo. So ignore memory accesses. 2131 ThreadIgnoreBegin(thr, pc); 2132 int res = REAL(getaddrinfo)(node, service, hints, rv); 2133 ThreadIgnoreEnd(thr, pc); 2134 return res; 2135 } 2136 2137 TSAN_INTERCEPTOR(int, fork, int fake) { 2138 if (in_symbolizer()) 2139 return REAL(fork)(fake); 2140 SCOPED_INTERCEPTOR_RAW(fork, fake); 2141 ForkBefore(thr, pc); 2142 int pid; 2143 { 2144 // On OS X, REAL(fork) can call intercepted functions (OSSpinLockLock), and 2145 // we'll assert in CheckNoLocks() unless we ignore interceptors. 2146 ScopedIgnoreInterceptors ignore; 2147 pid = REAL(fork)(fake); 2148 } 2149 if (pid == 0) { 2150 // child 2151 ForkChildAfter(thr, pc); 2152 FdOnFork(thr, pc); 2153 } else if (pid > 0) { 2154 // parent 2155 ForkParentAfter(thr, pc); 2156 } else { 2157 // error 2158 ForkParentAfter(thr, pc); 2159 } 2160 return pid; 2161 } 2162 2163 TSAN_INTERCEPTOR(int, vfork, int fake) { 2164 // Some programs (e.g. openjdk) call close for all file descriptors 2165 // in the child process. Under tsan it leads to false positives, because 2166 // address space is shared, so the parent process also thinks that 2167 // the descriptors are closed (while they are actually not). 2168 // This leads to false positives due to missed synchronization. 2169 // Strictly saying this is undefined behavior, because vfork child is not 2170 // allowed to call any functions other than exec/exit. But this is what 2171 // openjdk does, so we want to handle it. 2172 // We could disable interceptors in the child process. But it's not possible 2173 // to simply intercept and wrap vfork, because vfork child is not allowed 2174 // to return from the function that calls vfork, and that's exactly what 2175 // we would do. So this would require some assembly trickery as well. 2176 // Instead we simply turn vfork into fork. 2177 return WRAP(fork)(fake); 2178 } 2179 2180 #if !SANITIZER_MAC && !SANITIZER_ANDROID 2181 typedef int (*dl_iterate_phdr_cb_t)(__sanitizer_dl_phdr_info *info, SIZE_T size, 2182 void *data); 2183 struct dl_iterate_phdr_data { 2184 ThreadState *thr; 2185 uptr pc; 2186 dl_iterate_phdr_cb_t cb; 2187 void *data; 2188 }; 2189 2190 static bool IsAppNotRodata(uptr addr) { 2191 return IsAppMem(addr) && *(u64*)MemToShadow(addr) != kShadowRodata; 2192 } 2193 2194 static int dl_iterate_phdr_cb(__sanitizer_dl_phdr_info *info, SIZE_T size, 2195 void *data) { 2196 dl_iterate_phdr_data *cbdata = (dl_iterate_phdr_data *)data; 2197 // dlopen/dlclose allocate/free dynamic-linker-internal memory, which is later 2198 // accessible in dl_iterate_phdr callback. But we don't see synchronization 2199 // inside of dynamic linker, so we "unpoison" it here in order to not 2200 // produce false reports. Ignoring malloc/free in dlopen/dlclose is not enough 2201 // because some libc functions call __libc_dlopen. 2202 if (info && IsAppNotRodata((uptr)info->dlpi_name)) 2203 MemoryResetRange(cbdata->thr, cbdata->pc, (uptr)info->dlpi_name, 2204 internal_strlen(info->dlpi_name)); 2205 int res = cbdata->cb(info, size, cbdata->data); 2206 // Perform the check one more time in case info->dlpi_name was overwritten 2207 // by user callback. 2208 if (info && IsAppNotRodata((uptr)info->dlpi_name)) 2209 MemoryResetRange(cbdata->thr, cbdata->pc, (uptr)info->dlpi_name, 2210 internal_strlen(info->dlpi_name)); 2211 return res; 2212 } 2213 2214 TSAN_INTERCEPTOR(int, dl_iterate_phdr, dl_iterate_phdr_cb_t cb, void *data) { 2215 SCOPED_TSAN_INTERCEPTOR(dl_iterate_phdr, cb, data); 2216 dl_iterate_phdr_data cbdata; 2217 cbdata.thr = thr; 2218 cbdata.pc = pc; 2219 cbdata.cb = cb; 2220 cbdata.data = data; 2221 int res = REAL(dl_iterate_phdr)(dl_iterate_phdr_cb, &cbdata); 2222 return res; 2223 } 2224 #endif 2225 2226 static int OnExit(ThreadState *thr) { 2227 int status = Finalize(thr); 2228 FlushStreams(); 2229 return status; 2230 } 2231 2232 struct TsanInterceptorContext { 2233 ThreadState *thr; 2234 const uptr caller_pc; 2235 const uptr pc; 2236 }; 2237 2238 #if !SANITIZER_MAC 2239 static void HandleRecvmsg(ThreadState *thr, uptr pc, 2240 __sanitizer_msghdr *msg) { 2241 int fds[64]; 2242 int cnt = ExtractRecvmsgFDs(msg, fds, ARRAY_SIZE(fds)); 2243 for (int i = 0; i < cnt; i++) 2244 FdEventCreate(thr, pc, fds[i]); 2245 } 2246 #endif 2247 2248 #include "sanitizer_common/sanitizer_platform_interceptors.h" 2249 // Causes interceptor recursion (getaddrinfo() and fopen()) 2250 #undef SANITIZER_INTERCEPT_GETADDRINFO 2251 // We define our own. 2252 #if SANITIZER_INTERCEPT_TLS_GET_ADDR 2253 #define NEED_TLS_GET_ADDR 2254 #endif 2255 #undef SANITIZER_INTERCEPT_TLS_GET_ADDR 2256 #undef SANITIZER_INTERCEPT_PTHREAD_SIGMASK 2257 2258 #define COMMON_INTERCEPT_FUNCTION(name) INTERCEPT_FUNCTION(name) 2259 #define COMMON_INTERCEPT_FUNCTION_VER(name, ver) \ 2260 INTERCEPT_FUNCTION_VER(name, ver) 2261 2262 #define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \ 2263 MemoryAccessRange(((TsanInterceptorContext *)ctx)->thr, \ 2264 ((TsanInterceptorContext *)ctx)->pc, (uptr)ptr, size, \ 2265 true) 2266 2267 #define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) \ 2268 MemoryAccessRange(((TsanInterceptorContext *) ctx)->thr, \ 2269 ((TsanInterceptorContext *) ctx)->pc, (uptr) ptr, size, \ 2270 false) 2271 2272 #define COMMON_INTERCEPTOR_ENTER(ctx, func, ...) \ 2273 SCOPED_TSAN_INTERCEPTOR(func, __VA_ARGS__); \ 2274 TsanInterceptorContext _ctx = {thr, caller_pc, pc}; \ 2275 ctx = (void *)&_ctx; \ 2276 (void) ctx; 2277 2278 #define COMMON_INTERCEPTOR_ENTER_NOIGNORE(ctx, func, ...) \ 2279 SCOPED_INTERCEPTOR_RAW(func, __VA_ARGS__); \ 2280 TsanInterceptorContext _ctx = {thr, caller_pc, pc}; \ 2281 ctx = (void *)&_ctx; \ 2282 (void) ctx; 2283 2284 #define COMMON_INTERCEPTOR_FILE_OPEN(ctx, file, path) \ 2285 if (path) \ 2286 Acquire(thr, pc, File2addr(path)); \ 2287 if (file) { \ 2288 int fd = fileno_unlocked(file); \ 2289 if (fd >= 0) FdFileCreate(thr, pc, fd); \ 2290 } 2291 2292 #define COMMON_INTERCEPTOR_FILE_CLOSE(ctx, file) \ 2293 if (file) { \ 2294 int fd = fileno_unlocked(file); \ 2295 if (fd >= 0) FdClose(thr, pc, fd); \ 2296 } 2297 2298 #define COMMON_INTERCEPTOR_LIBRARY_LOADED(filename, handle) \ 2299 libignore()->OnLibraryLoaded(filename) 2300 2301 #define COMMON_INTERCEPTOR_LIBRARY_UNLOADED() \ 2302 libignore()->OnLibraryUnloaded() 2303 2304 #define COMMON_INTERCEPTOR_ACQUIRE(ctx, u) \ 2305 Acquire(((TsanInterceptorContext *) ctx)->thr, pc, u) 2306 2307 #define COMMON_INTERCEPTOR_RELEASE(ctx, u) \ 2308 Release(((TsanInterceptorContext *) ctx)->thr, pc, u) 2309 2310 #define COMMON_INTERCEPTOR_DIR_ACQUIRE(ctx, path) \ 2311 Acquire(((TsanInterceptorContext *) ctx)->thr, pc, Dir2addr(path)) 2312 2313 #define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \ 2314 FdAcquire(((TsanInterceptorContext *) ctx)->thr, pc, fd) 2315 2316 #define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \ 2317 FdRelease(((TsanInterceptorContext *) ctx)->thr, pc, fd) 2318 2319 #define COMMON_INTERCEPTOR_FD_ACCESS(ctx, fd) \ 2320 FdAccess(((TsanInterceptorContext *) ctx)->thr, pc, fd) 2321 2322 #define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \ 2323 FdSocketAccept(((TsanInterceptorContext *) ctx)->thr, pc, fd, newfd) 2324 2325 #define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) \ 2326 ThreadSetName(((TsanInterceptorContext *) ctx)->thr, name) 2327 2328 #define COMMON_INTERCEPTOR_SET_PTHREAD_NAME(ctx, thread, name) \ 2329 __tsan::ctx->thread_registry->SetThreadNameByUserId(thread, name) 2330 2331 #define COMMON_INTERCEPTOR_BLOCK_REAL(name) BLOCK_REAL(name) 2332 2333 #define COMMON_INTERCEPTOR_ON_EXIT(ctx) \ 2334 OnExit(((TsanInterceptorContext *) ctx)->thr) 2335 2336 #define COMMON_INTERCEPTOR_MUTEX_PRE_LOCK(ctx, m) \ 2337 MutexPreLock(((TsanInterceptorContext *)ctx)->thr, \ 2338 ((TsanInterceptorContext *)ctx)->pc, (uptr)m) 2339 2340 #define COMMON_INTERCEPTOR_MUTEX_POST_LOCK(ctx, m) \ 2341 MutexPostLock(((TsanInterceptorContext *)ctx)->thr, \ 2342 ((TsanInterceptorContext *)ctx)->pc, (uptr)m) 2343 2344 #define COMMON_INTERCEPTOR_MUTEX_UNLOCK(ctx, m) \ 2345 MutexUnlock(((TsanInterceptorContext *)ctx)->thr, \ 2346 ((TsanInterceptorContext *)ctx)->pc, (uptr)m) 2347 2348 #define COMMON_INTERCEPTOR_MUTEX_REPAIR(ctx, m) \ 2349 MutexRepair(((TsanInterceptorContext *)ctx)->thr, \ 2350 ((TsanInterceptorContext *)ctx)->pc, (uptr)m) 2351 2352 #define COMMON_INTERCEPTOR_MUTEX_INVALID(ctx, m) \ 2353 MutexInvalidAccess(((TsanInterceptorContext *)ctx)->thr, \ 2354 ((TsanInterceptorContext *)ctx)->pc, (uptr)m) 2355 2356 #define COMMON_INTERCEPTOR_MMAP_IMPL(ctx, mmap, addr, sz, prot, flags, fd, \ 2357 off) \ 2358 do { \ 2359 return mmap_interceptor(thr, pc, REAL(mmap), addr, sz, prot, flags, fd, \ 2360 off); \ 2361 } while (false) 2362 2363 #if !SANITIZER_MAC 2364 #define COMMON_INTERCEPTOR_HANDLE_RECVMSG(ctx, msg) \ 2365 HandleRecvmsg(((TsanInterceptorContext *)ctx)->thr, \ 2366 ((TsanInterceptorContext *)ctx)->pc, msg) 2367 #endif 2368 2369 #define COMMON_INTERCEPTOR_GET_TLS_RANGE(begin, end) \ 2370 if (TsanThread *t = GetCurrentThread()) { \ 2371 *begin = t->tls_begin(); \ 2372 *end = t->tls_end(); \ 2373 } else { \ 2374 *begin = *end = 0; \ 2375 } 2376 2377 #define COMMON_INTERCEPTOR_USER_CALLBACK_START() \ 2378 SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_START() 2379 2380 #define COMMON_INTERCEPTOR_USER_CALLBACK_END() \ 2381 SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_END() 2382 2383 #include "sanitizer_common/sanitizer_common_interceptors.inc" 2384 2385 static int sigaction_impl(int sig, const __sanitizer_sigaction *act, 2386 __sanitizer_sigaction *old); 2387 static __sanitizer_sighandler_ptr signal_impl(int sig, 2388 __sanitizer_sighandler_ptr h); 2389 2390 #define SIGNAL_INTERCEPTOR_SIGACTION_IMPL(signo, act, oldact) \ 2391 { return sigaction_impl(signo, act, oldact); } 2392 2393 #define SIGNAL_INTERCEPTOR_SIGNAL_IMPL(func, signo, handler) \ 2394 { return (uptr)signal_impl(signo, (__sanitizer_sighandler_ptr)handler); } 2395 2396 #include "sanitizer_common/sanitizer_signal_interceptors.inc" 2397 2398 int sigaction_impl(int sig, const __sanitizer_sigaction *act, 2399 __sanitizer_sigaction *old) { 2400 // Note: if we call REAL(sigaction) directly for any reason without proxying 2401 // the signal handler through rtl_sigaction, very bad things will happen. 2402 // The handler will run synchronously and corrupt tsan per-thread state. 2403 SCOPED_INTERCEPTOR_RAW(sigaction, sig, act, old); 2404 __sanitizer_sigaction *sigactions = interceptor_ctx()->sigactions; 2405 __sanitizer_sigaction old_stored; 2406 if (old) internal_memcpy(&old_stored, &sigactions[sig], sizeof(old_stored)); 2407 __sanitizer_sigaction newact; 2408 if (act) { 2409 // Copy act into sigactions[sig]. 2410 // Can't use struct copy, because compiler can emit call to memcpy. 2411 // Can't use internal_memcpy, because it copies byte-by-byte, 2412 // and signal handler reads the handler concurrently. It it can read 2413 // some bytes from old value and some bytes from new value. 2414 // Use volatile to prevent insertion of memcpy. 2415 sigactions[sig].handler = 2416 *(volatile __sanitizer_sighandler_ptr const *)&act->handler; 2417 sigactions[sig].sa_flags = *(volatile int const *)&act->sa_flags; 2418 internal_memcpy(&sigactions[sig].sa_mask, &act->sa_mask, 2419 sizeof(sigactions[sig].sa_mask)); 2420 #if !SANITIZER_FREEBSD && !SANITIZER_MAC && !SANITIZER_NETBSD 2421 sigactions[sig].sa_restorer = act->sa_restorer; 2422 #endif 2423 internal_memcpy(&newact, act, sizeof(newact)); 2424 internal_sigfillset(&newact.sa_mask); 2425 if ((uptr)act->handler != sig_ign && (uptr)act->handler != sig_dfl) { 2426 if (newact.sa_flags & SA_SIGINFO) 2427 newact.sigaction = rtl_sigaction; 2428 else 2429 newact.handler = rtl_sighandler; 2430 } 2431 ReleaseStore(thr, pc, (uptr)&sigactions[sig]); 2432 act = &newact; 2433 } 2434 int res = REAL(sigaction)(sig, act, old); 2435 if (res == 0 && old) { 2436 uptr cb = (uptr)old->sigaction; 2437 if (cb == (uptr)rtl_sigaction || cb == (uptr)rtl_sighandler) { 2438 internal_memcpy(old, &old_stored, sizeof(*old)); 2439 } 2440 } 2441 return res; 2442 } 2443 2444 static __sanitizer_sighandler_ptr signal_impl(int sig, 2445 __sanitizer_sighandler_ptr h) { 2446 __sanitizer_sigaction act; 2447 act.handler = h; 2448 internal_memset(&act.sa_mask, -1, sizeof(act.sa_mask)); 2449 act.sa_flags = 0; 2450 __sanitizer_sigaction old; 2451 int res = sigaction_symname(sig, &act, &old); 2452 if (res) return (__sanitizer_sighandler_ptr)sig_err; 2453 return old.handler; 2454 } 2455 2456 #define TSAN_SYSCALL() \ 2457 ThreadState *thr = cur_thread(); \ 2458 if (thr->ignore_interceptors) \ 2459 return; \ 2460 ScopedSyscall scoped_syscall(thr) \ 2461 /**/ 2462 2463 struct ScopedSyscall { 2464 ThreadState *thr; 2465 2466 explicit ScopedSyscall(ThreadState *thr) 2467 : thr(thr) { 2468 Initialize(thr); 2469 } 2470 2471 ~ScopedSyscall() { 2472 ProcessPendingSignals(thr); 2473 } 2474 }; 2475 2476 #if !SANITIZER_FREEBSD && !SANITIZER_MAC 2477 static void syscall_access_range(uptr pc, uptr p, uptr s, bool write) { 2478 TSAN_SYSCALL(); 2479 MemoryAccessRange(thr, pc, p, s, write); 2480 } 2481 2482 static USED void syscall_acquire(uptr pc, uptr addr) { 2483 TSAN_SYSCALL(); 2484 Acquire(thr, pc, addr); 2485 DPrintf("syscall_acquire(%p)\n", addr); 2486 } 2487 2488 static USED void syscall_release(uptr pc, uptr addr) { 2489 TSAN_SYSCALL(); 2490 DPrintf("syscall_release(%p)\n", addr); 2491 Release(thr, pc, addr); 2492 } 2493 2494 static void syscall_fd_close(uptr pc, int fd) { 2495 TSAN_SYSCALL(); 2496 FdClose(thr, pc, fd); 2497 } 2498 2499 static USED void syscall_fd_acquire(uptr pc, int fd) { 2500 TSAN_SYSCALL(); 2501 FdAcquire(thr, pc, fd); 2502 DPrintf("syscall_fd_acquire(%p)\n", fd); 2503 } 2504 2505 static USED void syscall_fd_release(uptr pc, int fd) { 2506 TSAN_SYSCALL(); 2507 DPrintf("syscall_fd_release(%p)\n", fd); 2508 FdRelease(thr, pc, fd); 2509 } 2510 2511 static void syscall_pre_fork(uptr pc) { 2512 TSAN_SYSCALL(); 2513 ForkBefore(thr, pc); 2514 } 2515 2516 static void syscall_post_fork(uptr pc, int pid) { 2517 TSAN_SYSCALL(); 2518 if (pid == 0) { 2519 // child 2520 ForkChildAfter(thr, pc); 2521 FdOnFork(thr, pc); 2522 } else if (pid > 0) { 2523 // parent 2524 ForkParentAfter(thr, pc); 2525 } else { 2526 // error 2527 ForkParentAfter(thr, pc); 2528 } 2529 } 2530 #endif 2531 2532 #define COMMON_SYSCALL_PRE_READ_RANGE(p, s) \ 2533 syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), false) 2534 2535 #define COMMON_SYSCALL_PRE_WRITE_RANGE(p, s) \ 2536 syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), true) 2537 2538 #define COMMON_SYSCALL_POST_READ_RANGE(p, s) \ 2539 do { \ 2540 (void)(p); \ 2541 (void)(s); \ 2542 } while (false) 2543 2544 #define COMMON_SYSCALL_POST_WRITE_RANGE(p, s) \ 2545 do { \ 2546 (void)(p); \ 2547 (void)(s); \ 2548 } while (false) 2549 2550 #define COMMON_SYSCALL_ACQUIRE(addr) \ 2551 syscall_acquire(GET_CALLER_PC(), (uptr)(addr)) 2552 2553 #define COMMON_SYSCALL_RELEASE(addr) \ 2554 syscall_release(GET_CALLER_PC(), (uptr)(addr)) 2555 2556 #define COMMON_SYSCALL_FD_CLOSE(fd) syscall_fd_close(GET_CALLER_PC(), fd) 2557 2558 #define COMMON_SYSCALL_FD_ACQUIRE(fd) syscall_fd_acquire(GET_CALLER_PC(), fd) 2559 2560 #define COMMON_SYSCALL_FD_RELEASE(fd) syscall_fd_release(GET_CALLER_PC(), fd) 2561 2562 #define COMMON_SYSCALL_PRE_FORK() \ 2563 syscall_pre_fork(GET_CALLER_PC()) 2564 2565 #define COMMON_SYSCALL_POST_FORK(res) \ 2566 syscall_post_fork(GET_CALLER_PC(), res) 2567 2568 #include "sanitizer_common/sanitizer_common_syscalls.inc" 2569 #include "sanitizer_common/sanitizer_syscalls_netbsd.inc" 2570 2571 #ifdef NEED_TLS_GET_ADDR 2572 // Define own interceptor instead of sanitizer_common's for three reasons: 2573 // 1. It must not process pending signals. 2574 // Signal handlers may contain MOVDQA instruction (see below). 2575 // 2. It must be as simple as possible to not contain MOVDQA. 2576 // 3. Sanitizer_common version uses COMMON_INTERCEPTOR_INITIALIZE_RANGE which 2577 // is empty for tsan (meant only for msan). 2578 // Note: __tls_get_addr can be called with mis-aligned stack due to: 2579 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58066 2580 // So the interceptor must work with mis-aligned stack, in particular, does not 2581 // execute MOVDQA with stack addresses. 2582 TSAN_INTERCEPTOR(void *, __tls_get_addr, void *arg) { 2583 void *res = REAL(__tls_get_addr)(arg); 2584 ThreadState *thr = cur_thread(); 2585 if (!thr) 2586 return res; 2587 DTLS::DTV *dtv = DTLS_on_tls_get_addr(arg, res, thr->tls_addr, 2588 thr->tls_addr + thr->tls_size); 2589 if (!dtv) 2590 return res; 2591 // New DTLS block has been allocated. 2592 MemoryResetRange(thr, 0, dtv->beg, dtv->size); 2593 return res; 2594 } 2595 #endif 2596 2597 #if SANITIZER_NETBSD 2598 TSAN_INTERCEPTOR(void, _lwp_exit) { 2599 SCOPED_TSAN_INTERCEPTOR(_lwp_exit); 2600 DestroyThreadState(); 2601 REAL(_lwp_exit)(); 2602 } 2603 #define TSAN_MAYBE_INTERCEPT__LWP_EXIT TSAN_INTERCEPT(_lwp_exit) 2604 #else 2605 #define TSAN_MAYBE_INTERCEPT__LWP_EXIT 2606 #endif 2607 2608 #if SANITIZER_FREEBSD 2609 TSAN_INTERCEPTOR(void, thr_exit, tid_t *state) { 2610 SCOPED_TSAN_INTERCEPTOR(thr_exit, state); 2611 DestroyThreadState(); 2612 REAL(thr_exit(state)); 2613 } 2614 #define TSAN_MAYBE_INTERCEPT_THR_EXIT TSAN_INTERCEPT(thr_exit) 2615 #else 2616 #define TSAN_MAYBE_INTERCEPT_THR_EXIT 2617 #endif 2618 2619 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_init, void *c, void *a) 2620 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_signal, void *c) 2621 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_broadcast, void *c) 2622 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_wait, void *c, void *m) 2623 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_destroy, void *c) 2624 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_init, void *m, void *a) 2625 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_destroy, void *m) 2626 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_trylock, void *m) 2627 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_init, void *m, void *a) 2628 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_destroy, void *m) 2629 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_rdlock, void *m) 2630 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_tryrdlock, void *m) 2631 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_wrlock, void *m) 2632 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_trywrlock, void *m) 2633 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_unlock, void *m) 2634 TSAN_INTERCEPTOR_NETBSD_ALIAS_THR(int, once, void *o, void (*f)()) 2635 TSAN_INTERCEPTOR_NETBSD_ALIAS_THR2(int, sigsetmask, sigmask, int a, void *b, 2636 void *c) 2637 2638 namespace __tsan { 2639 2640 static void finalize(void *arg) { 2641 ThreadState *thr = cur_thread(); 2642 int status = Finalize(thr); 2643 // Make sure the output is not lost. 2644 FlushStreams(); 2645 if (status) 2646 Die(); 2647 } 2648 2649 #if !SANITIZER_MAC && !SANITIZER_ANDROID 2650 static void unreachable() { 2651 Report("FATAL: ThreadSanitizer: unreachable called\n"); 2652 Die(); 2653 } 2654 #endif 2655 2656 // Define default implementation since interception of libdispatch is optional. 2657 SANITIZER_WEAK_ATTRIBUTE void InitializeLibdispatchInterceptors() {} 2658 2659 void InitializeInterceptors() { 2660 #if !SANITIZER_MAC 2661 // We need to setup it early, because functions like dlsym() can call it. 2662 REAL(memset) = internal_memset; 2663 REAL(memcpy) = internal_memcpy; 2664 #endif 2665 2666 // Instruct libc malloc to consume less memory. 2667 #if SANITIZER_GLIBC 2668 mallopt(1, 0); // M_MXFAST 2669 mallopt(-3, 32*1024); // M_MMAP_THRESHOLD 2670 #endif 2671 2672 new(interceptor_ctx()) InterceptorContext(); 2673 2674 InitializeCommonInterceptors(); 2675 InitializeSignalInterceptors(); 2676 InitializeLibdispatchInterceptors(); 2677 2678 #if !SANITIZER_MAC 2679 // We can not use TSAN_INTERCEPT to get setjmp addr, 2680 // because it does &setjmp and setjmp is not present in some versions of libc. 2681 using __interception::InterceptFunction; 2682 InterceptFunction(TSAN_STRING_SETJMP, (uptr*)&REAL(setjmp_symname), 0, 0); 2683 InterceptFunction("_setjmp", (uptr*)&REAL(_setjmp), 0, 0); 2684 InterceptFunction(TSAN_STRING_SIGSETJMP, (uptr*)&REAL(sigsetjmp_symname), 0, 2685 0); 2686 #if !SANITIZER_NETBSD 2687 InterceptFunction("__sigsetjmp", (uptr*)&REAL(__sigsetjmp), 0, 0); 2688 #endif 2689 #endif 2690 2691 TSAN_INTERCEPT(longjmp_symname); 2692 TSAN_INTERCEPT(siglongjmp_symname); 2693 #if SANITIZER_NETBSD 2694 TSAN_INTERCEPT(_longjmp); 2695 #endif 2696 2697 TSAN_INTERCEPT(malloc); 2698 TSAN_INTERCEPT(__libc_memalign); 2699 TSAN_INTERCEPT(calloc); 2700 TSAN_INTERCEPT(realloc); 2701 TSAN_INTERCEPT(reallocarray); 2702 TSAN_INTERCEPT(free); 2703 TSAN_INTERCEPT(cfree); 2704 TSAN_INTERCEPT(munmap); 2705 TSAN_MAYBE_INTERCEPT_MEMALIGN; 2706 TSAN_INTERCEPT(valloc); 2707 TSAN_MAYBE_INTERCEPT_PVALLOC; 2708 TSAN_INTERCEPT(posix_memalign); 2709 2710 TSAN_INTERCEPT(strcpy); 2711 TSAN_INTERCEPT(strncpy); 2712 TSAN_INTERCEPT(strdup); 2713 2714 TSAN_INTERCEPT(pthread_create); 2715 TSAN_INTERCEPT(pthread_join); 2716 TSAN_INTERCEPT(pthread_detach); 2717 TSAN_INTERCEPT(pthread_exit); 2718 #if SANITIZER_LINUX 2719 TSAN_INTERCEPT(pthread_tryjoin_np); 2720 TSAN_INTERCEPT(pthread_timedjoin_np); 2721 #endif 2722 2723 TSAN_INTERCEPT_VER(pthread_cond_init, PTHREAD_ABI_BASE); 2724 TSAN_INTERCEPT_VER(pthread_cond_signal, PTHREAD_ABI_BASE); 2725 TSAN_INTERCEPT_VER(pthread_cond_broadcast, PTHREAD_ABI_BASE); 2726 TSAN_INTERCEPT_VER(pthread_cond_wait, PTHREAD_ABI_BASE); 2727 TSAN_INTERCEPT_VER(pthread_cond_timedwait, PTHREAD_ABI_BASE); 2728 TSAN_INTERCEPT_VER(pthread_cond_destroy, PTHREAD_ABI_BASE); 2729 2730 TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT; 2731 2732 TSAN_INTERCEPT(pthread_mutex_init); 2733 TSAN_INTERCEPT(pthread_mutex_destroy); 2734 TSAN_INTERCEPT(pthread_mutex_trylock); 2735 TSAN_INTERCEPT(pthread_mutex_timedlock); 2736 2737 TSAN_INTERCEPT(pthread_spin_init); 2738 TSAN_INTERCEPT(pthread_spin_destroy); 2739 TSAN_INTERCEPT(pthread_spin_lock); 2740 TSAN_INTERCEPT(pthread_spin_trylock); 2741 TSAN_INTERCEPT(pthread_spin_unlock); 2742 2743 TSAN_INTERCEPT(pthread_rwlock_init); 2744 TSAN_INTERCEPT(pthread_rwlock_destroy); 2745 TSAN_INTERCEPT(pthread_rwlock_rdlock); 2746 TSAN_INTERCEPT(pthread_rwlock_tryrdlock); 2747 TSAN_INTERCEPT(pthread_rwlock_timedrdlock); 2748 TSAN_INTERCEPT(pthread_rwlock_wrlock); 2749 TSAN_INTERCEPT(pthread_rwlock_trywrlock); 2750 TSAN_INTERCEPT(pthread_rwlock_timedwrlock); 2751 TSAN_INTERCEPT(pthread_rwlock_unlock); 2752 2753 TSAN_INTERCEPT(pthread_barrier_init); 2754 TSAN_INTERCEPT(pthread_barrier_destroy); 2755 TSAN_INTERCEPT(pthread_barrier_wait); 2756 2757 TSAN_INTERCEPT(pthread_once); 2758 2759 TSAN_INTERCEPT(fstat); 2760 TSAN_MAYBE_INTERCEPT___FXSTAT; 2761 TSAN_MAYBE_INTERCEPT_FSTAT64; 2762 TSAN_MAYBE_INTERCEPT___FXSTAT64; 2763 TSAN_INTERCEPT(open); 2764 TSAN_MAYBE_INTERCEPT_OPEN64; 2765 TSAN_INTERCEPT(creat); 2766 TSAN_MAYBE_INTERCEPT_CREAT64; 2767 TSAN_INTERCEPT(dup); 2768 TSAN_INTERCEPT(dup2); 2769 TSAN_INTERCEPT(dup3); 2770 TSAN_MAYBE_INTERCEPT_EVENTFD; 2771 TSAN_MAYBE_INTERCEPT_SIGNALFD; 2772 TSAN_MAYBE_INTERCEPT_INOTIFY_INIT; 2773 TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1; 2774 TSAN_INTERCEPT(socket); 2775 TSAN_INTERCEPT(socketpair); 2776 TSAN_INTERCEPT(connect); 2777 TSAN_INTERCEPT(bind); 2778 TSAN_INTERCEPT(listen); 2779 TSAN_MAYBE_INTERCEPT_EPOLL; 2780 TSAN_INTERCEPT(close); 2781 TSAN_MAYBE_INTERCEPT___CLOSE; 2782 TSAN_MAYBE_INTERCEPT___RES_ICLOSE; 2783 TSAN_INTERCEPT(pipe); 2784 TSAN_INTERCEPT(pipe2); 2785 2786 TSAN_INTERCEPT(unlink); 2787 TSAN_INTERCEPT(tmpfile); 2788 TSAN_MAYBE_INTERCEPT_TMPFILE64; 2789 TSAN_INTERCEPT(abort); 2790 TSAN_INTERCEPT(rmdir); 2791 TSAN_INTERCEPT(closedir); 2792 2793 TSAN_INTERCEPT(sigsuspend); 2794 TSAN_INTERCEPT(sigblock); 2795 TSAN_INTERCEPT(sigsetmask); 2796 TSAN_INTERCEPT(pthread_sigmask); 2797 TSAN_INTERCEPT(raise); 2798 TSAN_INTERCEPT(kill); 2799 TSAN_INTERCEPT(pthread_kill); 2800 TSAN_INTERCEPT(sleep); 2801 TSAN_INTERCEPT(usleep); 2802 TSAN_INTERCEPT(nanosleep); 2803 TSAN_INTERCEPT(pause); 2804 TSAN_INTERCEPT(gettimeofday); 2805 TSAN_INTERCEPT(getaddrinfo); 2806 2807 TSAN_INTERCEPT(fork); 2808 TSAN_INTERCEPT(vfork); 2809 #if !SANITIZER_ANDROID 2810 TSAN_INTERCEPT(dl_iterate_phdr); 2811 #endif 2812 TSAN_MAYBE_INTERCEPT_ON_EXIT; 2813 TSAN_INTERCEPT(__cxa_atexit); 2814 TSAN_INTERCEPT(_exit); 2815 2816 #ifdef NEED_TLS_GET_ADDR 2817 TSAN_INTERCEPT(__tls_get_addr); 2818 #endif 2819 2820 TSAN_MAYBE_INTERCEPT__LWP_EXIT; 2821 TSAN_MAYBE_INTERCEPT_THR_EXIT; 2822 2823 #if !SANITIZER_MAC && !SANITIZER_ANDROID 2824 // Need to setup it, because interceptors check that the function is resolved. 2825 // But atexit is emitted directly into the module, so can't be resolved. 2826 REAL(atexit) = (int(*)(void(*)()))unreachable; 2827 #endif 2828 2829 if (REAL(__cxa_atexit)(&finalize, 0, 0)) { 2830 Printf("ThreadSanitizer: failed to setup atexit callback\n"); 2831 Die(); 2832 } 2833 2834 #if !SANITIZER_MAC && !SANITIZER_NETBSD && !SANITIZER_FREEBSD 2835 if (pthread_key_create(&interceptor_ctx()->finalize_key, &thread_finalize)) { 2836 Printf("ThreadSanitizer: failed to create thread key\n"); 2837 Die(); 2838 } 2839 #endif 2840 2841 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_init); 2842 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_signal); 2843 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_broadcast); 2844 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_wait); 2845 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_destroy); 2846 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_init); 2847 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_destroy); 2848 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_trylock); 2849 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_init); 2850 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_destroy); 2851 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_rdlock); 2852 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_tryrdlock); 2853 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_wrlock); 2854 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_trywrlock); 2855 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_unlock); 2856 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(once); 2857 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(sigsetmask); 2858 2859 FdInit(); 2860 } 2861 2862 } // namespace __tsan 2863 2864 // Invisible barrier for tests. 2865 // There were several unsuccessful iterations for this functionality: 2866 // 1. Initially it was implemented in user code using 2867 // REAL(pthread_barrier_wait). But pthread_barrier_wait is not supported on 2868 // MacOS. Futexes are linux-specific for this matter. 2869 // 2. Then we switched to atomics+usleep(10). But usleep produced parasitic 2870 // "as-if synchronized via sleep" messages in reports which failed some 2871 // output tests. 2872 // 3. Then we switched to atomics+sched_yield. But this produced tons of tsan- 2873 // visible events, which lead to "failed to restore stack trace" failures. 2874 // Note that no_sanitize_thread attribute does not turn off atomic interception 2875 // so attaching it to the function defined in user code does not help. 2876 // That's why we now have what we have. 2877 extern "C" SANITIZER_INTERFACE_ATTRIBUTE 2878 void __tsan_testonly_barrier_init(u64 *barrier, u32 count) { 2879 if (count >= (1 << 8)) { 2880 Printf("barrier_init: count is too large (%d)\n", count); 2881 Die(); 2882 } 2883 // 8 lsb is thread count, the remaining are count of entered threads. 2884 *barrier = count; 2885 } 2886 2887 extern "C" SANITIZER_INTERFACE_ATTRIBUTE 2888 void __tsan_testonly_barrier_wait(u64 *barrier) { 2889 unsigned old = __atomic_fetch_add(barrier, 1 << 8, __ATOMIC_RELAXED); 2890 unsigned old_epoch = (old >> 8) / (old & 0xff); 2891 for (;;) { 2892 unsigned cur = __atomic_load_n(barrier, __ATOMIC_RELAXED); 2893 unsigned cur_epoch = (cur >> 8) / (cur & 0xff); 2894 if (cur_epoch != old_epoch) 2895 return; 2896 internal_sched_yield(); 2897 } 2898 } 2899