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_errno.h"
18 #include "sanitizer_common/sanitizer_libc.h"
19 #include "sanitizer_common/sanitizer_linux.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"
31 #include "tsan_mman.h"
35 using namespace __tsan; // NOLINT
37 #if SANITIZER_FREEBSD || SANITIZER_MAC
38 #define stdout __stdoutp
39 #define stderr __stderrp
47 const int kSigCount = 129;
49 const int kSigCount = 65;
53 // The size is determined by looking at sizeof of real siginfo_t on linux.
54 u64 opaque[128 / sizeof(u64)];
59 u64 opaque[768 / sizeof(u64) + 1];
63 // The size is determined by looking at sizeof of real ucontext_t on linux.
64 u64 opaque[936 / sizeof(u64) + 1];
68 #if defined(__x86_64__) || defined(__mips__) || SANITIZER_PPC64V1
69 #define PTHREAD_ABI_BASE "GLIBC_2.3.2"
70 #elif defined(__aarch64__) || SANITIZER_PPC64V2
71 #define PTHREAD_ABI_BASE "GLIBC_2.17"
74 extern "C" int pthread_attr_init(void *attr);
75 extern "C" int pthread_attr_destroy(void *attr);
76 DECLARE_REAL(int, pthread_attr_getdetachstate, void *, void *)
77 extern "C" int pthread_attr_setstacksize(void *attr, uptr stacksize);
78 extern "C" int pthread_key_create(unsigned *key, void (*destructor)(void* v));
79 extern "C" int pthread_setspecific(unsigned key, const void *v);
80 DECLARE_REAL(int, pthread_mutexattr_gettype, void *, void *)
81 DECLARE_REAL(int, fflush, __sanitizer_FILE *fp)
82 DECLARE_REAL_AND_INTERCEPTOR(void *, malloc, uptr size)
83 DECLARE_REAL_AND_INTERCEPTOR(void, free, void *ptr)
84 extern "C" void *pthread_self();
85 extern "C" void _exit(int status);
86 extern "C" int fileno_unlocked(void *stream);
87 extern "C" int dirfd(void *dirp);
88 #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID
89 extern "C" int mallopt(int param, int value);
91 extern __sanitizer_FILE *stdout, *stderr;
92 #if !SANITIZER_FREEBSD && !SANITIZER_MAC
93 const int PTHREAD_MUTEX_RECURSIVE = 1;
94 const int PTHREAD_MUTEX_RECURSIVE_NP = 1;
96 const int PTHREAD_MUTEX_RECURSIVE = 2;
97 const int PTHREAD_MUTEX_RECURSIVE_NP = 2;
99 #if !SANITIZER_FREEBSD && !SANITIZER_MAC
100 const int EPOLL_CTL_ADD = 1;
102 const int SIGILL = 4;
103 const int SIGABRT = 6;
104 const int SIGFPE = 8;
105 const int SIGSEGV = 11;
106 const int SIGPIPE = 13;
107 const int SIGTERM = 15;
108 #if defined(__mips__) || SANITIZER_FREEBSD || SANITIZER_MAC
109 const int SIGBUS = 10;
110 const int SIGSYS = 12;
112 const int SIGBUS = 7;
113 const int SIGSYS = 31;
115 void *const MAP_FAILED = (void*)-1;
117 const int PTHREAD_BARRIER_SERIAL_THREAD = -1;
119 const int MAP_FIXED = 0x10;
120 typedef long long_t; // NOLINT
122 // From /usr/include/unistd.h
123 # define F_ULOCK 0 /* Unlock a previously locked region. */
124 # define F_LOCK 1 /* Lock a region for exclusive use. */
125 # define F_TLOCK 2 /* Test and lock a region for exclusive use. */
126 # define F_TEST 3 /* Test a region for other processes locks. */
128 typedef void (*sighandler_t)(int sig);
129 typedef void (*sigactionhandler_t)(int sig, my_siginfo_t *siginfo, void *uctx);
131 #if SANITIZER_ANDROID
135 sighandler_t sa_handler;
136 sigactionhandler_t sa_sigaction;
138 __sanitizer_sigset_t sa_mask;
139 void (*sa_restorer)();
147 sighandler_t sa_handler;
148 sigactionhandler_t sa_sigaction;
150 #if SANITIZER_FREEBSD
152 __sanitizer_sigset_t sa_mask;
154 __sanitizer_sigset_t sa_mask;
157 __sanitizer_sigset_t sa_mask;
161 void (*sa_restorer)();
166 const sighandler_t SIG_DFL = (sighandler_t)0;
167 const sighandler_t SIG_IGN = (sighandler_t)1;
168 const sighandler_t SIG_ERR = (sighandler_t)-1;
169 #if SANITIZER_FREEBSD || SANITIZER_MAC
170 const int SA_SIGINFO = 0x40;
171 const int SIG_SETMASK = 3;
172 #elif defined(__mips__)
173 const int SA_SIGINFO = 8;
174 const int SIG_SETMASK = 3;
176 const int SA_SIGINFO = 4;
177 const int SIG_SETMASK = 2;
180 #define COMMON_INTERCEPTOR_NOTHING_IS_INITIALIZED \
181 (!cur_thread()->is_inited)
183 static sigaction_t sigactions[kSigCount];
189 my_siginfo_t siginfo;
193 struct ThreadSignalContext {
195 atomic_uintptr_t in_blocking_func;
196 atomic_uintptr_t have_pending_signals;
197 SignalDesc pending_signals[kSigCount];
198 // emptyset and oldset are too big for stack.
199 __sanitizer_sigset_t emptyset;
200 __sanitizer_sigset_t oldset;
203 // The object is 64-byte aligned, because we want hot data to be located in
204 // a single cache line if possible (it's accessed in every interceptor).
205 static ALIGNED(64) char libignore_placeholder[sizeof(LibIgnore)];
206 LibIgnore *libignore() {
207 return reinterpret_cast<LibIgnore*>(&libignore_placeholder[0]);
210 void InitializeLibIgnore() {
211 const SuppressionContext &supp = *Suppressions();
212 const uptr n = supp.SuppressionCount();
213 for (uptr i = 0; i < n; i++) {
214 const Suppression *s = supp.SuppressionAt(i);
215 if (0 == internal_strcmp(s->type, kSuppressionLib))
216 libignore()->AddIgnoredLibrary(s->templ);
218 if (flags()->ignore_noninstrumented_modules)
219 libignore()->IgnoreNoninstrumentedModules(true);
220 libignore()->OnLibraryLoaded(0);
223 } // namespace __tsan
225 static ThreadSignalContext *SigCtx(ThreadState *thr) {
226 ThreadSignalContext *ctx = (ThreadSignalContext*)thr->signal_ctx;
227 if (ctx == 0 && !thr->is_dead) {
228 ctx = (ThreadSignalContext*)MmapOrDie(sizeof(*ctx), "ThreadSignalContext");
229 MemoryResetRange(thr, (uptr)&SigCtx, (uptr)ctx, sizeof(*ctx));
230 thr->signal_ctx = ctx;
236 static unsigned g_thread_finalize_key;
239 ScopedInterceptor::ScopedInterceptor(ThreadState *thr, const char *fname,
241 : thr_(thr), pc_(pc), in_ignored_lib_(false), ignoring_(false) {
243 if (!thr_->is_inited) return;
244 if (!thr_->ignore_interceptors) FuncEntry(thr, pc);
245 DPrintf("#%d: intercept %s()\n", thr_->tid, fname);
247 !thr_->in_ignored_lib && (flags()->ignore_interceptors_accesses ||
248 libignore()->IsIgnored(pc, &in_ignored_lib_));
252 ScopedInterceptor::~ScopedInterceptor() {
253 if (!thr_->is_inited) return;
255 if (!thr_->ignore_interceptors) {
256 ProcessPendingSignals(thr_);
262 void ScopedInterceptor::EnableIgnores() {
264 ThreadIgnoreBegin(thr_, pc_, /*save_stack=*/false);
265 if (flags()->ignore_noninstrumented_modules) thr_->suppress_reports++;
266 if (in_ignored_lib_) {
267 DCHECK(!thr_->in_ignored_lib);
268 thr_->in_ignored_lib = true;
273 void ScopedInterceptor::DisableIgnores() {
275 ThreadIgnoreEnd(thr_, pc_);
276 if (flags()->ignore_noninstrumented_modules) thr_->suppress_reports--;
277 if (in_ignored_lib_) {
278 DCHECK(thr_->in_ignored_lib);
279 thr_->in_ignored_lib = false;
284 #define TSAN_INTERCEPT(func) INTERCEPT_FUNCTION(func)
285 #if SANITIZER_FREEBSD
286 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION(func)
288 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION_VER(func, ver)
291 #define READ_STRING_OF_LEN(thr, pc, s, len, n) \
292 MemoryAccessRange((thr), (pc), (uptr)(s), \
293 common_flags()->strict_string_checks ? (len) + 1 : (n), false)
295 #define READ_STRING(thr, pc, s, n) \
296 READ_STRING_OF_LEN((thr), (pc), (s), internal_strlen(s), (n))
298 #define BLOCK_REAL(name) (BlockingCall(thr), REAL(name))
300 struct BlockingCall {
301 explicit BlockingCall(ThreadState *thr)
305 atomic_store(&ctx->in_blocking_func, 1, memory_order_relaxed);
306 if (atomic_load(&ctx->have_pending_signals, memory_order_relaxed) == 0)
308 atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
309 ProcessPendingSignals(thr);
311 // When we are in a "blocking call", we process signals asynchronously
312 // (right when they arrive). In this context we do not expect to be
313 // executing any user/runtime code. The known interceptor sequence when
314 // this is not true is: pthread_join -> munmap(stack). It's fine
315 // to ignore munmap in this case -- we handle stack shadow separately.
316 thr->ignore_interceptors++;
320 thr->ignore_interceptors--;
321 atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
325 ThreadSignalContext *ctx;
328 TSAN_INTERCEPTOR(unsigned, sleep, unsigned sec) {
329 SCOPED_TSAN_INTERCEPTOR(sleep, sec);
330 unsigned res = BLOCK_REAL(sleep)(sec);
335 TSAN_INTERCEPTOR(int, usleep, long_t usec) {
336 SCOPED_TSAN_INTERCEPTOR(usleep, usec);
337 int res = BLOCK_REAL(usleep)(usec);
342 TSAN_INTERCEPTOR(int, nanosleep, void *req, void *rem) {
343 SCOPED_TSAN_INTERCEPTOR(nanosleep, req, rem);
344 int res = BLOCK_REAL(nanosleep)(req, rem);
349 // The sole reason tsan wraps atexit callbacks is to establish synchronization
350 // between callback setup and callback execution.
356 static void at_exit_wrapper(void *arg) {
357 ThreadState *thr = cur_thread();
359 Acquire(thr, pc, (uptr)arg);
360 AtExitCtx *ctx = (AtExitCtx*)arg;
361 ((void(*)(void *arg))ctx->f)(ctx->arg);
365 static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(),
366 void *arg, void *dso);
368 #if !SANITIZER_ANDROID
369 TSAN_INTERCEPTOR(int, atexit, void (*f)()) {
370 if (cur_thread()->in_symbolizer)
372 // We want to setup the atexit callback even if we are in ignored lib
374 SCOPED_INTERCEPTOR_RAW(atexit, f);
375 return setup_at_exit_wrapper(thr, pc, (void(*)())f, 0, 0);
379 TSAN_INTERCEPTOR(int, __cxa_atexit, void (*f)(void *a), void *arg, void *dso) {
380 if (cur_thread()->in_symbolizer)
382 SCOPED_TSAN_INTERCEPTOR(__cxa_atexit, f, arg, dso);
383 return setup_at_exit_wrapper(thr, pc, (void(*)())f, arg, dso);
386 static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(),
387 void *arg, void *dso) {
388 AtExitCtx *ctx = (AtExitCtx*)InternalAlloc(sizeof(AtExitCtx));
391 Release(thr, pc, (uptr)ctx);
392 // Memory allocation in __cxa_atexit will race with free during exit,
393 // because we do not see synchronization around atexit callback list.
394 ThreadIgnoreBegin(thr, pc);
395 int res = REAL(__cxa_atexit)(at_exit_wrapper, ctx, dso);
396 ThreadIgnoreEnd(thr, pc);
401 static void on_exit_wrapper(int status, void *arg) {
402 ThreadState *thr = cur_thread();
404 Acquire(thr, pc, (uptr)arg);
405 AtExitCtx *ctx = (AtExitCtx*)arg;
406 ((void(*)(int status, void *arg))ctx->f)(status, ctx->arg);
410 TSAN_INTERCEPTOR(int, on_exit, void(*f)(int, void*), void *arg) {
411 if (cur_thread()->in_symbolizer)
413 SCOPED_TSAN_INTERCEPTOR(on_exit, f, arg);
414 AtExitCtx *ctx = (AtExitCtx*)InternalAlloc(sizeof(AtExitCtx));
415 ctx->f = (void(*)())f;
417 Release(thr, pc, (uptr)ctx);
418 // Memory allocation in __cxa_atexit will race with free during exit,
419 // because we do not see synchronization around atexit callback list.
420 ThreadIgnoreBegin(thr, pc);
421 int res = REAL(on_exit)(on_exit_wrapper, ctx);
422 ThreadIgnoreEnd(thr, pc);
428 static void JmpBufGarbageCollect(ThreadState *thr, uptr sp) {
429 for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) {
430 JmpBuf *buf = &thr->jmp_bufs[i];
432 uptr sz = thr->jmp_bufs.Size();
433 internal_memcpy(buf, &thr->jmp_bufs[sz - 1], sizeof(*buf));
434 thr->jmp_bufs.PopBack();
440 static void SetJmp(ThreadState *thr, uptr sp, uptr mangled_sp) {
441 if (!thr->is_inited) // called from libc guts during bootstrap
444 JmpBufGarbageCollect(thr, sp);
446 JmpBuf *buf = thr->jmp_bufs.PushBack();
448 buf->mangled_sp = mangled_sp;
449 buf->shadow_stack_pos = thr->shadow_stack_pos;
450 ThreadSignalContext *sctx = SigCtx(thr);
451 buf->int_signal_send = sctx ? sctx->int_signal_send : 0;
452 buf->in_blocking_func = sctx ?
453 atomic_load(&sctx->in_blocking_func, memory_order_relaxed) :
455 buf->in_signal_handler = atomic_load(&thr->in_signal_handler,
456 memory_order_relaxed);
459 static void LongJmp(ThreadState *thr, uptr *env) {
461 uptr mangled_sp = env[0];
462 #elif SANITIZER_FREEBSD
463 uptr mangled_sp = env[2];
466 uptr mangled_sp = env[13];
468 uptr mangled_sp = env[2];
470 #elif defined(SANITIZER_LINUX)
472 uptr mangled_sp = env[13];
473 # elif defined(__mips64)
474 uptr mangled_sp = env[1];
476 uptr mangled_sp = env[6];
479 // Find the saved buf by mangled_sp.
480 for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) {
481 JmpBuf *buf = &thr->jmp_bufs[i];
482 if (buf->mangled_sp == mangled_sp) {
483 CHECK_GE(thr->shadow_stack_pos, buf->shadow_stack_pos);
485 while (thr->shadow_stack_pos > buf->shadow_stack_pos)
487 ThreadSignalContext *sctx = SigCtx(thr);
489 sctx->int_signal_send = buf->int_signal_send;
490 atomic_store(&sctx->in_blocking_func, buf->in_blocking_func,
491 memory_order_relaxed);
493 atomic_store(&thr->in_signal_handler, buf->in_signal_handler,
494 memory_order_relaxed);
495 JmpBufGarbageCollect(thr, buf->sp - 1); // do not collect buf->sp
499 Printf("ThreadSanitizer: can't find longjmp buf\n");
503 // FIXME: put everything below into a common extern "C" block?
504 extern "C" void __tsan_setjmp(uptr sp, uptr mangled_sp) {
505 SetJmp(cur_thread(), sp, mangled_sp);
509 TSAN_INTERCEPTOR(int, setjmp, void *env);
510 TSAN_INTERCEPTOR(int, _setjmp, void *env);
511 TSAN_INTERCEPTOR(int, sigsetjmp, void *env);
512 #else // SANITIZER_MAC
513 // Not called. Merely to satisfy TSAN_INTERCEPT().
514 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
515 int __interceptor_setjmp(void *env);
516 extern "C" int __interceptor_setjmp(void *env) {
521 // FIXME: any reason to have a separate declaration?
522 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
523 int __interceptor__setjmp(void *env);
524 extern "C" int __interceptor__setjmp(void *env) {
529 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
530 int __interceptor_sigsetjmp(void *env);
531 extern "C" int __interceptor_sigsetjmp(void *env) {
536 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
537 int __interceptor___sigsetjmp(void *env);
538 extern "C" int __interceptor___sigsetjmp(void *env) {
543 extern "C" int setjmp(void *env);
544 extern "C" int _setjmp(void *env);
545 extern "C" int sigsetjmp(void *env);
546 extern "C" int __sigsetjmp(void *env);
547 DEFINE_REAL(int, setjmp, void *env)
548 DEFINE_REAL(int, _setjmp, void *env)
549 DEFINE_REAL(int, sigsetjmp, void *env)
550 DEFINE_REAL(int, __sigsetjmp, void *env)
551 #endif // SANITIZER_MAC
553 TSAN_INTERCEPTOR(void, longjmp, uptr *env, int val) {
554 // Note: if we call REAL(longjmp) in the context of ScopedInterceptor,
555 // bad things will happen. We will jump over ScopedInterceptor dtor and can
556 // leave thr->in_ignored_lib set.
558 SCOPED_INTERCEPTOR_RAW(longjmp, env, val);
560 LongJmp(cur_thread(), env);
561 REAL(longjmp)(env, val);
564 TSAN_INTERCEPTOR(void, siglongjmp, uptr *env, int val) {
566 SCOPED_INTERCEPTOR_RAW(siglongjmp, env, val);
568 LongJmp(cur_thread(), env);
569 REAL(siglongjmp)(env, val);
573 TSAN_INTERCEPTOR(void*, malloc, uptr size) {
574 if (cur_thread()->in_symbolizer)
575 return InternalAlloc(size);
578 SCOPED_INTERCEPTOR_RAW(malloc, size);
579 p = user_alloc(thr, pc, size);
581 invoke_malloc_hook(p, size);
585 TSAN_INTERCEPTOR(void*, __libc_memalign, uptr align, uptr sz) {
586 SCOPED_TSAN_INTERCEPTOR(__libc_memalign, align, sz);
587 return user_alloc(thr, pc, sz, align);
590 TSAN_INTERCEPTOR(void*, calloc, uptr size, uptr n) {
591 if (cur_thread()->in_symbolizer)
592 return InternalCalloc(size, n);
595 SCOPED_INTERCEPTOR_RAW(calloc, size, n);
596 p = user_calloc(thr, pc, size, n);
598 invoke_malloc_hook(p, n * size);
602 TSAN_INTERCEPTOR(void*, realloc, void *p, uptr size) {
603 if (cur_thread()->in_symbolizer)
604 return InternalRealloc(p, size);
608 SCOPED_INTERCEPTOR_RAW(realloc, p, size);
609 p = user_realloc(thr, pc, p, size);
611 invoke_malloc_hook(p, size);
615 TSAN_INTERCEPTOR(void, free, void *p) {
618 if (cur_thread()->in_symbolizer)
619 return InternalFree(p);
621 SCOPED_INTERCEPTOR_RAW(free, p);
622 user_free(thr, pc, p);
625 TSAN_INTERCEPTOR(void, cfree, void *p) {
628 if (cur_thread()->in_symbolizer)
629 return InternalFree(p);
631 SCOPED_INTERCEPTOR_RAW(cfree, p);
632 user_free(thr, pc, p);
635 TSAN_INTERCEPTOR(uptr, malloc_usable_size, void *p) {
636 SCOPED_INTERCEPTOR_RAW(malloc_usable_size, p);
637 return user_alloc_usable_size(p);
641 TSAN_INTERCEPTOR(char*, strcpy, char *dst, const char *src) { // NOLINT
642 SCOPED_TSAN_INTERCEPTOR(strcpy, dst, src); // NOLINT
643 uptr srclen = internal_strlen(src);
644 MemoryAccessRange(thr, pc, (uptr)dst, srclen + 1, true);
645 MemoryAccessRange(thr, pc, (uptr)src, srclen + 1, false);
646 return REAL(strcpy)(dst, src); // NOLINT
649 TSAN_INTERCEPTOR(char*, strncpy, char *dst, char *src, uptr n) {
650 SCOPED_TSAN_INTERCEPTOR(strncpy, dst, src, n);
651 uptr srclen = internal_strnlen(src, n);
652 MemoryAccessRange(thr, pc, (uptr)dst, n, true);
653 MemoryAccessRange(thr, pc, (uptr)src, min(srclen + 1, n), false);
654 return REAL(strncpy)(dst, src, n);
657 TSAN_INTERCEPTOR(char*, strdup, const char *str) {
658 SCOPED_TSAN_INTERCEPTOR(strdup, str);
659 // strdup will call malloc, so no instrumentation is required here.
660 return REAL(strdup)(str);
663 static bool fix_mmap_addr(void **addr, long_t sz, int flags) {
665 if (!IsAppMem((uptr)*addr) || !IsAppMem((uptr)*addr + sz - 1)) {
666 if (flags & MAP_FIXED) {
667 errno = errno_EINVAL;
677 TSAN_INTERCEPTOR(void *, mmap, void *addr, SIZE_T sz, int prot, int flags,
679 SCOPED_TSAN_INTERCEPTOR(mmap, addr, sz, prot, flags, fd, off);
680 if (!fix_mmap_addr(&addr, sz, flags))
682 void *res = REAL(mmap)(addr, sz, prot, flags, fd, off);
683 if (res != MAP_FAILED) {
685 FdAccess(thr, pc, fd);
687 if (thr->ignore_reads_and_writes == 0)
688 MemoryRangeImitateWrite(thr, pc, (uptr)res, sz);
690 MemoryResetRange(thr, pc, (uptr)res, sz);
696 TSAN_INTERCEPTOR(void *, mmap64, void *addr, SIZE_T sz, int prot, int flags,
697 int fd, OFF64_T off) {
698 SCOPED_TSAN_INTERCEPTOR(mmap64, addr, sz, prot, flags, fd, off);
699 if (!fix_mmap_addr(&addr, sz, flags))
701 void *res = REAL(mmap64)(addr, sz, prot, flags, fd, off);
702 if (res != MAP_FAILED) {
704 FdAccess(thr, pc, fd);
706 if (thr->ignore_reads_and_writes == 0)
707 MemoryRangeImitateWrite(thr, pc, (uptr)res, sz);
709 MemoryResetRange(thr, pc, (uptr)res, sz);
713 #define TSAN_MAYBE_INTERCEPT_MMAP64 TSAN_INTERCEPT(mmap64)
715 #define TSAN_MAYBE_INTERCEPT_MMAP64
718 TSAN_INTERCEPTOR(int, munmap, void *addr, long_t sz) {
719 SCOPED_TSAN_INTERCEPTOR(munmap, addr, sz);
721 // If sz == 0, munmap will return EINVAL and don't unmap any memory.
722 DontNeedShadowFor((uptr)addr, sz);
723 ScopedGlobalProcessor sgp;
724 ctx->metamap.ResetRange(thr->proc(), (uptr)addr, (uptr)sz);
726 int res = REAL(munmap)(addr, sz);
731 TSAN_INTERCEPTOR(void*, memalign, uptr align, uptr sz) {
732 SCOPED_INTERCEPTOR_RAW(memalign, align, sz);
733 return user_alloc(thr, pc, sz, align);
735 #define TSAN_MAYBE_INTERCEPT_MEMALIGN TSAN_INTERCEPT(memalign)
737 #define TSAN_MAYBE_INTERCEPT_MEMALIGN
741 TSAN_INTERCEPTOR(void*, aligned_alloc, uptr align, uptr sz) {
742 SCOPED_INTERCEPTOR_RAW(memalign, align, sz);
743 return user_alloc(thr, pc, sz, align);
746 TSAN_INTERCEPTOR(void*, valloc, uptr sz) {
747 SCOPED_INTERCEPTOR_RAW(valloc, sz);
748 return user_alloc(thr, pc, sz, GetPageSizeCached());
753 TSAN_INTERCEPTOR(void*, pvalloc, uptr sz) {
754 SCOPED_INTERCEPTOR_RAW(pvalloc, sz);
755 sz = RoundUp(sz, GetPageSizeCached());
756 return user_alloc(thr, pc, sz, GetPageSizeCached());
758 #define TSAN_MAYBE_INTERCEPT_PVALLOC TSAN_INTERCEPT(pvalloc)
760 #define TSAN_MAYBE_INTERCEPT_PVALLOC
764 TSAN_INTERCEPTOR(int, posix_memalign, void **memptr, uptr align, uptr sz) {
765 SCOPED_INTERCEPTOR_RAW(posix_memalign, memptr, align, sz);
766 *memptr = user_alloc(thr, pc, sz, align);
771 // __cxa_guard_acquire and friends need to be intercepted in a special way -
772 // regular interceptors will break statically-linked libstdc++. Linux
773 // interceptors are especially defined as weak functions (so that they don't
774 // cause link errors when user defines them as well). So they silently
775 // auto-disable themselves when such symbol is already present in the binary. If
776 // we link libstdc++ statically, it will bring own __cxa_guard_acquire which
777 // will silently replace our interceptor. That's why on Linux we simply export
778 // these interceptors with INTERFACE_ATTRIBUTE.
779 // On OS X, we don't support statically linking, so we just use a regular
782 #define STDCXX_INTERCEPTOR TSAN_INTERCEPTOR
784 #define STDCXX_INTERCEPTOR(rettype, name, ...) \
785 extern "C" rettype INTERFACE_ATTRIBUTE name(__VA_ARGS__)
788 // Used in thread-safe function static initialization.
789 STDCXX_INTERCEPTOR(int, __cxa_guard_acquire, atomic_uint32_t *g) {
790 SCOPED_INTERCEPTOR_RAW(__cxa_guard_acquire, g);
792 u32 cmp = atomic_load(g, memory_order_acquire);
794 if (atomic_compare_exchange_strong(g, &cmp, 1<<16, memory_order_relaxed))
796 } else if (cmp == 1) {
797 Acquire(thr, pc, (uptr)g);
800 internal_sched_yield();
805 STDCXX_INTERCEPTOR(void, __cxa_guard_release, atomic_uint32_t *g) {
806 SCOPED_INTERCEPTOR_RAW(__cxa_guard_release, g);
807 Release(thr, pc, (uptr)g);
808 atomic_store(g, 1, memory_order_release);
811 STDCXX_INTERCEPTOR(void, __cxa_guard_abort, atomic_uint32_t *g) {
812 SCOPED_INTERCEPTOR_RAW(__cxa_guard_abort, g);
813 atomic_store(g, 0, memory_order_relaxed);
817 void DestroyThreadState() {
818 ThreadState *thr = cur_thread();
819 Processor *proc = thr->proc();
821 ProcUnwire(proc, thr);
823 ThreadSignalContext *sctx = thr->signal_ctx;
826 UnmapOrDie(sctx, sizeof(*sctx));
829 cur_thread_finalize();
831 } // namespace __tsan
834 static void thread_finalize(void *v) {
837 if (pthread_setspecific(g_thread_finalize_key, (void*)(iter - 1))) {
838 Printf("ThreadSanitizer: failed to set thread key\n");
843 DestroyThreadState();
849 void* (*callback)(void *arg);
851 atomic_uintptr_t tid;
854 extern "C" void *__tsan_thread_start_func(void *arg) {
855 ThreadParam *p = (ThreadParam*)arg;
856 void* (*callback)(void *arg) = p->callback;
857 void *param = p->param;
860 ThreadState *thr = cur_thread();
861 // Thread-local state is not initialized yet.
862 ScopedIgnoreInterceptors ignore;
864 ThreadIgnoreBegin(thr, 0);
865 if (pthread_setspecific(g_thread_finalize_key,
866 (void *)GetPthreadDestructorIterations())) {
867 Printf("ThreadSanitizer: failed to set thread key\n");
870 ThreadIgnoreEnd(thr, 0);
872 while ((tid = atomic_load(&p->tid, memory_order_acquire)) == 0)
873 internal_sched_yield();
874 Processor *proc = ProcCreate();
876 ThreadStart(thr, tid, GetTid(), /*workerthread*/ false);
877 atomic_store(&p->tid, 0, memory_order_release);
879 void *res = callback(param);
880 // Prevent the callback from being tail called,
881 // it mixes up stack traces.
882 volatile int foo = 42;
887 TSAN_INTERCEPTOR(int, pthread_create,
888 void *th, void *attr, void *(*callback)(void*), void * param) {
889 SCOPED_INTERCEPTOR_RAW(pthread_create, th, attr, callback, param);
890 if (ctx->after_multithreaded_fork) {
891 if (flags()->die_after_fork) {
892 Report("ThreadSanitizer: starting new threads after multi-threaded "
893 "fork is not supported. Dying (set die_after_fork=0 to override)\n");
896 VPrintf(1, "ThreadSanitizer: starting new threads after multi-threaded "
897 "fork is not supported (pid %d). Continuing because of "
898 "die_after_fork=0, but you are on your own\n", internal_getpid());
901 __sanitizer_pthread_attr_t myattr;
903 pthread_attr_init(&myattr);
907 REAL(pthread_attr_getdetachstate)(attr, &detached);
908 AdjustStackSize(attr);
911 p.callback = callback;
913 atomic_store(&p.tid, 0, memory_order_relaxed);
916 // Otherwise we see false positives in pthread stack manipulation.
917 ScopedIgnoreInterceptors ignore;
918 ThreadIgnoreBegin(thr, pc);
919 res = REAL(pthread_create)(th, attr, __tsan_thread_start_func, &p);
920 ThreadIgnoreEnd(thr, pc);
923 int tid = ThreadCreate(thr, pc, *(uptr*)th, IsStateDetached(detached));
925 // Synchronization on p.tid serves two purposes:
926 // 1. ThreadCreate must finish before the new thread starts.
927 // Otherwise the new thread can call pthread_detach, but the pthread_t
928 // identifier is not yet registered in ThreadRegistry by ThreadCreate.
929 // 2. ThreadStart must finish before this thread continues.
930 // Otherwise, this thread can call pthread_detach and reset thr->sync
931 // before the new thread got a chance to acquire from it in ThreadStart.
932 atomic_store(&p.tid, tid, memory_order_release);
933 while (atomic_load(&p.tid, memory_order_acquire) != 0)
934 internal_sched_yield();
937 pthread_attr_destroy(&myattr);
941 TSAN_INTERCEPTOR(int, pthread_join, void *th, void **ret) {
942 SCOPED_INTERCEPTOR_RAW(pthread_join, th, ret);
943 int tid = ThreadTid(thr, pc, (uptr)th);
944 ThreadIgnoreBegin(thr, pc);
945 int res = BLOCK_REAL(pthread_join)(th, ret);
946 ThreadIgnoreEnd(thr, pc);
948 ThreadJoin(thr, pc, tid);
953 DEFINE_REAL_PTHREAD_FUNCTIONS
955 TSAN_INTERCEPTOR(int, pthread_detach, void *th) {
956 SCOPED_TSAN_INTERCEPTOR(pthread_detach, th);
957 int tid = ThreadTid(thr, pc, (uptr)th);
958 int res = REAL(pthread_detach)(th);
960 ThreadDetach(thr, pc, tid);
966 // NPTL implementation of pthread_cond has 2 versions (2.2.5 and 2.3.2).
967 // pthread_cond_t has different size in the different versions.
968 // If call new REAL functions for old pthread_cond_t, they will corrupt memory
969 // after pthread_cond_t (old cond is smaller).
970 // If we call old REAL functions for new pthread_cond_t, we will lose some
971 // functionality (e.g. old functions do not support waiting against
973 // Proper handling would require to have 2 versions of interceptors as well.
974 // But this is messy, in particular requires linker scripts when sanitizer
975 // runtime is linked into a shared library.
976 // Instead we assume we don't have dynamic libraries built against old
977 // pthread (2.2.5 is dated by 2002). And provide legacy_pthread_cond flag
978 // that allows to work with old libraries (but this mode does not support
979 // some features, e.g. pthread_condattr_getpshared).
980 static void *init_cond(void *c, bool force = false) {
981 // sizeof(pthread_cond_t) >= sizeof(uptr) in both versions.
982 // So we allocate additional memory on the side large enough to hold
983 // any pthread_cond_t object. Always call new REAL functions, but pass
984 // the aux object to them.
985 // Note: the code assumes that PTHREAD_COND_INITIALIZER initializes
986 // first word of pthread_cond_t to zero.
987 // It's all relevant only for linux.
988 if (!common_flags()->legacy_pthread_cond)
990 atomic_uintptr_t *p = (atomic_uintptr_t*)c;
991 uptr cond = atomic_load(p, memory_order_acquire);
992 if (!force && cond != 0)
994 void *newcond = WRAP(malloc)(pthread_cond_t_sz);
995 internal_memset(newcond, 0, pthread_cond_t_sz);
996 if (atomic_compare_exchange_strong(p, &cond, (uptr)newcond,
997 memory_order_acq_rel))
1003 struct CondMutexUnlockCtx {
1004 ScopedInterceptor *si;
1010 static void cond_mutex_unlock(CondMutexUnlockCtx *arg) {
1011 // pthread_cond_wait interceptor has enabled async signal delivery
1012 // (see BlockingCall below). Disable async signals since we are running
1013 // tsan code. Also ScopedInterceptor and BlockingCall destructors won't run
1014 // since the thread is cancelled, so we have to manually execute them
1015 // (the thread still can run some user code due to pthread_cleanup_push).
1016 ThreadSignalContext *ctx = SigCtx(arg->thr);
1017 CHECK_EQ(atomic_load(&ctx->in_blocking_func, memory_order_relaxed), 1);
1018 atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
1019 MutexPostLock(arg->thr, arg->pc, (uptr)arg->m, MutexFlagDoPreLockOnPostLock);
1020 // Undo BlockingCall ctor effects.
1021 arg->thr->ignore_interceptors--;
1022 arg->si->~ScopedInterceptor();
1025 INTERCEPTOR(int, pthread_cond_init, void *c, void *a) {
1026 void *cond = init_cond(c, true);
1027 SCOPED_TSAN_INTERCEPTOR(pthread_cond_init, cond, a);
1028 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true);
1029 return REAL(pthread_cond_init)(cond, a);
1032 static int cond_wait(ThreadState *thr, uptr pc, ScopedInterceptor *si,
1033 int (*fn)(void *c, void *m, void *abstime), void *c,
1035 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1036 MutexUnlock(thr, pc, (uptr)m);
1037 CondMutexUnlockCtx arg = {si, thr, pc, m};
1039 // This ensures that we handle mutex lock even in case of pthread_cancel.
1040 // See test/tsan/cond_cancel.cc.
1042 // Enable signal delivery while the thread is blocked.
1043 BlockingCall bc(thr);
1044 res = call_pthread_cancel_with_cleanup(
1045 fn, c, m, t, (void (*)(void *arg))cond_mutex_unlock, &arg);
1047 if (res == errno_EOWNERDEAD) MutexRepair(thr, pc, (uptr)m);
1048 MutexPostLock(thr, pc, (uptr)m, MutexFlagDoPreLockOnPostLock);
1052 INTERCEPTOR(int, pthread_cond_wait, void *c, void *m) {
1053 void *cond = init_cond(c);
1054 SCOPED_TSAN_INTERCEPTOR(pthread_cond_wait, cond, m);
1055 return cond_wait(thr, pc, &si, (int (*)(void *c, void *m, void *abstime))REAL(
1060 INTERCEPTOR(int, pthread_cond_timedwait, void *c, void *m, void *abstime) {
1061 void *cond = init_cond(c);
1062 SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait, cond, m, abstime);
1063 return cond_wait(thr, pc, &si, REAL(pthread_cond_timedwait), cond, m,
1068 INTERCEPTOR(int, pthread_cond_timedwait_relative_np, void *c, void *m,
1070 void *cond = init_cond(c);
1071 SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait_relative_np, cond, m, reltime);
1072 return cond_wait(thr, pc, &si, REAL(pthread_cond_timedwait_relative_np), cond,
1077 INTERCEPTOR(int, pthread_cond_signal, void *c) {
1078 void *cond = init_cond(c);
1079 SCOPED_TSAN_INTERCEPTOR(pthread_cond_signal, cond);
1080 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1081 return REAL(pthread_cond_signal)(cond);
1084 INTERCEPTOR(int, pthread_cond_broadcast, void *c) {
1085 void *cond = init_cond(c);
1086 SCOPED_TSAN_INTERCEPTOR(pthread_cond_broadcast, cond);
1087 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1088 return REAL(pthread_cond_broadcast)(cond);
1091 INTERCEPTOR(int, pthread_cond_destroy, void *c) {
1092 void *cond = init_cond(c);
1093 SCOPED_TSAN_INTERCEPTOR(pthread_cond_destroy, cond);
1094 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true);
1095 int res = REAL(pthread_cond_destroy)(cond);
1096 if (common_flags()->legacy_pthread_cond) {
1097 // Free our aux cond and zero the pointer to not leave dangling pointers.
1099 atomic_store((atomic_uintptr_t*)c, 0, memory_order_relaxed);
1104 TSAN_INTERCEPTOR(int, pthread_mutex_init, void *m, void *a) {
1105 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_init, m, a);
1106 int res = REAL(pthread_mutex_init)(m, a);
1111 if (REAL(pthread_mutexattr_gettype)(a, &type) == 0)
1112 if (type == PTHREAD_MUTEX_RECURSIVE ||
1113 type == PTHREAD_MUTEX_RECURSIVE_NP)
1114 flagz |= MutexFlagWriteReentrant;
1116 MutexCreate(thr, pc, (uptr)m, flagz);
1121 TSAN_INTERCEPTOR(int, pthread_mutex_destroy, void *m) {
1122 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_destroy, m);
1123 int res = REAL(pthread_mutex_destroy)(m);
1124 if (res == 0 || res == errno_EBUSY) {
1125 MutexDestroy(thr, pc, (uptr)m);
1130 TSAN_INTERCEPTOR(int, pthread_mutex_trylock, void *m) {
1131 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_trylock, m);
1132 int res = REAL(pthread_mutex_trylock)(m);
1133 if (res == errno_EOWNERDEAD)
1134 MutexRepair(thr, pc, (uptr)m);
1135 if (res == 0 || res == errno_EOWNERDEAD)
1136 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1141 TSAN_INTERCEPTOR(int, pthread_mutex_timedlock, void *m, void *abstime) {
1142 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_timedlock, m, abstime);
1143 int res = REAL(pthread_mutex_timedlock)(m, abstime);
1145 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1152 TSAN_INTERCEPTOR(int, pthread_spin_init, void *m, int pshared) {
1153 SCOPED_TSAN_INTERCEPTOR(pthread_spin_init, m, pshared);
1154 int res = REAL(pthread_spin_init)(m, pshared);
1156 MutexCreate(thr, pc, (uptr)m);
1161 TSAN_INTERCEPTOR(int, pthread_spin_destroy, void *m) {
1162 SCOPED_TSAN_INTERCEPTOR(pthread_spin_destroy, m);
1163 int res = REAL(pthread_spin_destroy)(m);
1165 MutexDestroy(thr, pc, (uptr)m);
1170 TSAN_INTERCEPTOR(int, pthread_spin_lock, void *m) {
1171 SCOPED_TSAN_INTERCEPTOR(pthread_spin_lock, m);
1172 MutexPreLock(thr, pc, (uptr)m);
1173 int res = REAL(pthread_spin_lock)(m);
1175 MutexPostLock(thr, pc, (uptr)m);
1180 TSAN_INTERCEPTOR(int, pthread_spin_trylock, void *m) {
1181 SCOPED_TSAN_INTERCEPTOR(pthread_spin_trylock, m);
1182 int res = REAL(pthread_spin_trylock)(m);
1184 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1189 TSAN_INTERCEPTOR(int, pthread_spin_unlock, void *m) {
1190 SCOPED_TSAN_INTERCEPTOR(pthread_spin_unlock, m);
1191 MutexUnlock(thr, pc, (uptr)m);
1192 int res = REAL(pthread_spin_unlock)(m);
1197 TSAN_INTERCEPTOR(int, pthread_rwlock_init, void *m, void *a) {
1198 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_init, m, a);
1199 int res = REAL(pthread_rwlock_init)(m, a);
1201 MutexCreate(thr, pc, (uptr)m);
1206 TSAN_INTERCEPTOR(int, pthread_rwlock_destroy, void *m) {
1207 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_destroy, m);
1208 int res = REAL(pthread_rwlock_destroy)(m);
1210 MutexDestroy(thr, pc, (uptr)m);
1215 TSAN_INTERCEPTOR(int, pthread_rwlock_rdlock, void *m) {
1216 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_rdlock, m);
1217 MutexPreReadLock(thr, pc, (uptr)m);
1218 int res = REAL(pthread_rwlock_rdlock)(m);
1220 MutexPostReadLock(thr, pc, (uptr)m);
1225 TSAN_INTERCEPTOR(int, pthread_rwlock_tryrdlock, void *m) {
1226 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_tryrdlock, m);
1227 int res = REAL(pthread_rwlock_tryrdlock)(m);
1229 MutexPostReadLock(thr, pc, (uptr)m, MutexFlagTryLock);
1235 TSAN_INTERCEPTOR(int, pthread_rwlock_timedrdlock, void *m, void *abstime) {
1236 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedrdlock, m, abstime);
1237 int res = REAL(pthread_rwlock_timedrdlock)(m, abstime);
1239 MutexPostReadLock(thr, pc, (uptr)m);
1245 TSAN_INTERCEPTOR(int, pthread_rwlock_wrlock, void *m) {
1246 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_wrlock, m);
1247 MutexPreLock(thr, pc, (uptr)m);
1248 int res = REAL(pthread_rwlock_wrlock)(m);
1250 MutexPostLock(thr, pc, (uptr)m);
1255 TSAN_INTERCEPTOR(int, pthread_rwlock_trywrlock, void *m) {
1256 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_trywrlock, m);
1257 int res = REAL(pthread_rwlock_trywrlock)(m);
1259 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1265 TSAN_INTERCEPTOR(int, pthread_rwlock_timedwrlock, void *m, void *abstime) {
1266 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedwrlock, m, abstime);
1267 int res = REAL(pthread_rwlock_timedwrlock)(m, abstime);
1269 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1275 TSAN_INTERCEPTOR(int, pthread_rwlock_unlock, void *m) {
1276 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_unlock, m);
1277 MutexReadOrWriteUnlock(thr, pc, (uptr)m);
1278 int res = REAL(pthread_rwlock_unlock)(m);
1283 TSAN_INTERCEPTOR(int, pthread_barrier_init, void *b, void *a, unsigned count) {
1284 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_init, b, a, count);
1285 MemoryWrite(thr, pc, (uptr)b, kSizeLog1);
1286 int res = REAL(pthread_barrier_init)(b, a, count);
1290 TSAN_INTERCEPTOR(int, pthread_barrier_destroy, void *b) {
1291 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_destroy, b);
1292 MemoryWrite(thr, pc, (uptr)b, kSizeLog1);
1293 int res = REAL(pthread_barrier_destroy)(b);
1297 TSAN_INTERCEPTOR(int, pthread_barrier_wait, void *b) {
1298 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_wait, b);
1299 Release(thr, pc, (uptr)b);
1300 MemoryRead(thr, pc, (uptr)b, kSizeLog1);
1301 int res = REAL(pthread_barrier_wait)(b);
1302 MemoryRead(thr, pc, (uptr)b, kSizeLog1);
1303 if (res == 0 || res == PTHREAD_BARRIER_SERIAL_THREAD) {
1304 Acquire(thr, pc, (uptr)b);
1310 TSAN_INTERCEPTOR(int, pthread_once, void *o, void (*f)()) {
1311 SCOPED_INTERCEPTOR_RAW(pthread_once, o, f);
1312 if (o == 0 || f == 0)
1313 return errno_EINVAL;
1316 a = static_cast<atomic_uint32_t*>(o);
1317 else // On OS X, pthread_once_t has a header with a long-sized signature.
1318 a = static_cast<atomic_uint32_t*>((void *)((char *)o + sizeof(long_t)));
1319 u32 v = atomic_load(a, memory_order_acquire);
1320 if (v == 0 && atomic_compare_exchange_strong(a, &v, 1,
1321 memory_order_relaxed)) {
1323 if (!thr->in_ignored_lib)
1324 Release(thr, pc, (uptr)o);
1325 atomic_store(a, 2, memory_order_release);
1328 internal_sched_yield();
1329 v = atomic_load(a, memory_order_acquire);
1331 if (!thr->in_ignored_lib)
1332 Acquire(thr, pc, (uptr)o);
1337 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1338 TSAN_INTERCEPTOR(int, __fxstat, int version, int fd, void *buf) {
1339 SCOPED_TSAN_INTERCEPTOR(__fxstat, version, fd, buf);
1341 FdAccess(thr, pc, fd);
1342 return REAL(__fxstat)(version, fd, buf);
1344 #define TSAN_MAYBE_INTERCEPT___FXSTAT TSAN_INTERCEPT(__fxstat)
1346 #define TSAN_MAYBE_INTERCEPT___FXSTAT
1349 TSAN_INTERCEPTOR(int, fstat, int fd, void *buf) {
1350 #if SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_ANDROID
1351 SCOPED_TSAN_INTERCEPTOR(fstat, fd, buf);
1353 FdAccess(thr, pc, fd);
1354 return REAL(fstat)(fd, buf);
1356 SCOPED_TSAN_INTERCEPTOR(__fxstat, 0, fd, buf);
1358 FdAccess(thr, pc, fd);
1359 return REAL(__fxstat)(0, fd, buf);
1363 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1364 TSAN_INTERCEPTOR(int, __fxstat64, int version, int fd, void *buf) {
1365 SCOPED_TSAN_INTERCEPTOR(__fxstat64, version, fd, buf);
1367 FdAccess(thr, pc, fd);
1368 return REAL(__fxstat64)(version, fd, buf);
1370 #define TSAN_MAYBE_INTERCEPT___FXSTAT64 TSAN_INTERCEPT(__fxstat64)
1372 #define TSAN_MAYBE_INTERCEPT___FXSTAT64
1375 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1376 TSAN_INTERCEPTOR(int, fstat64, int fd, void *buf) {
1377 SCOPED_TSAN_INTERCEPTOR(__fxstat64, 0, fd, buf);
1379 FdAccess(thr, pc, fd);
1380 return REAL(__fxstat64)(0, fd, buf);
1382 #define TSAN_MAYBE_INTERCEPT_FSTAT64 TSAN_INTERCEPT(fstat64)
1384 #define TSAN_MAYBE_INTERCEPT_FSTAT64
1387 TSAN_INTERCEPTOR(int, open, const char *name, int flags, int mode) {
1388 SCOPED_TSAN_INTERCEPTOR(open, name, flags, mode);
1389 READ_STRING(thr, pc, name, 0);
1390 int fd = REAL(open)(name, flags, mode);
1392 FdFileCreate(thr, pc, fd);
1397 TSAN_INTERCEPTOR(int, open64, const char *name, int flags, int mode) {
1398 SCOPED_TSAN_INTERCEPTOR(open64, name, flags, mode);
1399 READ_STRING(thr, pc, name, 0);
1400 int fd = REAL(open64)(name, flags, mode);
1402 FdFileCreate(thr, pc, fd);
1405 #define TSAN_MAYBE_INTERCEPT_OPEN64 TSAN_INTERCEPT(open64)
1407 #define TSAN_MAYBE_INTERCEPT_OPEN64
1410 TSAN_INTERCEPTOR(int, creat, const char *name, int mode) {
1411 SCOPED_TSAN_INTERCEPTOR(creat, name, mode);
1412 READ_STRING(thr, pc, name, 0);
1413 int fd = REAL(creat)(name, mode);
1415 FdFileCreate(thr, pc, fd);
1420 TSAN_INTERCEPTOR(int, creat64, const char *name, int mode) {
1421 SCOPED_TSAN_INTERCEPTOR(creat64, name, mode);
1422 READ_STRING(thr, pc, name, 0);
1423 int fd = REAL(creat64)(name, mode);
1425 FdFileCreate(thr, pc, fd);
1428 #define TSAN_MAYBE_INTERCEPT_CREAT64 TSAN_INTERCEPT(creat64)
1430 #define TSAN_MAYBE_INTERCEPT_CREAT64
1433 TSAN_INTERCEPTOR(int, dup, int oldfd) {
1434 SCOPED_TSAN_INTERCEPTOR(dup, oldfd);
1435 int newfd = REAL(dup)(oldfd);
1436 if (oldfd >= 0 && newfd >= 0 && newfd != oldfd)
1437 FdDup(thr, pc, oldfd, newfd, true);
1441 TSAN_INTERCEPTOR(int, dup2, int oldfd, int newfd) {
1442 SCOPED_TSAN_INTERCEPTOR(dup2, oldfd, newfd);
1443 int newfd2 = REAL(dup2)(oldfd, newfd);
1444 if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd)
1445 FdDup(thr, pc, oldfd, newfd2, false);
1450 TSAN_INTERCEPTOR(int, dup3, int oldfd, int newfd, int flags) {
1451 SCOPED_TSAN_INTERCEPTOR(dup3, oldfd, newfd, flags);
1452 int newfd2 = REAL(dup3)(oldfd, newfd, flags);
1453 if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd)
1454 FdDup(thr, pc, oldfd, newfd2, false);
1460 TSAN_INTERCEPTOR(int, eventfd, unsigned initval, int flags) {
1461 SCOPED_TSAN_INTERCEPTOR(eventfd, initval, flags);
1462 int fd = REAL(eventfd)(initval, flags);
1464 FdEventCreate(thr, pc, fd);
1467 #define TSAN_MAYBE_INTERCEPT_EVENTFD TSAN_INTERCEPT(eventfd)
1469 #define TSAN_MAYBE_INTERCEPT_EVENTFD
1473 TSAN_INTERCEPTOR(int, signalfd, int fd, void *mask, int flags) {
1474 SCOPED_TSAN_INTERCEPTOR(signalfd, fd, mask, flags);
1476 FdClose(thr, pc, fd);
1477 fd = REAL(signalfd)(fd, mask, flags);
1479 FdSignalCreate(thr, pc, fd);
1482 #define TSAN_MAYBE_INTERCEPT_SIGNALFD TSAN_INTERCEPT(signalfd)
1484 #define TSAN_MAYBE_INTERCEPT_SIGNALFD
1488 TSAN_INTERCEPTOR(int, inotify_init, int fake) {
1489 SCOPED_TSAN_INTERCEPTOR(inotify_init, fake);
1490 int fd = REAL(inotify_init)(fake);
1492 FdInotifyCreate(thr, pc, fd);
1495 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT TSAN_INTERCEPT(inotify_init)
1497 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT
1501 TSAN_INTERCEPTOR(int, inotify_init1, int flags) {
1502 SCOPED_TSAN_INTERCEPTOR(inotify_init1, flags);
1503 int fd = REAL(inotify_init1)(flags);
1505 FdInotifyCreate(thr, pc, fd);
1508 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1 TSAN_INTERCEPT(inotify_init1)
1510 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1
1513 TSAN_INTERCEPTOR(int, socket, int domain, int type, int protocol) {
1514 SCOPED_TSAN_INTERCEPTOR(socket, domain, type, protocol);
1515 int fd = REAL(socket)(domain, type, protocol);
1517 FdSocketCreate(thr, pc, fd);
1521 TSAN_INTERCEPTOR(int, socketpair, int domain, int type, int protocol, int *fd) {
1522 SCOPED_TSAN_INTERCEPTOR(socketpair, domain, type, protocol, fd);
1523 int res = REAL(socketpair)(domain, type, protocol, fd);
1524 if (res == 0 && fd[0] >= 0 && fd[1] >= 0)
1525 FdPipeCreate(thr, pc, fd[0], fd[1]);
1529 TSAN_INTERCEPTOR(int, connect, int fd, void *addr, unsigned addrlen) {
1530 SCOPED_TSAN_INTERCEPTOR(connect, fd, addr, addrlen);
1531 FdSocketConnecting(thr, pc, fd);
1532 int res = REAL(connect)(fd, addr, addrlen);
1533 if (res == 0 && fd >= 0)
1534 FdSocketConnect(thr, pc, fd);
1538 TSAN_INTERCEPTOR(int, bind, int fd, void *addr, unsigned addrlen) {
1539 SCOPED_TSAN_INTERCEPTOR(bind, fd, addr, addrlen);
1540 int res = REAL(bind)(fd, addr, addrlen);
1541 if (fd > 0 && res == 0)
1542 FdAccess(thr, pc, fd);
1546 TSAN_INTERCEPTOR(int, listen, int fd, int backlog) {
1547 SCOPED_TSAN_INTERCEPTOR(listen, fd, backlog);
1548 int res = REAL(listen)(fd, backlog);
1549 if (fd > 0 && res == 0)
1550 FdAccess(thr, pc, fd);
1554 TSAN_INTERCEPTOR(int, close, int fd) {
1555 SCOPED_TSAN_INTERCEPTOR(close, fd);
1557 FdClose(thr, pc, fd);
1558 return REAL(close)(fd);
1562 TSAN_INTERCEPTOR(int, __close, int fd) {
1563 SCOPED_TSAN_INTERCEPTOR(__close, fd);
1565 FdClose(thr, pc, fd);
1566 return REAL(__close)(fd);
1568 #define TSAN_MAYBE_INTERCEPT___CLOSE TSAN_INTERCEPT(__close)
1570 #define TSAN_MAYBE_INTERCEPT___CLOSE
1574 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1575 TSAN_INTERCEPTOR(void, __res_iclose, void *state, bool free_addr) {
1576 SCOPED_TSAN_INTERCEPTOR(__res_iclose, state, free_addr);
1578 int cnt = ExtractResolvFDs(state, fds, ARRAY_SIZE(fds));
1579 for (int i = 0; i < cnt; i++) {
1581 FdClose(thr, pc, fds[i]);
1583 REAL(__res_iclose)(state, free_addr);
1585 #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE TSAN_INTERCEPT(__res_iclose)
1587 #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE
1590 TSAN_INTERCEPTOR(int, pipe, int *pipefd) {
1591 SCOPED_TSAN_INTERCEPTOR(pipe, pipefd);
1592 int res = REAL(pipe)(pipefd);
1593 if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0)
1594 FdPipeCreate(thr, pc, pipefd[0], pipefd[1]);
1599 TSAN_INTERCEPTOR(int, pipe2, int *pipefd, int flags) {
1600 SCOPED_TSAN_INTERCEPTOR(pipe2, pipefd, flags);
1601 int res = REAL(pipe2)(pipefd, flags);
1602 if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0)
1603 FdPipeCreate(thr, pc, pipefd[0], pipefd[1]);
1608 TSAN_INTERCEPTOR(int, unlink, char *path) {
1609 SCOPED_TSAN_INTERCEPTOR(unlink, path);
1610 Release(thr, pc, File2addr(path));
1611 int res = REAL(unlink)(path);
1615 TSAN_INTERCEPTOR(void*, tmpfile, int fake) {
1616 SCOPED_TSAN_INTERCEPTOR(tmpfile, fake);
1617 void *res = REAL(tmpfile)(fake);
1619 int fd = fileno_unlocked(res);
1621 FdFileCreate(thr, pc, fd);
1627 TSAN_INTERCEPTOR(void*, tmpfile64, int fake) {
1628 SCOPED_TSAN_INTERCEPTOR(tmpfile64, fake);
1629 void *res = REAL(tmpfile64)(fake);
1631 int fd = fileno_unlocked(res);
1633 FdFileCreate(thr, pc, fd);
1637 #define TSAN_MAYBE_INTERCEPT_TMPFILE64 TSAN_INTERCEPT(tmpfile64)
1639 #define TSAN_MAYBE_INTERCEPT_TMPFILE64
1642 static void FlushStreams() {
1643 // Flushing all the streams here may freeze the process if a child thread is
1644 // performing file stream operations at the same time.
1645 REAL(fflush)(stdout);
1646 REAL(fflush)(stderr);
1649 TSAN_INTERCEPTOR(void, abort, int fake) {
1650 SCOPED_TSAN_INTERCEPTOR(abort, fake);
1655 TSAN_INTERCEPTOR(int, puts, const char *s) {
1656 SCOPED_TSAN_INTERCEPTOR(puts, s);
1657 MemoryAccessRange(thr, pc, (uptr)s, internal_strlen(s), false);
1658 return REAL(puts)(s);
1661 TSAN_INTERCEPTOR(int, rmdir, char *path) {
1662 SCOPED_TSAN_INTERCEPTOR(rmdir, path);
1663 Release(thr, pc, Dir2addr(path));
1664 int res = REAL(rmdir)(path);
1668 TSAN_INTERCEPTOR(int, closedir, void *dirp) {
1669 SCOPED_TSAN_INTERCEPTOR(closedir, dirp);
1671 int fd = dirfd(dirp);
1672 FdClose(thr, pc, fd);
1674 return REAL(closedir)(dirp);
1678 TSAN_INTERCEPTOR(int, epoll_create, int size) {
1679 SCOPED_TSAN_INTERCEPTOR(epoll_create, size);
1680 int fd = REAL(epoll_create)(size);
1682 FdPollCreate(thr, pc, fd);
1686 TSAN_INTERCEPTOR(int, epoll_create1, int flags) {
1687 SCOPED_TSAN_INTERCEPTOR(epoll_create1, flags);
1688 int fd = REAL(epoll_create1)(flags);
1690 FdPollCreate(thr, pc, fd);
1694 TSAN_INTERCEPTOR(int, epoll_ctl, int epfd, int op, int fd, void *ev) {
1695 SCOPED_TSAN_INTERCEPTOR(epoll_ctl, epfd, op, fd, ev);
1697 FdAccess(thr, pc, epfd);
1698 if (epfd >= 0 && fd >= 0)
1699 FdAccess(thr, pc, fd);
1700 if (op == EPOLL_CTL_ADD && epfd >= 0)
1701 FdRelease(thr, pc, epfd);
1702 int res = REAL(epoll_ctl)(epfd, op, fd, ev);
1706 TSAN_INTERCEPTOR(int, epoll_wait, int epfd, void *ev, int cnt, int timeout) {
1707 SCOPED_TSAN_INTERCEPTOR(epoll_wait, epfd, ev, cnt, timeout);
1709 FdAccess(thr, pc, epfd);
1710 int res = BLOCK_REAL(epoll_wait)(epfd, ev, cnt, timeout);
1711 if (res > 0 && epfd >= 0)
1712 FdAcquire(thr, pc, epfd);
1716 TSAN_INTERCEPTOR(int, epoll_pwait, int epfd, void *ev, int cnt, int timeout,
1718 SCOPED_TSAN_INTERCEPTOR(epoll_pwait, epfd, ev, cnt, timeout, sigmask);
1720 FdAccess(thr, pc, epfd);
1721 int res = BLOCK_REAL(epoll_pwait)(epfd, ev, cnt, timeout, sigmask);
1722 if (res > 0 && epfd >= 0)
1723 FdAcquire(thr, pc, epfd);
1727 #define TSAN_MAYBE_INTERCEPT_EPOLL \
1728 TSAN_INTERCEPT(epoll_create); \
1729 TSAN_INTERCEPT(epoll_create1); \
1730 TSAN_INTERCEPT(epoll_ctl); \
1731 TSAN_INTERCEPT(epoll_wait); \
1732 TSAN_INTERCEPT(epoll_pwait)
1734 #define TSAN_MAYBE_INTERCEPT_EPOLL
1737 // The following functions are intercepted merely to process pending signals.
1738 // If program blocks signal X, we must deliver the signal before the function
1739 // returns. Similarly, if program unblocks a signal (or returns from sigsuspend)
1740 // it's better to deliver the signal straight away.
1741 TSAN_INTERCEPTOR(int, sigsuspend, const __sanitizer_sigset_t *mask) {
1742 SCOPED_TSAN_INTERCEPTOR(sigsuspend, mask);
1743 return REAL(sigsuspend)(mask);
1746 TSAN_INTERCEPTOR(int, sigblock, int mask) {
1747 SCOPED_TSAN_INTERCEPTOR(sigblock, mask);
1748 return REAL(sigblock)(mask);
1751 TSAN_INTERCEPTOR(int, sigsetmask, int mask) {
1752 SCOPED_TSAN_INTERCEPTOR(sigsetmask, mask);
1753 return REAL(sigsetmask)(mask);
1756 TSAN_INTERCEPTOR(int, pthread_sigmask, int how, const __sanitizer_sigset_t *set,
1757 __sanitizer_sigset_t *oldset) {
1758 SCOPED_TSAN_INTERCEPTOR(pthread_sigmask, how, set, oldset);
1759 return REAL(pthread_sigmask)(how, set, oldset);
1764 static void CallUserSignalHandler(ThreadState *thr, bool sync, bool acquire,
1765 bool sigact, int sig, my_siginfo_t *info, void *uctx) {
1767 Acquire(thr, 0, (uptr)&sigactions[sig]);
1768 // Signals are generally asynchronous, so if we receive a signals when
1769 // ignores are enabled we should disable ignores. This is critical for sync
1770 // and interceptors, because otherwise we can miss syncronization and report
1772 int ignore_reads_and_writes = thr->ignore_reads_and_writes;
1773 int ignore_interceptors = thr->ignore_interceptors;
1774 int ignore_sync = thr->ignore_sync;
1775 if (!ctx->after_multithreaded_fork) {
1776 thr->ignore_reads_and_writes = 0;
1777 thr->fast_state.ClearIgnoreBit();
1778 thr->ignore_interceptors = 0;
1779 thr->ignore_sync = 0;
1781 // Ensure that the handler does not spoil errno.
1782 const int saved_errno = errno;
1784 // This code races with sigaction. Be careful to not read sa_sigaction twice.
1785 // Also need to remember pc for reporting before the call,
1786 // because the handler can reset it.
1787 volatile uptr pc = sigact ?
1788 (uptr)sigactions[sig].sa_sigaction :
1789 (uptr)sigactions[sig].sa_handler;
1790 if (pc != (uptr)SIG_DFL && pc != (uptr)SIG_IGN) {
1792 ((sigactionhandler_t)pc)(sig, info, uctx);
1794 ((sighandler_t)pc)(sig);
1796 if (!ctx->after_multithreaded_fork) {
1797 thr->ignore_reads_and_writes = ignore_reads_and_writes;
1798 if (ignore_reads_and_writes)
1799 thr->fast_state.SetIgnoreBit();
1800 thr->ignore_interceptors = ignore_interceptors;
1801 thr->ignore_sync = ignore_sync;
1803 // We do not detect errno spoiling for SIGTERM,
1804 // because some SIGTERM handlers do spoil errno but reraise SIGTERM,
1805 // tsan reports false positive in such case.
1806 // It's difficult to properly detect this situation (reraise),
1807 // because in async signal processing case (when handler is called directly
1808 // from rtl_generic_sighandler) we have not yet received the reraised
1809 // signal; and it looks too fragile to intercept all ways to reraise a signal.
1810 if (flags()->report_bugs && !sync && sig != SIGTERM && errno != 99) {
1811 VarSizeStackTrace stack;
1812 // StackTrace::GetNestInstructionPc(pc) is used because return address is
1813 // expected, OutputReport() will undo this.
1814 ObtainCurrentStack(thr, StackTrace::GetNextInstructionPc(pc), &stack);
1815 ThreadRegistryLock l(ctx->thread_registry);
1816 ScopedReport rep(ReportTypeErrnoInSignal);
1817 if (!IsFiredSuppression(ctx, ReportTypeErrnoInSignal, stack)) {
1818 rep.AddStack(stack, true);
1819 OutputReport(thr, rep);
1822 errno = saved_errno;
1825 void ProcessPendingSignals(ThreadState *thr) {
1826 ThreadSignalContext *sctx = SigCtx(thr);
1828 atomic_load(&sctx->have_pending_signals, memory_order_relaxed) == 0)
1830 atomic_store(&sctx->have_pending_signals, 0, memory_order_relaxed);
1831 atomic_fetch_add(&thr->in_signal_handler, 1, memory_order_relaxed);
1832 internal_sigfillset(&sctx->emptyset);
1833 int res = REAL(pthread_sigmask)(SIG_SETMASK, &sctx->emptyset, &sctx->oldset);
1835 for (int sig = 0; sig < kSigCount; sig++) {
1836 SignalDesc *signal = &sctx->pending_signals[sig];
1837 if (signal->armed) {
1838 signal->armed = false;
1839 CallUserSignalHandler(thr, false, true, signal->sigaction, sig,
1840 &signal->siginfo, &signal->ctx);
1843 res = REAL(pthread_sigmask)(SIG_SETMASK, &sctx->oldset, 0);
1845 atomic_fetch_add(&thr->in_signal_handler, -1, memory_order_relaxed);
1848 } // namespace __tsan
1850 static bool is_sync_signal(ThreadSignalContext *sctx, int sig) {
1851 return sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
1852 sig == SIGABRT || sig == SIGFPE || sig == SIGPIPE || sig == SIGSYS ||
1853 // If we are sending signal to ourselves, we must process it now.
1854 (sctx && sig == sctx->int_signal_send);
1857 void ALWAYS_INLINE rtl_generic_sighandler(bool sigact, int sig,
1858 my_siginfo_t *info, void *ctx) {
1859 ThreadState *thr = cur_thread();
1860 ThreadSignalContext *sctx = SigCtx(thr);
1861 if (sig < 0 || sig >= kSigCount) {
1862 VPrintf(1, "ThreadSanitizer: ignoring signal %d\n", sig);
1865 // Don't mess with synchronous signals.
1866 const bool sync = is_sync_signal(sctx, sig);
1868 // If we are in blocking function, we can safely process it now
1869 // (but check if we are in a recursive interceptor,
1870 // i.e. pthread_join()->munmap()).
1871 (sctx && atomic_load(&sctx->in_blocking_func, memory_order_relaxed))) {
1872 atomic_fetch_add(&thr->in_signal_handler, 1, memory_order_relaxed);
1873 if (sctx && atomic_load(&sctx->in_blocking_func, memory_order_relaxed)) {
1874 atomic_store(&sctx->in_blocking_func, 0, memory_order_relaxed);
1875 CallUserSignalHandler(thr, sync, true, sigact, sig, info, ctx);
1876 atomic_store(&sctx->in_blocking_func, 1, memory_order_relaxed);
1878 // Be very conservative with when we do acquire in this case.
1879 // It's unsafe to do acquire in async handlers, because ThreadState
1880 // can be in inconsistent state.
1881 // SIGSYS looks relatively safe -- it's synchronous and can actually
1882 // need some global state.
1883 bool acq = (sig == SIGSYS);
1884 CallUserSignalHandler(thr, sync, acq, sigact, sig, info, ctx);
1886 atomic_fetch_add(&thr->in_signal_handler, -1, memory_order_relaxed);
1892 SignalDesc *signal = &sctx->pending_signals[sig];
1893 if (signal->armed == false) {
1894 signal->armed = true;
1895 signal->sigaction = sigact;
1897 internal_memcpy(&signal->siginfo, info, sizeof(*info));
1899 internal_memcpy(&signal->ctx, ctx, sizeof(signal->ctx));
1900 atomic_store(&sctx->have_pending_signals, 1, memory_order_relaxed);
1904 static void rtl_sighandler(int sig) {
1905 rtl_generic_sighandler(false, sig, 0, 0);
1908 static void rtl_sigaction(int sig, my_siginfo_t *info, void *ctx) {
1909 rtl_generic_sighandler(true, sig, info, ctx);
1912 TSAN_INTERCEPTOR(int, sigaction, int sig, sigaction_t *act, sigaction_t *old) {
1913 // Note: if we call REAL(sigaction) directly for any reason without proxying
1914 // the signal handler through rtl_sigaction, very bad things will happen.
1915 // The handler will run synchronously and corrupt tsan per-thread state.
1916 SCOPED_INTERCEPTOR_RAW(sigaction, sig, act, old);
1918 internal_memcpy(old, &sigactions[sig], sizeof(*old));
1921 // Copy act into sigactions[sig].
1922 // Can't use struct copy, because compiler can emit call to memcpy.
1923 // Can't use internal_memcpy, because it copies byte-by-byte,
1924 // and signal handler reads the sa_handler concurrently. It it can read
1925 // some bytes from old value and some bytes from new value.
1926 // Use volatile to prevent insertion of memcpy.
1927 sigactions[sig].sa_handler = *(volatile sighandler_t*)&act->sa_handler;
1928 sigactions[sig].sa_flags = *(volatile int*)&act->sa_flags;
1929 internal_memcpy(&sigactions[sig].sa_mask, &act->sa_mask,
1930 sizeof(sigactions[sig].sa_mask));
1931 #if !SANITIZER_FREEBSD && !SANITIZER_MAC
1932 sigactions[sig].sa_restorer = act->sa_restorer;
1935 internal_memcpy(&newact, act, sizeof(newact));
1936 internal_sigfillset(&newact.sa_mask);
1937 if (act->sa_handler != SIG_IGN && act->sa_handler != SIG_DFL) {
1938 if (newact.sa_flags & SA_SIGINFO)
1939 newact.sa_sigaction = rtl_sigaction;
1941 newact.sa_handler = rtl_sighandler;
1943 ReleaseStore(thr, pc, (uptr)&sigactions[sig]);
1944 int res = REAL(sigaction)(sig, &newact, 0);
1948 TSAN_INTERCEPTOR(sighandler_t, signal, int sig, sighandler_t h) {
1951 internal_memset(&act.sa_mask, -1, sizeof(act.sa_mask));
1954 int res = sigaction(sig, &act, &old);
1957 return old.sa_handler;
1960 TSAN_INTERCEPTOR(int, raise, int sig) {
1961 SCOPED_TSAN_INTERCEPTOR(raise, sig);
1962 ThreadSignalContext *sctx = SigCtx(thr);
1964 int prev = sctx->int_signal_send;
1965 sctx->int_signal_send = sig;
1966 int res = REAL(raise)(sig);
1967 CHECK_EQ(sctx->int_signal_send, sig);
1968 sctx->int_signal_send = prev;
1972 TSAN_INTERCEPTOR(int, kill, int pid, int sig) {
1973 SCOPED_TSAN_INTERCEPTOR(kill, pid, sig);
1974 ThreadSignalContext *sctx = SigCtx(thr);
1976 int prev = sctx->int_signal_send;
1977 if (pid == (int)internal_getpid()) {
1978 sctx->int_signal_send = sig;
1980 int res = REAL(kill)(pid, sig);
1981 if (pid == (int)internal_getpid()) {
1982 CHECK_EQ(sctx->int_signal_send, sig);
1983 sctx->int_signal_send = prev;
1988 TSAN_INTERCEPTOR(int, pthread_kill, void *tid, int sig) {
1989 SCOPED_TSAN_INTERCEPTOR(pthread_kill, tid, sig);
1990 ThreadSignalContext *sctx = SigCtx(thr);
1992 int prev = sctx->int_signal_send;
1993 if (tid == pthread_self()) {
1994 sctx->int_signal_send = sig;
1996 int res = REAL(pthread_kill)(tid, sig);
1997 if (tid == pthread_self()) {
1998 CHECK_EQ(sctx->int_signal_send, sig);
1999 sctx->int_signal_send = prev;
2004 TSAN_INTERCEPTOR(int, gettimeofday, void *tv, void *tz) {
2005 SCOPED_TSAN_INTERCEPTOR(gettimeofday, tv, tz);
2006 // It's intercepted merely to process pending signals.
2007 return REAL(gettimeofday)(tv, tz);
2010 TSAN_INTERCEPTOR(int, getaddrinfo, void *node, void *service,
2011 void *hints, void *rv) {
2012 SCOPED_TSAN_INTERCEPTOR(getaddrinfo, node, service, hints, rv);
2013 // We miss atomic synchronization in getaddrinfo,
2014 // and can report false race between malloc and free
2015 // inside of getaddrinfo. So ignore memory accesses.
2016 ThreadIgnoreBegin(thr, pc);
2017 int res = REAL(getaddrinfo)(node, service, hints, rv);
2018 ThreadIgnoreEnd(thr, pc);
2022 TSAN_INTERCEPTOR(int, fork, int fake) {
2023 if (cur_thread()->in_symbolizer)
2024 return REAL(fork)(fake);
2025 SCOPED_INTERCEPTOR_RAW(fork, fake);
2026 ForkBefore(thr, pc);
2029 // On OS X, REAL(fork) can call intercepted functions (OSSpinLockLock), and
2030 // we'll assert in CheckNoLocks() unless we ignore interceptors.
2031 ScopedIgnoreInterceptors ignore;
2032 pid = REAL(fork)(fake);
2036 ForkChildAfter(thr, pc);
2038 } else if (pid > 0) {
2040 ForkParentAfter(thr, pc);
2043 ForkParentAfter(thr, pc);
2048 TSAN_INTERCEPTOR(int, vfork, int fake) {
2049 // Some programs (e.g. openjdk) call close for all file descriptors
2050 // in the child process. Under tsan it leads to false positives, because
2051 // address space is shared, so the parent process also thinks that
2052 // the descriptors are closed (while they are actually not).
2053 // This leads to false positives due to missed synchronization.
2054 // Strictly saying this is undefined behavior, because vfork child is not
2055 // allowed to call any functions other than exec/exit. But this is what
2056 // openjdk does, so we want to handle it.
2057 // We could disable interceptors in the child process. But it's not possible
2058 // to simply intercept and wrap vfork, because vfork child is not allowed
2059 // to return from the function that calls vfork, and that's exactly what
2060 // we would do. So this would require some assembly trickery as well.
2061 // Instead we simply turn vfork into fork.
2062 return WRAP(fork)(fake);
2065 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2066 typedef int (*dl_iterate_phdr_cb_t)(__sanitizer_dl_phdr_info *info, SIZE_T size,
2068 struct dl_iterate_phdr_data {
2071 dl_iterate_phdr_cb_t cb;
2075 static bool IsAppNotRodata(uptr addr) {
2076 return IsAppMem(addr) && *(u64*)MemToShadow(addr) != kShadowRodata;
2079 static int dl_iterate_phdr_cb(__sanitizer_dl_phdr_info *info, SIZE_T size,
2081 dl_iterate_phdr_data *cbdata = (dl_iterate_phdr_data *)data;
2082 // dlopen/dlclose allocate/free dynamic-linker-internal memory, which is later
2083 // accessible in dl_iterate_phdr callback. But we don't see synchronization
2084 // inside of dynamic linker, so we "unpoison" it here in order to not
2085 // produce false reports. Ignoring malloc/free in dlopen/dlclose is not enough
2086 // because some libc functions call __libc_dlopen.
2087 if (info && IsAppNotRodata((uptr)info->dlpi_name))
2088 MemoryResetRange(cbdata->thr, cbdata->pc, (uptr)info->dlpi_name,
2089 internal_strlen(info->dlpi_name));
2090 int res = cbdata->cb(info, size, cbdata->data);
2091 // Perform the check one more time in case info->dlpi_name was overwritten
2092 // by user callback.
2093 if (info && IsAppNotRodata((uptr)info->dlpi_name))
2094 MemoryResetRange(cbdata->thr, cbdata->pc, (uptr)info->dlpi_name,
2095 internal_strlen(info->dlpi_name));
2099 TSAN_INTERCEPTOR(int, dl_iterate_phdr, dl_iterate_phdr_cb_t cb, void *data) {
2100 SCOPED_TSAN_INTERCEPTOR(dl_iterate_phdr, cb, data);
2101 dl_iterate_phdr_data cbdata;
2106 int res = REAL(dl_iterate_phdr)(dl_iterate_phdr_cb, &cbdata);
2111 static int OnExit(ThreadState *thr) {
2112 int status = Finalize(thr);
2117 struct TsanInterceptorContext {
2119 const uptr caller_pc;
2124 static void HandleRecvmsg(ThreadState *thr, uptr pc,
2125 __sanitizer_msghdr *msg) {
2127 int cnt = ExtractRecvmsgFDs(msg, fds, ARRAY_SIZE(fds));
2128 for (int i = 0; i < cnt; i++)
2129 FdEventCreate(thr, pc, fds[i]);
2133 #include "sanitizer_common/sanitizer_platform_interceptors.h"
2134 // Causes interceptor recursion (getaddrinfo() and fopen())
2135 #undef SANITIZER_INTERCEPT_GETADDRINFO
2136 // There interceptors do not seem to be strictly necessary for tsan.
2137 // But we see cases where the interceptors consume 70% of execution time.
2138 // Memory blocks passed to fgetgrent_r are "written to" by tsan several times.
2139 // First, there is some recursion (getgrnam_r calls fgetgrent_r), and each
2140 // function "writes to" the buffer. Then, the same memory is "written to"
2141 // twice, first as buf and then as pwbufp (both of them refer to the same
2143 #undef SANITIZER_INTERCEPT_GETPWENT
2144 #undef SANITIZER_INTERCEPT_GETPWENT_R
2145 #undef SANITIZER_INTERCEPT_FGETPWENT
2146 #undef SANITIZER_INTERCEPT_GETPWNAM_AND_FRIENDS
2147 #undef SANITIZER_INTERCEPT_GETPWNAM_R_AND_FRIENDS
2148 // We define our own.
2149 #if SANITIZER_INTERCEPT_TLS_GET_ADDR
2150 #define NEED_TLS_GET_ADDR
2152 #undef SANITIZER_INTERCEPT_TLS_GET_ADDR
2154 #define COMMON_INTERCEPT_FUNCTION(name) INTERCEPT_FUNCTION(name)
2155 #define COMMON_INTERCEPT_FUNCTION_VER(name, ver) \
2156 INTERCEPT_FUNCTION_VER(name, ver)
2158 #define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \
2159 MemoryAccessRange(((TsanInterceptorContext *)ctx)->thr, \
2160 ((TsanInterceptorContext *)ctx)->pc, (uptr)ptr, size, \
2163 #define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) \
2164 MemoryAccessRange(((TsanInterceptorContext *) ctx)->thr, \
2165 ((TsanInterceptorContext *) ctx)->pc, (uptr) ptr, size, \
2168 #define COMMON_INTERCEPTOR_ENTER(ctx, func, ...) \
2169 SCOPED_TSAN_INTERCEPTOR(func, __VA_ARGS__); \
2170 TsanInterceptorContext _ctx = {thr, caller_pc, pc}; \
2171 ctx = (void *)&_ctx; \
2174 #define COMMON_INTERCEPTOR_ENTER_NOIGNORE(ctx, func, ...) \
2175 SCOPED_INTERCEPTOR_RAW(func, __VA_ARGS__); \
2176 TsanInterceptorContext _ctx = {thr, caller_pc, pc}; \
2177 ctx = (void *)&_ctx; \
2180 #define COMMON_INTERCEPTOR_FILE_OPEN(ctx, file, path) \
2181 Acquire(thr, pc, File2addr(path)); \
2183 int fd = fileno_unlocked(file); \
2184 if (fd >= 0) FdFileCreate(thr, pc, fd); \
2187 #define COMMON_INTERCEPTOR_FILE_CLOSE(ctx, file) \
2189 int fd = fileno_unlocked(file); \
2190 if (fd >= 0) FdClose(thr, pc, fd); \
2193 #define COMMON_INTERCEPTOR_LIBRARY_LOADED(filename, handle) \
2194 libignore()->OnLibraryLoaded(filename)
2196 #define COMMON_INTERCEPTOR_LIBRARY_UNLOADED() \
2197 libignore()->OnLibraryUnloaded()
2199 #define COMMON_INTERCEPTOR_ACQUIRE(ctx, u) \
2200 Acquire(((TsanInterceptorContext *) ctx)->thr, pc, u)
2202 #define COMMON_INTERCEPTOR_RELEASE(ctx, u) \
2203 Release(((TsanInterceptorContext *) ctx)->thr, pc, u)
2205 #define COMMON_INTERCEPTOR_DIR_ACQUIRE(ctx, path) \
2206 Acquire(((TsanInterceptorContext *) ctx)->thr, pc, Dir2addr(path))
2208 #define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \
2209 FdAcquire(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2211 #define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \
2212 FdRelease(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2214 #define COMMON_INTERCEPTOR_FD_ACCESS(ctx, fd) \
2215 FdAccess(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2217 #define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \
2218 FdSocketAccept(((TsanInterceptorContext *) ctx)->thr, pc, fd, newfd)
2220 #define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) \
2221 ThreadSetName(((TsanInterceptorContext *) ctx)->thr, name)
2223 #define COMMON_INTERCEPTOR_SET_PTHREAD_NAME(ctx, thread, name) \
2224 __tsan::ctx->thread_registry->SetThreadNameByUserId(thread, name)
2226 #define COMMON_INTERCEPTOR_BLOCK_REAL(name) BLOCK_REAL(name)
2228 #define COMMON_INTERCEPTOR_ON_EXIT(ctx) \
2229 OnExit(((TsanInterceptorContext *) ctx)->thr)
2231 #define COMMON_INTERCEPTOR_MUTEX_PRE_LOCK(ctx, m) \
2232 MutexPreLock(((TsanInterceptorContext *)ctx)->thr, \
2233 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2235 #define COMMON_INTERCEPTOR_MUTEX_POST_LOCK(ctx, m) \
2236 MutexPostLock(((TsanInterceptorContext *)ctx)->thr, \
2237 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2239 #define COMMON_INTERCEPTOR_MUTEX_UNLOCK(ctx, m) \
2240 MutexUnlock(((TsanInterceptorContext *)ctx)->thr, \
2241 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2243 #define COMMON_INTERCEPTOR_MUTEX_REPAIR(ctx, m) \
2244 MutexRepair(((TsanInterceptorContext *)ctx)->thr, \
2245 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2247 #define COMMON_INTERCEPTOR_MUTEX_INVALID(ctx, m) \
2248 MutexInvalidAccess(((TsanInterceptorContext *)ctx)->thr, \
2249 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2252 #define COMMON_INTERCEPTOR_HANDLE_RECVMSG(ctx, msg) \
2253 HandleRecvmsg(((TsanInterceptorContext *)ctx)->thr, \
2254 ((TsanInterceptorContext *)ctx)->pc, msg)
2257 #define COMMON_INTERCEPTOR_GET_TLS_RANGE(begin, end) \
2258 if (TsanThread *t = GetCurrentThread()) { \
2259 *begin = t->tls_begin(); \
2260 *end = t->tls_end(); \
2262 *begin = *end = 0; \
2265 #define COMMON_INTERCEPTOR_USER_CALLBACK_START() \
2266 SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_START()
2268 #define COMMON_INTERCEPTOR_USER_CALLBACK_END() \
2269 SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_END()
2271 #include "sanitizer_common/sanitizer_common_interceptors.inc"
2273 #define TSAN_SYSCALL() \
2274 ThreadState *thr = cur_thread(); \
2275 if (thr->ignore_interceptors) \
2277 ScopedSyscall scoped_syscall(thr) \
2280 struct ScopedSyscall {
2283 explicit ScopedSyscall(ThreadState *thr)
2289 ProcessPendingSignals(thr);
2293 #if !SANITIZER_FREEBSD && !SANITIZER_MAC
2294 static void syscall_access_range(uptr pc, uptr p, uptr s, bool write) {
2296 MemoryAccessRange(thr, pc, p, s, write);
2299 static void syscall_acquire(uptr pc, uptr addr) {
2301 Acquire(thr, pc, addr);
2302 DPrintf("syscall_acquire(%p)\n", addr);
2305 static void syscall_release(uptr pc, uptr addr) {
2307 DPrintf("syscall_release(%p)\n", addr);
2308 Release(thr, pc, addr);
2311 static void syscall_fd_close(uptr pc, int fd) {
2313 FdClose(thr, pc, fd);
2316 static USED void syscall_fd_acquire(uptr pc, int fd) {
2318 FdAcquire(thr, pc, fd);
2319 DPrintf("syscall_fd_acquire(%p)\n", fd);
2322 static USED void syscall_fd_release(uptr pc, int fd) {
2324 DPrintf("syscall_fd_release(%p)\n", fd);
2325 FdRelease(thr, pc, fd);
2328 static void syscall_pre_fork(uptr pc) {
2330 ForkBefore(thr, pc);
2333 static void syscall_post_fork(uptr pc, int pid) {
2337 ForkChildAfter(thr, pc);
2339 } else if (pid > 0) {
2341 ForkParentAfter(thr, pc);
2344 ForkParentAfter(thr, pc);
2349 #define COMMON_SYSCALL_PRE_READ_RANGE(p, s) \
2350 syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), false)
2352 #define COMMON_SYSCALL_PRE_WRITE_RANGE(p, s) \
2353 syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), true)
2355 #define COMMON_SYSCALL_POST_READ_RANGE(p, s) \
2361 #define COMMON_SYSCALL_POST_WRITE_RANGE(p, s) \
2367 #define COMMON_SYSCALL_ACQUIRE(addr) \
2368 syscall_acquire(GET_CALLER_PC(), (uptr)(addr))
2370 #define COMMON_SYSCALL_RELEASE(addr) \
2371 syscall_release(GET_CALLER_PC(), (uptr)(addr))
2373 #define COMMON_SYSCALL_FD_CLOSE(fd) syscall_fd_close(GET_CALLER_PC(), fd)
2375 #define COMMON_SYSCALL_FD_ACQUIRE(fd) syscall_fd_acquire(GET_CALLER_PC(), fd)
2377 #define COMMON_SYSCALL_FD_RELEASE(fd) syscall_fd_release(GET_CALLER_PC(), fd)
2379 #define COMMON_SYSCALL_PRE_FORK() \
2380 syscall_pre_fork(GET_CALLER_PC())
2382 #define COMMON_SYSCALL_POST_FORK(res) \
2383 syscall_post_fork(GET_CALLER_PC(), res)
2385 #include "sanitizer_common/sanitizer_common_syscalls.inc"
2387 #ifdef NEED_TLS_GET_ADDR
2388 // Define own interceptor instead of sanitizer_common's for three reasons:
2389 // 1. It must not process pending signals.
2390 // Signal handlers may contain MOVDQA instruction (see below).
2391 // 2. It must be as simple as possible to not contain MOVDQA.
2392 // 3. Sanitizer_common version uses COMMON_INTERCEPTOR_INITIALIZE_RANGE which
2393 // is empty for tsan (meant only for msan).
2394 // Note: __tls_get_addr can be called with mis-aligned stack due to:
2395 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58066
2396 // So the interceptor must work with mis-aligned stack, in particular, does not
2397 // execute MOVDQA with stack addresses.
2398 TSAN_INTERCEPTOR(void *, __tls_get_addr, void *arg) {
2399 void *res = REAL(__tls_get_addr)(arg);
2400 ThreadState *thr = cur_thread();
2403 DTLS::DTV *dtv = DTLS_on_tls_get_addr(arg, res, thr->tls_addr, thr->tls_size);
2406 // New DTLS block has been allocated.
2407 MemoryResetRange(thr, 0, dtv->beg, dtv->size);
2414 static void finalize(void *arg) {
2415 ThreadState *thr = cur_thread();
2416 int status = Finalize(thr);
2417 // Make sure the output is not lost.
2423 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2424 static void unreachable() {
2425 Report("FATAL: ThreadSanitizer: unreachable called\n");
2430 void InitializeInterceptors() {
2432 // We need to setup it early, because functions like dlsym() can call it.
2433 REAL(memset) = internal_memset;
2434 REAL(memcpy) = internal_memcpy;
2437 // Instruct libc malloc to consume less memory.
2439 mallopt(1, 0); // M_MXFAST
2440 mallopt(-3, 32*1024); // M_MMAP_THRESHOLD
2443 InitializeCommonInterceptors();
2446 // We can not use TSAN_INTERCEPT to get setjmp addr,
2447 // because it does &setjmp and setjmp is not present in some versions of libc.
2448 using __interception::GetRealFunctionAddress;
2449 GetRealFunctionAddress("setjmp", (uptr*)&REAL(setjmp), 0, 0);
2450 GetRealFunctionAddress("_setjmp", (uptr*)&REAL(_setjmp), 0, 0);
2451 GetRealFunctionAddress("sigsetjmp", (uptr*)&REAL(sigsetjmp), 0, 0);
2452 GetRealFunctionAddress("__sigsetjmp", (uptr*)&REAL(__sigsetjmp), 0, 0);
2455 TSAN_INTERCEPT(longjmp);
2456 TSAN_INTERCEPT(siglongjmp);
2458 TSAN_INTERCEPT(malloc);
2459 TSAN_INTERCEPT(__libc_memalign);
2460 TSAN_INTERCEPT(calloc);
2461 TSAN_INTERCEPT(realloc);
2462 TSAN_INTERCEPT(free);
2463 TSAN_INTERCEPT(cfree);
2464 TSAN_INTERCEPT(mmap);
2465 TSAN_MAYBE_INTERCEPT_MMAP64;
2466 TSAN_INTERCEPT(munmap);
2467 TSAN_MAYBE_INTERCEPT_MEMALIGN;
2468 TSAN_INTERCEPT(valloc);
2469 TSAN_MAYBE_INTERCEPT_PVALLOC;
2470 TSAN_INTERCEPT(posix_memalign);
2472 TSAN_INTERCEPT(strcpy); // NOLINT
2473 TSAN_INTERCEPT(strncpy);
2474 TSAN_INTERCEPT(strdup);
2476 TSAN_INTERCEPT(pthread_create);
2477 TSAN_INTERCEPT(pthread_join);
2478 TSAN_INTERCEPT(pthread_detach);
2480 TSAN_INTERCEPT_VER(pthread_cond_init, PTHREAD_ABI_BASE);
2481 TSAN_INTERCEPT_VER(pthread_cond_signal, PTHREAD_ABI_BASE);
2482 TSAN_INTERCEPT_VER(pthread_cond_broadcast, PTHREAD_ABI_BASE);
2483 TSAN_INTERCEPT_VER(pthread_cond_wait, PTHREAD_ABI_BASE);
2484 TSAN_INTERCEPT_VER(pthread_cond_timedwait, PTHREAD_ABI_BASE);
2485 TSAN_INTERCEPT_VER(pthread_cond_destroy, PTHREAD_ABI_BASE);
2487 TSAN_INTERCEPT(pthread_mutex_init);
2488 TSAN_INTERCEPT(pthread_mutex_destroy);
2489 TSAN_INTERCEPT(pthread_mutex_trylock);
2490 TSAN_INTERCEPT(pthread_mutex_timedlock);
2492 TSAN_INTERCEPT(pthread_spin_init);
2493 TSAN_INTERCEPT(pthread_spin_destroy);
2494 TSAN_INTERCEPT(pthread_spin_lock);
2495 TSAN_INTERCEPT(pthread_spin_trylock);
2496 TSAN_INTERCEPT(pthread_spin_unlock);
2498 TSAN_INTERCEPT(pthread_rwlock_init);
2499 TSAN_INTERCEPT(pthread_rwlock_destroy);
2500 TSAN_INTERCEPT(pthread_rwlock_rdlock);
2501 TSAN_INTERCEPT(pthread_rwlock_tryrdlock);
2502 TSAN_INTERCEPT(pthread_rwlock_timedrdlock);
2503 TSAN_INTERCEPT(pthread_rwlock_wrlock);
2504 TSAN_INTERCEPT(pthread_rwlock_trywrlock);
2505 TSAN_INTERCEPT(pthread_rwlock_timedwrlock);
2506 TSAN_INTERCEPT(pthread_rwlock_unlock);
2508 TSAN_INTERCEPT(pthread_barrier_init);
2509 TSAN_INTERCEPT(pthread_barrier_destroy);
2510 TSAN_INTERCEPT(pthread_barrier_wait);
2512 TSAN_INTERCEPT(pthread_once);
2514 TSAN_INTERCEPT(fstat);
2515 TSAN_MAYBE_INTERCEPT___FXSTAT;
2516 TSAN_MAYBE_INTERCEPT_FSTAT64;
2517 TSAN_MAYBE_INTERCEPT___FXSTAT64;
2518 TSAN_INTERCEPT(open);
2519 TSAN_MAYBE_INTERCEPT_OPEN64;
2520 TSAN_INTERCEPT(creat);
2521 TSAN_MAYBE_INTERCEPT_CREAT64;
2522 TSAN_INTERCEPT(dup);
2523 TSAN_INTERCEPT(dup2);
2524 TSAN_INTERCEPT(dup3);
2525 TSAN_MAYBE_INTERCEPT_EVENTFD;
2526 TSAN_MAYBE_INTERCEPT_SIGNALFD;
2527 TSAN_MAYBE_INTERCEPT_INOTIFY_INIT;
2528 TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1;
2529 TSAN_INTERCEPT(socket);
2530 TSAN_INTERCEPT(socketpair);
2531 TSAN_INTERCEPT(connect);
2532 TSAN_INTERCEPT(bind);
2533 TSAN_INTERCEPT(listen);
2534 TSAN_MAYBE_INTERCEPT_EPOLL;
2535 TSAN_INTERCEPT(close);
2536 TSAN_MAYBE_INTERCEPT___CLOSE;
2537 TSAN_MAYBE_INTERCEPT___RES_ICLOSE;
2538 TSAN_INTERCEPT(pipe);
2539 TSAN_INTERCEPT(pipe2);
2541 TSAN_INTERCEPT(unlink);
2542 TSAN_INTERCEPT(tmpfile);
2543 TSAN_MAYBE_INTERCEPT_TMPFILE64;
2544 TSAN_INTERCEPT(fread);
2545 TSAN_INTERCEPT(fwrite);
2546 TSAN_INTERCEPT(abort);
2547 TSAN_INTERCEPT(puts);
2548 TSAN_INTERCEPT(rmdir);
2549 TSAN_INTERCEPT(closedir);
2551 TSAN_INTERCEPT(sigaction);
2552 TSAN_INTERCEPT(signal);
2553 TSAN_INTERCEPT(sigsuspend);
2554 TSAN_INTERCEPT(sigblock);
2555 TSAN_INTERCEPT(sigsetmask);
2556 TSAN_INTERCEPT(pthread_sigmask);
2557 TSAN_INTERCEPT(raise);
2558 TSAN_INTERCEPT(kill);
2559 TSAN_INTERCEPT(pthread_kill);
2560 TSAN_INTERCEPT(sleep);
2561 TSAN_INTERCEPT(usleep);
2562 TSAN_INTERCEPT(nanosleep);
2563 TSAN_INTERCEPT(gettimeofday);
2564 TSAN_INTERCEPT(getaddrinfo);
2566 TSAN_INTERCEPT(fork);
2567 TSAN_INTERCEPT(vfork);
2568 #if !SANITIZER_ANDROID
2569 TSAN_INTERCEPT(dl_iterate_phdr);
2571 TSAN_INTERCEPT(on_exit);
2572 TSAN_INTERCEPT(__cxa_atexit);
2573 TSAN_INTERCEPT(_exit);
2575 #ifdef NEED_TLS_GET_ADDR
2576 TSAN_INTERCEPT(__tls_get_addr);
2579 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2580 // Need to setup it, because interceptors check that the function is resolved.
2581 // But atexit is emitted directly into the module, so can't be resolved.
2582 REAL(atexit) = (int(*)(void(*)()))unreachable;
2585 if (REAL(__cxa_atexit)(&finalize, 0, 0)) {
2586 Printf("ThreadSanitizer: failed to setup atexit callback\n");
2591 if (pthread_key_create(&g_thread_finalize_key, &thread_finalize)) {
2592 Printf("ThreadSanitizer: failed to create thread key\n");
2600 } // namespace __tsan
2602 // Invisible barrier for tests.
2603 // There were several unsuccessful iterations for this functionality:
2604 // 1. Initially it was implemented in user code using
2605 // REAL(pthread_barrier_wait). But pthread_barrier_wait is not supported on
2606 // MacOS. Futexes are linux-specific for this matter.
2607 // 2. Then we switched to atomics+usleep(10). But usleep produced parasitic
2608 // "as-if synchronized via sleep" messages in reports which failed some
2610 // 3. Then we switched to atomics+sched_yield. But this produced tons of tsan-
2611 // visible events, which lead to "failed to restore stack trace" failures.
2612 // Note that no_sanitize_thread attribute does not turn off atomic interception
2613 // so attaching it to the function defined in user code does not help.
2614 // That's why we now have what we have.
2615 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
2616 void __tsan_testonly_barrier_init(u64 *barrier, u32 count) {
2617 if (count >= (1 << 8)) {
2618 Printf("barrier_init: count is too large (%d)\n", count);
2621 // 8 lsb is thread count, the remaining are count of entered threads.
2625 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
2626 void __tsan_testonly_barrier_wait(u64 *barrier) {
2627 unsigned old = __atomic_fetch_add(barrier, 1 << 8, __ATOMIC_RELAXED);
2628 unsigned old_epoch = (old >> 8) / (old & 0xff);
2630 unsigned cur = __atomic_load_n(barrier, __ATOMIC_RELAXED);
2631 unsigned cur_epoch = (cur >> 8) / (cur & 0xff);
2632 if (cur_epoch != old_epoch)
2634 internal_sched_yield();