1 //===-- tsan_interceptors.cc ----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of ThreadSanitizer (TSan), a race detector.
12 // FIXME: move as many interceptors as possible into
13 // sanitizer_common/sanitizer_common_interceptors.inc
14 //===----------------------------------------------------------------------===//
16 #include "sanitizer_common/sanitizer_atomic.h"
17 #include "sanitizer_common/sanitizer_libc.h"
18 #include "sanitizer_common/sanitizer_linux.h"
19 #include "sanitizer_common/sanitizer_platform_limits_posix.h"
20 #include "sanitizer_common/sanitizer_placement_new.h"
21 #include "sanitizer_common/sanitizer_posix.h"
22 #include "sanitizer_common/sanitizer_stacktrace.h"
23 #include "sanitizer_common/sanitizer_tls_get_addr.h"
24 #include "interception/interception.h"
25 #include "tsan_interceptors.h"
26 #include "tsan_interface.h"
27 #include "tsan_platform.h"
28 #include "tsan_suppressions.h"
30 #include "tsan_mman.h"
34 using namespace __tsan; // NOLINT
36 #if SANITIZER_FREEBSD || SANITIZER_MAC
37 #define __errno_location __error
38 #define stdout __stdoutp
39 #define stderr __stderrp
43 #define __errno_location __errno
48 const int kSigCount = 129;
50 const int kSigCount = 65;
54 // The size is determined by looking at sizeof of real siginfo_t on linux.
55 u64 opaque[128 / sizeof(u64)];
60 u64 opaque[768 / sizeof(u64) + 1];
64 // The size is determined by looking at sizeof of real ucontext_t on linux.
65 u64 opaque[936 / sizeof(u64) + 1];
69 #if defined(__x86_64__) || defined(__mips__) || SANITIZER_PPC64V1
70 #define PTHREAD_ABI_BASE "GLIBC_2.3.2"
71 #elif defined(__aarch64__) || SANITIZER_PPC64V2
72 #define PTHREAD_ABI_BASE "GLIBC_2.17"
75 extern "C" int pthread_attr_init(void *attr);
76 extern "C" int pthread_attr_destroy(void *attr);
77 DECLARE_REAL(int, pthread_attr_getdetachstate, void *, void *)
78 extern "C" int pthread_attr_setstacksize(void *attr, uptr stacksize);
79 extern "C" int pthread_key_create(unsigned *key, void (*destructor)(void* v));
80 extern "C" int pthread_setspecific(unsigned key, const void *v);
81 DECLARE_REAL(int, pthread_mutexattr_gettype, void *, void *)
82 DECLARE_REAL(int, fflush, __sanitizer_FILE *fp)
83 DECLARE_REAL_AND_INTERCEPTOR(void *, malloc, uptr size)
84 DECLARE_REAL_AND_INTERCEPTOR(void, free, void *ptr)
85 extern "C" void *pthread_self();
86 extern "C" void _exit(int status);
87 extern "C" int *__errno_location();
88 extern "C" int fileno_unlocked(void *stream);
89 extern "C" int dirfd(void *dirp);
90 #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID
91 extern "C" int mallopt(int param, int value);
93 extern __sanitizer_FILE *stdout, *stderr;
94 #if !SANITIZER_FREEBSD && !SANITIZER_MAC
95 const int PTHREAD_MUTEX_RECURSIVE = 1;
96 const int PTHREAD_MUTEX_RECURSIVE_NP = 1;
98 const int PTHREAD_MUTEX_RECURSIVE = 2;
99 const int PTHREAD_MUTEX_RECURSIVE_NP = 2;
101 const int EINVAL = 22;
102 const int EBUSY = 16;
103 const int EOWNERDEAD = 130;
104 #if !SANITIZER_FREEBSD && !SANITIZER_MAC
105 const int EPOLL_CTL_ADD = 1;
107 const int SIGILL = 4;
108 const int SIGABRT = 6;
109 const int SIGFPE = 8;
110 const int SIGSEGV = 11;
111 const int SIGPIPE = 13;
112 const int SIGTERM = 15;
113 #if defined(__mips__) || SANITIZER_FREEBSD || SANITIZER_MAC
114 const int SIGBUS = 10;
115 const int SIGSYS = 12;
117 const int SIGBUS = 7;
118 const int SIGSYS = 31;
120 void *const MAP_FAILED = (void*)-1;
122 const int PTHREAD_BARRIER_SERIAL_THREAD = -1;
124 const int MAP_FIXED = 0x10;
125 typedef long long_t; // NOLINT
127 // From /usr/include/unistd.h
128 # define F_ULOCK 0 /* Unlock a previously locked region. */
129 # define F_LOCK 1 /* Lock a region for exclusive use. */
130 # define F_TLOCK 2 /* Test and lock a region for exclusive use. */
131 # define F_TEST 3 /* Test a region for other processes locks. */
133 #define errno (*__errno_location())
135 typedef void (*sighandler_t)(int sig);
136 typedef void (*sigactionhandler_t)(int sig, my_siginfo_t *siginfo, void *uctx);
138 #if SANITIZER_ANDROID
142 sighandler_t sa_handler;
143 sigactionhandler_t sa_sigaction;
145 __sanitizer_sigset_t sa_mask;
146 void (*sa_restorer)();
154 sighandler_t sa_handler;
155 sigactionhandler_t sa_sigaction;
157 #if SANITIZER_FREEBSD
159 __sanitizer_sigset_t sa_mask;
161 __sanitizer_sigset_t sa_mask;
164 __sanitizer_sigset_t sa_mask;
168 void (*sa_restorer)();
173 const sighandler_t SIG_DFL = (sighandler_t)0;
174 const sighandler_t SIG_IGN = (sighandler_t)1;
175 const sighandler_t SIG_ERR = (sighandler_t)-1;
176 #if SANITIZER_FREEBSD || SANITIZER_MAC
177 const int SA_SIGINFO = 0x40;
178 const int SIG_SETMASK = 3;
179 #elif defined(__mips__)
180 const int SA_SIGINFO = 8;
181 const int SIG_SETMASK = 3;
183 const int SA_SIGINFO = 4;
184 const int SIG_SETMASK = 2;
187 #define COMMON_INTERCEPTOR_NOTHING_IS_INITIALIZED \
188 (!cur_thread()->is_inited)
190 static sigaction_t sigactions[kSigCount];
196 my_siginfo_t siginfo;
200 struct ThreadSignalContext {
202 atomic_uintptr_t in_blocking_func;
203 atomic_uintptr_t have_pending_signals;
204 SignalDesc pending_signals[kSigCount];
205 // emptyset and oldset are too big for stack.
206 __sanitizer_sigset_t emptyset;
207 __sanitizer_sigset_t oldset;
210 // The object is 64-byte aligned, because we want hot data to be located in
211 // a single cache line if possible (it's accessed in every interceptor).
212 static ALIGNED(64) char libignore_placeholder[sizeof(LibIgnore)];
213 static LibIgnore *libignore() {
214 return reinterpret_cast<LibIgnore*>(&libignore_placeholder[0]);
217 void InitializeLibIgnore() {
218 const SuppressionContext &supp = *Suppressions();
219 const uptr n = supp.SuppressionCount();
220 for (uptr i = 0; i < n; i++) {
221 const Suppression *s = supp.SuppressionAt(i);
222 if (0 == internal_strcmp(s->type, kSuppressionLib))
223 libignore()->AddIgnoredLibrary(s->templ);
225 if (flags()->ignore_noninstrumented_modules)
226 libignore()->IgnoreNoninstrumentedModules(true);
227 libignore()->OnLibraryLoaded(0);
230 } // namespace __tsan
232 static ThreadSignalContext *SigCtx(ThreadState *thr) {
233 ThreadSignalContext *ctx = (ThreadSignalContext*)thr->signal_ctx;
234 if (ctx == 0 && !thr->is_dead) {
235 ctx = (ThreadSignalContext*)MmapOrDie(sizeof(*ctx), "ThreadSignalContext");
236 MemoryResetRange(thr, (uptr)&SigCtx, (uptr)ctx, sizeof(*ctx));
237 thr->signal_ctx = ctx;
243 static unsigned g_thread_finalize_key;
246 ScopedInterceptor::ScopedInterceptor(ThreadState *thr, const char *fname,
248 : thr_(thr), pc_(pc), in_ignored_lib_(false), ignoring_(false) {
250 if (!thr_->is_inited) return;
251 if (!thr_->ignore_interceptors) FuncEntry(thr, pc);
252 DPrintf("#%d: intercept %s()\n", thr_->tid, fname);
254 !thr_->in_ignored_lib && (flags()->ignore_interceptors_accesses ||
255 libignore()->IsIgnored(pc, &in_ignored_lib_));
259 ScopedInterceptor::~ScopedInterceptor() {
260 if (!thr_->is_inited) return;
262 if (!thr_->ignore_interceptors) {
263 ProcessPendingSignals(thr_);
269 void ScopedInterceptor::EnableIgnores() {
271 ThreadIgnoreBegin(thr_, pc_, false);
272 if (in_ignored_lib_) {
273 DCHECK(!thr_->in_ignored_lib);
274 thr_->in_ignored_lib = true;
279 void ScopedInterceptor::DisableIgnores() {
281 ThreadIgnoreEnd(thr_, pc_);
282 if (in_ignored_lib_) {
283 DCHECK(thr_->in_ignored_lib);
284 thr_->in_ignored_lib = false;
289 #define TSAN_INTERCEPT(func) INTERCEPT_FUNCTION(func)
290 #if SANITIZER_FREEBSD
291 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION(func)
293 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION_VER(func, ver)
296 #define READ_STRING_OF_LEN(thr, pc, s, len, n) \
297 MemoryAccessRange((thr), (pc), (uptr)(s), \
298 common_flags()->strict_string_checks ? (len) + 1 : (n), false)
300 #define READ_STRING(thr, pc, s, n) \
301 READ_STRING_OF_LEN((thr), (pc), (s), internal_strlen(s), (n))
303 #define BLOCK_REAL(name) (BlockingCall(thr), REAL(name))
305 struct BlockingCall {
306 explicit BlockingCall(ThreadState *thr)
310 atomic_store(&ctx->in_blocking_func, 1, memory_order_relaxed);
311 if (atomic_load(&ctx->have_pending_signals, memory_order_relaxed) == 0)
313 atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
314 ProcessPendingSignals(thr);
316 // When we are in a "blocking call", we process signals asynchronously
317 // (right when they arrive). In this context we do not expect to be
318 // executing any user/runtime code. The known interceptor sequence when
319 // this is not true is: pthread_join -> munmap(stack). It's fine
320 // to ignore munmap in this case -- we handle stack shadow separately.
321 thr->ignore_interceptors++;
325 thr->ignore_interceptors--;
326 atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
330 ThreadSignalContext *ctx;
333 TSAN_INTERCEPTOR(unsigned, sleep, unsigned sec) {
334 SCOPED_TSAN_INTERCEPTOR(sleep, sec);
335 unsigned res = BLOCK_REAL(sleep)(sec);
340 TSAN_INTERCEPTOR(int, usleep, long_t usec) {
341 SCOPED_TSAN_INTERCEPTOR(usleep, usec);
342 int res = BLOCK_REAL(usleep)(usec);
347 TSAN_INTERCEPTOR(int, nanosleep, void *req, void *rem) {
348 SCOPED_TSAN_INTERCEPTOR(nanosleep, req, rem);
349 int res = BLOCK_REAL(nanosleep)(req, rem);
354 // The sole reason tsan wraps atexit callbacks is to establish synchronization
355 // between callback setup and callback execution.
361 static void at_exit_wrapper(void *arg) {
362 ThreadState *thr = cur_thread();
364 Acquire(thr, pc, (uptr)arg);
365 AtExitCtx *ctx = (AtExitCtx*)arg;
366 ((void(*)(void *arg))ctx->f)(ctx->arg);
370 static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(),
371 void *arg, void *dso);
373 #if !SANITIZER_ANDROID
374 TSAN_INTERCEPTOR(int, atexit, void (*f)()) {
375 if (cur_thread()->in_symbolizer)
377 // We want to setup the atexit callback even if we are in ignored lib
379 SCOPED_INTERCEPTOR_RAW(atexit, f);
380 return setup_at_exit_wrapper(thr, pc, (void(*)())f, 0, 0);
384 TSAN_INTERCEPTOR(int, __cxa_atexit, void (*f)(void *a), void *arg, void *dso) {
385 if (cur_thread()->in_symbolizer)
387 SCOPED_TSAN_INTERCEPTOR(__cxa_atexit, f, arg, dso);
388 return setup_at_exit_wrapper(thr, pc, (void(*)())f, arg, dso);
391 static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(),
392 void *arg, void *dso) {
393 AtExitCtx *ctx = (AtExitCtx*)InternalAlloc(sizeof(AtExitCtx));
396 Release(thr, pc, (uptr)ctx);
397 // Memory allocation in __cxa_atexit will race with free during exit,
398 // because we do not see synchronization around atexit callback list.
399 ThreadIgnoreBegin(thr, pc);
400 int res = REAL(__cxa_atexit)(at_exit_wrapper, ctx, dso);
401 ThreadIgnoreEnd(thr, pc);
406 static void on_exit_wrapper(int status, void *arg) {
407 ThreadState *thr = cur_thread();
409 Acquire(thr, pc, (uptr)arg);
410 AtExitCtx *ctx = (AtExitCtx*)arg;
411 ((void(*)(int status, void *arg))ctx->f)(status, ctx->arg);
415 TSAN_INTERCEPTOR(int, on_exit, void(*f)(int, void*), void *arg) {
416 if (cur_thread()->in_symbolizer)
418 SCOPED_TSAN_INTERCEPTOR(on_exit, f, arg);
419 AtExitCtx *ctx = (AtExitCtx*)InternalAlloc(sizeof(AtExitCtx));
420 ctx->f = (void(*)())f;
422 Release(thr, pc, (uptr)ctx);
423 // Memory allocation in __cxa_atexit will race with free during exit,
424 // because we do not see synchronization around atexit callback list.
425 ThreadIgnoreBegin(thr, pc);
426 int res = REAL(on_exit)(on_exit_wrapper, ctx);
427 ThreadIgnoreEnd(thr, pc);
433 static void JmpBufGarbageCollect(ThreadState *thr, uptr sp) {
434 for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) {
435 JmpBuf *buf = &thr->jmp_bufs[i];
437 uptr sz = thr->jmp_bufs.Size();
438 internal_memcpy(buf, &thr->jmp_bufs[sz - 1], sizeof(*buf));
439 thr->jmp_bufs.PopBack();
445 static void SetJmp(ThreadState *thr, uptr sp, uptr mangled_sp) {
446 if (!thr->is_inited) // called from libc guts during bootstrap
449 JmpBufGarbageCollect(thr, sp);
451 JmpBuf *buf = thr->jmp_bufs.PushBack();
453 buf->mangled_sp = mangled_sp;
454 buf->shadow_stack_pos = thr->shadow_stack_pos;
455 ThreadSignalContext *sctx = SigCtx(thr);
456 buf->int_signal_send = sctx ? sctx->int_signal_send : 0;
457 buf->in_blocking_func = sctx ?
458 atomic_load(&sctx->in_blocking_func, memory_order_relaxed) :
460 buf->in_signal_handler = atomic_load(&thr->in_signal_handler,
461 memory_order_relaxed);
464 static void LongJmp(ThreadState *thr, uptr *env) {
466 uptr mangled_sp = env[0];
467 #elif SANITIZER_FREEBSD || SANITIZER_MAC
468 uptr mangled_sp = env[2];
469 #elif defined(SANITIZER_LINUX)
471 uptr mangled_sp = env[13];
472 # elif defined(__mips64)
473 uptr mangled_sp = env[1];
475 uptr mangled_sp = env[6];
478 // Find the saved buf by mangled_sp.
479 for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) {
480 JmpBuf *buf = &thr->jmp_bufs[i];
481 if (buf->mangled_sp == mangled_sp) {
482 CHECK_GE(thr->shadow_stack_pos, buf->shadow_stack_pos);
484 while (thr->shadow_stack_pos > buf->shadow_stack_pos)
486 ThreadSignalContext *sctx = SigCtx(thr);
488 sctx->int_signal_send = buf->int_signal_send;
489 atomic_store(&sctx->in_blocking_func, buf->in_blocking_func,
490 memory_order_relaxed);
492 atomic_store(&thr->in_signal_handler, buf->in_signal_handler,
493 memory_order_relaxed);
494 JmpBufGarbageCollect(thr, buf->sp - 1); // do not collect buf->sp
498 Printf("ThreadSanitizer: can't find longjmp buf\n");
502 // FIXME: put everything below into a common extern "C" block?
503 extern "C" void __tsan_setjmp(uptr sp, uptr mangled_sp) {
504 SetJmp(cur_thread(), sp, mangled_sp);
508 TSAN_INTERCEPTOR(int, setjmp, void *env);
509 TSAN_INTERCEPTOR(int, _setjmp, void *env);
510 TSAN_INTERCEPTOR(int, sigsetjmp, void *env);
511 #else // SANITIZER_MAC
512 // Not called. Merely to satisfy TSAN_INTERCEPT().
513 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
514 int __interceptor_setjmp(void *env);
515 extern "C" int __interceptor_setjmp(void *env) {
520 // FIXME: any reason to have a separate declaration?
521 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
522 int __interceptor__setjmp(void *env);
523 extern "C" int __interceptor__setjmp(void *env) {
528 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
529 int __interceptor_sigsetjmp(void *env);
530 extern "C" int __interceptor_sigsetjmp(void *env) {
535 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
536 int __interceptor___sigsetjmp(void *env);
537 extern "C" int __interceptor___sigsetjmp(void *env) {
542 extern "C" int setjmp(void *env);
543 extern "C" int _setjmp(void *env);
544 extern "C" int sigsetjmp(void *env);
545 extern "C" int __sigsetjmp(void *env);
546 DEFINE_REAL(int, setjmp, void *env)
547 DEFINE_REAL(int, _setjmp, void *env)
548 DEFINE_REAL(int, sigsetjmp, void *env)
549 DEFINE_REAL(int, __sigsetjmp, void *env)
550 #endif // SANITIZER_MAC
552 TSAN_INTERCEPTOR(void, longjmp, uptr *env, int val) {
553 // Note: if we call REAL(longjmp) in the context of ScopedInterceptor,
554 // bad things will happen. We will jump over ScopedInterceptor dtor and can
555 // leave thr->in_ignored_lib set.
557 SCOPED_INTERCEPTOR_RAW(longjmp, env, val);
559 LongJmp(cur_thread(), env);
560 REAL(longjmp)(env, val);
563 TSAN_INTERCEPTOR(void, siglongjmp, uptr *env, int val) {
565 SCOPED_INTERCEPTOR_RAW(siglongjmp, env, val);
567 LongJmp(cur_thread(), env);
568 REAL(siglongjmp)(env, val);
572 TSAN_INTERCEPTOR(void*, malloc, uptr size) {
573 if (cur_thread()->in_symbolizer)
574 return InternalAlloc(size);
577 SCOPED_INTERCEPTOR_RAW(malloc, size);
578 p = user_alloc(thr, pc, size);
580 invoke_malloc_hook(p, size);
584 TSAN_INTERCEPTOR(void*, __libc_memalign, uptr align, uptr sz) {
585 SCOPED_TSAN_INTERCEPTOR(__libc_memalign, align, sz);
586 return user_alloc(thr, pc, sz, align);
589 TSAN_INTERCEPTOR(void*, calloc, uptr size, uptr n) {
590 if (cur_thread()->in_symbolizer)
591 return InternalCalloc(size, n);
594 SCOPED_INTERCEPTOR_RAW(calloc, size, n);
595 p = user_calloc(thr, pc, size, n);
597 invoke_malloc_hook(p, n * size);
601 TSAN_INTERCEPTOR(void*, realloc, void *p, uptr size) {
602 if (cur_thread()->in_symbolizer)
603 return InternalRealloc(p, size);
607 SCOPED_INTERCEPTOR_RAW(realloc, p, size);
608 p = user_realloc(thr, pc, p, size);
610 invoke_malloc_hook(p, size);
614 TSAN_INTERCEPTOR(void, free, void *p) {
617 if (cur_thread()->in_symbolizer)
618 return InternalFree(p);
620 SCOPED_INTERCEPTOR_RAW(free, p);
621 user_free(thr, pc, p);
624 TSAN_INTERCEPTOR(void, cfree, void *p) {
627 if (cur_thread()->in_symbolizer)
628 return InternalFree(p);
630 SCOPED_INTERCEPTOR_RAW(cfree, p);
631 user_free(thr, pc, p);
634 TSAN_INTERCEPTOR(uptr, malloc_usable_size, void *p) {
635 SCOPED_INTERCEPTOR_RAW(malloc_usable_size, p);
636 return user_alloc_usable_size(p);
640 TSAN_INTERCEPTOR(char*, strcpy, char *dst, const char *src) { // NOLINT
641 SCOPED_TSAN_INTERCEPTOR(strcpy, dst, src); // NOLINT
642 uptr srclen = internal_strlen(src);
643 MemoryAccessRange(thr, pc, (uptr)dst, srclen + 1, true);
644 MemoryAccessRange(thr, pc, (uptr)src, srclen + 1, false);
645 return REAL(strcpy)(dst, src); // NOLINT
648 TSAN_INTERCEPTOR(char*, strncpy, char *dst, char *src, uptr n) {
649 SCOPED_TSAN_INTERCEPTOR(strncpy, dst, src, n);
650 uptr srclen = internal_strnlen(src, n);
651 MemoryAccessRange(thr, pc, (uptr)dst, n, true);
652 MemoryAccessRange(thr, pc, (uptr)src, min(srclen + 1, n), false);
653 return REAL(strncpy)(dst, src, n);
656 TSAN_INTERCEPTOR(char*, strdup, const char *str) {
657 SCOPED_TSAN_INTERCEPTOR(strdup, str);
658 // strdup will call malloc, so no instrumentation is required here.
659 return REAL(strdup)(str);
662 static bool fix_mmap_addr(void **addr, long_t sz, int flags) {
664 if (!IsAppMem((uptr)*addr) || !IsAppMem((uptr)*addr + sz - 1)) {
665 if (flags & MAP_FIXED) {
676 TSAN_INTERCEPTOR(void *, mmap, void *addr, SIZE_T sz, int prot, int flags,
678 SCOPED_TSAN_INTERCEPTOR(mmap, addr, sz, prot, flags, fd, off);
679 if (!fix_mmap_addr(&addr, sz, flags))
681 void *res = REAL(mmap)(addr, sz, prot, flags, fd, off);
682 if (res != MAP_FAILED) {
684 FdAccess(thr, pc, fd);
686 if (thr->ignore_reads_and_writes == 0)
687 MemoryRangeImitateWrite(thr, pc, (uptr)res, sz);
689 MemoryResetRange(thr, pc, (uptr)res, sz);
695 TSAN_INTERCEPTOR(void *, mmap64, void *addr, SIZE_T sz, int prot, int flags,
696 int fd, OFF64_T off) {
697 SCOPED_TSAN_INTERCEPTOR(mmap64, addr, sz, prot, flags, fd, off);
698 if (!fix_mmap_addr(&addr, sz, flags))
700 void *res = REAL(mmap64)(addr, sz, prot, flags, fd, off);
701 if (res != MAP_FAILED) {
703 FdAccess(thr, pc, fd);
705 if (thr->ignore_reads_and_writes == 0)
706 MemoryRangeImitateWrite(thr, pc, (uptr)res, sz);
708 MemoryResetRange(thr, pc, (uptr)res, sz);
712 #define TSAN_MAYBE_INTERCEPT_MMAP64 TSAN_INTERCEPT(mmap64)
714 #define TSAN_MAYBE_INTERCEPT_MMAP64
717 TSAN_INTERCEPTOR(int, munmap, void *addr, long_t sz) {
718 SCOPED_TSAN_INTERCEPTOR(munmap, addr, sz);
720 // If sz == 0, munmap will return EINVAL and don't unmap any memory.
721 DontNeedShadowFor((uptr)addr, sz);
722 ScopedGlobalProcessor sgp;
723 ctx->metamap.ResetRange(thr->proc(), (uptr)addr, (uptr)sz);
725 int res = REAL(munmap)(addr, sz);
730 TSAN_INTERCEPTOR(void*, memalign, uptr align, uptr sz) {
731 SCOPED_INTERCEPTOR_RAW(memalign, align, sz);
732 return user_alloc(thr, pc, sz, align);
734 #define TSAN_MAYBE_INTERCEPT_MEMALIGN TSAN_INTERCEPT(memalign)
736 #define TSAN_MAYBE_INTERCEPT_MEMALIGN
740 TSAN_INTERCEPTOR(void*, aligned_alloc, uptr align, uptr sz) {
741 SCOPED_INTERCEPTOR_RAW(memalign, align, sz);
742 return user_alloc(thr, pc, sz, align);
745 TSAN_INTERCEPTOR(void*, valloc, uptr sz) {
746 SCOPED_INTERCEPTOR_RAW(valloc, sz);
747 return user_alloc(thr, pc, sz, GetPageSizeCached());
752 TSAN_INTERCEPTOR(void*, pvalloc, uptr sz) {
753 SCOPED_INTERCEPTOR_RAW(pvalloc, sz);
754 sz = RoundUp(sz, GetPageSizeCached());
755 return user_alloc(thr, pc, sz, GetPageSizeCached());
757 #define TSAN_MAYBE_INTERCEPT_PVALLOC TSAN_INTERCEPT(pvalloc)
759 #define TSAN_MAYBE_INTERCEPT_PVALLOC
763 TSAN_INTERCEPTOR(int, posix_memalign, void **memptr, uptr align, uptr sz) {
764 SCOPED_INTERCEPTOR_RAW(posix_memalign, memptr, align, sz);
765 *memptr = user_alloc(thr, pc, sz, align);
770 // __cxa_guard_acquire and friends need to be intercepted in a special way -
771 // regular interceptors will break statically-linked libstdc++. Linux
772 // interceptors are especially defined as weak functions (so that they don't
773 // cause link errors when user defines them as well). So they silently
774 // auto-disable themselves when such symbol is already present in the binary. If
775 // we link libstdc++ statically, it will bring own __cxa_guard_acquire which
776 // will silently replace our interceptor. That's why on Linux we simply export
777 // these interceptors with INTERFACE_ATTRIBUTE.
778 // On OS X, we don't support statically linking, so we just use a regular
781 #define STDCXX_INTERCEPTOR TSAN_INTERCEPTOR
783 #define STDCXX_INTERCEPTOR(rettype, name, ...) \
784 extern "C" rettype INTERFACE_ATTRIBUTE name(__VA_ARGS__)
787 // Used in thread-safe function static initialization.
788 STDCXX_INTERCEPTOR(int, __cxa_guard_acquire, atomic_uint32_t *g) {
789 SCOPED_INTERCEPTOR_RAW(__cxa_guard_acquire, g);
791 u32 cmp = atomic_load(g, memory_order_acquire);
793 if (atomic_compare_exchange_strong(g, &cmp, 1<<16, memory_order_relaxed))
795 } else if (cmp == 1) {
796 Acquire(thr, pc, (uptr)g);
799 internal_sched_yield();
804 STDCXX_INTERCEPTOR(void, __cxa_guard_release, atomic_uint32_t *g) {
805 SCOPED_INTERCEPTOR_RAW(__cxa_guard_release, g);
806 Release(thr, pc, (uptr)g);
807 atomic_store(g, 1, memory_order_release);
810 STDCXX_INTERCEPTOR(void, __cxa_guard_abort, atomic_uint32_t *g) {
811 SCOPED_INTERCEPTOR_RAW(__cxa_guard_abort, g);
812 atomic_store(g, 0, memory_order_relaxed);
816 void DestroyThreadState() {
817 ThreadState *thr = cur_thread();
818 Processor *proc = thr->proc();
820 ProcUnwire(proc, thr);
822 ThreadSignalContext *sctx = thr->signal_ctx;
825 UnmapOrDie(sctx, sizeof(*sctx));
828 cur_thread_finalize();
830 } // namespace __tsan
833 static void thread_finalize(void *v) {
836 if (pthread_setspecific(g_thread_finalize_key, (void*)(iter - 1))) {
837 Printf("ThreadSanitizer: failed to set thread key\n");
842 DestroyThreadState();
848 void* (*callback)(void *arg);
850 atomic_uintptr_t tid;
853 extern "C" void *__tsan_thread_start_func(void *arg) {
854 ThreadParam *p = (ThreadParam*)arg;
855 void* (*callback)(void *arg) = p->callback;
856 void *param = p->param;
859 ThreadState *thr = cur_thread();
860 // Thread-local state is not initialized yet.
861 ScopedIgnoreInterceptors ignore;
863 ThreadIgnoreBegin(thr, 0);
864 if (pthread_setspecific(g_thread_finalize_key,
865 (void *)GetPthreadDestructorIterations())) {
866 Printf("ThreadSanitizer: failed to set thread key\n");
869 ThreadIgnoreEnd(thr, 0);
871 while ((tid = atomic_load(&p->tid, memory_order_acquire)) == 0)
872 internal_sched_yield();
873 Processor *proc = ProcCreate();
875 ThreadStart(thr, tid, GetTid(), /*workerthread*/ false);
876 atomic_store(&p->tid, 0, memory_order_release);
878 void *res = callback(param);
879 // Prevent the callback from being tail called,
880 // it mixes up stack traces.
881 volatile int foo = 42;
886 TSAN_INTERCEPTOR(int, pthread_create,
887 void *th, void *attr, void *(*callback)(void*), void * param) {
888 SCOPED_INTERCEPTOR_RAW(pthread_create, th, attr, callback, param);
889 if (ctx->after_multithreaded_fork) {
890 if (flags()->die_after_fork) {
891 Report("ThreadSanitizer: starting new threads after multi-threaded "
892 "fork is not supported. Dying (set die_after_fork=0 to override)\n");
895 VPrintf(1, "ThreadSanitizer: starting new threads after multi-threaded "
896 "fork is not supported (pid %d). Continuing because of "
897 "die_after_fork=0, but you are on your own\n", internal_getpid());
900 __sanitizer_pthread_attr_t myattr;
902 pthread_attr_init(&myattr);
906 REAL(pthread_attr_getdetachstate)(attr, &detached);
907 AdjustStackSize(attr);
910 p.callback = callback;
912 atomic_store(&p.tid, 0, memory_order_relaxed);
915 // Otherwise we see false positives in pthread stack manipulation.
916 ScopedIgnoreInterceptors ignore;
917 ThreadIgnoreBegin(thr, pc);
918 res = REAL(pthread_create)(th, attr, __tsan_thread_start_func, &p);
919 ThreadIgnoreEnd(thr, pc);
922 int tid = ThreadCreate(thr, pc, *(uptr*)th, IsStateDetached(detached));
924 // Synchronization on p.tid serves two purposes:
925 // 1. ThreadCreate must finish before the new thread starts.
926 // Otherwise the new thread can call pthread_detach, but the pthread_t
927 // identifier is not yet registered in ThreadRegistry by ThreadCreate.
928 // 2. ThreadStart must finish before this thread continues.
929 // Otherwise, this thread can call pthread_detach and reset thr->sync
930 // before the new thread got a chance to acquire from it in ThreadStart.
931 atomic_store(&p.tid, tid, memory_order_release);
932 while (atomic_load(&p.tid, memory_order_acquire) != 0)
933 internal_sched_yield();
936 pthread_attr_destroy(&myattr);
940 TSAN_INTERCEPTOR(int, pthread_join, void *th, void **ret) {
941 SCOPED_INTERCEPTOR_RAW(pthread_join, th, ret);
942 int tid = ThreadTid(thr, pc, (uptr)th);
943 ThreadIgnoreBegin(thr, pc);
944 int res = BLOCK_REAL(pthread_join)(th, ret);
945 ThreadIgnoreEnd(thr, pc);
947 ThreadJoin(thr, pc, tid);
952 DEFINE_REAL_PTHREAD_FUNCTIONS
954 TSAN_INTERCEPTOR(int, pthread_detach, void *th) {
955 SCOPED_TSAN_INTERCEPTOR(pthread_detach, th);
956 int tid = ThreadTid(thr, pc, (uptr)th);
957 int res = REAL(pthread_detach)(th);
959 ThreadDetach(thr, pc, tid);
965 // NPTL implementation of pthread_cond has 2 versions (2.2.5 and 2.3.2).
966 // pthread_cond_t has different size in the different versions.
967 // If call new REAL functions for old pthread_cond_t, they will corrupt memory
968 // after pthread_cond_t (old cond is smaller).
969 // If we call old REAL functions for new pthread_cond_t, we will lose some
970 // functionality (e.g. old functions do not support waiting against
972 // Proper handling would require to have 2 versions of interceptors as well.
973 // But this is messy, in particular requires linker scripts when sanitizer
974 // runtime is linked into a shared library.
975 // Instead we assume we don't have dynamic libraries built against old
976 // pthread (2.2.5 is dated by 2002). And provide legacy_pthread_cond flag
977 // that allows to work with old libraries (but this mode does not support
978 // some features, e.g. pthread_condattr_getpshared).
979 static void *init_cond(void *c, bool force = false) {
980 // sizeof(pthread_cond_t) >= sizeof(uptr) in both versions.
981 // So we allocate additional memory on the side large enough to hold
982 // any pthread_cond_t object. Always call new REAL functions, but pass
983 // the aux object to them.
984 // Note: the code assumes that PTHREAD_COND_INITIALIZER initializes
985 // first word of pthread_cond_t to zero.
986 // It's all relevant only for linux.
987 if (!common_flags()->legacy_pthread_cond)
989 atomic_uintptr_t *p = (atomic_uintptr_t*)c;
990 uptr cond = atomic_load(p, memory_order_acquire);
991 if (!force && cond != 0)
993 void *newcond = WRAP(malloc)(pthread_cond_t_sz);
994 internal_memset(newcond, 0, pthread_cond_t_sz);
995 if (atomic_compare_exchange_strong(p, &cond, (uptr)newcond,
996 memory_order_acq_rel))
1002 struct CondMutexUnlockCtx {
1003 ScopedInterceptor *si;
1009 static void cond_mutex_unlock(CondMutexUnlockCtx *arg) {
1010 // pthread_cond_wait interceptor has enabled async signal delivery
1011 // (see BlockingCall below). Disable async signals since we are running
1012 // tsan code. Also ScopedInterceptor and BlockingCall destructors won't run
1013 // since the thread is cancelled, so we have to manually execute them
1014 // (the thread still can run some user code due to pthread_cleanup_push).
1015 ThreadSignalContext *ctx = SigCtx(arg->thr);
1016 CHECK_EQ(atomic_load(&ctx->in_blocking_func, memory_order_relaxed), 1);
1017 atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
1018 MutexPostLock(arg->thr, arg->pc, (uptr)arg->m, MutexFlagDoPreLockOnPostLock);
1019 // Undo BlockingCall ctor effects.
1020 arg->thr->ignore_interceptors--;
1021 arg->si->~ScopedInterceptor();
1024 INTERCEPTOR(int, pthread_cond_init, void *c, void *a) {
1025 void *cond = init_cond(c, true);
1026 SCOPED_TSAN_INTERCEPTOR(pthread_cond_init, cond, a);
1027 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true);
1028 return REAL(pthread_cond_init)(cond, a);
1031 static int cond_wait(ThreadState *thr, uptr pc, ScopedInterceptor *si,
1032 int (*fn)(void *c, void *m, void *abstime), void *c,
1034 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1035 MutexUnlock(thr, pc, (uptr)m);
1036 CondMutexUnlockCtx arg = {si, thr, pc, m};
1038 // This ensures that we handle mutex lock even in case of pthread_cancel.
1039 // See test/tsan/cond_cancel.cc.
1041 // Enable signal delivery while the thread is blocked.
1042 BlockingCall bc(thr);
1043 res = call_pthread_cancel_with_cleanup(
1044 fn, c, m, t, (void (*)(void *arg))cond_mutex_unlock, &arg);
1046 if (res == errno_EOWNERDEAD) MutexRepair(thr, pc, (uptr)m);
1047 MutexPostLock(thr, pc, (uptr)m, MutexFlagDoPreLockOnPostLock);
1051 INTERCEPTOR(int, pthread_cond_wait, void *c, void *m) {
1052 void *cond = init_cond(c);
1053 SCOPED_TSAN_INTERCEPTOR(pthread_cond_wait, cond, m);
1054 return cond_wait(thr, pc, &si, (int (*)(void *c, void *m, void *abstime))REAL(
1059 INTERCEPTOR(int, pthread_cond_timedwait, void *c, void *m, void *abstime) {
1060 void *cond = init_cond(c);
1061 SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait, cond, m, abstime);
1062 return cond_wait(thr, pc, &si, REAL(pthread_cond_timedwait), cond, m,
1067 INTERCEPTOR(int, pthread_cond_timedwait_relative_np, void *c, void *m,
1069 void *cond = init_cond(c);
1070 SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait_relative_np, cond, m, reltime);
1071 return cond_wait(thr, pc, &si, REAL(pthread_cond_timedwait_relative_np), cond,
1076 INTERCEPTOR(int, pthread_cond_signal, void *c) {
1077 void *cond = init_cond(c);
1078 SCOPED_TSAN_INTERCEPTOR(pthread_cond_signal, cond);
1079 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1080 return REAL(pthread_cond_signal)(cond);
1083 INTERCEPTOR(int, pthread_cond_broadcast, void *c) {
1084 void *cond = init_cond(c);
1085 SCOPED_TSAN_INTERCEPTOR(pthread_cond_broadcast, cond);
1086 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1087 return REAL(pthread_cond_broadcast)(cond);
1090 INTERCEPTOR(int, pthread_cond_destroy, void *c) {
1091 void *cond = init_cond(c);
1092 SCOPED_TSAN_INTERCEPTOR(pthread_cond_destroy, cond);
1093 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true);
1094 int res = REAL(pthread_cond_destroy)(cond);
1095 if (common_flags()->legacy_pthread_cond) {
1096 // Free our aux cond and zero the pointer to not leave dangling pointers.
1098 atomic_store((atomic_uintptr_t*)c, 0, memory_order_relaxed);
1103 TSAN_INTERCEPTOR(int, pthread_mutex_init, void *m, void *a) {
1104 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_init, m, a);
1105 int res = REAL(pthread_mutex_init)(m, a);
1110 if (REAL(pthread_mutexattr_gettype)(a, &type) == 0)
1111 if (type == PTHREAD_MUTEX_RECURSIVE ||
1112 type == PTHREAD_MUTEX_RECURSIVE_NP)
1113 flagz |= MutexFlagWriteReentrant;
1115 MutexCreate(thr, pc, (uptr)m, flagz);
1120 TSAN_INTERCEPTOR(int, pthread_mutex_destroy, void *m) {
1121 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_destroy, m);
1122 int res = REAL(pthread_mutex_destroy)(m);
1123 if (res == 0 || res == EBUSY) {
1124 MutexDestroy(thr, pc, (uptr)m);
1129 TSAN_INTERCEPTOR(int, pthread_mutex_trylock, void *m) {
1130 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_trylock, m);
1131 int res = REAL(pthread_mutex_trylock)(m);
1132 if (res == EOWNERDEAD)
1133 MutexRepair(thr, pc, (uptr)m);
1134 if (res == 0 || res == EOWNERDEAD)
1135 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1140 TSAN_INTERCEPTOR(int, pthread_mutex_timedlock, void *m, void *abstime) {
1141 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_timedlock, m, abstime);
1142 int res = REAL(pthread_mutex_timedlock)(m, abstime);
1144 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1151 TSAN_INTERCEPTOR(int, pthread_spin_init, void *m, int pshared) {
1152 SCOPED_TSAN_INTERCEPTOR(pthread_spin_init, m, pshared);
1153 int res = REAL(pthread_spin_init)(m, pshared);
1155 MutexCreate(thr, pc, (uptr)m);
1160 TSAN_INTERCEPTOR(int, pthread_spin_destroy, void *m) {
1161 SCOPED_TSAN_INTERCEPTOR(pthread_spin_destroy, m);
1162 int res = REAL(pthread_spin_destroy)(m);
1164 MutexDestroy(thr, pc, (uptr)m);
1169 TSAN_INTERCEPTOR(int, pthread_spin_lock, void *m) {
1170 SCOPED_TSAN_INTERCEPTOR(pthread_spin_lock, m);
1171 MutexPreLock(thr, pc, (uptr)m);
1172 int res = REAL(pthread_spin_lock)(m);
1174 MutexPostLock(thr, pc, (uptr)m);
1179 TSAN_INTERCEPTOR(int, pthread_spin_trylock, void *m) {
1180 SCOPED_TSAN_INTERCEPTOR(pthread_spin_trylock, m);
1181 int res = REAL(pthread_spin_trylock)(m);
1183 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1188 TSAN_INTERCEPTOR(int, pthread_spin_unlock, void *m) {
1189 SCOPED_TSAN_INTERCEPTOR(pthread_spin_unlock, m);
1190 MutexUnlock(thr, pc, (uptr)m);
1191 int res = REAL(pthread_spin_unlock)(m);
1196 TSAN_INTERCEPTOR(int, pthread_rwlock_init, void *m, void *a) {
1197 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_init, m, a);
1198 int res = REAL(pthread_rwlock_init)(m, a);
1200 MutexCreate(thr, pc, (uptr)m);
1205 TSAN_INTERCEPTOR(int, pthread_rwlock_destroy, void *m) {
1206 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_destroy, m);
1207 int res = REAL(pthread_rwlock_destroy)(m);
1209 MutexDestroy(thr, pc, (uptr)m);
1214 TSAN_INTERCEPTOR(int, pthread_rwlock_rdlock, void *m) {
1215 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_rdlock, m);
1216 MutexPreReadLock(thr, pc, (uptr)m);
1217 int res = REAL(pthread_rwlock_rdlock)(m);
1219 MutexPostReadLock(thr, pc, (uptr)m);
1224 TSAN_INTERCEPTOR(int, pthread_rwlock_tryrdlock, void *m) {
1225 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_tryrdlock, m);
1226 int res = REAL(pthread_rwlock_tryrdlock)(m);
1228 MutexPostReadLock(thr, pc, (uptr)m, MutexFlagTryLock);
1234 TSAN_INTERCEPTOR(int, pthread_rwlock_timedrdlock, void *m, void *abstime) {
1235 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedrdlock, m, abstime);
1236 int res = REAL(pthread_rwlock_timedrdlock)(m, abstime);
1238 MutexPostReadLock(thr, pc, (uptr)m);
1244 TSAN_INTERCEPTOR(int, pthread_rwlock_wrlock, void *m) {
1245 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_wrlock, m);
1246 MutexPreLock(thr, pc, (uptr)m);
1247 int res = REAL(pthread_rwlock_wrlock)(m);
1249 MutexPostLock(thr, pc, (uptr)m);
1254 TSAN_INTERCEPTOR(int, pthread_rwlock_trywrlock, void *m) {
1255 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_trywrlock, m);
1256 int res = REAL(pthread_rwlock_trywrlock)(m);
1258 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1264 TSAN_INTERCEPTOR(int, pthread_rwlock_timedwrlock, void *m, void *abstime) {
1265 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedwrlock, m, abstime);
1266 int res = REAL(pthread_rwlock_timedwrlock)(m, abstime);
1268 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1274 TSAN_INTERCEPTOR(int, pthread_rwlock_unlock, void *m) {
1275 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_unlock, m);
1276 MutexReadOrWriteUnlock(thr, pc, (uptr)m);
1277 int res = REAL(pthread_rwlock_unlock)(m);
1282 TSAN_INTERCEPTOR(int, pthread_barrier_init, void *b, void *a, unsigned count) {
1283 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_init, b, a, count);
1284 MemoryWrite(thr, pc, (uptr)b, kSizeLog1);
1285 int res = REAL(pthread_barrier_init)(b, a, count);
1289 TSAN_INTERCEPTOR(int, pthread_barrier_destroy, void *b) {
1290 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_destroy, b);
1291 MemoryWrite(thr, pc, (uptr)b, kSizeLog1);
1292 int res = REAL(pthread_barrier_destroy)(b);
1296 TSAN_INTERCEPTOR(int, pthread_barrier_wait, void *b) {
1297 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_wait, b);
1298 Release(thr, pc, (uptr)b);
1299 MemoryRead(thr, pc, (uptr)b, kSizeLog1);
1300 int res = REAL(pthread_barrier_wait)(b);
1301 MemoryRead(thr, pc, (uptr)b, kSizeLog1);
1302 if (res == 0 || res == PTHREAD_BARRIER_SERIAL_THREAD) {
1303 Acquire(thr, pc, (uptr)b);
1309 TSAN_INTERCEPTOR(int, pthread_once, void *o, void (*f)()) {
1310 SCOPED_INTERCEPTOR_RAW(pthread_once, o, f);
1311 if (o == 0 || f == 0)
1315 a = static_cast<atomic_uint32_t*>(o);
1316 else // On OS X, pthread_once_t has a header with a long-sized signature.
1317 a = static_cast<atomic_uint32_t*>((void *)((char *)o + sizeof(long_t)));
1318 u32 v = atomic_load(a, memory_order_acquire);
1319 if (v == 0 && atomic_compare_exchange_strong(a, &v, 1,
1320 memory_order_relaxed)) {
1322 if (!thr->in_ignored_lib)
1323 Release(thr, pc, (uptr)o);
1324 atomic_store(a, 2, memory_order_release);
1327 internal_sched_yield();
1328 v = atomic_load(a, memory_order_acquire);
1330 if (!thr->in_ignored_lib)
1331 Acquire(thr, pc, (uptr)o);
1336 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1337 TSAN_INTERCEPTOR(int, __fxstat, int version, int fd, void *buf) {
1338 SCOPED_TSAN_INTERCEPTOR(__fxstat, version, fd, buf);
1340 FdAccess(thr, pc, fd);
1341 return REAL(__fxstat)(version, fd, buf);
1343 #define TSAN_MAYBE_INTERCEPT___FXSTAT TSAN_INTERCEPT(__fxstat)
1345 #define TSAN_MAYBE_INTERCEPT___FXSTAT
1348 TSAN_INTERCEPTOR(int, fstat, int fd, void *buf) {
1349 #if SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_ANDROID
1350 SCOPED_TSAN_INTERCEPTOR(fstat, fd, buf);
1352 FdAccess(thr, pc, fd);
1353 return REAL(fstat)(fd, buf);
1355 SCOPED_TSAN_INTERCEPTOR(__fxstat, 0, fd, buf);
1357 FdAccess(thr, pc, fd);
1358 return REAL(__fxstat)(0, fd, buf);
1362 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1363 TSAN_INTERCEPTOR(int, __fxstat64, int version, int fd, void *buf) {
1364 SCOPED_TSAN_INTERCEPTOR(__fxstat64, version, fd, buf);
1366 FdAccess(thr, pc, fd);
1367 return REAL(__fxstat64)(version, fd, buf);
1369 #define TSAN_MAYBE_INTERCEPT___FXSTAT64 TSAN_INTERCEPT(__fxstat64)
1371 #define TSAN_MAYBE_INTERCEPT___FXSTAT64
1374 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1375 TSAN_INTERCEPTOR(int, fstat64, int fd, void *buf) {
1376 SCOPED_TSAN_INTERCEPTOR(__fxstat64, 0, fd, buf);
1378 FdAccess(thr, pc, fd);
1379 return REAL(__fxstat64)(0, fd, buf);
1381 #define TSAN_MAYBE_INTERCEPT_FSTAT64 TSAN_INTERCEPT(fstat64)
1383 #define TSAN_MAYBE_INTERCEPT_FSTAT64
1386 TSAN_INTERCEPTOR(int, open, const char *name, int flags, int mode) {
1387 SCOPED_TSAN_INTERCEPTOR(open, name, flags, mode);
1388 READ_STRING(thr, pc, name, 0);
1389 int fd = REAL(open)(name, flags, mode);
1391 FdFileCreate(thr, pc, fd);
1396 TSAN_INTERCEPTOR(int, open64, const char *name, int flags, int mode) {
1397 SCOPED_TSAN_INTERCEPTOR(open64, name, flags, mode);
1398 READ_STRING(thr, pc, name, 0);
1399 int fd = REAL(open64)(name, flags, mode);
1401 FdFileCreate(thr, pc, fd);
1404 #define TSAN_MAYBE_INTERCEPT_OPEN64 TSAN_INTERCEPT(open64)
1406 #define TSAN_MAYBE_INTERCEPT_OPEN64
1409 TSAN_INTERCEPTOR(int, creat, const char *name, int mode) {
1410 SCOPED_TSAN_INTERCEPTOR(creat, name, mode);
1411 READ_STRING(thr, pc, name, 0);
1412 int fd = REAL(creat)(name, mode);
1414 FdFileCreate(thr, pc, fd);
1419 TSAN_INTERCEPTOR(int, creat64, const char *name, int mode) {
1420 SCOPED_TSAN_INTERCEPTOR(creat64, name, mode);
1421 READ_STRING(thr, pc, name, 0);
1422 int fd = REAL(creat64)(name, mode);
1424 FdFileCreate(thr, pc, fd);
1427 #define TSAN_MAYBE_INTERCEPT_CREAT64 TSAN_INTERCEPT(creat64)
1429 #define TSAN_MAYBE_INTERCEPT_CREAT64
1432 TSAN_INTERCEPTOR(int, dup, int oldfd) {
1433 SCOPED_TSAN_INTERCEPTOR(dup, oldfd);
1434 int newfd = REAL(dup)(oldfd);
1435 if (oldfd >= 0 && newfd >= 0 && newfd != oldfd)
1436 FdDup(thr, pc, oldfd, newfd, true);
1440 TSAN_INTERCEPTOR(int, dup2, int oldfd, int newfd) {
1441 SCOPED_TSAN_INTERCEPTOR(dup2, oldfd, newfd);
1442 int newfd2 = REAL(dup2)(oldfd, newfd);
1443 if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd)
1444 FdDup(thr, pc, oldfd, newfd2, false);
1449 TSAN_INTERCEPTOR(int, dup3, int oldfd, int newfd, int flags) {
1450 SCOPED_TSAN_INTERCEPTOR(dup3, oldfd, newfd, flags);
1451 int newfd2 = REAL(dup3)(oldfd, newfd, flags);
1452 if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd)
1453 FdDup(thr, pc, oldfd, newfd2, false);
1459 TSAN_INTERCEPTOR(int, eventfd, unsigned initval, int flags) {
1460 SCOPED_TSAN_INTERCEPTOR(eventfd, initval, flags);
1461 int fd = REAL(eventfd)(initval, flags);
1463 FdEventCreate(thr, pc, fd);
1466 #define TSAN_MAYBE_INTERCEPT_EVENTFD TSAN_INTERCEPT(eventfd)
1468 #define TSAN_MAYBE_INTERCEPT_EVENTFD
1472 TSAN_INTERCEPTOR(int, signalfd, int fd, void *mask, int flags) {
1473 SCOPED_TSAN_INTERCEPTOR(signalfd, fd, mask, flags);
1475 FdClose(thr, pc, fd);
1476 fd = REAL(signalfd)(fd, mask, flags);
1478 FdSignalCreate(thr, pc, fd);
1481 #define TSAN_MAYBE_INTERCEPT_SIGNALFD TSAN_INTERCEPT(signalfd)
1483 #define TSAN_MAYBE_INTERCEPT_SIGNALFD
1487 TSAN_INTERCEPTOR(int, inotify_init, int fake) {
1488 SCOPED_TSAN_INTERCEPTOR(inotify_init, fake);
1489 int fd = REAL(inotify_init)(fake);
1491 FdInotifyCreate(thr, pc, fd);
1494 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT TSAN_INTERCEPT(inotify_init)
1496 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT
1500 TSAN_INTERCEPTOR(int, inotify_init1, int flags) {
1501 SCOPED_TSAN_INTERCEPTOR(inotify_init1, flags);
1502 int fd = REAL(inotify_init1)(flags);
1504 FdInotifyCreate(thr, pc, fd);
1507 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1 TSAN_INTERCEPT(inotify_init1)
1509 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1
1512 TSAN_INTERCEPTOR(int, socket, int domain, int type, int protocol) {
1513 SCOPED_TSAN_INTERCEPTOR(socket, domain, type, protocol);
1514 int fd = REAL(socket)(domain, type, protocol);
1516 FdSocketCreate(thr, pc, fd);
1520 TSAN_INTERCEPTOR(int, socketpair, int domain, int type, int protocol, int *fd) {
1521 SCOPED_TSAN_INTERCEPTOR(socketpair, domain, type, protocol, fd);
1522 int res = REAL(socketpair)(domain, type, protocol, fd);
1523 if (res == 0 && fd[0] >= 0 && fd[1] >= 0)
1524 FdPipeCreate(thr, pc, fd[0], fd[1]);
1528 TSAN_INTERCEPTOR(int, connect, int fd, void *addr, unsigned addrlen) {
1529 SCOPED_TSAN_INTERCEPTOR(connect, fd, addr, addrlen);
1530 FdSocketConnecting(thr, pc, fd);
1531 int res = REAL(connect)(fd, addr, addrlen);
1532 if (res == 0 && fd >= 0)
1533 FdSocketConnect(thr, pc, fd);
1537 TSAN_INTERCEPTOR(int, bind, int fd, void *addr, unsigned addrlen) {
1538 SCOPED_TSAN_INTERCEPTOR(bind, fd, addr, addrlen);
1539 int res = REAL(bind)(fd, addr, addrlen);
1540 if (fd > 0 && res == 0)
1541 FdAccess(thr, pc, fd);
1545 TSAN_INTERCEPTOR(int, listen, int fd, int backlog) {
1546 SCOPED_TSAN_INTERCEPTOR(listen, fd, backlog);
1547 int res = REAL(listen)(fd, backlog);
1548 if (fd > 0 && res == 0)
1549 FdAccess(thr, pc, fd);
1553 TSAN_INTERCEPTOR(int, close, int fd) {
1554 SCOPED_TSAN_INTERCEPTOR(close, fd);
1556 FdClose(thr, pc, fd);
1557 return REAL(close)(fd);
1561 TSAN_INTERCEPTOR(int, __close, int fd) {
1562 SCOPED_TSAN_INTERCEPTOR(__close, fd);
1564 FdClose(thr, pc, fd);
1565 return REAL(__close)(fd);
1567 #define TSAN_MAYBE_INTERCEPT___CLOSE TSAN_INTERCEPT(__close)
1569 #define TSAN_MAYBE_INTERCEPT___CLOSE
1573 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1574 TSAN_INTERCEPTOR(void, __res_iclose, void *state, bool free_addr) {
1575 SCOPED_TSAN_INTERCEPTOR(__res_iclose, state, free_addr);
1577 int cnt = ExtractResolvFDs(state, fds, ARRAY_SIZE(fds));
1578 for (int i = 0; i < cnt; i++) {
1580 FdClose(thr, pc, fds[i]);
1582 REAL(__res_iclose)(state, free_addr);
1584 #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE TSAN_INTERCEPT(__res_iclose)
1586 #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE
1589 TSAN_INTERCEPTOR(int, pipe, int *pipefd) {
1590 SCOPED_TSAN_INTERCEPTOR(pipe, pipefd);
1591 int res = REAL(pipe)(pipefd);
1592 if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0)
1593 FdPipeCreate(thr, pc, pipefd[0], pipefd[1]);
1598 TSAN_INTERCEPTOR(int, pipe2, int *pipefd, int flags) {
1599 SCOPED_TSAN_INTERCEPTOR(pipe2, pipefd, flags);
1600 int res = REAL(pipe2)(pipefd, flags);
1601 if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0)
1602 FdPipeCreate(thr, pc, pipefd[0], pipefd[1]);
1607 TSAN_INTERCEPTOR(int, unlink, char *path) {
1608 SCOPED_TSAN_INTERCEPTOR(unlink, path);
1609 Release(thr, pc, File2addr(path));
1610 int res = REAL(unlink)(path);
1614 TSAN_INTERCEPTOR(void*, tmpfile, int fake) {
1615 SCOPED_TSAN_INTERCEPTOR(tmpfile, fake);
1616 void *res = REAL(tmpfile)(fake);
1618 int fd = fileno_unlocked(res);
1620 FdFileCreate(thr, pc, fd);
1626 TSAN_INTERCEPTOR(void*, tmpfile64, int fake) {
1627 SCOPED_TSAN_INTERCEPTOR(tmpfile64, fake);
1628 void *res = REAL(tmpfile64)(fake);
1630 int fd = fileno_unlocked(res);
1632 FdFileCreate(thr, pc, fd);
1636 #define TSAN_MAYBE_INTERCEPT_TMPFILE64 TSAN_INTERCEPT(tmpfile64)
1638 #define TSAN_MAYBE_INTERCEPT_TMPFILE64
1641 static void FlushStreams() {
1642 // Flushing all the streams here may freeze the process if a child thread is
1643 // performing file stream operations at the same time.
1644 REAL(fflush)(stdout);
1645 REAL(fflush)(stderr);
1648 TSAN_INTERCEPTOR(void, abort, int fake) {
1649 SCOPED_TSAN_INTERCEPTOR(abort, fake);
1654 TSAN_INTERCEPTOR(int, puts, const char *s) {
1655 SCOPED_TSAN_INTERCEPTOR(puts, s);
1656 MemoryAccessRange(thr, pc, (uptr)s, internal_strlen(s), false);
1657 return REAL(puts)(s);
1660 TSAN_INTERCEPTOR(int, rmdir, char *path) {
1661 SCOPED_TSAN_INTERCEPTOR(rmdir, path);
1662 Release(thr, pc, Dir2addr(path));
1663 int res = REAL(rmdir)(path);
1667 TSAN_INTERCEPTOR(int, closedir, void *dirp) {
1668 SCOPED_TSAN_INTERCEPTOR(closedir, dirp);
1670 int fd = dirfd(dirp);
1671 FdClose(thr, pc, fd);
1673 return REAL(closedir)(dirp);
1677 TSAN_INTERCEPTOR(int, epoll_create, int size) {
1678 SCOPED_TSAN_INTERCEPTOR(epoll_create, size);
1679 int fd = REAL(epoll_create)(size);
1681 FdPollCreate(thr, pc, fd);
1685 TSAN_INTERCEPTOR(int, epoll_create1, int flags) {
1686 SCOPED_TSAN_INTERCEPTOR(epoll_create1, flags);
1687 int fd = REAL(epoll_create1)(flags);
1689 FdPollCreate(thr, pc, fd);
1693 TSAN_INTERCEPTOR(int, epoll_ctl, int epfd, int op, int fd, void *ev) {
1694 SCOPED_TSAN_INTERCEPTOR(epoll_ctl, epfd, op, fd, ev);
1696 FdAccess(thr, pc, epfd);
1697 if (epfd >= 0 && fd >= 0)
1698 FdAccess(thr, pc, fd);
1699 if (op == EPOLL_CTL_ADD && epfd >= 0)
1700 FdRelease(thr, pc, epfd);
1701 int res = REAL(epoll_ctl)(epfd, op, fd, ev);
1705 TSAN_INTERCEPTOR(int, epoll_wait, int epfd, void *ev, int cnt, int timeout) {
1706 SCOPED_TSAN_INTERCEPTOR(epoll_wait, epfd, ev, cnt, timeout);
1708 FdAccess(thr, pc, epfd);
1709 int res = BLOCK_REAL(epoll_wait)(epfd, ev, cnt, timeout);
1710 if (res > 0 && epfd >= 0)
1711 FdAcquire(thr, pc, epfd);
1715 TSAN_INTERCEPTOR(int, epoll_pwait, int epfd, void *ev, int cnt, int timeout,
1717 SCOPED_TSAN_INTERCEPTOR(epoll_pwait, epfd, ev, cnt, timeout, sigmask);
1719 FdAccess(thr, pc, epfd);
1720 int res = BLOCK_REAL(epoll_pwait)(epfd, ev, cnt, timeout, sigmask);
1721 if (res > 0 && epfd >= 0)
1722 FdAcquire(thr, pc, epfd);
1726 #define TSAN_MAYBE_INTERCEPT_EPOLL \
1727 TSAN_INTERCEPT(epoll_create); \
1728 TSAN_INTERCEPT(epoll_create1); \
1729 TSAN_INTERCEPT(epoll_ctl); \
1730 TSAN_INTERCEPT(epoll_wait); \
1731 TSAN_INTERCEPT(epoll_pwait)
1733 #define TSAN_MAYBE_INTERCEPT_EPOLL
1736 // The following functions are intercepted merely to process pending signals.
1737 // If program blocks signal X, we must deliver the signal before the function
1738 // returns. Similarly, if program unblocks a signal (or returns from sigsuspend)
1739 // it's better to deliver the signal straight away.
1740 TSAN_INTERCEPTOR(int, sigsuspend, const __sanitizer_sigset_t *mask) {
1741 SCOPED_TSAN_INTERCEPTOR(sigsuspend, mask);
1742 return REAL(sigsuspend)(mask);
1745 TSAN_INTERCEPTOR(int, sigblock, int mask) {
1746 SCOPED_TSAN_INTERCEPTOR(sigblock, mask);
1747 return REAL(sigblock)(mask);
1750 TSAN_INTERCEPTOR(int, sigsetmask, int mask) {
1751 SCOPED_TSAN_INTERCEPTOR(sigsetmask, mask);
1752 return REAL(sigsetmask)(mask);
1755 TSAN_INTERCEPTOR(int, pthread_sigmask, int how, const __sanitizer_sigset_t *set,
1756 __sanitizer_sigset_t *oldset) {
1757 SCOPED_TSAN_INTERCEPTOR(pthread_sigmask, how, set, oldset);
1758 return REAL(pthread_sigmask)(how, set, oldset);
1763 static void CallUserSignalHandler(ThreadState *thr, bool sync, bool acquire,
1764 bool sigact, int sig, my_siginfo_t *info, void *uctx) {
1766 Acquire(thr, 0, (uptr)&sigactions[sig]);
1767 // Signals are generally asynchronous, so if we receive a signals when
1768 // ignores are enabled we should disable ignores. This is critical for sync
1769 // and interceptors, because otherwise we can miss syncronization and report
1771 int ignore_reads_and_writes = thr->ignore_reads_and_writes;
1772 int ignore_interceptors = thr->ignore_interceptors;
1773 int ignore_sync = thr->ignore_sync;
1774 if (!ctx->after_multithreaded_fork) {
1775 thr->ignore_reads_and_writes = 0;
1776 thr->fast_state.ClearIgnoreBit();
1777 thr->ignore_interceptors = 0;
1778 thr->ignore_sync = 0;
1780 // Ensure that the handler does not spoil errno.
1781 const int saved_errno = errno;
1783 // This code races with sigaction. Be careful to not read sa_sigaction twice.
1784 // Also need to remember pc for reporting before the call,
1785 // because the handler can reset it.
1786 volatile uptr pc = sigact ?
1787 (uptr)sigactions[sig].sa_sigaction :
1788 (uptr)sigactions[sig].sa_handler;
1789 if (pc != (uptr)SIG_DFL && pc != (uptr)SIG_IGN) {
1791 ((sigactionhandler_t)pc)(sig, info, uctx);
1793 ((sighandler_t)pc)(sig);
1795 if (!ctx->after_multithreaded_fork) {
1796 thr->ignore_reads_and_writes = ignore_reads_and_writes;
1797 if (ignore_reads_and_writes)
1798 thr->fast_state.SetIgnoreBit();
1799 thr->ignore_interceptors = ignore_interceptors;
1800 thr->ignore_sync = ignore_sync;
1802 // We do not detect errno spoiling for SIGTERM,
1803 // because some SIGTERM handlers do spoil errno but reraise SIGTERM,
1804 // tsan reports false positive in such case.
1805 // It's difficult to properly detect this situation (reraise),
1806 // because in async signal processing case (when handler is called directly
1807 // from rtl_generic_sighandler) we have not yet received the reraised
1808 // signal; and it looks too fragile to intercept all ways to reraise a signal.
1809 if (flags()->report_bugs && !sync && sig != SIGTERM && errno != 99) {
1810 VarSizeStackTrace stack;
1811 // StackTrace::GetNestInstructionPc(pc) is used because return address is
1812 // expected, OutputReport() will undo this.
1813 ObtainCurrentStack(thr, StackTrace::GetNextInstructionPc(pc), &stack);
1814 ThreadRegistryLock l(ctx->thread_registry);
1815 ScopedReport rep(ReportTypeErrnoInSignal);
1816 if (!IsFiredSuppression(ctx, ReportTypeErrnoInSignal, stack)) {
1817 rep.AddStack(stack, true);
1818 OutputReport(thr, rep);
1821 errno = saved_errno;
1824 void ProcessPendingSignals(ThreadState *thr) {
1825 ThreadSignalContext *sctx = SigCtx(thr);
1827 atomic_load(&sctx->have_pending_signals, memory_order_relaxed) == 0)
1829 atomic_store(&sctx->have_pending_signals, 0, memory_order_relaxed);
1830 atomic_fetch_add(&thr->in_signal_handler, 1, memory_order_relaxed);
1831 internal_sigfillset(&sctx->emptyset);
1832 int res = REAL(pthread_sigmask)(SIG_SETMASK, &sctx->emptyset, &sctx->oldset);
1834 for (int sig = 0; sig < kSigCount; sig++) {
1835 SignalDesc *signal = &sctx->pending_signals[sig];
1836 if (signal->armed) {
1837 signal->armed = false;
1838 CallUserSignalHandler(thr, false, true, signal->sigaction, sig,
1839 &signal->siginfo, &signal->ctx);
1842 res = REAL(pthread_sigmask)(SIG_SETMASK, &sctx->oldset, 0);
1844 atomic_fetch_add(&thr->in_signal_handler, -1, memory_order_relaxed);
1847 } // namespace __tsan
1849 static bool is_sync_signal(ThreadSignalContext *sctx, int sig) {
1850 return sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
1851 sig == SIGABRT || sig == SIGFPE || sig == SIGPIPE || sig == SIGSYS ||
1852 // If we are sending signal to ourselves, we must process it now.
1853 (sctx && sig == sctx->int_signal_send);
1856 void ALWAYS_INLINE rtl_generic_sighandler(bool sigact, int sig,
1857 my_siginfo_t *info, void *ctx) {
1858 ThreadState *thr = cur_thread();
1859 ThreadSignalContext *sctx = SigCtx(thr);
1860 if (sig < 0 || sig >= kSigCount) {
1861 VPrintf(1, "ThreadSanitizer: ignoring signal %d\n", sig);
1864 // Don't mess with synchronous signals.
1865 const bool sync = is_sync_signal(sctx, sig);
1867 // If we are in blocking function, we can safely process it now
1868 // (but check if we are in a recursive interceptor,
1869 // i.e. pthread_join()->munmap()).
1870 (sctx && atomic_load(&sctx->in_blocking_func, memory_order_relaxed))) {
1871 atomic_fetch_add(&thr->in_signal_handler, 1, memory_order_relaxed);
1872 if (sctx && atomic_load(&sctx->in_blocking_func, memory_order_relaxed)) {
1873 atomic_store(&sctx->in_blocking_func, 0, memory_order_relaxed);
1874 CallUserSignalHandler(thr, sync, true, sigact, sig, info, ctx);
1875 atomic_store(&sctx->in_blocking_func, 1, memory_order_relaxed);
1877 // Be very conservative with when we do acquire in this case.
1878 // It's unsafe to do acquire in async handlers, because ThreadState
1879 // can be in inconsistent state.
1880 // SIGSYS looks relatively safe -- it's synchronous and can actually
1881 // need some global state.
1882 bool acq = (sig == SIGSYS);
1883 CallUserSignalHandler(thr, sync, acq, sigact, sig, info, ctx);
1885 atomic_fetch_add(&thr->in_signal_handler, -1, memory_order_relaxed);
1891 SignalDesc *signal = &sctx->pending_signals[sig];
1892 if (signal->armed == false) {
1893 signal->armed = true;
1894 signal->sigaction = sigact;
1896 internal_memcpy(&signal->siginfo, info, sizeof(*info));
1898 internal_memcpy(&signal->ctx, ctx, sizeof(signal->ctx));
1899 atomic_store(&sctx->have_pending_signals, 1, memory_order_relaxed);
1903 static void rtl_sighandler(int sig) {
1904 rtl_generic_sighandler(false, sig, 0, 0);
1907 static void rtl_sigaction(int sig, my_siginfo_t *info, void *ctx) {
1908 rtl_generic_sighandler(true, sig, info, ctx);
1911 TSAN_INTERCEPTOR(int, sigaction, int sig, sigaction_t *act, sigaction_t *old) {
1912 // Note: if we call REAL(sigaction) directly for any reason without proxying
1913 // the signal handler through rtl_sigaction, very bad things will happen.
1914 // The handler will run synchronously and corrupt tsan per-thread state.
1915 SCOPED_INTERCEPTOR_RAW(sigaction, sig, act, old);
1917 internal_memcpy(old, &sigactions[sig], sizeof(*old));
1920 // Copy act into sigactions[sig].
1921 // Can't use struct copy, because compiler can emit call to memcpy.
1922 // Can't use internal_memcpy, because it copies byte-by-byte,
1923 // and signal handler reads the sa_handler concurrently. It it can read
1924 // some bytes from old value and some bytes from new value.
1925 // Use volatile to prevent insertion of memcpy.
1926 sigactions[sig].sa_handler = *(volatile sighandler_t*)&act->sa_handler;
1927 sigactions[sig].sa_flags = *(volatile int*)&act->sa_flags;
1928 internal_memcpy(&sigactions[sig].sa_mask, &act->sa_mask,
1929 sizeof(sigactions[sig].sa_mask));
1930 #if !SANITIZER_FREEBSD && !SANITIZER_MAC
1931 sigactions[sig].sa_restorer = act->sa_restorer;
1934 internal_memcpy(&newact, act, sizeof(newact));
1935 internal_sigfillset(&newact.sa_mask);
1936 if (act->sa_handler != SIG_IGN && act->sa_handler != SIG_DFL) {
1937 if (newact.sa_flags & SA_SIGINFO)
1938 newact.sa_sigaction = rtl_sigaction;
1940 newact.sa_handler = rtl_sighandler;
1942 ReleaseStore(thr, pc, (uptr)&sigactions[sig]);
1943 int res = REAL(sigaction)(sig, &newact, 0);
1947 TSAN_INTERCEPTOR(sighandler_t, signal, int sig, sighandler_t h) {
1950 internal_memset(&act.sa_mask, -1, sizeof(act.sa_mask));
1953 int res = sigaction(sig, &act, &old);
1956 return old.sa_handler;
1959 TSAN_INTERCEPTOR(int, raise, int sig) {
1960 SCOPED_TSAN_INTERCEPTOR(raise, sig);
1961 ThreadSignalContext *sctx = SigCtx(thr);
1963 int prev = sctx->int_signal_send;
1964 sctx->int_signal_send = sig;
1965 int res = REAL(raise)(sig);
1966 CHECK_EQ(sctx->int_signal_send, sig);
1967 sctx->int_signal_send = prev;
1971 TSAN_INTERCEPTOR(int, kill, int pid, int sig) {
1972 SCOPED_TSAN_INTERCEPTOR(kill, pid, sig);
1973 ThreadSignalContext *sctx = SigCtx(thr);
1975 int prev = sctx->int_signal_send;
1976 if (pid == (int)internal_getpid()) {
1977 sctx->int_signal_send = sig;
1979 int res = REAL(kill)(pid, sig);
1980 if (pid == (int)internal_getpid()) {
1981 CHECK_EQ(sctx->int_signal_send, sig);
1982 sctx->int_signal_send = prev;
1987 TSAN_INTERCEPTOR(int, pthread_kill, void *tid, int sig) {
1988 SCOPED_TSAN_INTERCEPTOR(pthread_kill, tid, sig);
1989 ThreadSignalContext *sctx = SigCtx(thr);
1991 int prev = sctx->int_signal_send;
1992 if (tid == pthread_self()) {
1993 sctx->int_signal_send = sig;
1995 int res = REAL(pthread_kill)(tid, sig);
1996 if (tid == pthread_self()) {
1997 CHECK_EQ(sctx->int_signal_send, sig);
1998 sctx->int_signal_send = prev;
2003 TSAN_INTERCEPTOR(int, gettimeofday, void *tv, void *tz) {
2004 SCOPED_TSAN_INTERCEPTOR(gettimeofday, tv, tz);
2005 // It's intercepted merely to process pending signals.
2006 return REAL(gettimeofday)(tv, tz);
2009 TSAN_INTERCEPTOR(int, getaddrinfo, void *node, void *service,
2010 void *hints, void *rv) {
2011 SCOPED_TSAN_INTERCEPTOR(getaddrinfo, node, service, hints, rv);
2012 // We miss atomic synchronization in getaddrinfo,
2013 // and can report false race between malloc and free
2014 // inside of getaddrinfo. So ignore memory accesses.
2015 ThreadIgnoreBegin(thr, pc);
2016 int res = REAL(getaddrinfo)(node, service, hints, rv);
2017 ThreadIgnoreEnd(thr, pc);
2021 TSAN_INTERCEPTOR(int, fork, int fake) {
2022 if (cur_thread()->in_symbolizer)
2023 return REAL(fork)(fake);
2024 SCOPED_INTERCEPTOR_RAW(fork, fake);
2025 ForkBefore(thr, pc);
2028 // On OS X, REAL(fork) can call intercepted functions (OSSpinLockLock), and
2029 // we'll assert in CheckNoLocks() unless we ignore interceptors.
2030 ScopedIgnoreInterceptors ignore;
2031 pid = REAL(fork)(fake);
2035 ForkChildAfter(thr, pc);
2037 } else if (pid > 0) {
2039 ForkParentAfter(thr, pc);
2042 ForkParentAfter(thr, pc);
2047 TSAN_INTERCEPTOR(int, vfork, int fake) {
2048 // Some programs (e.g. openjdk) call close for all file descriptors
2049 // in the child process. Under tsan it leads to false positives, because
2050 // address space is shared, so the parent process also thinks that
2051 // the descriptors are closed (while they are actually not).
2052 // This leads to false positives due to missed synchronization.
2053 // Strictly saying this is undefined behavior, because vfork child is not
2054 // allowed to call any functions other than exec/exit. But this is what
2055 // openjdk does, so we want to handle it.
2056 // We could disable interceptors in the child process. But it's not possible
2057 // to simply intercept and wrap vfork, because vfork child is not allowed
2058 // to return from the function that calls vfork, and that's exactly what
2059 // we would do. So this would require some assembly trickery as well.
2060 // Instead we simply turn vfork into fork.
2061 return WRAP(fork)(fake);
2064 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2065 typedef int (*dl_iterate_phdr_cb_t)(__sanitizer_dl_phdr_info *info, SIZE_T size,
2067 struct dl_iterate_phdr_data {
2070 dl_iterate_phdr_cb_t cb;
2074 static bool IsAppNotRodata(uptr addr) {
2075 return IsAppMem(addr) && *(u64*)MemToShadow(addr) != kShadowRodata;
2078 static int dl_iterate_phdr_cb(__sanitizer_dl_phdr_info *info, SIZE_T size,
2080 dl_iterate_phdr_data *cbdata = (dl_iterate_phdr_data *)data;
2081 // dlopen/dlclose allocate/free dynamic-linker-internal memory, which is later
2082 // accessible in dl_iterate_phdr callback. But we don't see synchronization
2083 // inside of dynamic linker, so we "unpoison" it here in order to not
2084 // produce false reports. Ignoring malloc/free in dlopen/dlclose is not enough
2085 // because some libc functions call __libc_dlopen.
2086 if (info && IsAppNotRodata((uptr)info->dlpi_name))
2087 MemoryResetRange(cbdata->thr, cbdata->pc, (uptr)info->dlpi_name,
2088 internal_strlen(info->dlpi_name));
2089 int res = cbdata->cb(info, size, cbdata->data);
2090 // Perform the check one more time in case info->dlpi_name was overwritten
2091 // by user callback.
2092 if (info && IsAppNotRodata((uptr)info->dlpi_name))
2093 MemoryResetRange(cbdata->thr, cbdata->pc, (uptr)info->dlpi_name,
2094 internal_strlen(info->dlpi_name));
2098 TSAN_INTERCEPTOR(int, dl_iterate_phdr, dl_iterate_phdr_cb_t cb, void *data) {
2099 SCOPED_TSAN_INTERCEPTOR(dl_iterate_phdr, cb, data);
2100 dl_iterate_phdr_data cbdata;
2105 int res = REAL(dl_iterate_phdr)(dl_iterate_phdr_cb, &cbdata);
2110 static int OnExit(ThreadState *thr) {
2111 int status = Finalize(thr);
2116 struct TsanInterceptorContext {
2118 const uptr caller_pc;
2123 static void HandleRecvmsg(ThreadState *thr, uptr pc,
2124 __sanitizer_msghdr *msg) {
2126 int cnt = ExtractRecvmsgFDs(msg, fds, ARRAY_SIZE(fds));
2127 for (int i = 0; i < cnt; i++)
2128 FdEventCreate(thr, pc, fds[i]);
2132 #include "sanitizer_common/sanitizer_platform_interceptors.h"
2133 // Causes interceptor recursion (getaddrinfo() and fopen())
2134 #undef SANITIZER_INTERCEPT_GETADDRINFO
2135 // There interceptors do not seem to be strictly necessary for tsan.
2136 // But we see cases where the interceptors consume 70% of execution time.
2137 // Memory blocks passed to fgetgrent_r are "written to" by tsan several times.
2138 // First, there is some recursion (getgrnam_r calls fgetgrent_r), and each
2139 // function "writes to" the buffer. Then, the same memory is "written to"
2140 // twice, first as buf and then as pwbufp (both of them refer to the same
2142 #undef SANITIZER_INTERCEPT_GETPWENT
2143 #undef SANITIZER_INTERCEPT_GETPWENT_R
2144 #undef SANITIZER_INTERCEPT_FGETPWENT
2145 #undef SANITIZER_INTERCEPT_GETPWNAM_AND_FRIENDS
2146 #undef SANITIZER_INTERCEPT_GETPWNAM_R_AND_FRIENDS
2147 // We define our own.
2148 #if SANITIZER_INTERCEPT_TLS_GET_ADDR
2149 #define NEED_TLS_GET_ADDR
2151 #undef SANITIZER_INTERCEPT_TLS_GET_ADDR
2153 #define COMMON_INTERCEPT_FUNCTION(name) INTERCEPT_FUNCTION(name)
2154 #define COMMON_INTERCEPT_FUNCTION_VER(name, ver) \
2155 INTERCEPT_FUNCTION_VER(name, ver)
2157 #define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \
2158 MemoryAccessRange(((TsanInterceptorContext *)ctx)->thr, \
2159 ((TsanInterceptorContext *)ctx)->pc, (uptr)ptr, size, \
2162 #define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) \
2163 MemoryAccessRange(((TsanInterceptorContext *) ctx)->thr, \
2164 ((TsanInterceptorContext *) ctx)->pc, (uptr) ptr, size, \
2167 #define COMMON_INTERCEPTOR_ENTER(ctx, func, ...) \
2168 SCOPED_TSAN_INTERCEPTOR(func, __VA_ARGS__); \
2169 TsanInterceptorContext _ctx = {thr, caller_pc, pc}; \
2170 ctx = (void *)&_ctx; \
2173 #define COMMON_INTERCEPTOR_ENTER_NOIGNORE(ctx, func, ...) \
2174 SCOPED_INTERCEPTOR_RAW(func, __VA_ARGS__); \
2175 TsanInterceptorContext _ctx = {thr, caller_pc, pc}; \
2176 ctx = (void *)&_ctx; \
2179 #define COMMON_INTERCEPTOR_FILE_OPEN(ctx, file, path) \
2180 Acquire(thr, pc, File2addr(path)); \
2182 int fd = fileno_unlocked(file); \
2183 if (fd >= 0) FdFileCreate(thr, pc, fd); \
2186 #define COMMON_INTERCEPTOR_FILE_CLOSE(ctx, file) \
2188 int fd = fileno_unlocked(file); \
2189 if (fd >= 0) FdClose(thr, pc, fd); \
2192 #define COMMON_INTERCEPTOR_LIBRARY_LOADED(filename, handle) \
2193 libignore()->OnLibraryLoaded(filename)
2195 #define COMMON_INTERCEPTOR_LIBRARY_UNLOADED() \
2196 libignore()->OnLibraryUnloaded()
2198 #define COMMON_INTERCEPTOR_ACQUIRE(ctx, u) \
2199 Acquire(((TsanInterceptorContext *) ctx)->thr, pc, u)
2201 #define COMMON_INTERCEPTOR_RELEASE(ctx, u) \
2202 Release(((TsanInterceptorContext *) ctx)->thr, pc, u)
2204 #define COMMON_INTERCEPTOR_DIR_ACQUIRE(ctx, path) \
2205 Acquire(((TsanInterceptorContext *) ctx)->thr, pc, Dir2addr(path))
2207 #define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \
2208 FdAcquire(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2210 #define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \
2211 FdRelease(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2213 #define COMMON_INTERCEPTOR_FD_ACCESS(ctx, fd) \
2214 FdAccess(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2216 #define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \
2217 FdSocketAccept(((TsanInterceptorContext *) ctx)->thr, pc, fd, newfd)
2219 #define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) \
2220 ThreadSetName(((TsanInterceptorContext *) ctx)->thr, name)
2222 #define COMMON_INTERCEPTOR_SET_PTHREAD_NAME(ctx, thread, name) \
2223 __tsan::ctx->thread_registry->SetThreadNameByUserId(thread, name)
2225 #define COMMON_INTERCEPTOR_BLOCK_REAL(name) BLOCK_REAL(name)
2227 #define COMMON_INTERCEPTOR_ON_EXIT(ctx) \
2228 OnExit(((TsanInterceptorContext *) ctx)->thr)
2230 #define COMMON_INTERCEPTOR_MUTEX_PRE_LOCK(ctx, m) \
2231 MutexPreLock(((TsanInterceptorContext *)ctx)->thr, \
2232 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2234 #define COMMON_INTERCEPTOR_MUTEX_POST_LOCK(ctx, m) \
2235 MutexPostLock(((TsanInterceptorContext *)ctx)->thr, \
2236 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2238 #define COMMON_INTERCEPTOR_MUTEX_UNLOCK(ctx, m) \
2239 MutexUnlock(((TsanInterceptorContext *)ctx)->thr, \
2240 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2242 #define COMMON_INTERCEPTOR_MUTEX_REPAIR(ctx, m) \
2243 MutexRepair(((TsanInterceptorContext *)ctx)->thr, \
2244 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2246 #define COMMON_INTERCEPTOR_MUTEX_INVALID(ctx, m) \
2247 MutexInvalidAccess(((TsanInterceptorContext *)ctx)->thr, \
2248 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2251 #define COMMON_INTERCEPTOR_HANDLE_RECVMSG(ctx, msg) \
2252 HandleRecvmsg(((TsanInterceptorContext *)ctx)->thr, \
2253 ((TsanInterceptorContext *)ctx)->pc, msg)
2256 #define COMMON_INTERCEPTOR_GET_TLS_RANGE(begin, end) \
2257 if (TsanThread *t = GetCurrentThread()) { \
2258 *begin = t->tls_begin(); \
2259 *end = t->tls_end(); \
2261 *begin = *end = 0; \
2264 #define COMMON_INTERCEPTOR_USER_CALLBACK_START() \
2265 SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_START()
2267 #define COMMON_INTERCEPTOR_USER_CALLBACK_END() \
2268 SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_END()
2270 #include "sanitizer_common/sanitizer_common_interceptors.inc"
2272 #define TSAN_SYSCALL() \
2273 ThreadState *thr = cur_thread(); \
2274 if (thr->ignore_interceptors) \
2276 ScopedSyscall scoped_syscall(thr) \
2279 struct ScopedSyscall {
2282 explicit ScopedSyscall(ThreadState *thr)
2288 ProcessPendingSignals(thr);
2292 #if !SANITIZER_FREEBSD && !SANITIZER_MAC
2293 static void syscall_access_range(uptr pc, uptr p, uptr s, bool write) {
2295 MemoryAccessRange(thr, pc, p, s, write);
2298 static void syscall_acquire(uptr pc, uptr addr) {
2300 Acquire(thr, pc, addr);
2301 DPrintf("syscall_acquire(%p)\n", addr);
2304 static void syscall_release(uptr pc, uptr addr) {
2306 DPrintf("syscall_release(%p)\n", addr);
2307 Release(thr, pc, addr);
2310 static void syscall_fd_close(uptr pc, int fd) {
2312 FdClose(thr, pc, fd);
2315 static USED void syscall_fd_acquire(uptr pc, int fd) {
2317 FdAcquire(thr, pc, fd);
2318 DPrintf("syscall_fd_acquire(%p)\n", fd);
2321 static USED void syscall_fd_release(uptr pc, int fd) {
2323 DPrintf("syscall_fd_release(%p)\n", fd);
2324 FdRelease(thr, pc, fd);
2327 static void syscall_pre_fork(uptr pc) {
2329 ForkBefore(thr, pc);
2332 static void syscall_post_fork(uptr pc, int pid) {
2336 ForkChildAfter(thr, pc);
2338 } else if (pid > 0) {
2340 ForkParentAfter(thr, pc);
2343 ForkParentAfter(thr, pc);
2348 #define COMMON_SYSCALL_PRE_READ_RANGE(p, s) \
2349 syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), false)
2351 #define COMMON_SYSCALL_PRE_WRITE_RANGE(p, s) \
2352 syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), true)
2354 #define COMMON_SYSCALL_POST_READ_RANGE(p, s) \
2360 #define COMMON_SYSCALL_POST_WRITE_RANGE(p, s) \
2366 #define COMMON_SYSCALL_ACQUIRE(addr) \
2367 syscall_acquire(GET_CALLER_PC(), (uptr)(addr))
2369 #define COMMON_SYSCALL_RELEASE(addr) \
2370 syscall_release(GET_CALLER_PC(), (uptr)(addr))
2372 #define COMMON_SYSCALL_FD_CLOSE(fd) syscall_fd_close(GET_CALLER_PC(), fd)
2374 #define COMMON_SYSCALL_FD_ACQUIRE(fd) syscall_fd_acquire(GET_CALLER_PC(), fd)
2376 #define COMMON_SYSCALL_FD_RELEASE(fd) syscall_fd_release(GET_CALLER_PC(), fd)
2378 #define COMMON_SYSCALL_PRE_FORK() \
2379 syscall_pre_fork(GET_CALLER_PC())
2381 #define COMMON_SYSCALL_POST_FORK(res) \
2382 syscall_post_fork(GET_CALLER_PC(), res)
2384 #include "sanitizer_common/sanitizer_common_syscalls.inc"
2386 #ifdef NEED_TLS_GET_ADDR
2387 // Define own interceptor instead of sanitizer_common's for three reasons:
2388 // 1. It must not process pending signals.
2389 // Signal handlers may contain MOVDQA instruction (see below).
2390 // 2. It must be as simple as possible to not contain MOVDQA.
2391 // 3. Sanitizer_common version uses COMMON_INTERCEPTOR_INITIALIZE_RANGE which
2392 // is empty for tsan (meant only for msan).
2393 // Note: __tls_get_addr can be called with mis-aligned stack due to:
2394 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58066
2395 // So the interceptor must work with mis-aligned stack, in particular, does not
2396 // execute MOVDQA with stack addresses.
2397 TSAN_INTERCEPTOR(void *, __tls_get_addr, void *arg) {
2398 void *res = REAL(__tls_get_addr)(arg);
2399 ThreadState *thr = cur_thread();
2402 DTLS::DTV *dtv = DTLS_on_tls_get_addr(arg, res, thr->tls_addr, thr->tls_size);
2405 // New DTLS block has been allocated.
2406 MemoryResetRange(thr, 0, dtv->beg, dtv->size);
2413 static void finalize(void *arg) {
2414 ThreadState *thr = cur_thread();
2415 int status = Finalize(thr);
2416 // Make sure the output is not lost.
2422 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2423 static void unreachable() {
2424 Report("FATAL: ThreadSanitizer: unreachable called\n");
2429 void InitializeInterceptors() {
2431 // We need to setup it early, because functions like dlsym() can call it.
2432 REAL(memset) = internal_memset;
2433 REAL(memcpy) = internal_memcpy;
2436 // Instruct libc malloc to consume less memory.
2438 mallopt(1, 0); // M_MXFAST
2439 mallopt(-3, 32*1024); // M_MMAP_THRESHOLD
2442 InitializeCommonInterceptors();
2445 // We can not use TSAN_INTERCEPT to get setjmp addr,
2446 // because it does &setjmp and setjmp is not present in some versions of libc.
2447 using __interception::GetRealFunctionAddress;
2448 GetRealFunctionAddress("setjmp", (uptr*)&REAL(setjmp), 0, 0);
2449 GetRealFunctionAddress("_setjmp", (uptr*)&REAL(_setjmp), 0, 0);
2450 GetRealFunctionAddress("sigsetjmp", (uptr*)&REAL(sigsetjmp), 0, 0);
2451 GetRealFunctionAddress("__sigsetjmp", (uptr*)&REAL(__sigsetjmp), 0, 0);
2454 TSAN_INTERCEPT(longjmp);
2455 TSAN_INTERCEPT(siglongjmp);
2457 TSAN_INTERCEPT(malloc);
2458 TSAN_INTERCEPT(__libc_memalign);
2459 TSAN_INTERCEPT(calloc);
2460 TSAN_INTERCEPT(realloc);
2461 TSAN_INTERCEPT(free);
2462 TSAN_INTERCEPT(cfree);
2463 TSAN_INTERCEPT(mmap);
2464 TSAN_MAYBE_INTERCEPT_MMAP64;
2465 TSAN_INTERCEPT(munmap);
2466 TSAN_MAYBE_INTERCEPT_MEMALIGN;
2467 TSAN_INTERCEPT(valloc);
2468 TSAN_MAYBE_INTERCEPT_PVALLOC;
2469 TSAN_INTERCEPT(posix_memalign);
2471 TSAN_INTERCEPT(strcpy); // NOLINT
2472 TSAN_INTERCEPT(strncpy);
2473 TSAN_INTERCEPT(strdup);
2475 TSAN_INTERCEPT(pthread_create);
2476 TSAN_INTERCEPT(pthread_join);
2477 TSAN_INTERCEPT(pthread_detach);
2479 TSAN_INTERCEPT_VER(pthread_cond_init, PTHREAD_ABI_BASE);
2480 TSAN_INTERCEPT_VER(pthread_cond_signal, PTHREAD_ABI_BASE);
2481 TSAN_INTERCEPT_VER(pthread_cond_broadcast, PTHREAD_ABI_BASE);
2482 TSAN_INTERCEPT_VER(pthread_cond_wait, PTHREAD_ABI_BASE);
2483 TSAN_INTERCEPT_VER(pthread_cond_timedwait, PTHREAD_ABI_BASE);
2484 TSAN_INTERCEPT_VER(pthread_cond_destroy, PTHREAD_ABI_BASE);
2486 TSAN_INTERCEPT(pthread_mutex_init);
2487 TSAN_INTERCEPT(pthread_mutex_destroy);
2488 TSAN_INTERCEPT(pthread_mutex_trylock);
2489 TSAN_INTERCEPT(pthread_mutex_timedlock);
2491 TSAN_INTERCEPT(pthread_spin_init);
2492 TSAN_INTERCEPT(pthread_spin_destroy);
2493 TSAN_INTERCEPT(pthread_spin_lock);
2494 TSAN_INTERCEPT(pthread_spin_trylock);
2495 TSAN_INTERCEPT(pthread_spin_unlock);
2497 TSAN_INTERCEPT(pthread_rwlock_init);
2498 TSAN_INTERCEPT(pthread_rwlock_destroy);
2499 TSAN_INTERCEPT(pthread_rwlock_rdlock);
2500 TSAN_INTERCEPT(pthread_rwlock_tryrdlock);
2501 TSAN_INTERCEPT(pthread_rwlock_timedrdlock);
2502 TSAN_INTERCEPT(pthread_rwlock_wrlock);
2503 TSAN_INTERCEPT(pthread_rwlock_trywrlock);
2504 TSAN_INTERCEPT(pthread_rwlock_timedwrlock);
2505 TSAN_INTERCEPT(pthread_rwlock_unlock);
2507 TSAN_INTERCEPT(pthread_barrier_init);
2508 TSAN_INTERCEPT(pthread_barrier_destroy);
2509 TSAN_INTERCEPT(pthread_barrier_wait);
2511 TSAN_INTERCEPT(pthread_once);
2513 TSAN_INTERCEPT(fstat);
2514 TSAN_MAYBE_INTERCEPT___FXSTAT;
2515 TSAN_MAYBE_INTERCEPT_FSTAT64;
2516 TSAN_MAYBE_INTERCEPT___FXSTAT64;
2517 TSAN_INTERCEPT(open);
2518 TSAN_MAYBE_INTERCEPT_OPEN64;
2519 TSAN_INTERCEPT(creat);
2520 TSAN_MAYBE_INTERCEPT_CREAT64;
2521 TSAN_INTERCEPT(dup);
2522 TSAN_INTERCEPT(dup2);
2523 TSAN_INTERCEPT(dup3);
2524 TSAN_MAYBE_INTERCEPT_EVENTFD;
2525 TSAN_MAYBE_INTERCEPT_SIGNALFD;
2526 TSAN_MAYBE_INTERCEPT_INOTIFY_INIT;
2527 TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1;
2528 TSAN_INTERCEPT(socket);
2529 TSAN_INTERCEPT(socketpair);
2530 TSAN_INTERCEPT(connect);
2531 TSAN_INTERCEPT(bind);
2532 TSAN_INTERCEPT(listen);
2533 TSAN_MAYBE_INTERCEPT_EPOLL;
2534 TSAN_INTERCEPT(close);
2535 TSAN_MAYBE_INTERCEPT___CLOSE;
2536 TSAN_MAYBE_INTERCEPT___RES_ICLOSE;
2537 TSAN_INTERCEPT(pipe);
2538 TSAN_INTERCEPT(pipe2);
2540 TSAN_INTERCEPT(unlink);
2541 TSAN_INTERCEPT(tmpfile);
2542 TSAN_MAYBE_INTERCEPT_TMPFILE64;
2543 TSAN_INTERCEPT(fread);
2544 TSAN_INTERCEPT(fwrite);
2545 TSAN_INTERCEPT(abort);
2546 TSAN_INTERCEPT(puts);
2547 TSAN_INTERCEPT(rmdir);
2548 TSAN_INTERCEPT(closedir);
2550 TSAN_INTERCEPT(sigaction);
2551 TSAN_INTERCEPT(signal);
2552 TSAN_INTERCEPT(sigsuspend);
2553 TSAN_INTERCEPT(sigblock);
2554 TSAN_INTERCEPT(sigsetmask);
2555 TSAN_INTERCEPT(pthread_sigmask);
2556 TSAN_INTERCEPT(raise);
2557 TSAN_INTERCEPT(kill);
2558 TSAN_INTERCEPT(pthread_kill);
2559 TSAN_INTERCEPT(sleep);
2560 TSAN_INTERCEPT(usleep);
2561 TSAN_INTERCEPT(nanosleep);
2562 TSAN_INTERCEPT(gettimeofday);
2563 TSAN_INTERCEPT(getaddrinfo);
2565 TSAN_INTERCEPT(fork);
2566 TSAN_INTERCEPT(vfork);
2567 #if !SANITIZER_ANDROID
2568 TSAN_INTERCEPT(dl_iterate_phdr);
2570 TSAN_INTERCEPT(on_exit);
2571 TSAN_INTERCEPT(__cxa_atexit);
2572 TSAN_INTERCEPT(_exit);
2574 #ifdef NEED_TLS_GET_ADDR
2575 TSAN_INTERCEPT(__tls_get_addr);
2578 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2579 // Need to setup it, because interceptors check that the function is resolved.
2580 // But atexit is emitted directly into the module, so can't be resolved.
2581 REAL(atexit) = (int(*)(void(*)()))unreachable;
2584 if (REAL(__cxa_atexit)(&finalize, 0, 0)) {
2585 Printf("ThreadSanitizer: failed to setup atexit callback\n");
2590 if (pthread_key_create(&g_thread_finalize_key, &thread_finalize)) {
2591 Printf("ThreadSanitizer: failed to create thread key\n");
2599 } // namespace __tsan
2601 // Invisible barrier for tests.
2602 // There were several unsuccessful iterations for this functionality:
2603 // 1. Initially it was implemented in user code using
2604 // REAL(pthread_barrier_wait). But pthread_barrier_wait is not supported on
2605 // MacOS. Futexes are linux-specific for this matter.
2606 // 2. Then we switched to atomics+usleep(10). But usleep produced parasitic
2607 // "as-if synchronized via sleep" messages in reports which failed some
2609 // 3. Then we switched to atomics+sched_yield. But this produced tons of tsan-
2610 // visible events, which lead to "failed to restore stack trace" failures.
2611 // Note that no_sanitize_thread attribute does not turn off atomic interception
2612 // so attaching it to the function defined in user code does not help.
2613 // That's why we now have what we have.
2614 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
2615 void __tsan_testonly_barrier_init(u64 *barrier, u32 count) {
2616 if (count >= (1 << 8)) {
2617 Printf("barrier_init: count is too large (%d)\n", count);
2620 // 8 lsb is thread count, the remaining are count of entered threads.
2624 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
2625 void __tsan_testonly_barrier_wait(u64 *barrier) {
2626 unsigned old = __atomic_fetch_add(barrier, 1 << 8, __ATOMIC_RELAXED);
2627 unsigned old_epoch = (old >> 8) / (old & 0xff);
2629 unsigned cur = __atomic_load_n(barrier, __ATOMIC_RELAXED);
2630 unsigned cur_epoch = (cur >> 8) / (cur & 0xff);
2631 if (cur_epoch != old_epoch)
2633 internal_sched_yield();