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 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 (flags()->ignore_noninstrumented_modules) thr_->suppress_reports++;
273 if (in_ignored_lib_) {
274 DCHECK(!thr_->in_ignored_lib);
275 thr_->in_ignored_lib = true;
280 void ScopedInterceptor::DisableIgnores() {
282 ThreadIgnoreEnd(thr_, pc_);
283 if (flags()->ignore_noninstrumented_modules) thr_->suppress_reports--;
284 if (in_ignored_lib_) {
285 DCHECK(thr_->in_ignored_lib);
286 thr_->in_ignored_lib = false;
291 #define TSAN_INTERCEPT(func) INTERCEPT_FUNCTION(func)
292 #if SANITIZER_FREEBSD
293 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION(func)
295 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION_VER(func, ver)
298 #define READ_STRING_OF_LEN(thr, pc, s, len, n) \
299 MemoryAccessRange((thr), (pc), (uptr)(s), \
300 common_flags()->strict_string_checks ? (len) + 1 : (n), false)
302 #define READ_STRING(thr, pc, s, n) \
303 READ_STRING_OF_LEN((thr), (pc), (s), internal_strlen(s), (n))
305 #define BLOCK_REAL(name) (BlockingCall(thr), REAL(name))
307 struct BlockingCall {
308 explicit BlockingCall(ThreadState *thr)
312 atomic_store(&ctx->in_blocking_func, 1, memory_order_relaxed);
313 if (atomic_load(&ctx->have_pending_signals, memory_order_relaxed) == 0)
315 atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
316 ProcessPendingSignals(thr);
318 // When we are in a "blocking call", we process signals asynchronously
319 // (right when they arrive). In this context we do not expect to be
320 // executing any user/runtime code. The known interceptor sequence when
321 // this is not true is: pthread_join -> munmap(stack). It's fine
322 // to ignore munmap in this case -- we handle stack shadow separately.
323 thr->ignore_interceptors++;
327 thr->ignore_interceptors--;
328 atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
332 ThreadSignalContext *ctx;
335 TSAN_INTERCEPTOR(unsigned, sleep, unsigned sec) {
336 SCOPED_TSAN_INTERCEPTOR(sleep, sec);
337 unsigned res = BLOCK_REAL(sleep)(sec);
342 TSAN_INTERCEPTOR(int, usleep, long_t usec) {
343 SCOPED_TSAN_INTERCEPTOR(usleep, usec);
344 int res = BLOCK_REAL(usleep)(usec);
349 TSAN_INTERCEPTOR(int, nanosleep, void *req, void *rem) {
350 SCOPED_TSAN_INTERCEPTOR(nanosleep, req, rem);
351 int res = BLOCK_REAL(nanosleep)(req, rem);
356 // The sole reason tsan wraps atexit callbacks is to establish synchronization
357 // between callback setup and callback execution.
363 static void at_exit_wrapper(void *arg) {
364 ThreadState *thr = cur_thread();
366 Acquire(thr, pc, (uptr)arg);
367 AtExitCtx *ctx = (AtExitCtx*)arg;
368 ((void(*)(void *arg))ctx->f)(ctx->arg);
372 static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(),
373 void *arg, void *dso);
375 #if !SANITIZER_ANDROID
376 TSAN_INTERCEPTOR(int, atexit, void (*f)()) {
377 if (cur_thread()->in_symbolizer)
379 // We want to setup the atexit callback even if we are in ignored lib
381 SCOPED_INTERCEPTOR_RAW(atexit, f);
382 return setup_at_exit_wrapper(thr, pc, (void(*)())f, 0, 0);
386 TSAN_INTERCEPTOR(int, __cxa_atexit, void (*f)(void *a), void *arg, void *dso) {
387 if (cur_thread()->in_symbolizer)
389 SCOPED_TSAN_INTERCEPTOR(__cxa_atexit, f, arg, dso);
390 return setup_at_exit_wrapper(thr, pc, (void(*)())f, arg, dso);
393 static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(),
394 void *arg, void *dso) {
395 AtExitCtx *ctx = (AtExitCtx*)InternalAlloc(sizeof(AtExitCtx));
398 Release(thr, pc, (uptr)ctx);
399 // Memory allocation in __cxa_atexit will race with free during exit,
400 // because we do not see synchronization around atexit callback list.
401 ThreadIgnoreBegin(thr, pc);
402 int res = REAL(__cxa_atexit)(at_exit_wrapper, ctx, dso);
403 ThreadIgnoreEnd(thr, pc);
408 static void on_exit_wrapper(int status, void *arg) {
409 ThreadState *thr = cur_thread();
411 Acquire(thr, pc, (uptr)arg);
412 AtExitCtx *ctx = (AtExitCtx*)arg;
413 ((void(*)(int status, void *arg))ctx->f)(status, ctx->arg);
417 TSAN_INTERCEPTOR(int, on_exit, void(*f)(int, void*), void *arg) {
418 if (cur_thread()->in_symbolizer)
420 SCOPED_TSAN_INTERCEPTOR(on_exit, f, arg);
421 AtExitCtx *ctx = (AtExitCtx*)InternalAlloc(sizeof(AtExitCtx));
422 ctx->f = (void(*)())f;
424 Release(thr, pc, (uptr)ctx);
425 // Memory allocation in __cxa_atexit will race with free during exit,
426 // because we do not see synchronization around atexit callback list.
427 ThreadIgnoreBegin(thr, pc);
428 int res = REAL(on_exit)(on_exit_wrapper, ctx);
429 ThreadIgnoreEnd(thr, pc);
435 static void JmpBufGarbageCollect(ThreadState *thr, uptr sp) {
436 for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) {
437 JmpBuf *buf = &thr->jmp_bufs[i];
439 uptr sz = thr->jmp_bufs.Size();
440 internal_memcpy(buf, &thr->jmp_bufs[sz - 1], sizeof(*buf));
441 thr->jmp_bufs.PopBack();
447 static void SetJmp(ThreadState *thr, uptr sp, uptr mangled_sp) {
448 if (!thr->is_inited) // called from libc guts during bootstrap
451 JmpBufGarbageCollect(thr, sp);
453 JmpBuf *buf = thr->jmp_bufs.PushBack();
455 buf->mangled_sp = mangled_sp;
456 buf->shadow_stack_pos = thr->shadow_stack_pos;
457 ThreadSignalContext *sctx = SigCtx(thr);
458 buf->int_signal_send = sctx ? sctx->int_signal_send : 0;
459 buf->in_blocking_func = sctx ?
460 atomic_load(&sctx->in_blocking_func, memory_order_relaxed) :
462 buf->in_signal_handler = atomic_load(&thr->in_signal_handler,
463 memory_order_relaxed);
466 static void LongJmp(ThreadState *thr, uptr *env) {
468 uptr mangled_sp = env[0];
469 #elif SANITIZER_FREEBSD || SANITIZER_MAC
470 uptr mangled_sp = env[2];
471 #elif defined(SANITIZER_LINUX)
473 uptr mangled_sp = env[13];
474 # elif defined(__mips64)
475 uptr mangled_sp = env[1];
477 uptr mangled_sp = env[6];
480 // Find the saved buf by mangled_sp.
481 for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) {
482 JmpBuf *buf = &thr->jmp_bufs[i];
483 if (buf->mangled_sp == mangled_sp) {
484 CHECK_GE(thr->shadow_stack_pos, buf->shadow_stack_pos);
486 while (thr->shadow_stack_pos > buf->shadow_stack_pos)
488 ThreadSignalContext *sctx = SigCtx(thr);
490 sctx->int_signal_send = buf->int_signal_send;
491 atomic_store(&sctx->in_blocking_func, buf->in_blocking_func,
492 memory_order_relaxed);
494 atomic_store(&thr->in_signal_handler, buf->in_signal_handler,
495 memory_order_relaxed);
496 JmpBufGarbageCollect(thr, buf->sp - 1); // do not collect buf->sp
500 Printf("ThreadSanitizer: can't find longjmp buf\n");
504 // FIXME: put everything below into a common extern "C" block?
505 extern "C" void __tsan_setjmp(uptr sp, uptr mangled_sp) {
506 SetJmp(cur_thread(), sp, mangled_sp);
510 TSAN_INTERCEPTOR(int, setjmp, void *env);
511 TSAN_INTERCEPTOR(int, _setjmp, void *env);
512 TSAN_INTERCEPTOR(int, sigsetjmp, void *env);
513 #else // SANITIZER_MAC
514 // Not called. Merely to satisfy TSAN_INTERCEPT().
515 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
516 int __interceptor_setjmp(void *env);
517 extern "C" int __interceptor_setjmp(void *env) {
522 // FIXME: any reason to have a separate declaration?
523 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
524 int __interceptor__setjmp(void *env);
525 extern "C" int __interceptor__setjmp(void *env) {
530 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
531 int __interceptor_sigsetjmp(void *env);
532 extern "C" int __interceptor_sigsetjmp(void *env) {
537 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
538 int __interceptor___sigsetjmp(void *env);
539 extern "C" int __interceptor___sigsetjmp(void *env) {
544 extern "C" int setjmp(void *env);
545 extern "C" int _setjmp(void *env);
546 extern "C" int sigsetjmp(void *env);
547 extern "C" int __sigsetjmp(void *env);
548 DEFINE_REAL(int, setjmp, void *env)
549 DEFINE_REAL(int, _setjmp, void *env)
550 DEFINE_REAL(int, sigsetjmp, void *env)
551 DEFINE_REAL(int, __sigsetjmp, void *env)
552 #endif // SANITIZER_MAC
554 TSAN_INTERCEPTOR(void, longjmp, uptr *env, int val) {
555 // Note: if we call REAL(longjmp) in the context of ScopedInterceptor,
556 // bad things will happen. We will jump over ScopedInterceptor dtor and can
557 // leave thr->in_ignored_lib set.
559 SCOPED_INTERCEPTOR_RAW(longjmp, env, val);
561 LongJmp(cur_thread(), env);
562 REAL(longjmp)(env, val);
565 TSAN_INTERCEPTOR(void, siglongjmp, uptr *env, int val) {
567 SCOPED_INTERCEPTOR_RAW(siglongjmp, env, val);
569 LongJmp(cur_thread(), env);
570 REAL(siglongjmp)(env, val);
574 TSAN_INTERCEPTOR(void*, malloc, uptr size) {
575 if (cur_thread()->in_symbolizer)
576 return InternalAlloc(size);
579 SCOPED_INTERCEPTOR_RAW(malloc, size);
580 p = user_alloc(thr, pc, size);
582 invoke_malloc_hook(p, size);
586 TSAN_INTERCEPTOR(void*, __libc_memalign, uptr align, uptr sz) {
587 SCOPED_TSAN_INTERCEPTOR(__libc_memalign, align, sz);
588 return user_alloc(thr, pc, sz, align);
591 TSAN_INTERCEPTOR(void*, calloc, uptr size, uptr n) {
592 if (cur_thread()->in_symbolizer)
593 return InternalCalloc(size, n);
596 SCOPED_INTERCEPTOR_RAW(calloc, size, n);
597 p = user_calloc(thr, pc, size, n);
599 invoke_malloc_hook(p, n * size);
603 TSAN_INTERCEPTOR(void*, realloc, void *p, uptr size) {
604 if (cur_thread()->in_symbolizer)
605 return InternalRealloc(p, size);
609 SCOPED_INTERCEPTOR_RAW(realloc, p, size);
610 p = user_realloc(thr, pc, p, size);
612 invoke_malloc_hook(p, size);
616 TSAN_INTERCEPTOR(void, free, void *p) {
619 if (cur_thread()->in_symbolizer)
620 return InternalFree(p);
622 SCOPED_INTERCEPTOR_RAW(free, p);
623 user_free(thr, pc, p);
626 TSAN_INTERCEPTOR(void, cfree, void *p) {
629 if (cur_thread()->in_symbolizer)
630 return InternalFree(p);
632 SCOPED_INTERCEPTOR_RAW(cfree, p);
633 user_free(thr, pc, p);
636 TSAN_INTERCEPTOR(uptr, malloc_usable_size, void *p) {
637 SCOPED_INTERCEPTOR_RAW(malloc_usable_size, p);
638 return user_alloc_usable_size(p);
642 TSAN_INTERCEPTOR(char*, strcpy, char *dst, const char *src) { // NOLINT
643 SCOPED_TSAN_INTERCEPTOR(strcpy, dst, src); // NOLINT
644 uptr srclen = internal_strlen(src);
645 MemoryAccessRange(thr, pc, (uptr)dst, srclen + 1, true);
646 MemoryAccessRange(thr, pc, (uptr)src, srclen + 1, false);
647 return REAL(strcpy)(dst, src); // NOLINT
650 TSAN_INTERCEPTOR(char*, strncpy, char *dst, char *src, uptr n) {
651 SCOPED_TSAN_INTERCEPTOR(strncpy, dst, src, n);
652 uptr srclen = internal_strnlen(src, n);
653 MemoryAccessRange(thr, pc, (uptr)dst, n, true);
654 MemoryAccessRange(thr, pc, (uptr)src, min(srclen + 1, n), false);
655 return REAL(strncpy)(dst, src, n);
658 TSAN_INTERCEPTOR(char*, strdup, const char *str) {
659 SCOPED_TSAN_INTERCEPTOR(strdup, str);
660 // strdup will call malloc, so no instrumentation is required here.
661 return REAL(strdup)(str);
664 static bool fix_mmap_addr(void **addr, long_t sz, int flags) {
666 if (!IsAppMem((uptr)*addr) || !IsAppMem((uptr)*addr + sz - 1)) {
667 if (flags & MAP_FIXED) {
678 TSAN_INTERCEPTOR(void *, mmap, void *addr, SIZE_T sz, int prot, int flags,
680 SCOPED_TSAN_INTERCEPTOR(mmap, addr, sz, prot, flags, fd, off);
681 if (!fix_mmap_addr(&addr, sz, flags))
683 void *res = REAL(mmap)(addr, sz, prot, flags, fd, off);
684 if (res != MAP_FAILED) {
686 FdAccess(thr, pc, fd);
688 if (thr->ignore_reads_and_writes == 0)
689 MemoryRangeImitateWrite(thr, pc, (uptr)res, sz);
691 MemoryResetRange(thr, pc, (uptr)res, sz);
697 TSAN_INTERCEPTOR(void *, mmap64, void *addr, SIZE_T sz, int prot, int flags,
698 int fd, OFF64_T off) {
699 SCOPED_TSAN_INTERCEPTOR(mmap64, addr, sz, prot, flags, fd, off);
700 if (!fix_mmap_addr(&addr, sz, flags))
702 void *res = REAL(mmap64)(addr, sz, prot, flags, fd, off);
703 if (res != MAP_FAILED) {
705 FdAccess(thr, pc, fd);
707 if (thr->ignore_reads_and_writes == 0)
708 MemoryRangeImitateWrite(thr, pc, (uptr)res, sz);
710 MemoryResetRange(thr, pc, (uptr)res, sz);
714 #define TSAN_MAYBE_INTERCEPT_MMAP64 TSAN_INTERCEPT(mmap64)
716 #define TSAN_MAYBE_INTERCEPT_MMAP64
719 TSAN_INTERCEPTOR(int, munmap, void *addr, long_t sz) {
720 SCOPED_TSAN_INTERCEPTOR(munmap, addr, sz);
722 // If sz == 0, munmap will return EINVAL and don't unmap any memory.
723 DontNeedShadowFor((uptr)addr, sz);
724 ScopedGlobalProcessor sgp;
725 ctx->metamap.ResetRange(thr->proc(), (uptr)addr, (uptr)sz);
727 int res = REAL(munmap)(addr, sz);
732 TSAN_INTERCEPTOR(void*, memalign, uptr align, uptr sz) {
733 SCOPED_INTERCEPTOR_RAW(memalign, align, sz);
734 return user_alloc(thr, pc, sz, align);
736 #define TSAN_MAYBE_INTERCEPT_MEMALIGN TSAN_INTERCEPT(memalign)
738 #define TSAN_MAYBE_INTERCEPT_MEMALIGN
742 TSAN_INTERCEPTOR(void*, aligned_alloc, uptr align, uptr sz) {
743 SCOPED_INTERCEPTOR_RAW(memalign, align, sz);
744 return user_alloc(thr, pc, sz, align);
747 TSAN_INTERCEPTOR(void*, valloc, uptr sz) {
748 SCOPED_INTERCEPTOR_RAW(valloc, sz);
749 return user_alloc(thr, pc, sz, GetPageSizeCached());
754 TSAN_INTERCEPTOR(void*, pvalloc, uptr sz) {
755 SCOPED_INTERCEPTOR_RAW(pvalloc, sz);
756 sz = RoundUp(sz, GetPageSizeCached());
757 return user_alloc(thr, pc, sz, GetPageSizeCached());
759 #define TSAN_MAYBE_INTERCEPT_PVALLOC TSAN_INTERCEPT(pvalloc)
761 #define TSAN_MAYBE_INTERCEPT_PVALLOC
765 TSAN_INTERCEPTOR(int, posix_memalign, void **memptr, uptr align, uptr sz) {
766 SCOPED_INTERCEPTOR_RAW(posix_memalign, memptr, align, sz);
767 *memptr = user_alloc(thr, pc, sz, align);
772 // __cxa_guard_acquire and friends need to be intercepted in a special way -
773 // regular interceptors will break statically-linked libstdc++. Linux
774 // interceptors are especially defined as weak functions (so that they don't
775 // cause link errors when user defines them as well). So they silently
776 // auto-disable themselves when such symbol is already present in the binary. If
777 // we link libstdc++ statically, it will bring own __cxa_guard_acquire which
778 // will silently replace our interceptor. That's why on Linux we simply export
779 // these interceptors with INTERFACE_ATTRIBUTE.
780 // On OS X, we don't support statically linking, so we just use a regular
783 #define STDCXX_INTERCEPTOR TSAN_INTERCEPTOR
785 #define STDCXX_INTERCEPTOR(rettype, name, ...) \
786 extern "C" rettype INTERFACE_ATTRIBUTE name(__VA_ARGS__)
789 // Used in thread-safe function static initialization.
790 STDCXX_INTERCEPTOR(int, __cxa_guard_acquire, atomic_uint32_t *g) {
791 SCOPED_INTERCEPTOR_RAW(__cxa_guard_acquire, g);
793 u32 cmp = atomic_load(g, memory_order_acquire);
795 if (atomic_compare_exchange_strong(g, &cmp, 1<<16, memory_order_relaxed))
797 } else if (cmp == 1) {
798 Acquire(thr, pc, (uptr)g);
801 internal_sched_yield();
806 STDCXX_INTERCEPTOR(void, __cxa_guard_release, atomic_uint32_t *g) {
807 SCOPED_INTERCEPTOR_RAW(__cxa_guard_release, g);
808 Release(thr, pc, (uptr)g);
809 atomic_store(g, 1, memory_order_release);
812 STDCXX_INTERCEPTOR(void, __cxa_guard_abort, atomic_uint32_t *g) {
813 SCOPED_INTERCEPTOR_RAW(__cxa_guard_abort, g);
814 atomic_store(g, 0, memory_order_relaxed);
818 void DestroyThreadState() {
819 ThreadState *thr = cur_thread();
820 Processor *proc = thr->proc();
822 ProcUnwire(proc, thr);
824 ThreadSignalContext *sctx = thr->signal_ctx;
827 UnmapOrDie(sctx, sizeof(*sctx));
830 cur_thread_finalize();
832 } // namespace __tsan
835 static void thread_finalize(void *v) {
838 if (pthread_setspecific(g_thread_finalize_key, (void*)(iter - 1))) {
839 Printf("ThreadSanitizer: failed to set thread key\n");
844 DestroyThreadState();
850 void* (*callback)(void *arg);
852 atomic_uintptr_t tid;
855 extern "C" void *__tsan_thread_start_func(void *arg) {
856 ThreadParam *p = (ThreadParam*)arg;
857 void* (*callback)(void *arg) = p->callback;
858 void *param = p->param;
861 ThreadState *thr = cur_thread();
862 // Thread-local state is not initialized yet.
863 ScopedIgnoreInterceptors ignore;
865 ThreadIgnoreBegin(thr, 0);
866 if (pthread_setspecific(g_thread_finalize_key,
867 (void *)GetPthreadDestructorIterations())) {
868 Printf("ThreadSanitizer: failed to set thread key\n");
871 ThreadIgnoreEnd(thr, 0);
873 while ((tid = atomic_load(&p->tid, memory_order_acquire)) == 0)
874 internal_sched_yield();
875 Processor *proc = ProcCreate();
877 ThreadStart(thr, tid, GetTid(), /*workerthread*/ false);
878 atomic_store(&p->tid, 0, memory_order_release);
880 void *res = callback(param);
881 // Prevent the callback from being tail called,
882 // it mixes up stack traces.
883 volatile int foo = 42;
888 TSAN_INTERCEPTOR(int, pthread_create,
889 void *th, void *attr, void *(*callback)(void*), void * param) {
890 SCOPED_INTERCEPTOR_RAW(pthread_create, th, attr, callback, param);
891 if (ctx->after_multithreaded_fork) {
892 if (flags()->die_after_fork) {
893 Report("ThreadSanitizer: starting new threads after multi-threaded "
894 "fork is not supported. Dying (set die_after_fork=0 to override)\n");
897 VPrintf(1, "ThreadSanitizer: starting new threads after multi-threaded "
898 "fork is not supported (pid %d). Continuing because of "
899 "die_after_fork=0, but you are on your own\n", internal_getpid());
902 __sanitizer_pthread_attr_t myattr;
904 pthread_attr_init(&myattr);
908 REAL(pthread_attr_getdetachstate)(attr, &detached);
909 AdjustStackSize(attr);
912 p.callback = callback;
914 atomic_store(&p.tid, 0, memory_order_relaxed);
917 // Otherwise we see false positives in pthread stack manipulation.
918 ScopedIgnoreInterceptors ignore;
919 ThreadIgnoreBegin(thr, pc);
920 res = REAL(pthread_create)(th, attr, __tsan_thread_start_func, &p);
921 ThreadIgnoreEnd(thr, pc);
924 int tid = ThreadCreate(thr, pc, *(uptr*)th, IsStateDetached(detached));
926 // Synchronization on p.tid serves two purposes:
927 // 1. ThreadCreate must finish before the new thread starts.
928 // Otherwise the new thread can call pthread_detach, but the pthread_t
929 // identifier is not yet registered in ThreadRegistry by ThreadCreate.
930 // 2. ThreadStart must finish before this thread continues.
931 // Otherwise, this thread can call pthread_detach and reset thr->sync
932 // before the new thread got a chance to acquire from it in ThreadStart.
933 atomic_store(&p.tid, tid, memory_order_release);
934 while (atomic_load(&p.tid, memory_order_acquire) != 0)
935 internal_sched_yield();
938 pthread_attr_destroy(&myattr);
942 TSAN_INTERCEPTOR(int, pthread_join, void *th, void **ret) {
943 SCOPED_INTERCEPTOR_RAW(pthread_join, th, ret);
944 int tid = ThreadTid(thr, pc, (uptr)th);
945 ThreadIgnoreBegin(thr, pc);
946 int res = BLOCK_REAL(pthread_join)(th, ret);
947 ThreadIgnoreEnd(thr, pc);
949 ThreadJoin(thr, pc, tid);
954 DEFINE_REAL_PTHREAD_FUNCTIONS
956 TSAN_INTERCEPTOR(int, pthread_detach, void *th) {
957 SCOPED_TSAN_INTERCEPTOR(pthread_detach, th);
958 int tid = ThreadTid(thr, pc, (uptr)th);
959 int res = REAL(pthread_detach)(th);
961 ThreadDetach(thr, pc, tid);
967 // NPTL implementation of pthread_cond has 2 versions (2.2.5 and 2.3.2).
968 // pthread_cond_t has different size in the different versions.
969 // If call new REAL functions for old pthread_cond_t, they will corrupt memory
970 // after pthread_cond_t (old cond is smaller).
971 // If we call old REAL functions for new pthread_cond_t, we will lose some
972 // functionality (e.g. old functions do not support waiting against
974 // Proper handling would require to have 2 versions of interceptors as well.
975 // But this is messy, in particular requires linker scripts when sanitizer
976 // runtime is linked into a shared library.
977 // Instead we assume we don't have dynamic libraries built against old
978 // pthread (2.2.5 is dated by 2002). And provide legacy_pthread_cond flag
979 // that allows to work with old libraries (but this mode does not support
980 // some features, e.g. pthread_condattr_getpshared).
981 static void *init_cond(void *c, bool force = false) {
982 // sizeof(pthread_cond_t) >= sizeof(uptr) in both versions.
983 // So we allocate additional memory on the side large enough to hold
984 // any pthread_cond_t object. Always call new REAL functions, but pass
985 // the aux object to them.
986 // Note: the code assumes that PTHREAD_COND_INITIALIZER initializes
987 // first word of pthread_cond_t to zero.
988 // It's all relevant only for linux.
989 if (!common_flags()->legacy_pthread_cond)
991 atomic_uintptr_t *p = (atomic_uintptr_t*)c;
992 uptr cond = atomic_load(p, memory_order_acquire);
993 if (!force && cond != 0)
995 void *newcond = WRAP(malloc)(pthread_cond_t_sz);
996 internal_memset(newcond, 0, pthread_cond_t_sz);
997 if (atomic_compare_exchange_strong(p, &cond, (uptr)newcond,
998 memory_order_acq_rel))
1000 WRAP(free)(newcond);
1004 struct CondMutexUnlockCtx {
1005 ScopedInterceptor *si;
1011 static void cond_mutex_unlock(CondMutexUnlockCtx *arg) {
1012 // pthread_cond_wait interceptor has enabled async signal delivery
1013 // (see BlockingCall below). Disable async signals since we are running
1014 // tsan code. Also ScopedInterceptor and BlockingCall destructors won't run
1015 // since the thread is cancelled, so we have to manually execute them
1016 // (the thread still can run some user code due to pthread_cleanup_push).
1017 ThreadSignalContext *ctx = SigCtx(arg->thr);
1018 CHECK_EQ(atomic_load(&ctx->in_blocking_func, memory_order_relaxed), 1);
1019 atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
1020 MutexPostLock(arg->thr, arg->pc, (uptr)arg->m, MutexFlagDoPreLockOnPostLock);
1021 // Undo BlockingCall ctor effects.
1022 arg->thr->ignore_interceptors--;
1023 arg->si->~ScopedInterceptor();
1026 INTERCEPTOR(int, pthread_cond_init, void *c, void *a) {
1027 void *cond = init_cond(c, true);
1028 SCOPED_TSAN_INTERCEPTOR(pthread_cond_init, cond, a);
1029 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true);
1030 return REAL(pthread_cond_init)(cond, a);
1033 static int cond_wait(ThreadState *thr, uptr pc, ScopedInterceptor *si,
1034 int (*fn)(void *c, void *m, void *abstime), void *c,
1036 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1037 MutexUnlock(thr, pc, (uptr)m);
1038 CondMutexUnlockCtx arg = {si, thr, pc, m};
1040 // This ensures that we handle mutex lock even in case of pthread_cancel.
1041 // See test/tsan/cond_cancel.cc.
1043 // Enable signal delivery while the thread is blocked.
1044 BlockingCall bc(thr);
1045 res = call_pthread_cancel_with_cleanup(
1046 fn, c, m, t, (void (*)(void *arg))cond_mutex_unlock, &arg);
1048 if (res == errno_EOWNERDEAD) MutexRepair(thr, pc, (uptr)m);
1049 MutexPostLock(thr, pc, (uptr)m, MutexFlagDoPreLockOnPostLock);
1053 INTERCEPTOR(int, pthread_cond_wait, void *c, void *m) {
1054 void *cond = init_cond(c);
1055 SCOPED_TSAN_INTERCEPTOR(pthread_cond_wait, cond, m);
1056 return cond_wait(thr, pc, &si, (int (*)(void *c, void *m, void *abstime))REAL(
1061 INTERCEPTOR(int, pthread_cond_timedwait, void *c, void *m, void *abstime) {
1062 void *cond = init_cond(c);
1063 SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait, cond, m, abstime);
1064 return cond_wait(thr, pc, &si, REAL(pthread_cond_timedwait), cond, m,
1069 INTERCEPTOR(int, pthread_cond_timedwait_relative_np, void *c, void *m,
1071 void *cond = init_cond(c);
1072 SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait_relative_np, cond, m, reltime);
1073 return cond_wait(thr, pc, &si, REAL(pthread_cond_timedwait_relative_np), cond,
1078 INTERCEPTOR(int, pthread_cond_signal, void *c) {
1079 void *cond = init_cond(c);
1080 SCOPED_TSAN_INTERCEPTOR(pthread_cond_signal, cond);
1081 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1082 return REAL(pthread_cond_signal)(cond);
1085 INTERCEPTOR(int, pthread_cond_broadcast, void *c) {
1086 void *cond = init_cond(c);
1087 SCOPED_TSAN_INTERCEPTOR(pthread_cond_broadcast, cond);
1088 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1089 return REAL(pthread_cond_broadcast)(cond);
1092 INTERCEPTOR(int, pthread_cond_destroy, void *c) {
1093 void *cond = init_cond(c);
1094 SCOPED_TSAN_INTERCEPTOR(pthread_cond_destroy, cond);
1095 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true);
1096 int res = REAL(pthread_cond_destroy)(cond);
1097 if (common_flags()->legacy_pthread_cond) {
1098 // Free our aux cond and zero the pointer to not leave dangling pointers.
1100 atomic_store((atomic_uintptr_t*)c, 0, memory_order_relaxed);
1105 TSAN_INTERCEPTOR(int, pthread_mutex_init, void *m, void *a) {
1106 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_init, m, a);
1107 int res = REAL(pthread_mutex_init)(m, a);
1112 if (REAL(pthread_mutexattr_gettype)(a, &type) == 0)
1113 if (type == PTHREAD_MUTEX_RECURSIVE ||
1114 type == PTHREAD_MUTEX_RECURSIVE_NP)
1115 flagz |= MutexFlagWriteReentrant;
1117 MutexCreate(thr, pc, (uptr)m, flagz);
1122 TSAN_INTERCEPTOR(int, pthread_mutex_destroy, void *m) {
1123 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_destroy, m);
1124 int res = REAL(pthread_mutex_destroy)(m);
1125 if (res == 0 || res == EBUSY) {
1126 MutexDestroy(thr, pc, (uptr)m);
1131 TSAN_INTERCEPTOR(int, pthread_mutex_trylock, void *m) {
1132 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_trylock, m);
1133 int res = REAL(pthread_mutex_trylock)(m);
1134 if (res == EOWNERDEAD)
1135 MutexRepair(thr, pc, (uptr)m);
1136 if (res == 0 || res == EOWNERDEAD)
1137 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1142 TSAN_INTERCEPTOR(int, pthread_mutex_timedlock, void *m, void *abstime) {
1143 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_timedlock, m, abstime);
1144 int res = REAL(pthread_mutex_timedlock)(m, abstime);
1146 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1153 TSAN_INTERCEPTOR(int, pthread_spin_init, void *m, int pshared) {
1154 SCOPED_TSAN_INTERCEPTOR(pthread_spin_init, m, pshared);
1155 int res = REAL(pthread_spin_init)(m, pshared);
1157 MutexCreate(thr, pc, (uptr)m);
1162 TSAN_INTERCEPTOR(int, pthread_spin_destroy, void *m) {
1163 SCOPED_TSAN_INTERCEPTOR(pthread_spin_destroy, m);
1164 int res = REAL(pthread_spin_destroy)(m);
1166 MutexDestroy(thr, pc, (uptr)m);
1171 TSAN_INTERCEPTOR(int, pthread_spin_lock, void *m) {
1172 SCOPED_TSAN_INTERCEPTOR(pthread_spin_lock, m);
1173 MutexPreLock(thr, pc, (uptr)m);
1174 int res = REAL(pthread_spin_lock)(m);
1176 MutexPostLock(thr, pc, (uptr)m);
1181 TSAN_INTERCEPTOR(int, pthread_spin_trylock, void *m) {
1182 SCOPED_TSAN_INTERCEPTOR(pthread_spin_trylock, m);
1183 int res = REAL(pthread_spin_trylock)(m);
1185 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1190 TSAN_INTERCEPTOR(int, pthread_spin_unlock, void *m) {
1191 SCOPED_TSAN_INTERCEPTOR(pthread_spin_unlock, m);
1192 MutexUnlock(thr, pc, (uptr)m);
1193 int res = REAL(pthread_spin_unlock)(m);
1198 TSAN_INTERCEPTOR(int, pthread_rwlock_init, void *m, void *a) {
1199 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_init, m, a);
1200 int res = REAL(pthread_rwlock_init)(m, a);
1202 MutexCreate(thr, pc, (uptr)m);
1207 TSAN_INTERCEPTOR(int, pthread_rwlock_destroy, void *m) {
1208 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_destroy, m);
1209 int res = REAL(pthread_rwlock_destroy)(m);
1211 MutexDestroy(thr, pc, (uptr)m);
1216 TSAN_INTERCEPTOR(int, pthread_rwlock_rdlock, void *m) {
1217 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_rdlock, m);
1218 MutexPreReadLock(thr, pc, (uptr)m);
1219 int res = REAL(pthread_rwlock_rdlock)(m);
1221 MutexPostReadLock(thr, pc, (uptr)m);
1226 TSAN_INTERCEPTOR(int, pthread_rwlock_tryrdlock, void *m) {
1227 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_tryrdlock, m);
1228 int res = REAL(pthread_rwlock_tryrdlock)(m);
1230 MutexPostReadLock(thr, pc, (uptr)m, MutexFlagTryLock);
1236 TSAN_INTERCEPTOR(int, pthread_rwlock_timedrdlock, void *m, void *abstime) {
1237 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedrdlock, m, abstime);
1238 int res = REAL(pthread_rwlock_timedrdlock)(m, abstime);
1240 MutexPostReadLock(thr, pc, (uptr)m);
1246 TSAN_INTERCEPTOR(int, pthread_rwlock_wrlock, void *m) {
1247 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_wrlock, m);
1248 MutexPreLock(thr, pc, (uptr)m);
1249 int res = REAL(pthread_rwlock_wrlock)(m);
1251 MutexPostLock(thr, pc, (uptr)m);
1256 TSAN_INTERCEPTOR(int, pthread_rwlock_trywrlock, void *m) {
1257 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_trywrlock, m);
1258 int res = REAL(pthread_rwlock_trywrlock)(m);
1260 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1266 TSAN_INTERCEPTOR(int, pthread_rwlock_timedwrlock, void *m, void *abstime) {
1267 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedwrlock, m, abstime);
1268 int res = REAL(pthread_rwlock_timedwrlock)(m, abstime);
1270 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1276 TSAN_INTERCEPTOR(int, pthread_rwlock_unlock, void *m) {
1277 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_unlock, m);
1278 MutexReadOrWriteUnlock(thr, pc, (uptr)m);
1279 int res = REAL(pthread_rwlock_unlock)(m);
1284 TSAN_INTERCEPTOR(int, pthread_barrier_init, void *b, void *a, unsigned count) {
1285 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_init, b, a, count);
1286 MemoryWrite(thr, pc, (uptr)b, kSizeLog1);
1287 int res = REAL(pthread_barrier_init)(b, a, count);
1291 TSAN_INTERCEPTOR(int, pthread_barrier_destroy, void *b) {
1292 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_destroy, b);
1293 MemoryWrite(thr, pc, (uptr)b, kSizeLog1);
1294 int res = REAL(pthread_barrier_destroy)(b);
1298 TSAN_INTERCEPTOR(int, pthread_barrier_wait, void *b) {
1299 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_wait, b);
1300 Release(thr, pc, (uptr)b);
1301 MemoryRead(thr, pc, (uptr)b, kSizeLog1);
1302 int res = REAL(pthread_barrier_wait)(b);
1303 MemoryRead(thr, pc, (uptr)b, kSizeLog1);
1304 if (res == 0 || res == PTHREAD_BARRIER_SERIAL_THREAD) {
1305 Acquire(thr, pc, (uptr)b);
1311 TSAN_INTERCEPTOR(int, pthread_once, void *o, void (*f)()) {
1312 SCOPED_INTERCEPTOR_RAW(pthread_once, o, f);
1313 if (o == 0 || f == 0)
1317 a = static_cast<atomic_uint32_t*>(o);
1318 else // On OS X, pthread_once_t has a header with a long-sized signature.
1319 a = static_cast<atomic_uint32_t*>((void *)((char *)o + sizeof(long_t)));
1320 u32 v = atomic_load(a, memory_order_acquire);
1321 if (v == 0 && atomic_compare_exchange_strong(a, &v, 1,
1322 memory_order_relaxed)) {
1324 if (!thr->in_ignored_lib)
1325 Release(thr, pc, (uptr)o);
1326 atomic_store(a, 2, memory_order_release);
1329 internal_sched_yield();
1330 v = atomic_load(a, memory_order_acquire);
1332 if (!thr->in_ignored_lib)
1333 Acquire(thr, pc, (uptr)o);
1338 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1339 TSAN_INTERCEPTOR(int, __fxstat, int version, int fd, void *buf) {
1340 SCOPED_TSAN_INTERCEPTOR(__fxstat, version, fd, buf);
1342 FdAccess(thr, pc, fd);
1343 return REAL(__fxstat)(version, fd, buf);
1345 #define TSAN_MAYBE_INTERCEPT___FXSTAT TSAN_INTERCEPT(__fxstat)
1347 #define TSAN_MAYBE_INTERCEPT___FXSTAT
1350 TSAN_INTERCEPTOR(int, fstat, int fd, void *buf) {
1351 #if SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_ANDROID
1352 SCOPED_TSAN_INTERCEPTOR(fstat, fd, buf);
1354 FdAccess(thr, pc, fd);
1355 return REAL(fstat)(fd, buf);
1357 SCOPED_TSAN_INTERCEPTOR(__fxstat, 0, fd, buf);
1359 FdAccess(thr, pc, fd);
1360 return REAL(__fxstat)(0, fd, buf);
1364 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1365 TSAN_INTERCEPTOR(int, __fxstat64, int version, int fd, void *buf) {
1366 SCOPED_TSAN_INTERCEPTOR(__fxstat64, version, fd, buf);
1368 FdAccess(thr, pc, fd);
1369 return REAL(__fxstat64)(version, fd, buf);
1371 #define TSAN_MAYBE_INTERCEPT___FXSTAT64 TSAN_INTERCEPT(__fxstat64)
1373 #define TSAN_MAYBE_INTERCEPT___FXSTAT64
1376 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1377 TSAN_INTERCEPTOR(int, fstat64, int fd, void *buf) {
1378 SCOPED_TSAN_INTERCEPTOR(__fxstat64, 0, fd, buf);
1380 FdAccess(thr, pc, fd);
1381 return REAL(__fxstat64)(0, fd, buf);
1383 #define TSAN_MAYBE_INTERCEPT_FSTAT64 TSAN_INTERCEPT(fstat64)
1385 #define TSAN_MAYBE_INTERCEPT_FSTAT64
1388 TSAN_INTERCEPTOR(int, open, const char *name, int flags, int mode) {
1389 SCOPED_TSAN_INTERCEPTOR(open, name, flags, mode);
1390 READ_STRING(thr, pc, name, 0);
1391 int fd = REAL(open)(name, flags, mode);
1393 FdFileCreate(thr, pc, fd);
1398 TSAN_INTERCEPTOR(int, open64, const char *name, int flags, int mode) {
1399 SCOPED_TSAN_INTERCEPTOR(open64, name, flags, mode);
1400 READ_STRING(thr, pc, name, 0);
1401 int fd = REAL(open64)(name, flags, mode);
1403 FdFileCreate(thr, pc, fd);
1406 #define TSAN_MAYBE_INTERCEPT_OPEN64 TSAN_INTERCEPT(open64)
1408 #define TSAN_MAYBE_INTERCEPT_OPEN64
1411 TSAN_INTERCEPTOR(int, creat, const char *name, int mode) {
1412 SCOPED_TSAN_INTERCEPTOR(creat, name, mode);
1413 READ_STRING(thr, pc, name, 0);
1414 int fd = REAL(creat)(name, mode);
1416 FdFileCreate(thr, pc, fd);
1421 TSAN_INTERCEPTOR(int, creat64, const char *name, int mode) {
1422 SCOPED_TSAN_INTERCEPTOR(creat64, name, mode);
1423 READ_STRING(thr, pc, name, 0);
1424 int fd = REAL(creat64)(name, mode);
1426 FdFileCreate(thr, pc, fd);
1429 #define TSAN_MAYBE_INTERCEPT_CREAT64 TSAN_INTERCEPT(creat64)
1431 #define TSAN_MAYBE_INTERCEPT_CREAT64
1434 TSAN_INTERCEPTOR(int, dup, int oldfd) {
1435 SCOPED_TSAN_INTERCEPTOR(dup, oldfd);
1436 int newfd = REAL(dup)(oldfd);
1437 if (oldfd >= 0 && newfd >= 0 && newfd != oldfd)
1438 FdDup(thr, pc, oldfd, newfd, true);
1442 TSAN_INTERCEPTOR(int, dup2, int oldfd, int newfd) {
1443 SCOPED_TSAN_INTERCEPTOR(dup2, oldfd, newfd);
1444 int newfd2 = REAL(dup2)(oldfd, newfd);
1445 if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd)
1446 FdDup(thr, pc, oldfd, newfd2, false);
1451 TSAN_INTERCEPTOR(int, dup3, int oldfd, int newfd, int flags) {
1452 SCOPED_TSAN_INTERCEPTOR(dup3, oldfd, newfd, flags);
1453 int newfd2 = REAL(dup3)(oldfd, newfd, flags);
1454 if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd)
1455 FdDup(thr, pc, oldfd, newfd2, false);
1461 TSAN_INTERCEPTOR(int, eventfd, unsigned initval, int flags) {
1462 SCOPED_TSAN_INTERCEPTOR(eventfd, initval, flags);
1463 int fd = REAL(eventfd)(initval, flags);
1465 FdEventCreate(thr, pc, fd);
1468 #define TSAN_MAYBE_INTERCEPT_EVENTFD TSAN_INTERCEPT(eventfd)
1470 #define TSAN_MAYBE_INTERCEPT_EVENTFD
1474 TSAN_INTERCEPTOR(int, signalfd, int fd, void *mask, int flags) {
1475 SCOPED_TSAN_INTERCEPTOR(signalfd, fd, mask, flags);
1477 FdClose(thr, pc, fd);
1478 fd = REAL(signalfd)(fd, mask, flags);
1480 FdSignalCreate(thr, pc, fd);
1483 #define TSAN_MAYBE_INTERCEPT_SIGNALFD TSAN_INTERCEPT(signalfd)
1485 #define TSAN_MAYBE_INTERCEPT_SIGNALFD
1489 TSAN_INTERCEPTOR(int, inotify_init, int fake) {
1490 SCOPED_TSAN_INTERCEPTOR(inotify_init, fake);
1491 int fd = REAL(inotify_init)(fake);
1493 FdInotifyCreate(thr, pc, fd);
1496 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT TSAN_INTERCEPT(inotify_init)
1498 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT
1502 TSAN_INTERCEPTOR(int, inotify_init1, int flags) {
1503 SCOPED_TSAN_INTERCEPTOR(inotify_init1, flags);
1504 int fd = REAL(inotify_init1)(flags);
1506 FdInotifyCreate(thr, pc, fd);
1509 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1 TSAN_INTERCEPT(inotify_init1)
1511 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1
1514 TSAN_INTERCEPTOR(int, socket, int domain, int type, int protocol) {
1515 SCOPED_TSAN_INTERCEPTOR(socket, domain, type, protocol);
1516 int fd = REAL(socket)(domain, type, protocol);
1518 FdSocketCreate(thr, pc, fd);
1522 TSAN_INTERCEPTOR(int, socketpair, int domain, int type, int protocol, int *fd) {
1523 SCOPED_TSAN_INTERCEPTOR(socketpair, domain, type, protocol, fd);
1524 int res = REAL(socketpair)(domain, type, protocol, fd);
1525 if (res == 0 && fd[0] >= 0 && fd[1] >= 0)
1526 FdPipeCreate(thr, pc, fd[0], fd[1]);
1530 TSAN_INTERCEPTOR(int, connect, int fd, void *addr, unsigned addrlen) {
1531 SCOPED_TSAN_INTERCEPTOR(connect, fd, addr, addrlen);
1532 FdSocketConnecting(thr, pc, fd);
1533 int res = REAL(connect)(fd, addr, addrlen);
1534 if (res == 0 && fd >= 0)
1535 FdSocketConnect(thr, pc, fd);
1539 TSAN_INTERCEPTOR(int, bind, int fd, void *addr, unsigned addrlen) {
1540 SCOPED_TSAN_INTERCEPTOR(bind, fd, addr, addrlen);
1541 int res = REAL(bind)(fd, addr, addrlen);
1542 if (fd > 0 && res == 0)
1543 FdAccess(thr, pc, fd);
1547 TSAN_INTERCEPTOR(int, listen, int fd, int backlog) {
1548 SCOPED_TSAN_INTERCEPTOR(listen, fd, backlog);
1549 int res = REAL(listen)(fd, backlog);
1550 if (fd > 0 && res == 0)
1551 FdAccess(thr, pc, fd);
1555 TSAN_INTERCEPTOR(int, close, int fd) {
1556 SCOPED_TSAN_INTERCEPTOR(close, fd);
1558 FdClose(thr, pc, fd);
1559 return REAL(close)(fd);
1563 TSAN_INTERCEPTOR(int, __close, int fd) {
1564 SCOPED_TSAN_INTERCEPTOR(__close, fd);
1566 FdClose(thr, pc, fd);
1567 return REAL(__close)(fd);
1569 #define TSAN_MAYBE_INTERCEPT___CLOSE TSAN_INTERCEPT(__close)
1571 #define TSAN_MAYBE_INTERCEPT___CLOSE
1575 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1576 TSAN_INTERCEPTOR(void, __res_iclose, void *state, bool free_addr) {
1577 SCOPED_TSAN_INTERCEPTOR(__res_iclose, state, free_addr);
1579 int cnt = ExtractResolvFDs(state, fds, ARRAY_SIZE(fds));
1580 for (int i = 0; i < cnt; i++) {
1582 FdClose(thr, pc, fds[i]);
1584 REAL(__res_iclose)(state, free_addr);
1586 #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE TSAN_INTERCEPT(__res_iclose)
1588 #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE
1591 TSAN_INTERCEPTOR(int, pipe, int *pipefd) {
1592 SCOPED_TSAN_INTERCEPTOR(pipe, pipefd);
1593 int res = REAL(pipe)(pipefd);
1594 if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0)
1595 FdPipeCreate(thr, pc, pipefd[0], pipefd[1]);
1600 TSAN_INTERCEPTOR(int, pipe2, int *pipefd, int flags) {
1601 SCOPED_TSAN_INTERCEPTOR(pipe2, pipefd, flags);
1602 int res = REAL(pipe2)(pipefd, flags);
1603 if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0)
1604 FdPipeCreate(thr, pc, pipefd[0], pipefd[1]);
1609 TSAN_INTERCEPTOR(int, unlink, char *path) {
1610 SCOPED_TSAN_INTERCEPTOR(unlink, path);
1611 Release(thr, pc, File2addr(path));
1612 int res = REAL(unlink)(path);
1616 TSAN_INTERCEPTOR(void*, tmpfile, int fake) {
1617 SCOPED_TSAN_INTERCEPTOR(tmpfile, fake);
1618 void *res = REAL(tmpfile)(fake);
1620 int fd = fileno_unlocked(res);
1622 FdFileCreate(thr, pc, fd);
1628 TSAN_INTERCEPTOR(void*, tmpfile64, int fake) {
1629 SCOPED_TSAN_INTERCEPTOR(tmpfile64, fake);
1630 void *res = REAL(tmpfile64)(fake);
1632 int fd = fileno_unlocked(res);
1634 FdFileCreate(thr, pc, fd);
1638 #define TSAN_MAYBE_INTERCEPT_TMPFILE64 TSAN_INTERCEPT(tmpfile64)
1640 #define TSAN_MAYBE_INTERCEPT_TMPFILE64
1643 static void FlushStreams() {
1644 // Flushing all the streams here may freeze the process if a child thread is
1645 // performing file stream operations at the same time.
1646 REAL(fflush)(stdout);
1647 REAL(fflush)(stderr);
1650 TSAN_INTERCEPTOR(void, abort, int fake) {
1651 SCOPED_TSAN_INTERCEPTOR(abort, fake);
1656 TSAN_INTERCEPTOR(int, puts, const char *s) {
1657 SCOPED_TSAN_INTERCEPTOR(puts, s);
1658 MemoryAccessRange(thr, pc, (uptr)s, internal_strlen(s), false);
1659 return REAL(puts)(s);
1662 TSAN_INTERCEPTOR(int, rmdir, char *path) {
1663 SCOPED_TSAN_INTERCEPTOR(rmdir, path);
1664 Release(thr, pc, Dir2addr(path));
1665 int res = REAL(rmdir)(path);
1669 TSAN_INTERCEPTOR(int, closedir, void *dirp) {
1670 SCOPED_TSAN_INTERCEPTOR(closedir, dirp);
1672 int fd = dirfd(dirp);
1673 FdClose(thr, pc, fd);
1675 return REAL(closedir)(dirp);
1679 TSAN_INTERCEPTOR(int, epoll_create, int size) {
1680 SCOPED_TSAN_INTERCEPTOR(epoll_create, size);
1681 int fd = REAL(epoll_create)(size);
1683 FdPollCreate(thr, pc, fd);
1687 TSAN_INTERCEPTOR(int, epoll_create1, int flags) {
1688 SCOPED_TSAN_INTERCEPTOR(epoll_create1, flags);
1689 int fd = REAL(epoll_create1)(flags);
1691 FdPollCreate(thr, pc, fd);
1695 TSAN_INTERCEPTOR(int, epoll_ctl, int epfd, int op, int fd, void *ev) {
1696 SCOPED_TSAN_INTERCEPTOR(epoll_ctl, epfd, op, fd, ev);
1698 FdAccess(thr, pc, epfd);
1699 if (epfd >= 0 && fd >= 0)
1700 FdAccess(thr, pc, fd);
1701 if (op == EPOLL_CTL_ADD && epfd >= 0)
1702 FdRelease(thr, pc, epfd);
1703 int res = REAL(epoll_ctl)(epfd, op, fd, ev);
1707 TSAN_INTERCEPTOR(int, epoll_wait, int epfd, void *ev, int cnt, int timeout) {
1708 SCOPED_TSAN_INTERCEPTOR(epoll_wait, epfd, ev, cnt, timeout);
1710 FdAccess(thr, pc, epfd);
1711 int res = BLOCK_REAL(epoll_wait)(epfd, ev, cnt, timeout);
1712 if (res > 0 && epfd >= 0)
1713 FdAcquire(thr, pc, epfd);
1717 TSAN_INTERCEPTOR(int, epoll_pwait, int epfd, void *ev, int cnt, int timeout,
1719 SCOPED_TSAN_INTERCEPTOR(epoll_pwait, epfd, ev, cnt, timeout, sigmask);
1721 FdAccess(thr, pc, epfd);
1722 int res = BLOCK_REAL(epoll_pwait)(epfd, ev, cnt, timeout, sigmask);
1723 if (res > 0 && epfd >= 0)
1724 FdAcquire(thr, pc, epfd);
1728 #define TSAN_MAYBE_INTERCEPT_EPOLL \
1729 TSAN_INTERCEPT(epoll_create); \
1730 TSAN_INTERCEPT(epoll_create1); \
1731 TSAN_INTERCEPT(epoll_ctl); \
1732 TSAN_INTERCEPT(epoll_wait); \
1733 TSAN_INTERCEPT(epoll_pwait)
1735 #define TSAN_MAYBE_INTERCEPT_EPOLL
1738 // The following functions are intercepted merely to process pending signals.
1739 // If program blocks signal X, we must deliver the signal before the function
1740 // returns. Similarly, if program unblocks a signal (or returns from sigsuspend)
1741 // it's better to deliver the signal straight away.
1742 TSAN_INTERCEPTOR(int, sigsuspend, const __sanitizer_sigset_t *mask) {
1743 SCOPED_TSAN_INTERCEPTOR(sigsuspend, mask);
1744 return REAL(sigsuspend)(mask);
1747 TSAN_INTERCEPTOR(int, sigblock, int mask) {
1748 SCOPED_TSAN_INTERCEPTOR(sigblock, mask);
1749 return REAL(sigblock)(mask);
1752 TSAN_INTERCEPTOR(int, sigsetmask, int mask) {
1753 SCOPED_TSAN_INTERCEPTOR(sigsetmask, mask);
1754 return REAL(sigsetmask)(mask);
1757 TSAN_INTERCEPTOR(int, pthread_sigmask, int how, const __sanitizer_sigset_t *set,
1758 __sanitizer_sigset_t *oldset) {
1759 SCOPED_TSAN_INTERCEPTOR(pthread_sigmask, how, set, oldset);
1760 return REAL(pthread_sigmask)(how, set, oldset);
1765 static void CallUserSignalHandler(ThreadState *thr, bool sync, bool acquire,
1766 bool sigact, int sig, my_siginfo_t *info, void *uctx) {
1768 Acquire(thr, 0, (uptr)&sigactions[sig]);
1769 // Signals are generally asynchronous, so if we receive a signals when
1770 // ignores are enabled we should disable ignores. This is critical for sync
1771 // and interceptors, because otherwise we can miss syncronization and report
1773 int ignore_reads_and_writes = thr->ignore_reads_and_writes;
1774 int ignore_interceptors = thr->ignore_interceptors;
1775 int ignore_sync = thr->ignore_sync;
1776 if (!ctx->after_multithreaded_fork) {
1777 thr->ignore_reads_and_writes = 0;
1778 thr->fast_state.ClearIgnoreBit();
1779 thr->ignore_interceptors = 0;
1780 thr->ignore_sync = 0;
1782 // Ensure that the handler does not spoil errno.
1783 const int saved_errno = errno;
1785 // This code races with sigaction. Be careful to not read sa_sigaction twice.
1786 // Also need to remember pc for reporting before the call,
1787 // because the handler can reset it.
1788 volatile uptr pc = sigact ?
1789 (uptr)sigactions[sig].sa_sigaction :
1790 (uptr)sigactions[sig].sa_handler;
1791 if (pc != (uptr)SIG_DFL && pc != (uptr)SIG_IGN) {
1793 ((sigactionhandler_t)pc)(sig, info, uctx);
1795 ((sighandler_t)pc)(sig);
1797 if (!ctx->after_multithreaded_fork) {
1798 thr->ignore_reads_and_writes = ignore_reads_and_writes;
1799 if (ignore_reads_and_writes)
1800 thr->fast_state.SetIgnoreBit();
1801 thr->ignore_interceptors = ignore_interceptors;
1802 thr->ignore_sync = ignore_sync;
1804 // We do not detect errno spoiling for SIGTERM,
1805 // because some SIGTERM handlers do spoil errno but reraise SIGTERM,
1806 // tsan reports false positive in such case.
1807 // It's difficult to properly detect this situation (reraise),
1808 // because in async signal processing case (when handler is called directly
1809 // from rtl_generic_sighandler) we have not yet received the reraised
1810 // signal; and it looks too fragile to intercept all ways to reraise a signal.
1811 if (flags()->report_bugs && !sync && sig != SIGTERM && errno != 99) {
1812 VarSizeStackTrace stack;
1813 // StackTrace::GetNestInstructionPc(pc) is used because return address is
1814 // expected, OutputReport() will undo this.
1815 ObtainCurrentStack(thr, StackTrace::GetNextInstructionPc(pc), &stack);
1816 ThreadRegistryLock l(ctx->thread_registry);
1817 ScopedReport rep(ReportTypeErrnoInSignal);
1818 if (!IsFiredSuppression(ctx, ReportTypeErrnoInSignal, stack)) {
1819 rep.AddStack(stack, true);
1820 OutputReport(thr, rep);
1823 errno = saved_errno;
1826 void ProcessPendingSignals(ThreadState *thr) {
1827 ThreadSignalContext *sctx = SigCtx(thr);
1829 atomic_load(&sctx->have_pending_signals, memory_order_relaxed) == 0)
1831 atomic_store(&sctx->have_pending_signals, 0, memory_order_relaxed);
1832 atomic_fetch_add(&thr->in_signal_handler, 1, memory_order_relaxed);
1833 internal_sigfillset(&sctx->emptyset);
1834 int res = REAL(pthread_sigmask)(SIG_SETMASK, &sctx->emptyset, &sctx->oldset);
1836 for (int sig = 0; sig < kSigCount; sig++) {
1837 SignalDesc *signal = &sctx->pending_signals[sig];
1838 if (signal->armed) {
1839 signal->armed = false;
1840 CallUserSignalHandler(thr, false, true, signal->sigaction, sig,
1841 &signal->siginfo, &signal->ctx);
1844 res = REAL(pthread_sigmask)(SIG_SETMASK, &sctx->oldset, 0);
1846 atomic_fetch_add(&thr->in_signal_handler, -1, memory_order_relaxed);
1849 } // namespace __tsan
1851 static bool is_sync_signal(ThreadSignalContext *sctx, int sig) {
1852 return sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
1853 sig == SIGABRT || sig == SIGFPE || sig == SIGPIPE || sig == SIGSYS ||
1854 // If we are sending signal to ourselves, we must process it now.
1855 (sctx && sig == sctx->int_signal_send);
1858 void ALWAYS_INLINE rtl_generic_sighandler(bool sigact, int sig,
1859 my_siginfo_t *info, void *ctx) {
1860 ThreadState *thr = cur_thread();
1861 ThreadSignalContext *sctx = SigCtx(thr);
1862 if (sig < 0 || sig >= kSigCount) {
1863 VPrintf(1, "ThreadSanitizer: ignoring signal %d\n", sig);
1866 // Don't mess with synchronous signals.
1867 const bool sync = is_sync_signal(sctx, sig);
1869 // If we are in blocking function, we can safely process it now
1870 // (but check if we are in a recursive interceptor,
1871 // i.e. pthread_join()->munmap()).
1872 (sctx && atomic_load(&sctx->in_blocking_func, memory_order_relaxed))) {
1873 atomic_fetch_add(&thr->in_signal_handler, 1, memory_order_relaxed);
1874 if (sctx && atomic_load(&sctx->in_blocking_func, memory_order_relaxed)) {
1875 atomic_store(&sctx->in_blocking_func, 0, memory_order_relaxed);
1876 CallUserSignalHandler(thr, sync, true, sigact, sig, info, ctx);
1877 atomic_store(&sctx->in_blocking_func, 1, memory_order_relaxed);
1879 // Be very conservative with when we do acquire in this case.
1880 // It's unsafe to do acquire in async handlers, because ThreadState
1881 // can be in inconsistent state.
1882 // SIGSYS looks relatively safe -- it's synchronous and can actually
1883 // need some global state.
1884 bool acq = (sig == SIGSYS);
1885 CallUserSignalHandler(thr, sync, acq, sigact, sig, info, ctx);
1887 atomic_fetch_add(&thr->in_signal_handler, -1, memory_order_relaxed);
1893 SignalDesc *signal = &sctx->pending_signals[sig];
1894 if (signal->armed == false) {
1895 signal->armed = true;
1896 signal->sigaction = sigact;
1898 internal_memcpy(&signal->siginfo, info, sizeof(*info));
1900 internal_memcpy(&signal->ctx, ctx, sizeof(signal->ctx));
1901 atomic_store(&sctx->have_pending_signals, 1, memory_order_relaxed);
1905 static void rtl_sighandler(int sig) {
1906 rtl_generic_sighandler(false, sig, 0, 0);
1909 static void rtl_sigaction(int sig, my_siginfo_t *info, void *ctx) {
1910 rtl_generic_sighandler(true, sig, info, ctx);
1913 TSAN_INTERCEPTOR(int, sigaction, int sig, sigaction_t *act, sigaction_t *old) {
1914 // Note: if we call REAL(sigaction) directly for any reason without proxying
1915 // the signal handler through rtl_sigaction, very bad things will happen.
1916 // The handler will run synchronously and corrupt tsan per-thread state.
1917 SCOPED_INTERCEPTOR_RAW(sigaction, sig, act, old);
1919 internal_memcpy(old, &sigactions[sig], sizeof(*old));
1922 // Copy act into sigactions[sig].
1923 // Can't use struct copy, because compiler can emit call to memcpy.
1924 // Can't use internal_memcpy, because it copies byte-by-byte,
1925 // and signal handler reads the sa_handler concurrently. It it can read
1926 // some bytes from old value and some bytes from new value.
1927 // Use volatile to prevent insertion of memcpy.
1928 sigactions[sig].sa_handler = *(volatile sighandler_t*)&act->sa_handler;
1929 sigactions[sig].sa_flags = *(volatile int*)&act->sa_flags;
1930 internal_memcpy(&sigactions[sig].sa_mask, &act->sa_mask,
1931 sizeof(sigactions[sig].sa_mask));
1932 #if !SANITIZER_FREEBSD && !SANITIZER_MAC
1933 sigactions[sig].sa_restorer = act->sa_restorer;
1936 internal_memcpy(&newact, act, sizeof(newact));
1937 internal_sigfillset(&newact.sa_mask);
1938 if (act->sa_handler != SIG_IGN && act->sa_handler != SIG_DFL) {
1939 if (newact.sa_flags & SA_SIGINFO)
1940 newact.sa_sigaction = rtl_sigaction;
1942 newact.sa_handler = rtl_sighandler;
1944 ReleaseStore(thr, pc, (uptr)&sigactions[sig]);
1945 int res = REAL(sigaction)(sig, &newact, 0);
1949 TSAN_INTERCEPTOR(sighandler_t, signal, int sig, sighandler_t h) {
1952 internal_memset(&act.sa_mask, -1, sizeof(act.sa_mask));
1955 int res = sigaction(sig, &act, &old);
1958 return old.sa_handler;
1961 TSAN_INTERCEPTOR(int, raise, int sig) {
1962 SCOPED_TSAN_INTERCEPTOR(raise, sig);
1963 ThreadSignalContext *sctx = SigCtx(thr);
1965 int prev = sctx->int_signal_send;
1966 sctx->int_signal_send = sig;
1967 int res = REAL(raise)(sig);
1968 CHECK_EQ(sctx->int_signal_send, sig);
1969 sctx->int_signal_send = prev;
1973 TSAN_INTERCEPTOR(int, kill, int pid, int sig) {
1974 SCOPED_TSAN_INTERCEPTOR(kill, pid, sig);
1975 ThreadSignalContext *sctx = SigCtx(thr);
1977 int prev = sctx->int_signal_send;
1978 if (pid == (int)internal_getpid()) {
1979 sctx->int_signal_send = sig;
1981 int res = REAL(kill)(pid, sig);
1982 if (pid == (int)internal_getpid()) {
1983 CHECK_EQ(sctx->int_signal_send, sig);
1984 sctx->int_signal_send = prev;
1989 TSAN_INTERCEPTOR(int, pthread_kill, void *tid, int sig) {
1990 SCOPED_TSAN_INTERCEPTOR(pthread_kill, tid, sig);
1991 ThreadSignalContext *sctx = SigCtx(thr);
1993 int prev = sctx->int_signal_send;
1994 if (tid == pthread_self()) {
1995 sctx->int_signal_send = sig;
1997 int res = REAL(pthread_kill)(tid, sig);
1998 if (tid == pthread_self()) {
1999 CHECK_EQ(sctx->int_signal_send, sig);
2000 sctx->int_signal_send = prev;
2005 TSAN_INTERCEPTOR(int, gettimeofday, void *tv, void *tz) {
2006 SCOPED_TSAN_INTERCEPTOR(gettimeofday, tv, tz);
2007 // It's intercepted merely to process pending signals.
2008 return REAL(gettimeofday)(tv, tz);
2011 TSAN_INTERCEPTOR(int, getaddrinfo, void *node, void *service,
2012 void *hints, void *rv) {
2013 SCOPED_TSAN_INTERCEPTOR(getaddrinfo, node, service, hints, rv);
2014 // We miss atomic synchronization in getaddrinfo,
2015 // and can report false race between malloc and free
2016 // inside of getaddrinfo. So ignore memory accesses.
2017 ThreadIgnoreBegin(thr, pc);
2018 int res = REAL(getaddrinfo)(node, service, hints, rv);
2019 ThreadIgnoreEnd(thr, pc);
2023 TSAN_INTERCEPTOR(int, fork, int fake) {
2024 if (cur_thread()->in_symbolizer)
2025 return REAL(fork)(fake);
2026 SCOPED_INTERCEPTOR_RAW(fork, fake);
2027 ForkBefore(thr, pc);
2030 // On OS X, REAL(fork) can call intercepted functions (OSSpinLockLock), and
2031 // we'll assert in CheckNoLocks() unless we ignore interceptors.
2032 ScopedIgnoreInterceptors ignore;
2033 pid = REAL(fork)(fake);
2037 ForkChildAfter(thr, pc);
2039 } else if (pid > 0) {
2041 ForkParentAfter(thr, pc);
2044 ForkParentAfter(thr, pc);
2049 TSAN_INTERCEPTOR(int, vfork, int fake) {
2050 // Some programs (e.g. openjdk) call close for all file descriptors
2051 // in the child process. Under tsan it leads to false positives, because
2052 // address space is shared, so the parent process also thinks that
2053 // the descriptors are closed (while they are actually not).
2054 // This leads to false positives due to missed synchronization.
2055 // Strictly saying this is undefined behavior, because vfork child is not
2056 // allowed to call any functions other than exec/exit. But this is what
2057 // openjdk does, so we want to handle it.
2058 // We could disable interceptors in the child process. But it's not possible
2059 // to simply intercept and wrap vfork, because vfork child is not allowed
2060 // to return from the function that calls vfork, and that's exactly what
2061 // we would do. So this would require some assembly trickery as well.
2062 // Instead we simply turn vfork into fork.
2063 return WRAP(fork)(fake);
2066 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2067 typedef int (*dl_iterate_phdr_cb_t)(__sanitizer_dl_phdr_info *info, SIZE_T size,
2069 struct dl_iterate_phdr_data {
2072 dl_iterate_phdr_cb_t cb;
2076 static bool IsAppNotRodata(uptr addr) {
2077 return IsAppMem(addr) && *(u64*)MemToShadow(addr) != kShadowRodata;
2080 static int dl_iterate_phdr_cb(__sanitizer_dl_phdr_info *info, SIZE_T size,
2082 dl_iterate_phdr_data *cbdata = (dl_iterate_phdr_data *)data;
2083 // dlopen/dlclose allocate/free dynamic-linker-internal memory, which is later
2084 // accessible in dl_iterate_phdr callback. But we don't see synchronization
2085 // inside of dynamic linker, so we "unpoison" it here in order to not
2086 // produce false reports. Ignoring malloc/free in dlopen/dlclose is not enough
2087 // because some libc functions call __libc_dlopen.
2088 if (info && IsAppNotRodata((uptr)info->dlpi_name))
2089 MemoryResetRange(cbdata->thr, cbdata->pc, (uptr)info->dlpi_name,
2090 internal_strlen(info->dlpi_name));
2091 int res = cbdata->cb(info, size, cbdata->data);
2092 // Perform the check one more time in case info->dlpi_name was overwritten
2093 // by user callback.
2094 if (info && IsAppNotRodata((uptr)info->dlpi_name))
2095 MemoryResetRange(cbdata->thr, cbdata->pc, (uptr)info->dlpi_name,
2096 internal_strlen(info->dlpi_name));
2100 TSAN_INTERCEPTOR(int, dl_iterate_phdr, dl_iterate_phdr_cb_t cb, void *data) {
2101 SCOPED_TSAN_INTERCEPTOR(dl_iterate_phdr, cb, data);
2102 dl_iterate_phdr_data cbdata;
2107 int res = REAL(dl_iterate_phdr)(dl_iterate_phdr_cb, &cbdata);
2112 static int OnExit(ThreadState *thr) {
2113 int status = Finalize(thr);
2118 struct TsanInterceptorContext {
2120 const uptr caller_pc;
2125 static void HandleRecvmsg(ThreadState *thr, uptr pc,
2126 __sanitizer_msghdr *msg) {
2128 int cnt = ExtractRecvmsgFDs(msg, fds, ARRAY_SIZE(fds));
2129 for (int i = 0; i < cnt; i++)
2130 FdEventCreate(thr, pc, fds[i]);
2134 #include "sanitizer_common/sanitizer_platform_interceptors.h"
2135 // Causes interceptor recursion (getaddrinfo() and fopen())
2136 #undef SANITIZER_INTERCEPT_GETADDRINFO
2137 // There interceptors do not seem to be strictly necessary for tsan.
2138 // But we see cases where the interceptors consume 70% of execution time.
2139 // Memory blocks passed to fgetgrent_r are "written to" by tsan several times.
2140 // First, there is some recursion (getgrnam_r calls fgetgrent_r), and each
2141 // function "writes to" the buffer. Then, the same memory is "written to"
2142 // twice, first as buf and then as pwbufp (both of them refer to the same
2144 #undef SANITIZER_INTERCEPT_GETPWENT
2145 #undef SANITIZER_INTERCEPT_GETPWENT_R
2146 #undef SANITIZER_INTERCEPT_FGETPWENT
2147 #undef SANITIZER_INTERCEPT_GETPWNAM_AND_FRIENDS
2148 #undef SANITIZER_INTERCEPT_GETPWNAM_R_AND_FRIENDS
2149 // We define our own.
2150 #if SANITIZER_INTERCEPT_TLS_GET_ADDR
2151 #define NEED_TLS_GET_ADDR
2153 #undef SANITIZER_INTERCEPT_TLS_GET_ADDR
2155 #define COMMON_INTERCEPT_FUNCTION(name) INTERCEPT_FUNCTION(name)
2156 #define COMMON_INTERCEPT_FUNCTION_VER(name, ver) \
2157 INTERCEPT_FUNCTION_VER(name, ver)
2159 #define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \
2160 MemoryAccessRange(((TsanInterceptorContext *)ctx)->thr, \
2161 ((TsanInterceptorContext *)ctx)->pc, (uptr)ptr, size, \
2164 #define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) \
2165 MemoryAccessRange(((TsanInterceptorContext *) ctx)->thr, \
2166 ((TsanInterceptorContext *) ctx)->pc, (uptr) ptr, size, \
2169 #define COMMON_INTERCEPTOR_ENTER(ctx, func, ...) \
2170 SCOPED_TSAN_INTERCEPTOR(func, __VA_ARGS__); \
2171 TsanInterceptorContext _ctx = {thr, caller_pc, pc}; \
2172 ctx = (void *)&_ctx; \
2175 #define COMMON_INTERCEPTOR_ENTER_NOIGNORE(ctx, func, ...) \
2176 SCOPED_INTERCEPTOR_RAW(func, __VA_ARGS__); \
2177 TsanInterceptorContext _ctx = {thr, caller_pc, pc}; \
2178 ctx = (void *)&_ctx; \
2181 #define COMMON_INTERCEPTOR_FILE_OPEN(ctx, file, path) \
2182 Acquire(thr, pc, File2addr(path)); \
2184 int fd = fileno_unlocked(file); \
2185 if (fd >= 0) FdFileCreate(thr, pc, fd); \
2188 #define COMMON_INTERCEPTOR_FILE_CLOSE(ctx, file) \
2190 int fd = fileno_unlocked(file); \
2191 if (fd >= 0) FdClose(thr, pc, fd); \
2194 #define COMMON_INTERCEPTOR_LIBRARY_LOADED(filename, handle) \
2195 libignore()->OnLibraryLoaded(filename)
2197 #define COMMON_INTERCEPTOR_LIBRARY_UNLOADED() \
2198 libignore()->OnLibraryUnloaded()
2200 #define COMMON_INTERCEPTOR_ACQUIRE(ctx, u) \
2201 Acquire(((TsanInterceptorContext *) ctx)->thr, pc, u)
2203 #define COMMON_INTERCEPTOR_RELEASE(ctx, u) \
2204 Release(((TsanInterceptorContext *) ctx)->thr, pc, u)
2206 #define COMMON_INTERCEPTOR_DIR_ACQUIRE(ctx, path) \
2207 Acquire(((TsanInterceptorContext *) ctx)->thr, pc, Dir2addr(path))
2209 #define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \
2210 FdAcquire(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2212 #define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \
2213 FdRelease(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2215 #define COMMON_INTERCEPTOR_FD_ACCESS(ctx, fd) \
2216 FdAccess(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2218 #define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \
2219 FdSocketAccept(((TsanInterceptorContext *) ctx)->thr, pc, fd, newfd)
2221 #define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) \
2222 ThreadSetName(((TsanInterceptorContext *) ctx)->thr, name)
2224 #define COMMON_INTERCEPTOR_SET_PTHREAD_NAME(ctx, thread, name) \
2225 __tsan::ctx->thread_registry->SetThreadNameByUserId(thread, name)
2227 #define COMMON_INTERCEPTOR_BLOCK_REAL(name) BLOCK_REAL(name)
2229 #define COMMON_INTERCEPTOR_ON_EXIT(ctx) \
2230 OnExit(((TsanInterceptorContext *) ctx)->thr)
2232 #define COMMON_INTERCEPTOR_MUTEX_PRE_LOCK(ctx, m) \
2233 MutexPreLock(((TsanInterceptorContext *)ctx)->thr, \
2234 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2236 #define COMMON_INTERCEPTOR_MUTEX_POST_LOCK(ctx, m) \
2237 MutexPostLock(((TsanInterceptorContext *)ctx)->thr, \
2238 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2240 #define COMMON_INTERCEPTOR_MUTEX_UNLOCK(ctx, m) \
2241 MutexUnlock(((TsanInterceptorContext *)ctx)->thr, \
2242 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2244 #define COMMON_INTERCEPTOR_MUTEX_REPAIR(ctx, m) \
2245 MutexRepair(((TsanInterceptorContext *)ctx)->thr, \
2246 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2248 #define COMMON_INTERCEPTOR_MUTEX_INVALID(ctx, m) \
2249 MutexInvalidAccess(((TsanInterceptorContext *)ctx)->thr, \
2250 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2253 #define COMMON_INTERCEPTOR_HANDLE_RECVMSG(ctx, msg) \
2254 HandleRecvmsg(((TsanInterceptorContext *)ctx)->thr, \
2255 ((TsanInterceptorContext *)ctx)->pc, msg)
2258 #define COMMON_INTERCEPTOR_GET_TLS_RANGE(begin, end) \
2259 if (TsanThread *t = GetCurrentThread()) { \
2260 *begin = t->tls_begin(); \
2261 *end = t->tls_end(); \
2263 *begin = *end = 0; \
2266 #define COMMON_INTERCEPTOR_USER_CALLBACK_START() \
2267 SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_START()
2269 #define COMMON_INTERCEPTOR_USER_CALLBACK_END() \
2270 SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_END()
2272 #include "sanitizer_common/sanitizer_common_interceptors.inc"
2274 #define TSAN_SYSCALL() \
2275 ThreadState *thr = cur_thread(); \
2276 if (thr->ignore_interceptors) \
2278 ScopedSyscall scoped_syscall(thr) \
2281 struct ScopedSyscall {
2284 explicit ScopedSyscall(ThreadState *thr)
2290 ProcessPendingSignals(thr);
2294 #if !SANITIZER_FREEBSD && !SANITIZER_MAC
2295 static void syscall_access_range(uptr pc, uptr p, uptr s, bool write) {
2297 MemoryAccessRange(thr, pc, p, s, write);
2300 static void syscall_acquire(uptr pc, uptr addr) {
2302 Acquire(thr, pc, addr);
2303 DPrintf("syscall_acquire(%p)\n", addr);
2306 static void syscall_release(uptr pc, uptr addr) {
2308 DPrintf("syscall_release(%p)\n", addr);
2309 Release(thr, pc, addr);
2312 static void syscall_fd_close(uptr pc, int fd) {
2314 FdClose(thr, pc, fd);
2317 static USED void syscall_fd_acquire(uptr pc, int fd) {
2319 FdAcquire(thr, pc, fd);
2320 DPrintf("syscall_fd_acquire(%p)\n", fd);
2323 static USED void syscall_fd_release(uptr pc, int fd) {
2325 DPrintf("syscall_fd_release(%p)\n", fd);
2326 FdRelease(thr, pc, fd);
2329 static void syscall_pre_fork(uptr pc) {
2331 ForkBefore(thr, pc);
2334 static void syscall_post_fork(uptr pc, int pid) {
2338 ForkChildAfter(thr, pc);
2340 } else if (pid > 0) {
2342 ForkParentAfter(thr, pc);
2345 ForkParentAfter(thr, pc);
2350 #define COMMON_SYSCALL_PRE_READ_RANGE(p, s) \
2351 syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), false)
2353 #define COMMON_SYSCALL_PRE_WRITE_RANGE(p, s) \
2354 syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), true)
2356 #define COMMON_SYSCALL_POST_READ_RANGE(p, s) \
2362 #define COMMON_SYSCALL_POST_WRITE_RANGE(p, s) \
2368 #define COMMON_SYSCALL_ACQUIRE(addr) \
2369 syscall_acquire(GET_CALLER_PC(), (uptr)(addr))
2371 #define COMMON_SYSCALL_RELEASE(addr) \
2372 syscall_release(GET_CALLER_PC(), (uptr)(addr))
2374 #define COMMON_SYSCALL_FD_CLOSE(fd) syscall_fd_close(GET_CALLER_PC(), fd)
2376 #define COMMON_SYSCALL_FD_ACQUIRE(fd) syscall_fd_acquire(GET_CALLER_PC(), fd)
2378 #define COMMON_SYSCALL_FD_RELEASE(fd) syscall_fd_release(GET_CALLER_PC(), fd)
2380 #define COMMON_SYSCALL_PRE_FORK() \
2381 syscall_pre_fork(GET_CALLER_PC())
2383 #define COMMON_SYSCALL_POST_FORK(res) \
2384 syscall_post_fork(GET_CALLER_PC(), res)
2386 #include "sanitizer_common/sanitizer_common_syscalls.inc"
2388 #ifdef NEED_TLS_GET_ADDR
2389 // Define own interceptor instead of sanitizer_common's for three reasons:
2390 // 1. It must not process pending signals.
2391 // Signal handlers may contain MOVDQA instruction (see below).
2392 // 2. It must be as simple as possible to not contain MOVDQA.
2393 // 3. Sanitizer_common version uses COMMON_INTERCEPTOR_INITIALIZE_RANGE which
2394 // is empty for tsan (meant only for msan).
2395 // Note: __tls_get_addr can be called with mis-aligned stack due to:
2396 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58066
2397 // So the interceptor must work with mis-aligned stack, in particular, does not
2398 // execute MOVDQA with stack addresses.
2399 TSAN_INTERCEPTOR(void *, __tls_get_addr, void *arg) {
2400 void *res = REAL(__tls_get_addr)(arg);
2401 ThreadState *thr = cur_thread();
2404 DTLS::DTV *dtv = DTLS_on_tls_get_addr(arg, res, thr->tls_addr, thr->tls_size);
2407 // New DTLS block has been allocated.
2408 MemoryResetRange(thr, 0, dtv->beg, dtv->size);
2415 static void finalize(void *arg) {
2416 ThreadState *thr = cur_thread();
2417 int status = Finalize(thr);
2418 // Make sure the output is not lost.
2424 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2425 static void unreachable() {
2426 Report("FATAL: ThreadSanitizer: unreachable called\n");
2431 void InitializeInterceptors() {
2433 // We need to setup it early, because functions like dlsym() can call it.
2434 REAL(memset) = internal_memset;
2435 REAL(memcpy) = internal_memcpy;
2438 // Instruct libc malloc to consume less memory.
2440 mallopt(1, 0); // M_MXFAST
2441 mallopt(-3, 32*1024); // M_MMAP_THRESHOLD
2444 InitializeCommonInterceptors();
2447 // We can not use TSAN_INTERCEPT to get setjmp addr,
2448 // because it does &setjmp and setjmp is not present in some versions of libc.
2449 using __interception::GetRealFunctionAddress;
2450 GetRealFunctionAddress("setjmp", (uptr*)&REAL(setjmp), 0, 0);
2451 GetRealFunctionAddress("_setjmp", (uptr*)&REAL(_setjmp), 0, 0);
2452 GetRealFunctionAddress("sigsetjmp", (uptr*)&REAL(sigsetjmp), 0, 0);
2453 GetRealFunctionAddress("__sigsetjmp", (uptr*)&REAL(__sigsetjmp), 0, 0);
2456 TSAN_INTERCEPT(longjmp);
2457 TSAN_INTERCEPT(siglongjmp);
2459 TSAN_INTERCEPT(malloc);
2460 TSAN_INTERCEPT(__libc_memalign);
2461 TSAN_INTERCEPT(calloc);
2462 TSAN_INTERCEPT(realloc);
2463 TSAN_INTERCEPT(free);
2464 TSAN_INTERCEPT(cfree);
2465 TSAN_INTERCEPT(mmap);
2466 TSAN_MAYBE_INTERCEPT_MMAP64;
2467 TSAN_INTERCEPT(munmap);
2468 TSAN_MAYBE_INTERCEPT_MEMALIGN;
2469 TSAN_INTERCEPT(valloc);
2470 TSAN_MAYBE_INTERCEPT_PVALLOC;
2471 TSAN_INTERCEPT(posix_memalign);
2473 TSAN_INTERCEPT(strcpy); // NOLINT
2474 TSAN_INTERCEPT(strncpy);
2475 TSAN_INTERCEPT(strdup);
2477 TSAN_INTERCEPT(pthread_create);
2478 TSAN_INTERCEPT(pthread_join);
2479 TSAN_INTERCEPT(pthread_detach);
2481 TSAN_INTERCEPT_VER(pthread_cond_init, PTHREAD_ABI_BASE);
2482 TSAN_INTERCEPT_VER(pthread_cond_signal, PTHREAD_ABI_BASE);
2483 TSAN_INTERCEPT_VER(pthread_cond_broadcast, PTHREAD_ABI_BASE);
2484 TSAN_INTERCEPT_VER(pthread_cond_wait, PTHREAD_ABI_BASE);
2485 TSAN_INTERCEPT_VER(pthread_cond_timedwait, PTHREAD_ABI_BASE);
2486 TSAN_INTERCEPT_VER(pthread_cond_destroy, PTHREAD_ABI_BASE);
2488 TSAN_INTERCEPT(pthread_mutex_init);
2489 TSAN_INTERCEPT(pthread_mutex_destroy);
2490 TSAN_INTERCEPT(pthread_mutex_trylock);
2491 TSAN_INTERCEPT(pthread_mutex_timedlock);
2493 TSAN_INTERCEPT(pthread_spin_init);
2494 TSAN_INTERCEPT(pthread_spin_destroy);
2495 TSAN_INTERCEPT(pthread_spin_lock);
2496 TSAN_INTERCEPT(pthread_spin_trylock);
2497 TSAN_INTERCEPT(pthread_spin_unlock);
2499 TSAN_INTERCEPT(pthread_rwlock_init);
2500 TSAN_INTERCEPT(pthread_rwlock_destroy);
2501 TSAN_INTERCEPT(pthread_rwlock_rdlock);
2502 TSAN_INTERCEPT(pthread_rwlock_tryrdlock);
2503 TSAN_INTERCEPT(pthread_rwlock_timedrdlock);
2504 TSAN_INTERCEPT(pthread_rwlock_wrlock);
2505 TSAN_INTERCEPT(pthread_rwlock_trywrlock);
2506 TSAN_INTERCEPT(pthread_rwlock_timedwrlock);
2507 TSAN_INTERCEPT(pthread_rwlock_unlock);
2509 TSAN_INTERCEPT(pthread_barrier_init);
2510 TSAN_INTERCEPT(pthread_barrier_destroy);
2511 TSAN_INTERCEPT(pthread_barrier_wait);
2513 TSAN_INTERCEPT(pthread_once);
2515 TSAN_INTERCEPT(fstat);
2516 TSAN_MAYBE_INTERCEPT___FXSTAT;
2517 TSAN_MAYBE_INTERCEPT_FSTAT64;
2518 TSAN_MAYBE_INTERCEPT___FXSTAT64;
2519 TSAN_INTERCEPT(open);
2520 TSAN_MAYBE_INTERCEPT_OPEN64;
2521 TSAN_INTERCEPT(creat);
2522 TSAN_MAYBE_INTERCEPT_CREAT64;
2523 TSAN_INTERCEPT(dup);
2524 TSAN_INTERCEPT(dup2);
2525 TSAN_INTERCEPT(dup3);
2526 TSAN_MAYBE_INTERCEPT_EVENTFD;
2527 TSAN_MAYBE_INTERCEPT_SIGNALFD;
2528 TSAN_MAYBE_INTERCEPT_INOTIFY_INIT;
2529 TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1;
2530 TSAN_INTERCEPT(socket);
2531 TSAN_INTERCEPT(socketpair);
2532 TSAN_INTERCEPT(connect);
2533 TSAN_INTERCEPT(bind);
2534 TSAN_INTERCEPT(listen);
2535 TSAN_MAYBE_INTERCEPT_EPOLL;
2536 TSAN_INTERCEPT(close);
2537 TSAN_MAYBE_INTERCEPT___CLOSE;
2538 TSAN_MAYBE_INTERCEPT___RES_ICLOSE;
2539 TSAN_INTERCEPT(pipe);
2540 TSAN_INTERCEPT(pipe2);
2542 TSAN_INTERCEPT(unlink);
2543 TSAN_INTERCEPT(tmpfile);
2544 TSAN_MAYBE_INTERCEPT_TMPFILE64;
2545 TSAN_INTERCEPT(fread);
2546 TSAN_INTERCEPT(fwrite);
2547 TSAN_INTERCEPT(abort);
2548 TSAN_INTERCEPT(puts);
2549 TSAN_INTERCEPT(rmdir);
2550 TSAN_INTERCEPT(closedir);
2552 TSAN_INTERCEPT(sigaction);
2553 TSAN_INTERCEPT(signal);
2554 TSAN_INTERCEPT(sigsuspend);
2555 TSAN_INTERCEPT(sigblock);
2556 TSAN_INTERCEPT(sigsetmask);
2557 TSAN_INTERCEPT(pthread_sigmask);
2558 TSAN_INTERCEPT(raise);
2559 TSAN_INTERCEPT(kill);
2560 TSAN_INTERCEPT(pthread_kill);
2561 TSAN_INTERCEPT(sleep);
2562 TSAN_INTERCEPT(usleep);
2563 TSAN_INTERCEPT(nanosleep);
2564 TSAN_INTERCEPT(gettimeofday);
2565 TSAN_INTERCEPT(getaddrinfo);
2567 TSAN_INTERCEPT(fork);
2568 TSAN_INTERCEPT(vfork);
2569 #if !SANITIZER_ANDROID
2570 TSAN_INTERCEPT(dl_iterate_phdr);
2572 TSAN_INTERCEPT(on_exit);
2573 TSAN_INTERCEPT(__cxa_atexit);
2574 TSAN_INTERCEPT(_exit);
2576 #ifdef NEED_TLS_GET_ADDR
2577 TSAN_INTERCEPT(__tls_get_addr);
2580 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2581 // Need to setup it, because interceptors check that the function is resolved.
2582 // But atexit is emitted directly into the module, so can't be resolved.
2583 REAL(atexit) = (int(*)(void(*)()))unreachable;
2586 if (REAL(__cxa_atexit)(&finalize, 0, 0)) {
2587 Printf("ThreadSanitizer: failed to setup atexit callback\n");
2592 if (pthread_key_create(&g_thread_finalize_key, &thread_finalize)) {
2593 Printf("ThreadSanitizer: failed to create thread key\n");
2601 } // namespace __tsan
2603 // Invisible barrier for tests.
2604 // There were several unsuccessful iterations for this functionality:
2605 // 1. Initially it was implemented in user code using
2606 // REAL(pthread_barrier_wait). But pthread_barrier_wait is not supported on
2607 // MacOS. Futexes are linux-specific for this matter.
2608 // 2. Then we switched to atomics+usleep(10). But usleep produced parasitic
2609 // "as-if synchronized via sleep" messages in reports which failed some
2611 // 3. Then we switched to atomics+sched_yield. But this produced tons of tsan-
2612 // visible events, which lead to "failed to restore stack trace" failures.
2613 // Note that no_sanitize_thread attribute does not turn off atomic interception
2614 // so attaching it to the function defined in user code does not help.
2615 // That's why we now have what we have.
2616 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
2617 void __tsan_testonly_barrier_init(u64 *barrier, u32 count) {
2618 if (count >= (1 << 8)) {
2619 Printf("barrier_init: count is too large (%d)\n", count);
2622 // 8 lsb is thread count, the remaining are count of entered threads.
2626 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
2627 void __tsan_testonly_barrier_wait(u64 *barrier) {
2628 unsigned old = __atomic_fetch_add(barrier, 1 << 8, __ATOMIC_RELAXED);
2629 unsigned old_epoch = (old >> 8) / (old & 0xff);
2631 unsigned cur = __atomic_load_n(barrier, __ATOMIC_RELAXED);
2632 unsigned cur_epoch = (cur >> 8) / (cur & 0xff);
2633 if (cur_epoch != old_epoch)
2635 internal_sched_yield();