1 //===-- tsan_interceptors_posix.cpp ---------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file is a part of ThreadSanitizer (TSan), a race detector.
11 // FIXME: move as many interceptors as possible into
12 // sanitizer_common/sanitizer_common_interceptors.inc
13 //===----------------------------------------------------------------------===//
15 #include "sanitizer_common/sanitizer_atomic.h"
16 #include "sanitizer_common/sanitizer_errno.h"
17 #include "sanitizer_common/sanitizer_libc.h"
18 #include "sanitizer_common/sanitizer_linux.h"
19 #include "sanitizer_common/sanitizer_platform_limits_netbsd.h"
20 #include "sanitizer_common/sanitizer_platform_limits_posix.h"
21 #include "sanitizer_common/sanitizer_placement_new.h"
22 #include "sanitizer_common/sanitizer_posix.h"
23 #include "sanitizer_common/sanitizer_stacktrace.h"
24 #include "sanitizer_common/sanitizer_tls_get_addr.h"
25 #include "interception/interception.h"
26 #include "tsan_interceptors.h"
27 #include "tsan_interface.h"
28 #include "tsan_platform.h"
29 #include "tsan_suppressions.h"
31 #include "tsan_mman.h"
36 using namespace __tsan
;
38 #if SANITIZER_FREEBSD || SANITIZER_MAC
39 #define stdout __stdoutp
40 #define stderr __stderrp
44 #define dirfd(dirp) (*(int *)(dirp))
45 #define fileno_unlocked(fp) \
46 (((__sanitizer_FILE *)fp)->_file == -1 \
48 : (int)(unsigned short)(((__sanitizer_FILE *)fp)->_file))
50 #define stdout ((__sanitizer_FILE*)&__sF[1])
51 #define stderr ((__sanitizer_FILE*)&__sF[2])
53 #define nanosleep __nanosleep50
54 #define vfork __vfork14
58 const int kSigCount
= 129;
60 const int kSigCount
= 65;
65 u64 opaque
[768 / sizeof(u64
) + 1];
69 // The size is determined by looking at sizeof of real ucontext_t on linux.
70 u64 opaque
[936 / sizeof(u64
) + 1];
74 #if defined(__x86_64__) || defined(__mips__) || SANITIZER_PPC64V1 || \
76 #define PTHREAD_ABI_BASE "GLIBC_2.3.2"
77 #elif defined(__aarch64__) || SANITIZER_PPC64V2
78 #define PTHREAD_ABI_BASE "GLIBC_2.17"
81 extern "C" int pthread_attr_init(void *attr
);
82 extern "C" int pthread_attr_destroy(void *attr
);
83 DECLARE_REAL(int, pthread_attr_getdetachstate
, void *, void *)
84 extern "C" int pthread_attr_setstacksize(void *attr
, uptr stacksize
);
85 extern "C" int pthread_atfork(void (*prepare
)(void), void (*parent
)(void),
87 extern "C" int pthread_key_create(unsigned *key
, void (*destructor
)(void* v
));
88 extern "C" int pthread_setspecific(unsigned key
, const void *v
);
89 DECLARE_REAL(int, pthread_mutexattr_gettype
, void *, void *)
90 DECLARE_REAL(int, fflush
, __sanitizer_FILE
*fp
)
91 DECLARE_REAL_AND_INTERCEPTOR(void *, malloc
, uptr size
)
92 DECLARE_REAL_AND_INTERCEPTOR(void, free
, void *ptr
)
93 extern "C" int pthread_equal(void *t1
, void *t2
);
94 extern "C" void *pthread_self();
95 extern "C" void _exit(int status
);
97 extern "C" int fileno_unlocked(void *stream
);
98 extern "C" int dirfd(void *dirp
);
101 extern __sanitizer_FILE __sF
[];
103 extern __sanitizer_FILE
*stdout
, *stderr
;
105 #if !SANITIZER_FREEBSD && !SANITIZER_MAC && !SANITIZER_NETBSD
106 const int PTHREAD_MUTEX_RECURSIVE
= 1;
107 const int PTHREAD_MUTEX_RECURSIVE_NP
= 1;
109 const int PTHREAD_MUTEX_RECURSIVE
= 2;
110 const int PTHREAD_MUTEX_RECURSIVE_NP
= 2;
112 #if !SANITIZER_FREEBSD && !SANITIZER_MAC && !SANITIZER_NETBSD
113 const int EPOLL_CTL_ADD
= 1;
115 const int SIGILL
= 4;
116 const int SIGTRAP
= 5;
117 const int SIGABRT
= 6;
118 const int SIGFPE
= 8;
119 const int SIGSEGV
= 11;
120 const int SIGPIPE
= 13;
121 const int SIGTERM
= 15;
122 #if defined(__mips__) || SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_NETBSD
123 const int SIGBUS
= 10;
124 const int SIGSYS
= 12;
126 const int SIGBUS
= 7;
127 const int SIGSYS
= 31;
129 void *const MAP_FAILED
= (void*)-1;
131 const int PTHREAD_BARRIER_SERIAL_THREAD
= 1234567;
133 const int PTHREAD_BARRIER_SERIAL_THREAD
= -1;
135 const int MAP_FIXED
= 0x10;
137 typedef __sanitizer::u16 mode_t
;
139 // From /usr/include/unistd.h
140 # define F_ULOCK 0 /* Unlock a previously locked region. */
141 # define F_LOCK 1 /* Lock a region for exclusive use. */
142 # define F_TLOCK 2 /* Test and lock a region for exclusive use. */
143 # define F_TEST 3 /* Test a region for other processes locks. */
145 #if SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_NETBSD
146 const int SA_SIGINFO
= 0x40;
147 const int SIG_SETMASK
= 3;
148 #elif defined(__mips__)
149 const int SA_SIGINFO
= 8;
150 const int SIG_SETMASK
= 3;
152 const int SA_SIGINFO
= 4;
153 const int SIG_SETMASK
= 2;
156 #define COMMON_INTERCEPTOR_NOTHING_IS_INITIALIZED \
157 (!cur_thread_init()->is_inited)
162 __sanitizer_siginfo siginfo
;
166 struct ThreadSignalContext
{
168 atomic_uintptr_t in_blocking_func
;
169 SignalDesc pending_signals
[kSigCount
];
170 // emptyset and oldset are too big for stack.
171 __sanitizer_sigset_t emptyset
;
172 __sanitizer_sigset_t oldset
;
175 // The sole reason tsan wraps atexit callbacks is to establish synchronization
176 // between callback setup and callback execution.
183 // InterceptorContext holds all global data required for interceptors.
184 // It's explicitly constructed in InitializeInterceptors with placement new
185 // and is never destroyed. This allows usage of members with non-trivial
186 // constructors and destructors.
187 struct InterceptorContext
{
188 // The object is 64-byte aligned, because we want hot data to be located
189 // in a single cache line if possible (it's accessed in every interceptor).
190 ALIGNED(64) LibIgnore libignore
;
191 __sanitizer_sigaction sigactions
[kSigCount
];
192 #if !SANITIZER_MAC && !SANITIZER_NETBSD
193 unsigned finalize_key
;
197 Vector
<struct AtExitCtx
*> AtExitStack
;
199 InterceptorContext() : libignore(LINKER_INITIALIZED
), atexit_mu(MutexTypeAtExit
), AtExitStack() {}
202 static ALIGNED(64) char interceptor_placeholder
[sizeof(InterceptorContext
)];
203 InterceptorContext
*interceptor_ctx() {
204 return reinterpret_cast<InterceptorContext
*>(&interceptor_placeholder
[0]);
207 LibIgnore
*libignore() {
208 return &interceptor_ctx()->libignore
;
211 void InitializeLibIgnore() {
212 const SuppressionContext
&supp
= *Suppressions();
213 const uptr n
= supp
.SuppressionCount();
214 for (uptr i
= 0; i
< n
; i
++) {
215 const Suppression
*s
= supp
.SuppressionAt(i
);
216 if (0 == internal_strcmp(s
->type
, kSuppressionLib
))
217 libignore()->AddIgnoredLibrary(s
->templ
);
219 if (flags()->ignore_noninstrumented_modules
)
220 libignore()->IgnoreNoninstrumentedModules(true);
221 libignore()->OnLibraryLoaded(0);
224 // The following two hooks can be used by for cooperative scheduling when
226 #ifdef TSAN_EXTERNAL_HOOKS
227 void OnPotentiallyBlockingRegionBegin();
228 void OnPotentiallyBlockingRegionEnd();
230 SANITIZER_WEAK_CXX_DEFAULT_IMPL
void OnPotentiallyBlockingRegionBegin() {}
231 SANITIZER_WEAK_CXX_DEFAULT_IMPL
void OnPotentiallyBlockingRegionEnd() {}
234 } // namespace __tsan
236 static ThreadSignalContext
*SigCtx(ThreadState
*thr
) {
237 ThreadSignalContext
*ctx
= (ThreadSignalContext
*)thr
->signal_ctx
;
238 if (ctx
== 0 && !thr
->is_dead
) {
239 ctx
= (ThreadSignalContext
*)MmapOrDie(sizeof(*ctx
), "ThreadSignalContext");
240 MemoryResetRange(thr
, (uptr
)&SigCtx
, (uptr
)ctx
, sizeof(*ctx
));
241 thr
->signal_ctx
= ctx
;
246 ScopedInterceptor::ScopedInterceptor(ThreadState
*thr
, const char *fname
,
248 : thr_(thr
), 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_
);
265 CheckedMutex::CheckNoLocks();
270 void ScopedInterceptor::EnableIgnoresImpl() {
271 ThreadIgnoreBegin(thr_
, 0);
272 if (flags()->ignore_noninstrumented_modules
)
273 thr_
->suppress_reports
++;
274 if (in_ignored_lib_
) {
275 DCHECK(!thr_
->in_ignored_lib
);
276 thr_
->in_ignored_lib
= true;
281 void ScopedInterceptor::DisableIgnoresImpl() {
282 ThreadIgnoreEnd(thr_
);
283 if (flags()->ignore_noninstrumented_modules
)
284 thr_
->suppress_reports
--;
285 if (in_ignored_lib_
) {
286 DCHECK(thr_
->in_ignored_lib
);
287 thr_
->in_ignored_lib
= false;
291 #define TSAN_INTERCEPT(func) INTERCEPT_FUNCTION(func)
292 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
293 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION(func)
295 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION_VER(func, ver)
297 #if SANITIZER_FREEBSD
298 # define TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(func) \
299 INTERCEPT_FUNCTION(_pthread_##func)
301 # define TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(func)
304 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(func) \
305 INTERCEPT_FUNCTION(__libc_##func)
306 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(func) \
307 INTERCEPT_FUNCTION(__libc_thr_##func)
309 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(func)
310 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(func)
313 #define READ_STRING_OF_LEN(thr, pc, s, len, n) \
314 MemoryAccessRange((thr), (pc), (uptr)(s), \
315 common_flags()->strict_string_checks ? (len) + 1 : (n), false)
317 #define READ_STRING(thr, pc, s, n) \
318 READ_STRING_OF_LEN((thr), (pc), (s), internal_strlen(s), (n))
320 #define BLOCK_REAL(name) (BlockingCall(thr), REAL(name))
322 struct BlockingCall
{
323 explicit BlockingCall(ThreadState
*thr
)
327 atomic_store(&ctx
->in_blocking_func
, 1, memory_order_relaxed
);
328 if (atomic_load(&thr
->pending_signals
, memory_order_relaxed
) == 0)
330 atomic_store(&ctx
->in_blocking_func
, 0, memory_order_relaxed
);
331 ProcessPendingSignals(thr
);
333 // When we are in a "blocking call", we process signals asynchronously
334 // (right when they arrive). In this context we do not expect to be
335 // executing any user/runtime code. The known interceptor sequence when
336 // this is not true is: pthread_join -> munmap(stack). It's fine
337 // to ignore munmap in this case -- we handle stack shadow separately.
338 thr
->ignore_interceptors
++;
342 thr
->ignore_interceptors
--;
343 atomic_store(&ctx
->in_blocking_func
, 0, memory_order_relaxed
);
347 ThreadSignalContext
*ctx
;
350 TSAN_INTERCEPTOR(unsigned, sleep
, unsigned sec
) {
351 SCOPED_TSAN_INTERCEPTOR(sleep
, sec
);
352 unsigned res
= BLOCK_REAL(sleep
)(sec
);
357 TSAN_INTERCEPTOR(int, usleep
, long_t usec
) {
358 SCOPED_TSAN_INTERCEPTOR(usleep
, usec
);
359 int res
= BLOCK_REAL(usleep
)(usec
);
364 TSAN_INTERCEPTOR(int, nanosleep
, void *req
, void *rem
) {
365 SCOPED_TSAN_INTERCEPTOR(nanosleep
, req
, rem
);
366 int res
= BLOCK_REAL(nanosleep
)(req
, rem
);
371 TSAN_INTERCEPTOR(int, pause
, int fake
) {
372 SCOPED_TSAN_INTERCEPTOR(pause
, fake
);
373 return BLOCK_REAL(pause
)(fake
);
376 // Note: we specifically call the function in such strange way
377 // with "installed_at" because in reports it will appear between
378 // callback frames and the frame that installed the callback.
379 static void at_exit_callback_installed_at() {
382 // Ensure thread-safety.
383 Lock
l(&interceptor_ctx()->atexit_mu
);
385 // Pop AtExitCtx from the top of the stack of callback functions
386 uptr element
= interceptor_ctx()->AtExitStack
.Size() - 1;
387 ctx
= interceptor_ctx()->AtExitStack
[element
];
388 interceptor_ctx()->AtExitStack
.PopBack();
391 ThreadState
*thr
= cur_thread();
392 Acquire(thr
, ctx
->pc
, (uptr
)ctx
);
393 FuncEntry(thr
, ctx
->pc
);
394 ((void(*)())ctx
->f
)();
399 static void cxa_at_exit_callback_installed_at(void *arg
) {
400 ThreadState
*thr
= cur_thread();
401 AtExitCtx
*ctx
= (AtExitCtx
*)arg
;
402 Acquire(thr
, ctx
->pc
, (uptr
)arg
);
403 FuncEntry(thr
, ctx
->pc
);
404 ((void(*)(void *arg
))ctx
->f
)(ctx
->arg
);
409 static int setup_at_exit_wrapper(ThreadState
*thr
, uptr pc
, void(*f
)(),
410 void *arg
, void *dso
);
412 #if !SANITIZER_ANDROID
413 TSAN_INTERCEPTOR(int, atexit
, void (*f
)()) {
416 // We want to setup the atexit callback even if we are in ignored lib
418 SCOPED_INTERCEPTOR_RAW(atexit
, f
);
419 return setup_at_exit_wrapper(thr
, GET_CALLER_PC(), (void (*)())f
, 0, 0);
423 TSAN_INTERCEPTOR(int, __cxa_atexit
, void (*f
)(void *a
), void *arg
, void *dso
) {
426 SCOPED_TSAN_INTERCEPTOR(__cxa_atexit
, f
, arg
, dso
);
427 return setup_at_exit_wrapper(thr
, GET_CALLER_PC(), (void (*)())f
, arg
, dso
);
430 static int setup_at_exit_wrapper(ThreadState
*thr
, uptr pc
, void(*f
)(),
431 void *arg
, void *dso
) {
432 auto *ctx
= New
<AtExitCtx
>();
436 Release(thr
, pc
, (uptr
)ctx
);
437 // Memory allocation in __cxa_atexit will race with free during exit,
438 // because we do not see synchronization around atexit callback list.
439 ThreadIgnoreBegin(thr
, pc
);
442 // NetBSD does not preserve the 2nd argument if dso is equal to 0
443 // Store ctx in a local stack-like structure
445 // Ensure thread-safety.
446 Lock
l(&interceptor_ctx()->atexit_mu
);
447 // __cxa_atexit calls calloc. If we don't ignore interceptors, we will fail
448 // due to atexit_mu held on exit from the calloc interceptor.
449 ScopedIgnoreInterceptors ignore
;
451 res
= REAL(__cxa_atexit
)((void (*)(void *a
))at_exit_callback_installed_at
,
453 // Push AtExitCtx on the top of the stack of callback functions
455 interceptor_ctx()->AtExitStack
.PushBack(ctx
);
458 res
= REAL(__cxa_atexit
)(cxa_at_exit_callback_installed_at
, ctx
, dso
);
460 ThreadIgnoreEnd(thr
);
464 #if !SANITIZER_MAC && !SANITIZER_NETBSD
465 static void on_exit_callback_installed_at(int status
, void *arg
) {
466 ThreadState
*thr
= cur_thread();
467 AtExitCtx
*ctx
= (AtExitCtx
*)arg
;
468 Acquire(thr
, ctx
->pc
, (uptr
)arg
);
469 FuncEntry(thr
, ctx
->pc
);
470 ((void(*)(int status
, void *arg
))ctx
->f
)(status
, ctx
->arg
);
475 TSAN_INTERCEPTOR(int, on_exit
, void(*f
)(int, void*), void *arg
) {
478 SCOPED_TSAN_INTERCEPTOR(on_exit
, f
, arg
);
479 auto *ctx
= New
<AtExitCtx
>();
480 ctx
->f
= (void(*)())f
;
482 ctx
->pc
= GET_CALLER_PC();
483 Release(thr
, pc
, (uptr
)ctx
);
484 // Memory allocation in __cxa_atexit will race with free during exit,
485 // because we do not see synchronization around atexit callback list.
486 ThreadIgnoreBegin(thr
, pc
);
487 int res
= REAL(on_exit
)(on_exit_callback_installed_at
, ctx
);
488 ThreadIgnoreEnd(thr
);
491 #define TSAN_MAYBE_INTERCEPT_ON_EXIT TSAN_INTERCEPT(on_exit)
493 #define TSAN_MAYBE_INTERCEPT_ON_EXIT
497 static void JmpBufGarbageCollect(ThreadState
*thr
, uptr sp
) {
498 for (uptr i
= 0; i
< thr
->jmp_bufs
.Size(); i
++) {
499 JmpBuf
*buf
= &thr
->jmp_bufs
[i
];
501 uptr sz
= thr
->jmp_bufs
.Size();
502 internal_memcpy(buf
, &thr
->jmp_bufs
[sz
- 1], sizeof(*buf
));
503 thr
->jmp_bufs
.PopBack();
509 static void SetJmp(ThreadState
*thr
, uptr sp
) {
510 if (!thr
->is_inited
) // called from libc guts during bootstrap
513 JmpBufGarbageCollect(thr
, sp
);
515 JmpBuf
*buf
= thr
->jmp_bufs
.PushBack();
517 buf
->shadow_stack_pos
= thr
->shadow_stack_pos
;
518 ThreadSignalContext
*sctx
= SigCtx(thr
);
519 buf
->int_signal_send
= sctx
? sctx
->int_signal_send
: 0;
520 buf
->in_blocking_func
= sctx
?
521 atomic_load(&sctx
->in_blocking_func
, memory_order_relaxed
) :
523 buf
->in_signal_handler
= atomic_load(&thr
->in_signal_handler
,
524 memory_order_relaxed
);
527 static void LongJmp(ThreadState
*thr
, uptr
*env
) {
528 uptr sp
= ExtractLongJmpSp(env
);
529 // Find the saved buf with matching sp.
530 for (uptr i
= 0; i
< thr
->jmp_bufs
.Size(); i
++) {
531 JmpBuf
*buf
= &thr
->jmp_bufs
[i
];
533 CHECK_GE(thr
->shadow_stack_pos
, buf
->shadow_stack_pos
);
535 while (thr
->shadow_stack_pos
> buf
->shadow_stack_pos
)
537 ThreadSignalContext
*sctx
= SigCtx(thr
);
539 sctx
->int_signal_send
= buf
->int_signal_send
;
540 atomic_store(&sctx
->in_blocking_func
, buf
->in_blocking_func
,
541 memory_order_relaxed
);
543 atomic_store(&thr
->in_signal_handler
, buf
->in_signal_handler
,
544 memory_order_relaxed
);
545 JmpBufGarbageCollect(thr
, buf
->sp
- 1); // do not collect buf->sp
549 Printf("ThreadSanitizer: can't find longjmp buf\n");
553 // FIXME: put everything below into a common extern "C" block?
554 extern "C" void __tsan_setjmp(uptr sp
) { SetJmp(cur_thread_init(), sp
); }
557 TSAN_INTERCEPTOR(int, setjmp
, void *env
);
558 TSAN_INTERCEPTOR(int, _setjmp
, void *env
);
559 TSAN_INTERCEPTOR(int, sigsetjmp
, void *env
);
560 #else // SANITIZER_MAC
563 #define setjmp_symname __setjmp14
564 #define sigsetjmp_symname __sigsetjmp14
566 #define setjmp_symname setjmp
567 #define sigsetjmp_symname sigsetjmp
570 #define TSAN_INTERCEPTOR_SETJMP_(x) __interceptor_ ## x
571 #define TSAN_INTERCEPTOR_SETJMP__(x) TSAN_INTERCEPTOR_SETJMP_(x)
572 #define TSAN_INTERCEPTOR_SETJMP TSAN_INTERCEPTOR_SETJMP__(setjmp_symname)
573 #define TSAN_INTERCEPTOR_SIGSETJMP TSAN_INTERCEPTOR_SETJMP__(sigsetjmp_symname)
575 #define TSAN_STRING_SETJMP SANITIZER_STRINGIFY(setjmp_symname)
576 #define TSAN_STRING_SIGSETJMP SANITIZER_STRINGIFY(sigsetjmp_symname)
578 // Not called. Merely to satisfy TSAN_INTERCEPT().
579 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
580 int TSAN_INTERCEPTOR_SETJMP(void *env
);
581 extern "C" int TSAN_INTERCEPTOR_SETJMP(void *env
) {
586 // FIXME: any reason to have a separate declaration?
587 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
588 int __interceptor__setjmp(void *env
);
589 extern "C" int __interceptor__setjmp(void *env
) {
594 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
595 int TSAN_INTERCEPTOR_SIGSETJMP(void *env
);
596 extern "C" int TSAN_INTERCEPTOR_SIGSETJMP(void *env
) {
601 #if !SANITIZER_NETBSD
602 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
603 int __interceptor___sigsetjmp(void *env
);
604 extern "C" int __interceptor___sigsetjmp(void *env
) {
610 extern "C" int setjmp_symname(void *env
);
611 extern "C" int _setjmp(void *env
);
612 extern "C" int sigsetjmp_symname(void *env
);
613 #if !SANITIZER_NETBSD
614 extern "C" int __sigsetjmp(void *env
);
616 DEFINE_REAL(int, setjmp_symname
, void *env
)
617 DEFINE_REAL(int, _setjmp
, void *env
)
618 DEFINE_REAL(int, sigsetjmp_symname
, void *env
)
619 #if !SANITIZER_NETBSD
620 DEFINE_REAL(int, __sigsetjmp
, void *env
)
622 #endif // SANITIZER_MAC
625 #define longjmp_symname __longjmp14
626 #define siglongjmp_symname __siglongjmp14
628 #define longjmp_symname longjmp
629 #define siglongjmp_symname siglongjmp
632 TSAN_INTERCEPTOR(void, longjmp_symname
, uptr
*env
, int val
) {
633 // Note: if we call REAL(longjmp) in the context of ScopedInterceptor,
634 // bad things will happen. We will jump over ScopedInterceptor dtor and can
635 // leave thr->in_ignored_lib set.
637 SCOPED_INTERCEPTOR_RAW(longjmp_symname
, env
, val
);
639 LongJmp(cur_thread(), env
);
640 REAL(longjmp_symname
)(env
, val
);
643 TSAN_INTERCEPTOR(void, siglongjmp_symname
, uptr
*env
, int val
) {
645 SCOPED_INTERCEPTOR_RAW(siglongjmp_symname
, env
, val
);
647 LongJmp(cur_thread(), env
);
648 REAL(siglongjmp_symname
)(env
, val
);
652 TSAN_INTERCEPTOR(void, _longjmp
, uptr
*env
, int val
) {
654 SCOPED_INTERCEPTOR_RAW(_longjmp
, env
, val
);
656 LongJmp(cur_thread(), env
);
657 REAL(_longjmp
)(env
, val
);
662 TSAN_INTERCEPTOR(void*, malloc
, uptr size
) {
664 return InternalAlloc(size
);
667 SCOPED_INTERCEPTOR_RAW(malloc
, size
);
668 p
= user_alloc(thr
, pc
, size
);
670 invoke_malloc_hook(p
, size
);
674 // In glibc<2.25, dynamic TLS blocks are allocated by __libc_memalign. Intercept
675 // __libc_memalign so that (1) we can detect races (2) free will not be called
676 // on libc internally allocated blocks.
677 TSAN_INTERCEPTOR(void*, __libc_memalign
, uptr align
, uptr sz
) {
678 SCOPED_INTERCEPTOR_RAW(__libc_memalign
, align
, sz
);
679 return user_memalign(thr
, pc
, align
, sz
);
682 TSAN_INTERCEPTOR(void*, calloc
, uptr size
, uptr n
) {
684 return InternalCalloc(size
, n
);
687 SCOPED_INTERCEPTOR_RAW(calloc
, size
, n
);
688 p
= user_calloc(thr
, pc
, size
, n
);
690 invoke_malloc_hook(p
, n
* size
);
694 TSAN_INTERCEPTOR(void*, realloc
, void *p
, uptr size
) {
696 return InternalRealloc(p
, size
);
700 SCOPED_INTERCEPTOR_RAW(realloc
, p
, size
);
701 p
= user_realloc(thr
, pc
, p
, size
);
703 invoke_malloc_hook(p
, size
);
707 TSAN_INTERCEPTOR(void*, reallocarray
, void *p
, uptr size
, uptr n
) {
709 return InternalReallocArray(p
, size
, n
);
713 SCOPED_INTERCEPTOR_RAW(reallocarray
, p
, size
, n
);
714 p
= user_reallocarray(thr
, pc
, p
, size
, n
);
716 invoke_malloc_hook(p
, size
);
720 TSAN_INTERCEPTOR(void, free
, void *p
) {
724 return InternalFree(p
);
726 SCOPED_INTERCEPTOR_RAW(free
, p
);
727 user_free(thr
, pc
, p
);
730 TSAN_INTERCEPTOR(void, cfree
, void *p
) {
734 return InternalFree(p
);
736 SCOPED_INTERCEPTOR_RAW(cfree
, p
);
737 user_free(thr
, pc
, p
);
740 TSAN_INTERCEPTOR(uptr
, malloc_usable_size
, void *p
) {
741 SCOPED_INTERCEPTOR_RAW(malloc_usable_size
, p
);
742 return user_alloc_usable_size(p
);
746 TSAN_INTERCEPTOR(char *, strcpy
, char *dst
, const char *src
) {
747 SCOPED_TSAN_INTERCEPTOR(strcpy
, dst
, src
);
748 uptr srclen
= internal_strlen(src
);
749 MemoryAccessRange(thr
, pc
, (uptr
)dst
, srclen
+ 1, true);
750 MemoryAccessRange(thr
, pc
, (uptr
)src
, srclen
+ 1, false);
751 return REAL(strcpy
)(dst
, src
);
754 TSAN_INTERCEPTOR(char*, strncpy
, char *dst
, char *src
, uptr n
) {
755 SCOPED_TSAN_INTERCEPTOR(strncpy
, dst
, src
, n
);
756 uptr srclen
= internal_strnlen(src
, n
);
757 MemoryAccessRange(thr
, pc
, (uptr
)dst
, n
, true);
758 MemoryAccessRange(thr
, pc
, (uptr
)src
, min(srclen
+ 1, n
), false);
759 return REAL(strncpy
)(dst
, src
, n
);
762 TSAN_INTERCEPTOR(char*, strdup
, const char *str
) {
763 SCOPED_TSAN_INTERCEPTOR(strdup
, str
);
764 // strdup will call malloc, so no instrumentation is required here.
765 return REAL(strdup
)(str
);
768 // Zero out addr if it points into shadow memory and was provided as a hint
769 // only, i.e., MAP_FIXED is not set.
770 static bool fix_mmap_addr(void **addr
, long_t sz
, int flags
) {
772 if (!IsAppMem((uptr
)*addr
) || !IsAppMem((uptr
)*addr
+ sz
- 1)) {
773 if (flags
& MAP_FIXED
) {
774 errno
= errno_EINVAL
;
784 template <class Mmap
>
785 static void *mmap_interceptor(ThreadState
*thr
, uptr pc
, Mmap real_mmap
,
786 void *addr
, SIZE_T sz
, int prot
, int flags
,
787 int fd
, OFF64_T off
) {
788 if (!fix_mmap_addr(&addr
, sz
, flags
)) return MAP_FAILED
;
789 void *res
= real_mmap(addr
, sz
, prot
, flags
, fd
, off
);
790 if (res
!= MAP_FAILED
) {
791 if (!IsAppMem((uptr
)res
) || !IsAppMem((uptr
)res
+ sz
- 1)) {
792 Report("ThreadSanitizer: mmap at bad address: addr=%p size=%p res=%p\n",
793 addr
, (void*)sz
, res
);
796 if (fd
> 0) FdAccess(thr
, pc
, fd
);
797 MemoryRangeImitateWriteOrResetRange(thr
, pc
, (uptr
)res
, sz
);
802 TSAN_INTERCEPTOR(int, munmap
, void *addr
, long_t sz
) {
803 SCOPED_TSAN_INTERCEPTOR(munmap
, addr
, sz
);
804 UnmapShadow(thr
, (uptr
)addr
, sz
);
805 int res
= REAL(munmap
)(addr
, sz
);
810 TSAN_INTERCEPTOR(void*, memalign
, uptr align
, uptr sz
) {
811 SCOPED_INTERCEPTOR_RAW(memalign
, align
, sz
);
812 return user_memalign(thr
, pc
, align
, sz
);
814 #define TSAN_MAYBE_INTERCEPT_MEMALIGN TSAN_INTERCEPT(memalign)
816 #define TSAN_MAYBE_INTERCEPT_MEMALIGN
820 TSAN_INTERCEPTOR(void*, aligned_alloc
, uptr align
, uptr sz
) {
822 return InternalAlloc(sz
, nullptr, align
);
823 SCOPED_INTERCEPTOR_RAW(aligned_alloc
, align
, sz
);
824 return user_aligned_alloc(thr
, pc
, align
, sz
);
827 TSAN_INTERCEPTOR(void*, valloc
, uptr sz
) {
829 return InternalAlloc(sz
, nullptr, GetPageSizeCached());
830 SCOPED_INTERCEPTOR_RAW(valloc
, sz
);
831 return user_valloc(thr
, pc
, sz
);
836 TSAN_INTERCEPTOR(void*, pvalloc
, uptr sz
) {
837 if (in_symbolizer()) {
838 uptr PageSize
= GetPageSizeCached();
839 sz
= sz
? RoundUpTo(sz
, PageSize
) : PageSize
;
840 return InternalAlloc(sz
, nullptr, PageSize
);
842 SCOPED_INTERCEPTOR_RAW(pvalloc
, sz
);
843 return user_pvalloc(thr
, pc
, sz
);
845 #define TSAN_MAYBE_INTERCEPT_PVALLOC TSAN_INTERCEPT(pvalloc)
847 #define TSAN_MAYBE_INTERCEPT_PVALLOC
851 TSAN_INTERCEPTOR(int, posix_memalign
, void **memptr
, uptr align
, uptr sz
) {
852 if (in_symbolizer()) {
853 void *p
= InternalAlloc(sz
, nullptr, align
);
859 SCOPED_INTERCEPTOR_RAW(posix_memalign
, memptr
, align
, sz
);
860 return user_posix_memalign(thr
, pc
, memptr
, align
, sz
);
864 // Both __cxa_guard_acquire and pthread_once 0-initialize
865 // the object initially. pthread_once does not have any
866 // other ABI requirements. __cxa_guard_acquire assumes
867 // that any non-0 value in the first byte means that
868 // initialization is completed. Contents of the remaining
869 // bytes are up to us.
870 constexpr u32 kGuardInit
= 0;
871 constexpr u32 kGuardDone
= 1;
872 constexpr u32 kGuardRunning
= 1 << 16;
873 constexpr u32 kGuardWaiter
= 1 << 17;
875 static int guard_acquire(ThreadState
*thr
, uptr pc
, atomic_uint32_t
*g
,
876 bool blocking_hooks
= true) {
878 OnPotentiallyBlockingRegionBegin();
879 auto on_exit
= at_scope_exit([blocking_hooks
] {
881 OnPotentiallyBlockingRegionEnd();
885 u32 cmp
= atomic_load(g
, memory_order_acquire
);
886 if (cmp
== kGuardInit
) {
887 if (atomic_compare_exchange_strong(g
, &cmp
, kGuardRunning
,
888 memory_order_relaxed
))
890 } else if (cmp
== kGuardDone
) {
891 if (!thr
->in_ignored_lib
)
892 Acquire(thr
, pc
, (uptr
)g
);
895 if ((cmp
& kGuardWaiter
) ||
896 atomic_compare_exchange_strong(g
, &cmp
, cmp
| kGuardWaiter
,
897 memory_order_relaxed
))
898 FutexWait(g
, cmp
| kGuardWaiter
);
903 static void guard_release(ThreadState
*thr
, uptr pc
, atomic_uint32_t
*g
,
905 if (!thr
->in_ignored_lib
)
906 Release(thr
, pc
, (uptr
)g
);
907 u32 old
= atomic_exchange(g
, v
, memory_order_release
);
908 if (old
& kGuardWaiter
)
909 FutexWake(g
, 1 << 30);
912 // __cxa_guard_acquire and friends need to be intercepted in a special way -
913 // regular interceptors will break statically-linked libstdc++. Linux
914 // interceptors are especially defined as weak functions (so that they don't
915 // cause link errors when user defines them as well). So they silently
916 // auto-disable themselves when such symbol is already present in the binary. If
917 // we link libstdc++ statically, it will bring own __cxa_guard_acquire which
918 // will silently replace our interceptor. That's why on Linux we simply export
919 // these interceptors with INTERFACE_ATTRIBUTE.
920 // On OS X, we don't support statically linking, so we just use a regular
923 #define STDCXX_INTERCEPTOR TSAN_INTERCEPTOR
925 #define STDCXX_INTERCEPTOR(rettype, name, ...) \
926 extern "C" rettype INTERFACE_ATTRIBUTE name(__VA_ARGS__)
929 // Used in thread-safe function static initialization.
930 STDCXX_INTERCEPTOR(int, __cxa_guard_acquire
, atomic_uint32_t
*g
) {
931 SCOPED_INTERCEPTOR_RAW(__cxa_guard_acquire
, g
);
932 return guard_acquire(thr
, pc
, g
);
935 STDCXX_INTERCEPTOR(void, __cxa_guard_release
, atomic_uint32_t
*g
) {
936 SCOPED_INTERCEPTOR_RAW(__cxa_guard_release
, g
);
937 guard_release(thr
, pc
, g
, kGuardDone
);
940 STDCXX_INTERCEPTOR(void, __cxa_guard_abort
, atomic_uint32_t
*g
) {
941 SCOPED_INTERCEPTOR_RAW(__cxa_guard_abort
, g
);
942 guard_release(thr
, pc
, g
, kGuardInit
);
946 void DestroyThreadState() {
947 ThreadState
*thr
= cur_thread();
948 Processor
*proc
= thr
->proc();
950 ProcUnwire(proc
, thr
);
953 cur_thread_finalize();
956 void PlatformCleanUpThreadState(ThreadState
*thr
) {
957 ThreadSignalContext
*sctx
= thr
->signal_ctx
;
960 UnmapOrDie(sctx
, sizeof(*sctx
));
963 } // namespace __tsan
965 #if !SANITIZER_MAC && !SANITIZER_NETBSD && !SANITIZER_FREEBSD
966 static void thread_finalize(void *v
) {
969 if (pthread_setspecific(interceptor_ctx()->finalize_key
,
970 (void*)(iter
- 1))) {
971 Printf("ThreadSanitizer: failed to set thread key\n");
976 DestroyThreadState();
982 void* (*callback
)(void *arg
);
989 extern "C" void *__tsan_thread_start_func(void *arg
) {
990 ThreadParam
*p
= (ThreadParam
*)arg
;
991 void* (*callback
)(void *arg
) = p
->callback
;
992 void *param
= p
->param
;
994 ThreadState
*thr
= cur_thread_init();
995 // Thread-local state is not initialized yet.
996 ScopedIgnoreInterceptors ignore
;
997 #if !SANITIZER_MAC && !SANITIZER_NETBSD && !SANITIZER_FREEBSD
998 ThreadIgnoreBegin(thr
, 0);
999 if (pthread_setspecific(interceptor_ctx()->finalize_key
,
1000 (void *)GetPthreadDestructorIterations())) {
1001 Printf("ThreadSanitizer: failed to set thread key\n");
1004 ThreadIgnoreEnd(thr
);
1007 Processor
*proc
= ProcCreate();
1008 ProcWire(proc
, thr
);
1009 ThreadStart(thr
, p
->tid
, GetTid(), ThreadType::Regular
);
1012 void *res
= callback(param
);
1013 // Prevent the callback from being tail called,
1014 // it mixes up stack traces.
1015 volatile int foo
= 42;
1020 TSAN_INTERCEPTOR(int, pthread_create
,
1021 void *th
, void *attr
, void *(*callback
)(void*), void * param
) {
1022 SCOPED_INTERCEPTOR_RAW(pthread_create
, th
, attr
, callback
, param
);
1024 MaybeSpawnBackgroundThread();
1026 if (ctx
->after_multithreaded_fork
) {
1027 if (flags()->die_after_fork
) {
1028 Report("ThreadSanitizer: starting new threads after multi-threaded "
1029 "fork is not supported. Dying (set die_after_fork=0 to override)\n");
1033 "ThreadSanitizer: starting new threads after multi-threaded "
1034 "fork is not supported (pid %lu). Continuing because of "
1035 "die_after_fork=0, but you are on your own\n",
1039 __sanitizer_pthread_attr_t myattr
;
1041 pthread_attr_init(&myattr
);
1045 REAL(pthread_attr_getdetachstate
)(attr
, &detached
);
1046 AdjustStackSize(attr
);
1049 p
.callback
= callback
;
1054 // Otherwise we see false positives in pthread stack manipulation.
1055 ScopedIgnoreInterceptors ignore
;
1056 ThreadIgnoreBegin(thr
, pc
);
1057 res
= REAL(pthread_create
)(th
, attr
, __tsan_thread_start_func
, &p
);
1058 ThreadIgnoreEnd(thr
);
1061 p
.tid
= ThreadCreate(thr
, pc
, *(uptr
*)th
, IsStateDetached(detached
));
1062 CHECK_NE(p
.tid
, kMainTid
);
1063 // Synchronization on p.tid serves two purposes:
1064 // 1. ThreadCreate must finish before the new thread starts.
1065 // Otherwise the new thread can call pthread_detach, but the pthread_t
1066 // identifier is not yet registered in ThreadRegistry by ThreadCreate.
1067 // 2. ThreadStart must finish before this thread continues.
1068 // Otherwise, this thread can call pthread_detach and reset thr->sync
1069 // before the new thread got a chance to acquire from it in ThreadStart.
1073 if (attr
== &myattr
)
1074 pthread_attr_destroy(&myattr
);
1078 TSAN_INTERCEPTOR(int, pthread_join
, void *th
, void **ret
) {
1079 SCOPED_INTERCEPTOR_RAW(pthread_join
, th
, ret
);
1080 Tid tid
= ThreadConsumeTid(thr
, pc
, (uptr
)th
);
1081 ThreadIgnoreBegin(thr
, pc
);
1082 int res
= BLOCK_REAL(pthread_join
)(th
, ret
);
1083 ThreadIgnoreEnd(thr
);
1085 ThreadJoin(thr
, pc
, tid
);
1090 DEFINE_REAL_PTHREAD_FUNCTIONS
1092 TSAN_INTERCEPTOR(int, pthread_detach
, void *th
) {
1093 SCOPED_INTERCEPTOR_RAW(pthread_detach
, th
);
1094 Tid tid
= ThreadConsumeTid(thr
, pc
, (uptr
)th
);
1095 int res
= REAL(pthread_detach
)(th
);
1097 ThreadDetach(thr
, pc
, tid
);
1102 TSAN_INTERCEPTOR(void, pthread_exit
, void *retval
) {
1104 SCOPED_INTERCEPTOR_RAW(pthread_exit
, retval
);
1105 #if !SANITIZER_MAC && !SANITIZER_ANDROID
1106 CHECK_EQ(thr
, &cur_thread_placeholder
);
1109 REAL(pthread_exit
)(retval
);
1113 TSAN_INTERCEPTOR(int, pthread_tryjoin_np
, void *th
, void **ret
) {
1114 SCOPED_INTERCEPTOR_RAW(pthread_tryjoin_np
, th
, ret
);
1115 Tid tid
= ThreadConsumeTid(thr
, pc
, (uptr
)th
);
1116 ThreadIgnoreBegin(thr
, pc
);
1117 int res
= REAL(pthread_tryjoin_np
)(th
, ret
);
1118 ThreadIgnoreEnd(thr
);
1120 ThreadJoin(thr
, pc
, tid
);
1122 ThreadNotJoined(thr
, pc
, tid
, (uptr
)th
);
1126 TSAN_INTERCEPTOR(int, pthread_timedjoin_np
, void *th
, void **ret
,
1127 const struct timespec
*abstime
) {
1128 SCOPED_INTERCEPTOR_RAW(pthread_timedjoin_np
, th
, ret
, abstime
);
1129 Tid tid
= ThreadConsumeTid(thr
, pc
, (uptr
)th
);
1130 ThreadIgnoreBegin(thr
, pc
);
1131 int res
= BLOCK_REAL(pthread_timedjoin_np
)(th
, ret
, abstime
);
1132 ThreadIgnoreEnd(thr
);
1134 ThreadJoin(thr
, pc
, tid
);
1136 ThreadNotJoined(thr
, pc
, tid
, (uptr
)th
);
1142 // NPTL implementation of pthread_cond has 2 versions (2.2.5 and 2.3.2).
1143 // pthread_cond_t has different size in the different versions.
1144 // If call new REAL functions for old pthread_cond_t, they will corrupt memory
1145 // after pthread_cond_t (old cond is smaller).
1146 // If we call old REAL functions for new pthread_cond_t, we will lose some
1147 // functionality (e.g. old functions do not support waiting against
1149 // Proper handling would require to have 2 versions of interceptors as well.
1150 // But this is messy, in particular requires linker scripts when sanitizer
1151 // runtime is linked into a shared library.
1152 // Instead we assume we don't have dynamic libraries built against old
1153 // pthread (2.2.5 is dated by 2002). And provide legacy_pthread_cond flag
1154 // that allows to work with old libraries (but this mode does not support
1155 // some features, e.g. pthread_condattr_getpshared).
1156 static void *init_cond(void *c
, bool force
= false) {
1157 // sizeof(pthread_cond_t) >= sizeof(uptr) in both versions.
1158 // So we allocate additional memory on the side large enough to hold
1159 // any pthread_cond_t object. Always call new REAL functions, but pass
1160 // the aux object to them.
1161 // Note: the code assumes that PTHREAD_COND_INITIALIZER initializes
1162 // first word of pthread_cond_t to zero.
1163 // It's all relevant only for linux.
1164 if (!common_flags()->legacy_pthread_cond
)
1166 atomic_uintptr_t
*p
= (atomic_uintptr_t
*)c
;
1167 uptr cond
= atomic_load(p
, memory_order_acquire
);
1168 if (!force
&& cond
!= 0)
1170 void *newcond
= WRAP(malloc
)(pthread_cond_t_sz
);
1171 internal_memset(newcond
, 0, pthread_cond_t_sz
);
1172 if (atomic_compare_exchange_strong(p
, &cond
, (uptr
)newcond
,
1173 memory_order_acq_rel
))
1175 WRAP(free
)(newcond
);
1182 struct CondMutexUnlockCtx
{
1183 ScopedInterceptor
*si
;
1190 int Cancel() const { return fn(); }
1191 void Unlock() const;
1195 void CondMutexUnlockCtx
<Fn
>::Unlock() const {
1196 // pthread_cond_wait interceptor has enabled async signal delivery
1197 // (see BlockingCall below). Disable async signals since we are running
1198 // tsan code. Also ScopedInterceptor and BlockingCall destructors won't run
1199 // since the thread is cancelled, so we have to manually execute them
1200 // (the thread still can run some user code due to pthread_cleanup_push).
1201 ThreadSignalContext
*ctx
= SigCtx(thr
);
1202 CHECK_EQ(atomic_load(&ctx
->in_blocking_func
, memory_order_relaxed
), 1);
1203 atomic_store(&ctx
->in_blocking_func
, 0, memory_order_relaxed
);
1204 MutexPostLock(thr
, pc
, (uptr
)m
, MutexFlagDoPreLockOnPostLock
);
1205 // Undo BlockingCall ctor effects.
1206 thr
->ignore_interceptors
--;
1207 si
->~ScopedInterceptor();
1211 INTERCEPTOR(int, pthread_cond_init
, void *c
, void *a
) {
1212 void *cond
= init_cond(c
, true);
1213 SCOPED_TSAN_INTERCEPTOR(pthread_cond_init
, cond
, a
);
1214 MemoryAccessRange(thr
, pc
, (uptr
)c
, sizeof(uptr
), true);
1215 return REAL(pthread_cond_init
)(cond
, a
);
1219 int cond_wait(ThreadState
*thr
, uptr pc
, ScopedInterceptor
*si
, const Fn
&fn
,
1221 MemoryAccessRange(thr
, pc
, (uptr
)c
, sizeof(uptr
), false);
1222 MutexUnlock(thr
, pc
, (uptr
)m
);
1224 // This ensures that we handle mutex lock even in case of pthread_cancel.
1225 // See test/tsan/cond_cancel.cpp.
1227 // Enable signal delivery while the thread is blocked.
1228 BlockingCall
bc(thr
);
1229 CondMutexUnlockCtx
<Fn
> arg
= {si
, thr
, pc
, m
, c
, fn
};
1230 res
= call_pthread_cancel_with_cleanup(
1231 [](void *arg
) -> int {
1232 return ((const CondMutexUnlockCtx
<Fn
> *)arg
)->Cancel();
1234 [](void *arg
) { ((const CondMutexUnlockCtx
<Fn
> *)arg
)->Unlock(); },
1237 if (res
== errno_EOWNERDEAD
) MutexRepair(thr
, pc
, (uptr
)m
);
1238 MutexPostLock(thr
, pc
, (uptr
)m
, MutexFlagDoPreLockOnPostLock
);
1242 INTERCEPTOR(int, pthread_cond_wait
, void *c
, void *m
) {
1243 void *cond
= init_cond(c
);
1244 SCOPED_TSAN_INTERCEPTOR(pthread_cond_wait
, cond
, m
);
1246 thr
, pc
, &si
, [=]() { return REAL(pthread_cond_wait
)(cond
, m
); }, cond
,
1250 INTERCEPTOR(int, pthread_cond_timedwait
, void *c
, void *m
, void *abstime
) {
1251 void *cond
= init_cond(c
);
1252 SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait
, cond
, m
, abstime
);
1255 [=]() { return REAL(pthread_cond_timedwait
)(cond
, m
, abstime
); }, cond
,
1260 INTERCEPTOR(int, pthread_cond_clockwait
, void *c
, void *m
,
1261 __sanitizer_clockid_t clock
, void *abstime
) {
1262 void *cond
= init_cond(c
);
1263 SCOPED_TSAN_INTERCEPTOR(pthread_cond_clockwait
, cond
, m
, clock
, abstime
);
1266 [=]() { return REAL(pthread_cond_clockwait
)(cond
, m
, clock
, abstime
); },
1269 #define TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT TSAN_INTERCEPT(pthread_cond_clockwait)
1271 #define TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT
1275 INTERCEPTOR(int, pthread_cond_timedwait_relative_np
, void *c
, void *m
,
1277 void *cond
= init_cond(c
);
1278 SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait_relative_np
, cond
, m
, reltime
);
1282 return REAL(pthread_cond_timedwait_relative_np
)(cond
, m
, reltime
);
1288 INTERCEPTOR(int, pthread_cond_signal
, void *c
) {
1289 void *cond
= init_cond(c
);
1290 SCOPED_TSAN_INTERCEPTOR(pthread_cond_signal
, cond
);
1291 MemoryAccessRange(thr
, pc
, (uptr
)c
, sizeof(uptr
), false);
1292 return REAL(pthread_cond_signal
)(cond
);
1295 INTERCEPTOR(int, pthread_cond_broadcast
, void *c
) {
1296 void *cond
= init_cond(c
);
1297 SCOPED_TSAN_INTERCEPTOR(pthread_cond_broadcast
, cond
);
1298 MemoryAccessRange(thr
, pc
, (uptr
)c
, sizeof(uptr
), false);
1299 return REAL(pthread_cond_broadcast
)(cond
);
1302 INTERCEPTOR(int, pthread_cond_destroy
, void *c
) {
1303 void *cond
= init_cond(c
);
1304 SCOPED_TSAN_INTERCEPTOR(pthread_cond_destroy
, cond
);
1305 MemoryAccessRange(thr
, pc
, (uptr
)c
, sizeof(uptr
), true);
1306 int res
= REAL(pthread_cond_destroy
)(cond
);
1307 if (common_flags()->legacy_pthread_cond
) {
1308 // Free our aux cond and zero the pointer to not leave dangling pointers.
1310 atomic_store((atomic_uintptr_t
*)c
, 0, memory_order_relaxed
);
1315 TSAN_INTERCEPTOR(int, pthread_mutex_init
, void *m
, void *a
) {
1316 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_init
, m
, a
);
1317 int res
= REAL(pthread_mutex_init
)(m
, a
);
1322 if (REAL(pthread_mutexattr_gettype
)(a
, &type
) == 0)
1323 if (type
== PTHREAD_MUTEX_RECURSIVE
||
1324 type
== PTHREAD_MUTEX_RECURSIVE_NP
)
1325 flagz
|= MutexFlagWriteReentrant
;
1327 MutexCreate(thr
, pc
, (uptr
)m
, flagz
);
1332 TSAN_INTERCEPTOR(int, pthread_mutex_destroy
, void *m
) {
1333 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_destroy
, m
);
1334 int res
= REAL(pthread_mutex_destroy
)(m
);
1335 if (res
== 0 || res
== errno_EBUSY
) {
1336 MutexDestroy(thr
, pc
, (uptr
)m
);
1341 TSAN_INTERCEPTOR(int, pthread_mutex_trylock
, void *m
) {
1342 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_trylock
, m
);
1343 int res
= REAL(pthread_mutex_trylock
)(m
);
1344 if (res
== errno_EOWNERDEAD
)
1345 MutexRepair(thr
, pc
, (uptr
)m
);
1346 if (res
== 0 || res
== errno_EOWNERDEAD
)
1347 MutexPostLock(thr
, pc
, (uptr
)m
, MutexFlagTryLock
);
1352 TSAN_INTERCEPTOR(int, pthread_mutex_timedlock
, void *m
, void *abstime
) {
1353 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_timedlock
, m
, abstime
);
1354 int res
= REAL(pthread_mutex_timedlock
)(m
, abstime
);
1356 MutexPostLock(thr
, pc
, (uptr
)m
, MutexFlagTryLock
);
1363 TSAN_INTERCEPTOR(int, pthread_spin_init
, void *m
, int pshared
) {
1364 SCOPED_TSAN_INTERCEPTOR(pthread_spin_init
, m
, pshared
);
1365 int res
= REAL(pthread_spin_init
)(m
, pshared
);
1367 MutexCreate(thr
, pc
, (uptr
)m
);
1372 TSAN_INTERCEPTOR(int, pthread_spin_destroy
, void *m
) {
1373 SCOPED_TSAN_INTERCEPTOR(pthread_spin_destroy
, m
);
1374 int res
= REAL(pthread_spin_destroy
)(m
);
1376 MutexDestroy(thr
, pc
, (uptr
)m
);
1381 TSAN_INTERCEPTOR(int, pthread_spin_lock
, void *m
) {
1382 SCOPED_TSAN_INTERCEPTOR(pthread_spin_lock
, m
);
1383 MutexPreLock(thr
, pc
, (uptr
)m
);
1384 int res
= REAL(pthread_spin_lock
)(m
);
1386 MutexPostLock(thr
, pc
, (uptr
)m
);
1391 TSAN_INTERCEPTOR(int, pthread_spin_trylock
, void *m
) {
1392 SCOPED_TSAN_INTERCEPTOR(pthread_spin_trylock
, m
);
1393 int res
= REAL(pthread_spin_trylock
)(m
);
1395 MutexPostLock(thr
, pc
, (uptr
)m
, MutexFlagTryLock
);
1400 TSAN_INTERCEPTOR(int, pthread_spin_unlock
, void *m
) {
1401 SCOPED_TSAN_INTERCEPTOR(pthread_spin_unlock
, m
);
1402 MutexUnlock(thr
, pc
, (uptr
)m
);
1403 int res
= REAL(pthread_spin_unlock
)(m
);
1408 TSAN_INTERCEPTOR(int, pthread_rwlock_init
, void *m
, void *a
) {
1409 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_init
, m
, a
);
1410 int res
= REAL(pthread_rwlock_init
)(m
, a
);
1412 MutexCreate(thr
, pc
, (uptr
)m
);
1417 TSAN_INTERCEPTOR(int, pthread_rwlock_destroy
, void *m
) {
1418 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_destroy
, m
);
1419 int res
= REAL(pthread_rwlock_destroy
)(m
);
1421 MutexDestroy(thr
, pc
, (uptr
)m
);
1426 TSAN_INTERCEPTOR(int, pthread_rwlock_rdlock
, void *m
) {
1427 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_rdlock
, m
);
1428 MutexPreReadLock(thr
, pc
, (uptr
)m
);
1429 int res
= REAL(pthread_rwlock_rdlock
)(m
);
1431 MutexPostReadLock(thr
, pc
, (uptr
)m
);
1436 TSAN_INTERCEPTOR(int, pthread_rwlock_tryrdlock
, void *m
) {
1437 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_tryrdlock
, m
);
1438 int res
= REAL(pthread_rwlock_tryrdlock
)(m
);
1440 MutexPostReadLock(thr
, pc
, (uptr
)m
, MutexFlagTryLock
);
1446 TSAN_INTERCEPTOR(int, pthread_rwlock_timedrdlock
, void *m
, void *abstime
) {
1447 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedrdlock
, m
, abstime
);
1448 int res
= REAL(pthread_rwlock_timedrdlock
)(m
, abstime
);
1450 MutexPostReadLock(thr
, pc
, (uptr
)m
);
1456 TSAN_INTERCEPTOR(int, pthread_rwlock_wrlock
, void *m
) {
1457 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_wrlock
, m
);
1458 MutexPreLock(thr
, pc
, (uptr
)m
);
1459 int res
= REAL(pthread_rwlock_wrlock
)(m
);
1461 MutexPostLock(thr
, pc
, (uptr
)m
);
1466 TSAN_INTERCEPTOR(int, pthread_rwlock_trywrlock
, void *m
) {
1467 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_trywrlock
, m
);
1468 int res
= REAL(pthread_rwlock_trywrlock
)(m
);
1470 MutexPostLock(thr
, pc
, (uptr
)m
, MutexFlagTryLock
);
1476 TSAN_INTERCEPTOR(int, pthread_rwlock_timedwrlock
, void *m
, void *abstime
) {
1477 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedwrlock
, m
, abstime
);
1478 int res
= REAL(pthread_rwlock_timedwrlock
)(m
, abstime
);
1480 MutexPostLock(thr
, pc
, (uptr
)m
, MutexFlagTryLock
);
1486 TSAN_INTERCEPTOR(int, pthread_rwlock_unlock
, void *m
) {
1487 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_unlock
, m
);
1488 MutexReadOrWriteUnlock(thr
, pc
, (uptr
)m
);
1489 int res
= REAL(pthread_rwlock_unlock
)(m
);
1494 TSAN_INTERCEPTOR(int, pthread_barrier_init
, void *b
, void *a
, unsigned count
) {
1495 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_init
, b
, a
, count
);
1496 MemoryAccess(thr
, pc
, (uptr
)b
, 1, kAccessWrite
);
1497 int res
= REAL(pthread_barrier_init
)(b
, a
, count
);
1501 TSAN_INTERCEPTOR(int, pthread_barrier_destroy
, void *b
) {
1502 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_destroy
, b
);
1503 MemoryAccess(thr
, pc
, (uptr
)b
, 1, kAccessWrite
);
1504 int res
= REAL(pthread_barrier_destroy
)(b
);
1508 TSAN_INTERCEPTOR(int, pthread_barrier_wait
, void *b
) {
1509 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_wait
, b
);
1510 Release(thr
, pc
, (uptr
)b
);
1511 MemoryAccess(thr
, pc
, (uptr
)b
, 1, kAccessRead
);
1512 int res
= REAL(pthread_barrier_wait
)(b
);
1513 MemoryAccess(thr
, pc
, (uptr
)b
, 1, kAccessRead
);
1514 if (res
== 0 || res
== PTHREAD_BARRIER_SERIAL_THREAD
) {
1515 Acquire(thr
, pc
, (uptr
)b
);
1521 TSAN_INTERCEPTOR(int, pthread_once
, void *o
, void (*f
)()) {
1522 SCOPED_INTERCEPTOR_RAW(pthread_once
, o
, f
);
1523 if (o
== 0 || f
== 0)
1524 return errno_EINVAL
;
1528 a
= static_cast<atomic_uint32_t
*>((void *)((char *)o
+ sizeof(long_t
)));
1529 else if (SANITIZER_NETBSD
)
1530 a
= static_cast<atomic_uint32_t
*>
1531 ((void *)((char *)o
+ __sanitizer::pthread_mutex_t_sz
));
1533 a
= static_cast<atomic_uint32_t
*>(o
);
1535 // Mac OS X appears to use pthread_once() where calling BlockingRegion hooks
1536 // result in crashes due to too little stack space.
1537 if (guard_acquire(thr
, pc
, a
, !SANITIZER_MAC
)) {
1539 guard_release(thr
, pc
, a
, kGuardDone
);
1545 TSAN_INTERCEPTOR(int, __fxstat
, int version
, int fd
, void *buf
) {
1546 SCOPED_TSAN_INTERCEPTOR(__fxstat
, version
, fd
, buf
);
1548 FdAccess(thr
, pc
, fd
);
1549 return REAL(__fxstat
)(version
, fd
, buf
);
1551 #define TSAN_MAYBE_INTERCEPT___FXSTAT TSAN_INTERCEPT(__fxstat)
1553 #define TSAN_MAYBE_INTERCEPT___FXSTAT
1556 TSAN_INTERCEPTOR(int, fstat
, int fd
, void *buf
) {
1558 SCOPED_TSAN_INTERCEPTOR(__fxstat
, 0, fd
, buf
);
1560 FdAccess(thr
, pc
, fd
);
1561 return REAL(__fxstat
)(0, fd
, buf
);
1563 SCOPED_TSAN_INTERCEPTOR(fstat
, fd
, buf
);
1565 FdAccess(thr
, pc
, fd
);
1566 return REAL(fstat
)(fd
, buf
);
1571 TSAN_INTERCEPTOR(int, __fxstat64
, int version
, int fd
, void *buf
) {
1572 SCOPED_TSAN_INTERCEPTOR(__fxstat64
, version
, fd
, buf
);
1574 FdAccess(thr
, pc
, fd
);
1575 return REAL(__fxstat64
)(version
, fd
, buf
);
1577 #define TSAN_MAYBE_INTERCEPT___FXSTAT64 TSAN_INTERCEPT(__fxstat64)
1579 #define TSAN_MAYBE_INTERCEPT___FXSTAT64
1583 TSAN_INTERCEPTOR(int, fstat64
, int fd
, void *buf
) {
1584 SCOPED_TSAN_INTERCEPTOR(__fxstat64
, 0, fd
, buf
);
1586 FdAccess(thr
, pc
, fd
);
1587 return REAL(__fxstat64
)(0, fd
, buf
);
1589 #define TSAN_MAYBE_INTERCEPT_FSTAT64 TSAN_INTERCEPT(fstat64)
1591 #define TSAN_MAYBE_INTERCEPT_FSTAT64
1594 TSAN_INTERCEPTOR(int, open
, const char *name
, int oflag
, ...) {
1596 va_start(ap
, oflag
);
1597 mode_t mode
= va_arg(ap
, int);
1599 SCOPED_TSAN_INTERCEPTOR(open
, name
, oflag
, mode
);
1600 READ_STRING(thr
, pc
, name
, 0);
1601 int fd
= REAL(open
)(name
, oflag
, mode
);
1603 FdFileCreate(thr
, pc
, fd
);
1608 TSAN_INTERCEPTOR(int, open64
, const char *name
, int oflag
, ...) {
1610 va_start(ap
, oflag
);
1611 mode_t mode
= va_arg(ap
, int);
1613 SCOPED_TSAN_INTERCEPTOR(open64
, name
, oflag
, mode
);
1614 READ_STRING(thr
, pc
, name
, 0);
1615 int fd
= REAL(open64
)(name
, oflag
, mode
);
1617 FdFileCreate(thr
, pc
, fd
);
1620 #define TSAN_MAYBE_INTERCEPT_OPEN64 TSAN_INTERCEPT(open64)
1622 #define TSAN_MAYBE_INTERCEPT_OPEN64
1625 TSAN_INTERCEPTOR(int, creat
, const char *name
, int mode
) {
1626 SCOPED_TSAN_INTERCEPTOR(creat
, name
, mode
);
1627 READ_STRING(thr
, pc
, name
, 0);
1628 int fd
= REAL(creat
)(name
, mode
);
1630 FdFileCreate(thr
, pc
, fd
);
1635 TSAN_INTERCEPTOR(int, creat64
, const char *name
, int mode
) {
1636 SCOPED_TSAN_INTERCEPTOR(creat64
, name
, mode
);
1637 READ_STRING(thr
, pc
, name
, 0);
1638 int fd
= REAL(creat64
)(name
, mode
);
1640 FdFileCreate(thr
, pc
, fd
);
1643 #define TSAN_MAYBE_INTERCEPT_CREAT64 TSAN_INTERCEPT(creat64)
1645 #define TSAN_MAYBE_INTERCEPT_CREAT64
1648 TSAN_INTERCEPTOR(int, dup
, int oldfd
) {
1649 SCOPED_TSAN_INTERCEPTOR(dup
, oldfd
);
1650 int newfd
= REAL(dup
)(oldfd
);
1651 if (oldfd
>= 0 && newfd
>= 0 && newfd
!= oldfd
)
1652 FdDup(thr
, pc
, oldfd
, newfd
, true);
1656 TSAN_INTERCEPTOR(int, dup2
, int oldfd
, int newfd
) {
1657 SCOPED_TSAN_INTERCEPTOR(dup2
, oldfd
, newfd
);
1658 int newfd2
= REAL(dup2
)(oldfd
, newfd
);
1659 if (oldfd
>= 0 && newfd2
>= 0 && newfd2
!= oldfd
)
1660 FdDup(thr
, pc
, oldfd
, newfd2
, false);
1665 TSAN_INTERCEPTOR(int, dup3
, int oldfd
, int newfd
, int flags
) {
1666 SCOPED_TSAN_INTERCEPTOR(dup3
, oldfd
, newfd
, flags
);
1667 int newfd2
= REAL(dup3
)(oldfd
, newfd
, flags
);
1668 if (oldfd
>= 0 && newfd2
>= 0 && newfd2
!= oldfd
)
1669 FdDup(thr
, pc
, oldfd
, newfd2
, false);
1675 TSAN_INTERCEPTOR(int, eventfd
, unsigned initval
, int flags
) {
1676 SCOPED_TSAN_INTERCEPTOR(eventfd
, initval
, flags
);
1677 int fd
= REAL(eventfd
)(initval
, flags
);
1679 FdEventCreate(thr
, pc
, fd
);
1682 #define TSAN_MAYBE_INTERCEPT_EVENTFD TSAN_INTERCEPT(eventfd)
1684 #define TSAN_MAYBE_INTERCEPT_EVENTFD
1688 TSAN_INTERCEPTOR(int, signalfd
, int fd
, void *mask
, int flags
) {
1689 SCOPED_INTERCEPTOR_RAW(signalfd
, fd
, mask
, flags
);
1690 FdClose(thr
, pc
, fd
);
1691 fd
= REAL(signalfd
)(fd
, mask
, flags
);
1692 if (!MustIgnoreInterceptor(thr
))
1693 FdSignalCreate(thr
, pc
, fd
);
1696 #define TSAN_MAYBE_INTERCEPT_SIGNALFD TSAN_INTERCEPT(signalfd)
1698 #define TSAN_MAYBE_INTERCEPT_SIGNALFD
1702 TSAN_INTERCEPTOR(int, inotify_init
, int fake
) {
1703 SCOPED_TSAN_INTERCEPTOR(inotify_init
, fake
);
1704 int fd
= REAL(inotify_init
)(fake
);
1706 FdInotifyCreate(thr
, pc
, fd
);
1709 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT TSAN_INTERCEPT(inotify_init)
1711 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT
1715 TSAN_INTERCEPTOR(int, inotify_init1
, int flags
) {
1716 SCOPED_TSAN_INTERCEPTOR(inotify_init1
, flags
);
1717 int fd
= REAL(inotify_init1
)(flags
);
1719 FdInotifyCreate(thr
, pc
, fd
);
1722 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1 TSAN_INTERCEPT(inotify_init1)
1724 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1
1727 TSAN_INTERCEPTOR(int, socket
, int domain
, int type
, int protocol
) {
1728 SCOPED_TSAN_INTERCEPTOR(socket
, domain
, type
, protocol
);
1729 int fd
= REAL(socket
)(domain
, type
, protocol
);
1731 FdSocketCreate(thr
, pc
, fd
);
1735 TSAN_INTERCEPTOR(int, socketpair
, int domain
, int type
, int protocol
, int *fd
) {
1736 SCOPED_TSAN_INTERCEPTOR(socketpair
, domain
, type
, protocol
, fd
);
1737 int res
= REAL(socketpair
)(domain
, type
, protocol
, fd
);
1738 if (res
== 0 && fd
[0] >= 0 && fd
[1] >= 0)
1739 FdPipeCreate(thr
, pc
, fd
[0], fd
[1]);
1743 TSAN_INTERCEPTOR(int, connect
, int fd
, void *addr
, unsigned addrlen
) {
1744 SCOPED_TSAN_INTERCEPTOR(connect
, fd
, addr
, addrlen
);
1745 FdSocketConnecting(thr
, pc
, fd
);
1746 int res
= REAL(connect
)(fd
, addr
, addrlen
);
1747 if (res
== 0 && fd
>= 0)
1748 FdSocketConnect(thr
, pc
, fd
);
1752 TSAN_INTERCEPTOR(int, bind
, int fd
, void *addr
, unsigned addrlen
) {
1753 SCOPED_TSAN_INTERCEPTOR(bind
, fd
, addr
, addrlen
);
1754 int res
= REAL(bind
)(fd
, addr
, addrlen
);
1755 if (fd
> 0 && res
== 0)
1756 FdAccess(thr
, pc
, fd
);
1760 TSAN_INTERCEPTOR(int, listen
, int fd
, int backlog
) {
1761 SCOPED_TSAN_INTERCEPTOR(listen
, fd
, backlog
);
1762 int res
= REAL(listen
)(fd
, backlog
);
1763 if (fd
> 0 && res
== 0)
1764 FdAccess(thr
, pc
, fd
);
1768 TSAN_INTERCEPTOR(int, close
, int fd
) {
1769 SCOPED_INTERCEPTOR_RAW(close
, fd
);
1770 FdClose(thr
, pc
, fd
);
1771 return REAL(close
)(fd
);
1775 TSAN_INTERCEPTOR(int, __close
, int fd
) {
1776 SCOPED_INTERCEPTOR_RAW(__close
, fd
);
1777 FdClose(thr
, pc
, fd
);
1778 return REAL(__close
)(fd
);
1780 #define TSAN_MAYBE_INTERCEPT___CLOSE TSAN_INTERCEPT(__close)
1782 #define TSAN_MAYBE_INTERCEPT___CLOSE
1786 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1787 TSAN_INTERCEPTOR(void, __res_iclose
, void *state
, bool free_addr
) {
1788 SCOPED_INTERCEPTOR_RAW(__res_iclose
, state
, free_addr
);
1790 int cnt
= ExtractResolvFDs(state
, fds
, ARRAY_SIZE(fds
));
1791 for (int i
= 0; i
< cnt
; i
++) FdClose(thr
, pc
, fds
[i
]);
1792 REAL(__res_iclose
)(state
, free_addr
);
1794 #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE TSAN_INTERCEPT(__res_iclose)
1796 #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE
1799 TSAN_INTERCEPTOR(int, pipe
, int *pipefd
) {
1800 SCOPED_TSAN_INTERCEPTOR(pipe
, pipefd
);
1801 int res
= REAL(pipe
)(pipefd
);
1802 if (res
== 0 && pipefd
[0] >= 0 && pipefd
[1] >= 0)
1803 FdPipeCreate(thr
, pc
, pipefd
[0], pipefd
[1]);
1808 TSAN_INTERCEPTOR(int, pipe2
, int *pipefd
, int flags
) {
1809 SCOPED_TSAN_INTERCEPTOR(pipe2
, pipefd
, flags
);
1810 int res
= REAL(pipe2
)(pipefd
, flags
);
1811 if (res
== 0 && pipefd
[0] >= 0 && pipefd
[1] >= 0)
1812 FdPipeCreate(thr
, pc
, pipefd
[0], pipefd
[1]);
1817 TSAN_INTERCEPTOR(int, unlink
, char *path
) {
1818 SCOPED_TSAN_INTERCEPTOR(unlink
, path
);
1819 Release(thr
, pc
, File2addr(path
));
1820 int res
= REAL(unlink
)(path
);
1824 TSAN_INTERCEPTOR(void*, tmpfile
, int fake
) {
1825 SCOPED_TSAN_INTERCEPTOR(tmpfile
, fake
);
1826 void *res
= REAL(tmpfile
)(fake
);
1828 int fd
= fileno_unlocked(res
);
1830 FdFileCreate(thr
, pc
, fd
);
1836 TSAN_INTERCEPTOR(void*, tmpfile64
, int fake
) {
1837 SCOPED_TSAN_INTERCEPTOR(tmpfile64
, fake
);
1838 void *res
= REAL(tmpfile64
)(fake
);
1840 int fd
= fileno_unlocked(res
);
1842 FdFileCreate(thr
, pc
, fd
);
1846 #define TSAN_MAYBE_INTERCEPT_TMPFILE64 TSAN_INTERCEPT(tmpfile64)
1848 #define TSAN_MAYBE_INTERCEPT_TMPFILE64
1851 static void FlushStreams() {
1852 // Flushing all the streams here may freeze the process if a child thread is
1853 // performing file stream operations at the same time.
1854 REAL(fflush
)(stdout
);
1855 REAL(fflush
)(stderr
);
1858 TSAN_INTERCEPTOR(void, abort
, int fake
) {
1859 SCOPED_TSAN_INTERCEPTOR(abort
, fake
);
1864 TSAN_INTERCEPTOR(int, rmdir
, char *path
) {
1865 SCOPED_TSAN_INTERCEPTOR(rmdir
, path
);
1866 Release(thr
, pc
, Dir2addr(path
));
1867 int res
= REAL(rmdir
)(path
);
1871 TSAN_INTERCEPTOR(int, closedir
, void *dirp
) {
1872 SCOPED_INTERCEPTOR_RAW(closedir
, dirp
);
1874 int fd
= dirfd(dirp
);
1875 FdClose(thr
, pc
, fd
);
1877 return REAL(closedir
)(dirp
);
1881 TSAN_INTERCEPTOR(int, epoll_create
, int size
) {
1882 SCOPED_TSAN_INTERCEPTOR(epoll_create
, size
);
1883 int fd
= REAL(epoll_create
)(size
);
1885 FdPollCreate(thr
, pc
, fd
);
1889 TSAN_INTERCEPTOR(int, epoll_create1
, int flags
) {
1890 SCOPED_TSAN_INTERCEPTOR(epoll_create1
, flags
);
1891 int fd
= REAL(epoll_create1
)(flags
);
1893 FdPollCreate(thr
, pc
, fd
);
1897 TSAN_INTERCEPTOR(int, epoll_ctl
, int epfd
, int op
, int fd
, void *ev
) {
1898 SCOPED_TSAN_INTERCEPTOR(epoll_ctl
, epfd
, op
, fd
, ev
);
1900 FdAccess(thr
, pc
, epfd
);
1901 if (epfd
>= 0 && fd
>= 0)
1902 FdAccess(thr
, pc
, fd
);
1903 if (op
== EPOLL_CTL_ADD
&& epfd
>= 0)
1904 FdRelease(thr
, pc
, epfd
);
1905 int res
= REAL(epoll_ctl
)(epfd
, op
, fd
, ev
);
1909 TSAN_INTERCEPTOR(int, epoll_wait
, int epfd
, void *ev
, int cnt
, int timeout
) {
1910 SCOPED_TSAN_INTERCEPTOR(epoll_wait
, epfd
, ev
, cnt
, timeout
);
1912 FdAccess(thr
, pc
, epfd
);
1913 int res
= BLOCK_REAL(epoll_wait
)(epfd
, ev
, cnt
, timeout
);
1914 if (res
> 0 && epfd
>= 0)
1915 FdAcquire(thr
, pc
, epfd
);
1919 TSAN_INTERCEPTOR(int, epoll_pwait
, int epfd
, void *ev
, int cnt
, int timeout
,
1921 SCOPED_TSAN_INTERCEPTOR(epoll_pwait
, epfd
, ev
, cnt
, timeout
, sigmask
);
1923 FdAccess(thr
, pc
, epfd
);
1924 int res
= BLOCK_REAL(epoll_pwait
)(epfd
, ev
, cnt
, timeout
, sigmask
);
1925 if (res
> 0 && epfd
>= 0)
1926 FdAcquire(thr
, pc
, epfd
);
1930 #define TSAN_MAYBE_INTERCEPT_EPOLL \
1931 TSAN_INTERCEPT(epoll_create); \
1932 TSAN_INTERCEPT(epoll_create1); \
1933 TSAN_INTERCEPT(epoll_ctl); \
1934 TSAN_INTERCEPT(epoll_wait); \
1935 TSAN_INTERCEPT(epoll_pwait)
1937 #define TSAN_MAYBE_INTERCEPT_EPOLL
1940 // The following functions are intercepted merely to process pending signals.
1941 // If program blocks signal X, we must deliver the signal before the function
1942 // returns. Similarly, if program unblocks a signal (or returns from sigsuspend)
1943 // it's better to deliver the signal straight away.
1944 TSAN_INTERCEPTOR(int, sigsuspend
, const __sanitizer_sigset_t
*mask
) {
1945 SCOPED_TSAN_INTERCEPTOR(sigsuspend
, mask
);
1946 return REAL(sigsuspend
)(mask
);
1949 TSAN_INTERCEPTOR(int, sigblock
, int mask
) {
1950 SCOPED_TSAN_INTERCEPTOR(sigblock
, mask
);
1951 return REAL(sigblock
)(mask
);
1954 TSAN_INTERCEPTOR(int, sigsetmask
, int mask
) {
1955 SCOPED_TSAN_INTERCEPTOR(sigsetmask
, mask
);
1956 return REAL(sigsetmask
)(mask
);
1959 TSAN_INTERCEPTOR(int, pthread_sigmask
, int how
, const __sanitizer_sigset_t
*set
,
1960 __sanitizer_sigset_t
*oldset
) {
1961 SCOPED_TSAN_INTERCEPTOR(pthread_sigmask
, how
, set
, oldset
);
1962 return REAL(pthread_sigmask
)(how
, set
, oldset
);
1967 static void ReportErrnoSpoiling(ThreadState
*thr
, uptr pc
, int sig
) {
1968 VarSizeStackTrace stack
;
1969 // StackTrace::GetNestInstructionPc(pc) is used because return address is
1970 // expected, OutputReport() will undo this.
1971 ObtainCurrentStack(thr
, StackTrace::GetNextInstructionPc(pc
), &stack
);
1972 ThreadRegistryLock
l(&ctx
->thread_registry
);
1973 ScopedReport
rep(ReportTypeErrnoInSignal
);
1975 if (!IsFiredSuppression(ctx
, ReportTypeErrnoInSignal
, stack
)) {
1976 rep
.AddStack(stack
, true);
1977 OutputReport(thr
, rep
);
1981 static void CallUserSignalHandler(ThreadState
*thr
, bool sync
, bool acquire
,
1982 int sig
, __sanitizer_siginfo
*info
,
1985 __sanitizer_sigaction
*sigactions
= interceptor_ctx()->sigactions
;
1987 Acquire(thr
, 0, (uptr
)&sigactions
[sig
]);
1988 // Signals are generally asynchronous, so if we receive a signals when
1989 // ignores are enabled we should disable ignores. This is critical for sync
1990 // and interceptors, because otherwise we can miss synchronization and report
1992 int ignore_reads_and_writes
= thr
->ignore_reads_and_writes
;
1993 int ignore_interceptors
= thr
->ignore_interceptors
;
1994 int ignore_sync
= thr
->ignore_sync
;
1995 // For symbolizer we only process SIGSEGVs synchronously
1996 // (bug in symbolizer or in tsan). But we want to reset
1997 // in_symbolizer to fail gracefully. Symbolizer and user code
1998 // use different memory allocators, so if we don't reset
1999 // in_symbolizer we can get memory allocated with one being
2000 // feed with another, which can cause more crashes.
2001 int in_symbolizer
= thr
->in_symbolizer
;
2002 if (!ctx
->after_multithreaded_fork
) {
2003 thr
->ignore_reads_and_writes
= 0;
2004 thr
->fast_state
.ClearIgnoreBit();
2005 thr
->ignore_interceptors
= 0;
2006 thr
->ignore_sync
= 0;
2007 thr
->in_symbolizer
= 0;
2009 // Ensure that the handler does not spoil errno.
2010 const int saved_errno
= errno
;
2012 // This code races with sigaction. Be careful to not read sa_sigaction twice.
2013 // Also need to remember pc for reporting before the call,
2014 // because the handler can reset it.
2015 volatile uptr pc
= (sigactions
[sig
].sa_flags
& SA_SIGINFO
)
2016 ? (uptr
)sigactions
[sig
].sigaction
2017 : (uptr
)sigactions
[sig
].handler
;
2018 if (pc
!= sig_dfl
&& pc
!= sig_ign
) {
2019 // The callback can be either sa_handler or sa_sigaction.
2020 // They have different signatures, but we assume that passing
2021 // additional arguments to sa_handler works and is harmless.
2022 ((__sanitizer_sigactionhandler_ptr
)pc
)(sig
, info
, uctx
);
2024 if (!ctx
->after_multithreaded_fork
) {
2025 thr
->ignore_reads_and_writes
= ignore_reads_and_writes
;
2026 if (ignore_reads_and_writes
)
2027 thr
->fast_state
.SetIgnoreBit();
2028 thr
->ignore_interceptors
= ignore_interceptors
;
2029 thr
->ignore_sync
= ignore_sync
;
2030 thr
->in_symbolizer
= in_symbolizer
;
2032 // We do not detect errno spoiling for SIGTERM,
2033 // because some SIGTERM handlers do spoil errno but reraise SIGTERM,
2034 // tsan reports false positive in such case.
2035 // It's difficult to properly detect this situation (reraise),
2036 // because in async signal processing case (when handler is called directly
2037 // from rtl_generic_sighandler) we have not yet received the reraised
2038 // signal; and it looks too fragile to intercept all ways to reraise a signal.
2039 if (ShouldReport(thr
, ReportTypeErrnoInSignal
) && !sync
&& sig
!= SIGTERM
&&
2041 ReportErrnoSpoiling(thr
, pc
, sig
);
2042 errno
= saved_errno
;
2045 void ProcessPendingSignalsImpl(ThreadState
*thr
) {
2046 atomic_store(&thr
->pending_signals
, 0, memory_order_relaxed
);
2047 ThreadSignalContext
*sctx
= SigCtx(thr
);
2050 atomic_fetch_add(&thr
->in_signal_handler
, 1, memory_order_relaxed
);
2051 internal_sigfillset(&sctx
->emptyset
);
2052 int res
= REAL(pthread_sigmask
)(SIG_SETMASK
, &sctx
->emptyset
, &sctx
->oldset
);
2054 for (int sig
= 0; sig
< kSigCount
; sig
++) {
2055 SignalDesc
*signal
= &sctx
->pending_signals
[sig
];
2056 if (signal
->armed
) {
2057 signal
->armed
= false;
2058 CallUserSignalHandler(thr
, false, true, sig
, &signal
->siginfo
,
2062 res
= REAL(pthread_sigmask
)(SIG_SETMASK
, &sctx
->oldset
, 0);
2064 atomic_fetch_add(&thr
->in_signal_handler
, -1, memory_order_relaxed
);
2067 } // namespace __tsan
2069 static bool is_sync_signal(ThreadSignalContext
*sctx
, int sig
) {
2070 return sig
== SIGSEGV
|| sig
== SIGBUS
|| sig
== SIGILL
|| sig
== SIGTRAP
||
2071 sig
== SIGABRT
|| sig
== SIGFPE
|| sig
== SIGPIPE
|| sig
== SIGSYS
||
2072 // If we are sending signal to ourselves, we must process it now.
2073 (sctx
&& sig
== sctx
->int_signal_send
);
2076 void sighandler(int sig
, __sanitizer_siginfo
*info
, void *ctx
) {
2077 ThreadState
*thr
= cur_thread_init();
2078 ThreadSignalContext
*sctx
= SigCtx(thr
);
2079 if (sig
< 0 || sig
>= kSigCount
) {
2080 VPrintf(1, "ThreadSanitizer: ignoring signal %d\n", sig
);
2083 // Don't mess with synchronous signals.
2084 const bool sync
= is_sync_signal(sctx
, sig
);
2086 // If we are in blocking function, we can safely process it now
2087 // (but check if we are in a recursive interceptor,
2088 // i.e. pthread_join()->munmap()).
2089 (sctx
&& atomic_load(&sctx
->in_blocking_func
, memory_order_relaxed
))) {
2090 atomic_fetch_add(&thr
->in_signal_handler
, 1, memory_order_relaxed
);
2091 if (sctx
&& atomic_load(&sctx
->in_blocking_func
, memory_order_relaxed
)) {
2092 atomic_store(&sctx
->in_blocking_func
, 0, memory_order_relaxed
);
2093 CallUserSignalHandler(thr
, sync
, true, sig
, info
, ctx
);
2094 atomic_store(&sctx
->in_blocking_func
, 1, memory_order_relaxed
);
2096 // Be very conservative with when we do acquire in this case.
2097 // It's unsafe to do acquire in async handlers, because ThreadState
2098 // can be in inconsistent state.
2099 // SIGSYS looks relatively safe -- it's synchronous and can actually
2100 // need some global state.
2101 bool acq
= (sig
== SIGSYS
);
2102 CallUserSignalHandler(thr
, sync
, acq
, sig
, info
, ctx
);
2104 atomic_fetch_add(&thr
->in_signal_handler
, -1, memory_order_relaxed
);
2110 SignalDesc
*signal
= &sctx
->pending_signals
[sig
];
2111 if (signal
->armed
== false) {
2112 signal
->armed
= true;
2113 internal_memcpy(&signal
->siginfo
, info
, sizeof(*info
));
2114 internal_memcpy(&signal
->ctx
, ctx
, sizeof(signal
->ctx
));
2115 atomic_store(&thr
->pending_signals
, 1, memory_order_relaxed
);
2119 TSAN_INTERCEPTOR(int, raise
, int sig
) {
2120 SCOPED_TSAN_INTERCEPTOR(raise
, sig
);
2121 ThreadSignalContext
*sctx
= SigCtx(thr
);
2123 int prev
= sctx
->int_signal_send
;
2124 sctx
->int_signal_send
= sig
;
2125 int res
= REAL(raise
)(sig
);
2126 CHECK_EQ(sctx
->int_signal_send
, sig
);
2127 sctx
->int_signal_send
= prev
;
2131 TSAN_INTERCEPTOR(int, kill
, int pid
, int sig
) {
2132 SCOPED_TSAN_INTERCEPTOR(kill
, pid
, sig
);
2133 ThreadSignalContext
*sctx
= SigCtx(thr
);
2135 int prev
= sctx
->int_signal_send
;
2136 if (pid
== (int)internal_getpid()) {
2137 sctx
->int_signal_send
= sig
;
2139 int res
= REAL(kill
)(pid
, sig
);
2140 if (pid
== (int)internal_getpid()) {
2141 CHECK_EQ(sctx
->int_signal_send
, sig
);
2142 sctx
->int_signal_send
= prev
;
2147 TSAN_INTERCEPTOR(int, pthread_kill
, void *tid
, int sig
) {
2148 SCOPED_TSAN_INTERCEPTOR(pthread_kill
, tid
, sig
);
2149 ThreadSignalContext
*sctx
= SigCtx(thr
);
2151 int prev
= sctx
->int_signal_send
;
2152 bool self
= pthread_equal(tid
, pthread_self());
2154 sctx
->int_signal_send
= sig
;
2155 int res
= REAL(pthread_kill
)(tid
, sig
);
2157 CHECK_EQ(sctx
->int_signal_send
, sig
);
2158 sctx
->int_signal_send
= prev
;
2163 TSAN_INTERCEPTOR(int, gettimeofday
, void *tv
, void *tz
) {
2164 SCOPED_TSAN_INTERCEPTOR(gettimeofday
, tv
, tz
);
2165 // It's intercepted merely to process pending signals.
2166 return REAL(gettimeofday
)(tv
, tz
);
2169 TSAN_INTERCEPTOR(int, getaddrinfo
, void *node
, void *service
,
2170 void *hints
, void *rv
) {
2171 SCOPED_TSAN_INTERCEPTOR(getaddrinfo
, node
, service
, hints
, rv
);
2172 // We miss atomic synchronization in getaddrinfo,
2173 // and can report false race between malloc and free
2174 // inside of getaddrinfo. So ignore memory accesses.
2175 ThreadIgnoreBegin(thr
, pc
);
2176 int res
= REAL(getaddrinfo
)(node
, service
, hints
, rv
);
2177 ThreadIgnoreEnd(thr
);
2181 TSAN_INTERCEPTOR(int, fork
, int fake
) {
2182 if (in_symbolizer())
2183 return REAL(fork
)(fake
);
2184 SCOPED_INTERCEPTOR_RAW(fork
, fake
);
2185 return REAL(fork
)(fake
);
2188 void atfork_prepare() {
2189 if (in_symbolizer())
2191 ThreadState
*thr
= cur_thread();
2192 const uptr pc
= StackTrace::GetCurrentPc();
2193 ForkBefore(thr
, pc
);
2196 void atfork_parent() {
2197 if (in_symbolizer())
2199 ThreadState
*thr
= cur_thread();
2200 const uptr pc
= StackTrace::GetCurrentPc();
2201 ForkParentAfter(thr
, pc
);
2204 void atfork_child() {
2205 if (in_symbolizer())
2207 ThreadState
*thr
= cur_thread();
2208 const uptr pc
= StackTrace::GetCurrentPc();
2209 ForkChildAfter(thr
, pc
, true);
2214 TSAN_INTERCEPTOR(int, vfork
, int fake
) {
2215 // Some programs (e.g. openjdk) call close for all file descriptors
2216 // in the child process. Under tsan it leads to false positives, because
2217 // address space is shared, so the parent process also thinks that
2218 // the descriptors are closed (while they are actually not).
2219 // This leads to false positives due to missed synchronization.
2220 // Strictly saying this is undefined behavior, because vfork child is not
2221 // allowed to call any functions other than exec/exit. But this is what
2222 // openjdk does, so we want to handle it.
2223 // We could disable interceptors in the child process. But it's not possible
2224 // to simply intercept and wrap vfork, because vfork child is not allowed
2225 // to return from the function that calls vfork, and that's exactly what
2226 // we would do. So this would require some assembly trickery as well.
2227 // Instead we simply turn vfork into fork.
2228 return WRAP(fork
)(fake
);
2233 TSAN_INTERCEPTOR(int, clone
, int (*fn
)(void *), void *stack
, int flags
,
2234 void *arg
, int *parent_tid
, void *tls
, pid_t
*child_tid
) {
2235 SCOPED_INTERCEPTOR_RAW(clone
, fn
, stack
, flags
, arg
, parent_tid
, tls
,
2241 auto wrapper
= +[](void *p
) -> int {
2242 auto *thr
= cur_thread();
2243 uptr pc
= GET_CURRENT_PC();
2244 // Start the background thread for fork, but not for clone.
2245 // For fork we did this always and it's known to work (or user code has
2246 // adopted). But if we do this for the new clone interceptor some code
2247 // (sandbox2) fails. So model we used to do for years and don't start the
2248 // background thread after clone.
2249 ForkChildAfter(thr
, pc
, false);
2251 auto *arg
= static_cast<Arg
*>(p
);
2252 return arg
->fn(arg
->arg
);
2254 ForkBefore(thr
, pc
);
2255 Arg arg_wrapper
= {fn
, arg
};
2256 int pid
= REAL(clone
)(wrapper
, stack
, flags
, &arg_wrapper
, parent_tid
, tls
,
2258 ForkParentAfter(thr
, pc
);
2263 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2264 typedef int (*dl_iterate_phdr_cb_t
)(__sanitizer_dl_phdr_info
*info
, SIZE_T size
,
2266 struct dl_iterate_phdr_data
{
2269 dl_iterate_phdr_cb_t cb
;
2273 static bool IsAppNotRodata(uptr addr
) {
2274 return IsAppMem(addr
) && *MemToShadow(addr
) != Shadow::kRodata
;
2277 static int dl_iterate_phdr_cb(__sanitizer_dl_phdr_info
*info
, SIZE_T size
,
2279 dl_iterate_phdr_data
*cbdata
= (dl_iterate_phdr_data
*)data
;
2280 // dlopen/dlclose allocate/free dynamic-linker-internal memory, which is later
2281 // accessible in dl_iterate_phdr callback. But we don't see synchronization
2282 // inside of dynamic linker, so we "unpoison" it here in order to not
2283 // produce false reports. Ignoring malloc/free in dlopen/dlclose is not enough
2284 // because some libc functions call __libc_dlopen.
2285 if (info
&& IsAppNotRodata((uptr
)info
->dlpi_name
))
2286 MemoryResetRange(cbdata
->thr
, cbdata
->pc
, (uptr
)info
->dlpi_name
,
2287 internal_strlen(info
->dlpi_name
));
2288 int res
= cbdata
->cb(info
, size
, cbdata
->data
);
2289 // Perform the check one more time in case info->dlpi_name was overwritten
2290 // by user callback.
2291 if (info
&& IsAppNotRodata((uptr
)info
->dlpi_name
))
2292 MemoryResetRange(cbdata
->thr
, cbdata
->pc
, (uptr
)info
->dlpi_name
,
2293 internal_strlen(info
->dlpi_name
));
2297 TSAN_INTERCEPTOR(int, dl_iterate_phdr
, dl_iterate_phdr_cb_t cb
, void *data
) {
2298 SCOPED_TSAN_INTERCEPTOR(dl_iterate_phdr
, cb
, data
);
2299 dl_iterate_phdr_data cbdata
;
2304 int res
= REAL(dl_iterate_phdr
)(dl_iterate_phdr_cb
, &cbdata
);
2309 static int OnExit(ThreadState
*thr
) {
2310 int status
= Finalize(thr
);
2315 struct TsanInterceptorContext
{
2321 static void HandleRecvmsg(ThreadState
*thr
, uptr pc
,
2322 __sanitizer_msghdr
*msg
) {
2324 int cnt
= ExtractRecvmsgFDs(msg
, fds
, ARRAY_SIZE(fds
));
2325 for (int i
= 0; i
< cnt
; i
++)
2326 FdEventCreate(thr
, pc
, fds
[i
]);
2330 #include "sanitizer_common/sanitizer_platform_interceptors.h"
2331 // Causes interceptor recursion (getaddrinfo() and fopen())
2332 #undef SANITIZER_INTERCEPT_GETADDRINFO
2333 // We define our own.
2334 #if SANITIZER_INTERCEPT_TLS_GET_ADDR
2335 #define NEED_TLS_GET_ADDR
2337 #undef SANITIZER_INTERCEPT_TLS_GET_ADDR
2338 #define SANITIZER_INTERCEPT_TLS_GET_OFFSET 1
2339 #undef SANITIZER_INTERCEPT_PTHREAD_SIGMASK
2341 #define COMMON_INTERCEPT_FUNCTION(name) INTERCEPT_FUNCTION(name)
2342 #define COMMON_INTERCEPT_FUNCTION_VER(name, ver) \
2343 INTERCEPT_FUNCTION_VER(name, ver)
2344 #define COMMON_INTERCEPT_FUNCTION_VER_UNVERSIONED_FALLBACK(name, ver) \
2345 (INTERCEPT_FUNCTION_VER(name, ver) || INTERCEPT_FUNCTION(name))
2347 #define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \
2348 MemoryAccessRange(((TsanInterceptorContext *)ctx)->thr, \
2349 ((TsanInterceptorContext *)ctx)->pc, (uptr)ptr, size, \
2352 #define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) \
2353 MemoryAccessRange(((TsanInterceptorContext *) ctx)->thr, \
2354 ((TsanInterceptorContext *) ctx)->pc, (uptr) ptr, size, \
2357 #define COMMON_INTERCEPTOR_ENTER(ctx, func, ...) \
2358 SCOPED_TSAN_INTERCEPTOR(func, __VA_ARGS__); \
2359 TsanInterceptorContext _ctx = {thr, pc}; \
2360 ctx = (void *)&_ctx; \
2363 #define COMMON_INTERCEPTOR_ENTER_NOIGNORE(ctx, func, ...) \
2364 SCOPED_INTERCEPTOR_RAW(func, __VA_ARGS__); \
2365 TsanInterceptorContext _ctx = {thr, pc}; \
2366 ctx = (void *)&_ctx; \
2369 #define COMMON_INTERCEPTOR_FILE_OPEN(ctx, file, path) \
2371 Acquire(thr, pc, File2addr(path)); \
2373 int fd = fileno_unlocked(file); \
2374 if (fd >= 0) FdFileCreate(thr, pc, fd); \
2377 #define COMMON_INTERCEPTOR_FILE_CLOSE(ctx, file) \
2379 int fd = fileno_unlocked(file); \
2380 FdClose(thr, pc, fd); \
2383 #define COMMON_INTERCEPTOR_DLOPEN(filename, flag) \
2385 CheckNoDeepBind(filename, flag); \
2386 ThreadIgnoreBegin(thr, 0); \
2387 void *res = REAL(dlopen)(filename, flag); \
2388 ThreadIgnoreEnd(thr); \
2392 #define COMMON_INTERCEPTOR_LIBRARY_LOADED(filename, handle) \
2393 libignore()->OnLibraryLoaded(filename)
2395 #define COMMON_INTERCEPTOR_LIBRARY_UNLOADED() \
2396 libignore()->OnLibraryUnloaded()
2398 #define COMMON_INTERCEPTOR_ACQUIRE(ctx, u) \
2399 Acquire(((TsanInterceptorContext *) ctx)->thr, pc, u)
2401 #define COMMON_INTERCEPTOR_RELEASE(ctx, u) \
2402 Release(((TsanInterceptorContext *) ctx)->thr, pc, u)
2404 #define COMMON_INTERCEPTOR_DIR_ACQUIRE(ctx, path) \
2405 Acquire(((TsanInterceptorContext *) ctx)->thr, pc, Dir2addr(path))
2407 #define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \
2408 FdAcquire(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2410 #define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \
2411 FdRelease(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2413 #define COMMON_INTERCEPTOR_FD_ACCESS(ctx, fd) \
2414 FdAccess(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2416 #define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \
2417 FdSocketAccept(((TsanInterceptorContext *) ctx)->thr, pc, fd, newfd)
2419 #define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) \
2420 ThreadSetName(((TsanInterceptorContext *) ctx)->thr, name)
2422 #define COMMON_INTERCEPTOR_SET_PTHREAD_NAME(ctx, thread, name) \
2423 if (pthread_equal(pthread_self(), reinterpret_cast<void *>(thread))) \
2424 COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name); \
2426 __tsan::ctx->thread_registry.SetThreadNameByUserId(thread, name)
2428 #define COMMON_INTERCEPTOR_BLOCK_REAL(name) BLOCK_REAL(name)
2430 #define COMMON_INTERCEPTOR_ON_EXIT(ctx) \
2431 OnExit(((TsanInterceptorContext *) ctx)->thr)
2433 #define COMMON_INTERCEPTOR_MUTEX_PRE_LOCK(ctx, m) \
2434 MutexPreLock(((TsanInterceptorContext *)ctx)->thr, \
2435 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2437 #define COMMON_INTERCEPTOR_MUTEX_POST_LOCK(ctx, m) \
2438 MutexPostLock(((TsanInterceptorContext *)ctx)->thr, \
2439 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2441 #define COMMON_INTERCEPTOR_MUTEX_UNLOCK(ctx, m) \
2442 MutexUnlock(((TsanInterceptorContext *)ctx)->thr, \
2443 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2445 #define COMMON_INTERCEPTOR_MUTEX_REPAIR(ctx, m) \
2446 MutexRepair(((TsanInterceptorContext *)ctx)->thr, \
2447 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2449 #define COMMON_INTERCEPTOR_MUTEX_INVALID(ctx, m) \
2450 MutexInvalidAccess(((TsanInterceptorContext *)ctx)->thr, \
2451 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2453 #define COMMON_INTERCEPTOR_MMAP_IMPL(ctx, mmap, addr, sz, prot, flags, fd, \
2456 return mmap_interceptor(thr, pc, REAL(mmap), addr, sz, prot, flags, fd, \
2461 #define COMMON_INTERCEPTOR_HANDLE_RECVMSG(ctx, msg) \
2462 HandleRecvmsg(((TsanInterceptorContext *)ctx)->thr, \
2463 ((TsanInterceptorContext *)ctx)->pc, msg)
2466 #define COMMON_INTERCEPTOR_GET_TLS_RANGE(begin, end) \
2467 if (TsanThread *t = GetCurrentThread()) { \
2468 *begin = t->tls_begin(); \
2469 *end = t->tls_end(); \
2471 *begin = *end = 0; \
2474 #define COMMON_INTERCEPTOR_USER_CALLBACK_START() \
2475 SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_START()
2477 #define COMMON_INTERCEPTOR_USER_CALLBACK_END() \
2478 SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_END()
2480 #include "sanitizer_common/sanitizer_common_interceptors.inc"
2482 static int sigaction_impl(int sig
, const __sanitizer_sigaction
*act
,
2483 __sanitizer_sigaction
*old
);
2484 static __sanitizer_sighandler_ptr
signal_impl(int sig
,
2485 __sanitizer_sighandler_ptr h
);
2487 #define SIGNAL_INTERCEPTOR_SIGACTION_IMPL(signo, act, oldact) \
2488 { return sigaction_impl(signo, act, oldact); }
2490 #define SIGNAL_INTERCEPTOR_SIGNAL_IMPL(func, signo, handler) \
2491 { return (uptr)signal_impl(signo, (__sanitizer_sighandler_ptr)handler); }
2493 #include "sanitizer_common/sanitizer_signal_interceptors.inc"
2495 int sigaction_impl(int sig
, const __sanitizer_sigaction
*act
,
2496 __sanitizer_sigaction
*old
) {
2497 // Note: if we call REAL(sigaction) directly for any reason without proxying
2498 // the signal handler through sighandler, very bad things will happen.
2499 // The handler will run synchronously and corrupt tsan per-thread state.
2500 SCOPED_INTERCEPTOR_RAW(sigaction
, sig
, act
, old
);
2501 if (sig
<= 0 || sig
>= kSigCount
) {
2502 errno
= errno_EINVAL
;
2505 __sanitizer_sigaction
*sigactions
= interceptor_ctx()->sigactions
;
2506 __sanitizer_sigaction old_stored
;
2507 if (old
) internal_memcpy(&old_stored
, &sigactions
[sig
], sizeof(old_stored
));
2508 __sanitizer_sigaction newact
;
2510 // Copy act into sigactions[sig].
2511 // Can't use struct copy, because compiler can emit call to memcpy.
2512 // Can't use internal_memcpy, because it copies byte-by-byte,
2513 // and signal handler reads the handler concurrently. It it can read
2514 // some bytes from old value and some bytes from new value.
2515 // Use volatile to prevent insertion of memcpy.
2516 sigactions
[sig
].handler
=
2517 *(volatile __sanitizer_sighandler_ptr
const *)&act
->handler
;
2518 sigactions
[sig
].sa_flags
= *(volatile int const *)&act
->sa_flags
;
2519 internal_memcpy(&sigactions
[sig
].sa_mask
, &act
->sa_mask
,
2520 sizeof(sigactions
[sig
].sa_mask
));
2521 #if !SANITIZER_FREEBSD && !SANITIZER_MAC && !SANITIZER_NETBSD
2522 sigactions
[sig
].sa_restorer
= act
->sa_restorer
;
2524 internal_memcpy(&newact
, act
, sizeof(newact
));
2525 internal_sigfillset(&newact
.sa_mask
);
2526 if ((act
->sa_flags
& SA_SIGINFO
) ||
2527 ((uptr
)act
->handler
!= sig_ign
&& (uptr
)act
->handler
!= sig_dfl
)) {
2528 newact
.sa_flags
|= SA_SIGINFO
;
2529 newact
.sigaction
= sighandler
;
2531 ReleaseStore(thr
, pc
, (uptr
)&sigactions
[sig
]);
2534 int res
= REAL(sigaction
)(sig
, act
, old
);
2535 if (res
== 0 && old
&& old
->sigaction
== sighandler
)
2536 internal_memcpy(old
, &old_stored
, sizeof(*old
));
2540 static __sanitizer_sighandler_ptr
signal_impl(int sig
,
2541 __sanitizer_sighandler_ptr h
) {
2542 __sanitizer_sigaction act
;
2544 internal_memset(&act
.sa_mask
, -1, sizeof(act
.sa_mask
));
2546 __sanitizer_sigaction old
;
2547 int res
= sigaction_symname(sig
, &act
, &old
);
2548 if (res
) return (__sanitizer_sighandler_ptr
)sig_err
;
2552 #define TSAN_SYSCALL() \
2553 ThreadState *thr = cur_thread(); \
2554 if (thr->ignore_interceptors) \
2556 ScopedSyscall scoped_syscall(thr)
2558 struct ScopedSyscall
{
2561 explicit ScopedSyscall(ThreadState
*thr
) : thr(thr
) { LazyInitialize(thr
); }
2564 ProcessPendingSignals(thr
);
2568 #if !SANITIZER_FREEBSD && !SANITIZER_MAC
2569 static void syscall_access_range(uptr pc
, uptr p
, uptr s
, bool write
) {
2571 MemoryAccessRange(thr
, pc
, p
, s
, write
);
2574 static USED
void syscall_acquire(uptr pc
, uptr addr
) {
2576 Acquire(thr
, pc
, addr
);
2577 DPrintf("syscall_acquire(0x%zx))\n", addr
);
2580 static USED
void syscall_release(uptr pc
, uptr addr
) {
2582 DPrintf("syscall_release(0x%zx)\n", addr
);
2583 Release(thr
, pc
, addr
);
2586 static void syscall_fd_close(uptr pc
, int fd
) {
2587 auto *thr
= cur_thread();
2588 FdClose(thr
, pc
, fd
);
2591 static USED
void syscall_fd_acquire(uptr pc
, int fd
) {
2593 FdAcquire(thr
, pc
, fd
);
2594 DPrintf("syscall_fd_acquire(%d)\n", fd
);
2597 static USED
void syscall_fd_release(uptr pc
, int fd
) {
2599 DPrintf("syscall_fd_release(%d)\n", fd
);
2600 FdRelease(thr
, pc
, fd
);
2603 static void syscall_pre_fork(uptr pc
) { ForkBefore(cur_thread(), pc
); }
2605 static void syscall_post_fork(uptr pc
, int pid
) {
2606 ThreadState
*thr
= cur_thread();
2609 ForkChildAfter(thr
, pc
, true);
2611 } else if (pid
> 0) {
2613 ForkParentAfter(thr
, pc
);
2616 ForkParentAfter(thr
, pc
);
2621 #define COMMON_SYSCALL_PRE_READ_RANGE(p, s) \
2622 syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), false)
2624 #define COMMON_SYSCALL_PRE_WRITE_RANGE(p, s) \
2625 syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), true)
2627 #define COMMON_SYSCALL_POST_READ_RANGE(p, s) \
2633 #define COMMON_SYSCALL_POST_WRITE_RANGE(p, s) \
2639 #define COMMON_SYSCALL_ACQUIRE(addr) \
2640 syscall_acquire(GET_CALLER_PC(), (uptr)(addr))
2642 #define COMMON_SYSCALL_RELEASE(addr) \
2643 syscall_release(GET_CALLER_PC(), (uptr)(addr))
2645 #define COMMON_SYSCALL_FD_CLOSE(fd) syscall_fd_close(GET_CALLER_PC(), fd)
2647 #define COMMON_SYSCALL_FD_ACQUIRE(fd) syscall_fd_acquire(GET_CALLER_PC(), fd)
2649 #define COMMON_SYSCALL_FD_RELEASE(fd) syscall_fd_release(GET_CALLER_PC(), fd)
2651 #define COMMON_SYSCALL_PRE_FORK() \
2652 syscall_pre_fork(GET_CALLER_PC())
2654 #define COMMON_SYSCALL_POST_FORK(res) \
2655 syscall_post_fork(GET_CALLER_PC(), res)
2657 #include "sanitizer_common/sanitizer_common_syscalls.inc"
2658 #include "sanitizer_common/sanitizer_syscalls_netbsd.inc"
2660 #ifdef NEED_TLS_GET_ADDR
2662 static void handle_tls_addr(void *arg
, void *res
) {
2663 ThreadState
*thr
= cur_thread();
2666 DTLS::DTV
*dtv
= DTLS_on_tls_get_addr(arg
, res
, thr
->tls_addr
,
2667 thr
->tls_addr
+ thr
->tls_size
);
2670 // New DTLS block has been allocated.
2671 MemoryResetRange(thr
, 0, dtv
->beg
, dtv
->size
);
2675 // Define own interceptor instead of sanitizer_common's for three reasons:
2676 // 1. It must not process pending signals.
2677 // Signal handlers may contain MOVDQA instruction (see below).
2678 // 2. It must be as simple as possible to not contain MOVDQA.
2679 // 3. Sanitizer_common version uses COMMON_INTERCEPTOR_INITIALIZE_RANGE which
2680 // is empty for tsan (meant only for msan).
2681 // Note: __tls_get_addr can be called with mis-aligned stack due to:
2682 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58066
2683 // So the interceptor must work with mis-aligned stack, in particular, does not
2684 // execute MOVDQA with stack addresses.
2685 TSAN_INTERCEPTOR(void *, __tls_get_addr
, void *arg
) {
2686 void *res
= REAL(__tls_get_addr
)(arg
);
2687 handle_tls_addr(arg
, res
);
2690 #else // SANITIZER_S390
2691 TSAN_INTERCEPTOR(uptr
, __tls_get_addr_internal
, void *arg
) {
2692 uptr res
= __tls_get_offset_wrapper(arg
, REAL(__tls_get_offset
));
2693 char *tp
= static_cast<char *>(__builtin_thread_pointer());
2694 handle_tls_addr(arg
, res
+ tp
);
2700 #if SANITIZER_NETBSD
2701 TSAN_INTERCEPTOR(void, _lwp_exit
) {
2702 SCOPED_TSAN_INTERCEPTOR(_lwp_exit
);
2703 DestroyThreadState();
2706 #define TSAN_MAYBE_INTERCEPT__LWP_EXIT TSAN_INTERCEPT(_lwp_exit)
2708 #define TSAN_MAYBE_INTERCEPT__LWP_EXIT
2711 #if SANITIZER_FREEBSD
2712 TSAN_INTERCEPTOR(void, thr_exit
, tid_t
*state
) {
2713 SCOPED_TSAN_INTERCEPTOR(thr_exit
, state
);
2714 DestroyThreadState();
2715 REAL(thr_exit(state
));
2717 #define TSAN_MAYBE_INTERCEPT_THR_EXIT TSAN_INTERCEPT(thr_exit)
2719 #define TSAN_MAYBE_INTERCEPT_THR_EXIT
2722 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, cond_init
, void *c
, void *a
)
2723 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, cond_destroy
, void *c
)
2724 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, cond_signal
, void *c
)
2725 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, cond_broadcast
, void *c
)
2726 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, cond_wait
, void *c
, void *m
)
2727 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, mutex_init
, void *m
, void *a
)
2728 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, mutex_destroy
, void *m
)
2729 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, mutex_lock
, void *m
)
2730 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, mutex_trylock
, void *m
)
2731 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, mutex_unlock
, void *m
)
2732 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, rwlock_init
, void *l
, void *a
)
2733 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, rwlock_destroy
, void *l
)
2734 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, rwlock_rdlock
, void *l
)
2735 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, rwlock_tryrdlock
, void *l
)
2736 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, rwlock_wrlock
, void *l
)
2737 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, rwlock_trywrlock
, void *l
)
2738 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, rwlock_unlock
, void *l
)
2739 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, once
, void *o
, void (*i
)())
2740 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, sigmask
, int f
, void *n
, void *o
)
2742 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_init
, void *c
, void *a
)
2743 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_signal
, void *c
)
2744 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_broadcast
, void *c
)
2745 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_wait
, void *c
, void *m
)
2746 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_destroy
, void *c
)
2747 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_init
, void *m
, void *a
)
2748 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_destroy
, void *m
)
2749 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_trylock
, void *m
)
2750 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_init
, void *m
, void *a
)
2751 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_destroy
, void *m
)
2752 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_rdlock
, void *m
)
2753 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_tryrdlock
, void *m
)
2754 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_wrlock
, void *m
)
2755 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_trywrlock
, void *m
)
2756 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_unlock
, void *m
)
2757 TSAN_INTERCEPTOR_NETBSD_ALIAS_THR(int, once
, void *o
, void (*f
)())
2758 TSAN_INTERCEPTOR_NETBSD_ALIAS_THR2(int, sigsetmask
, sigmask
, int a
, void *b
,
2763 static void finalize(void *arg
) {
2764 ThreadState
*thr
= cur_thread();
2765 int status
= Finalize(thr
);
2766 // Make sure the output is not lost.
2772 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2773 static void unreachable() {
2774 Report("FATAL: ThreadSanitizer: unreachable called\n");
2779 // Define default implementation since interception of libdispatch is optional.
2780 SANITIZER_WEAK_ATTRIBUTE
void InitializeLibdispatchInterceptors() {}
2782 void InitializeInterceptors() {
2784 // We need to setup it early, because functions like dlsym() can call it.
2785 REAL(memset
) = internal_memset
;
2786 REAL(memcpy
) = internal_memcpy
;
2789 new(interceptor_ctx()) InterceptorContext();
2791 InitializeCommonInterceptors();
2792 InitializeSignalInterceptors();
2793 InitializeLibdispatchInterceptors();
2796 // We can not use TSAN_INTERCEPT to get setjmp addr,
2797 // because it does &setjmp and setjmp is not present in some versions of libc.
2798 using __interception::InterceptFunction
;
2799 InterceptFunction(TSAN_STRING_SETJMP
, (uptr
*)&REAL(setjmp_symname
), 0, 0);
2800 InterceptFunction("_setjmp", (uptr
*)&REAL(_setjmp
), 0, 0);
2801 InterceptFunction(TSAN_STRING_SIGSETJMP
, (uptr
*)&REAL(sigsetjmp_symname
), 0,
2803 #if !SANITIZER_NETBSD
2804 InterceptFunction("__sigsetjmp", (uptr
*)&REAL(__sigsetjmp
), 0, 0);
2808 TSAN_INTERCEPT(longjmp_symname
);
2809 TSAN_INTERCEPT(siglongjmp_symname
);
2810 #if SANITIZER_NETBSD
2811 TSAN_INTERCEPT(_longjmp
);
2814 TSAN_INTERCEPT(malloc
);
2815 TSAN_INTERCEPT(__libc_memalign
);
2816 TSAN_INTERCEPT(calloc
);
2817 TSAN_INTERCEPT(realloc
);
2818 TSAN_INTERCEPT(reallocarray
);
2819 TSAN_INTERCEPT(free
);
2820 TSAN_INTERCEPT(cfree
);
2821 TSAN_INTERCEPT(munmap
);
2822 TSAN_MAYBE_INTERCEPT_MEMALIGN
;
2823 TSAN_INTERCEPT(valloc
);
2824 TSAN_MAYBE_INTERCEPT_PVALLOC
;
2825 TSAN_INTERCEPT(posix_memalign
);
2827 TSAN_INTERCEPT(strcpy
);
2828 TSAN_INTERCEPT(strncpy
);
2829 TSAN_INTERCEPT(strdup
);
2831 TSAN_INTERCEPT(pthread_create
);
2832 TSAN_INTERCEPT(pthread_join
);
2833 TSAN_INTERCEPT(pthread_detach
);
2834 TSAN_INTERCEPT(pthread_exit
);
2836 TSAN_INTERCEPT(pthread_tryjoin_np
);
2837 TSAN_INTERCEPT(pthread_timedjoin_np
);
2840 TSAN_INTERCEPT_VER(pthread_cond_init
, PTHREAD_ABI_BASE
);
2841 TSAN_INTERCEPT_VER(pthread_cond_signal
, PTHREAD_ABI_BASE
);
2842 TSAN_INTERCEPT_VER(pthread_cond_broadcast
, PTHREAD_ABI_BASE
);
2843 TSAN_INTERCEPT_VER(pthread_cond_wait
, PTHREAD_ABI_BASE
);
2844 TSAN_INTERCEPT_VER(pthread_cond_timedwait
, PTHREAD_ABI_BASE
);
2845 TSAN_INTERCEPT_VER(pthread_cond_destroy
, PTHREAD_ABI_BASE
);
2847 TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT
;
2849 TSAN_INTERCEPT(pthread_mutex_init
);
2850 TSAN_INTERCEPT(pthread_mutex_destroy
);
2851 TSAN_INTERCEPT(pthread_mutex_trylock
);
2852 TSAN_INTERCEPT(pthread_mutex_timedlock
);
2854 TSAN_INTERCEPT(pthread_spin_init
);
2855 TSAN_INTERCEPT(pthread_spin_destroy
);
2856 TSAN_INTERCEPT(pthread_spin_lock
);
2857 TSAN_INTERCEPT(pthread_spin_trylock
);
2858 TSAN_INTERCEPT(pthread_spin_unlock
);
2860 TSAN_INTERCEPT(pthread_rwlock_init
);
2861 TSAN_INTERCEPT(pthread_rwlock_destroy
);
2862 TSAN_INTERCEPT(pthread_rwlock_rdlock
);
2863 TSAN_INTERCEPT(pthread_rwlock_tryrdlock
);
2864 TSAN_INTERCEPT(pthread_rwlock_timedrdlock
);
2865 TSAN_INTERCEPT(pthread_rwlock_wrlock
);
2866 TSAN_INTERCEPT(pthread_rwlock_trywrlock
);
2867 TSAN_INTERCEPT(pthread_rwlock_timedwrlock
);
2868 TSAN_INTERCEPT(pthread_rwlock_unlock
);
2870 TSAN_INTERCEPT(pthread_barrier_init
);
2871 TSAN_INTERCEPT(pthread_barrier_destroy
);
2872 TSAN_INTERCEPT(pthread_barrier_wait
);
2874 TSAN_INTERCEPT(pthread_once
);
2876 TSAN_INTERCEPT(fstat
);
2877 TSAN_MAYBE_INTERCEPT___FXSTAT
;
2878 TSAN_MAYBE_INTERCEPT_FSTAT64
;
2879 TSAN_MAYBE_INTERCEPT___FXSTAT64
;
2880 TSAN_INTERCEPT(open
);
2881 TSAN_MAYBE_INTERCEPT_OPEN64
;
2882 TSAN_INTERCEPT(creat
);
2883 TSAN_MAYBE_INTERCEPT_CREAT64
;
2884 TSAN_INTERCEPT(dup
);
2885 TSAN_INTERCEPT(dup2
);
2886 TSAN_INTERCEPT(dup3
);
2887 TSAN_MAYBE_INTERCEPT_EVENTFD
;
2888 TSAN_MAYBE_INTERCEPT_SIGNALFD
;
2889 TSAN_MAYBE_INTERCEPT_INOTIFY_INIT
;
2890 TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1
;
2891 TSAN_INTERCEPT(socket
);
2892 TSAN_INTERCEPT(socketpair
);
2893 TSAN_INTERCEPT(connect
);
2894 TSAN_INTERCEPT(bind
);
2895 TSAN_INTERCEPT(listen
);
2896 TSAN_MAYBE_INTERCEPT_EPOLL
;
2897 TSAN_INTERCEPT(close
);
2898 TSAN_MAYBE_INTERCEPT___CLOSE
;
2899 TSAN_MAYBE_INTERCEPT___RES_ICLOSE
;
2900 TSAN_INTERCEPT(pipe
);
2901 TSAN_INTERCEPT(pipe2
);
2903 TSAN_INTERCEPT(unlink
);
2904 TSAN_INTERCEPT(tmpfile
);
2905 TSAN_MAYBE_INTERCEPT_TMPFILE64
;
2906 TSAN_INTERCEPT(abort
);
2907 TSAN_INTERCEPT(rmdir
);
2908 TSAN_INTERCEPT(closedir
);
2910 TSAN_INTERCEPT(sigsuspend
);
2911 TSAN_INTERCEPT(sigblock
);
2912 TSAN_INTERCEPT(sigsetmask
);
2913 TSAN_INTERCEPT(pthread_sigmask
);
2914 TSAN_INTERCEPT(raise
);
2915 TSAN_INTERCEPT(kill
);
2916 TSAN_INTERCEPT(pthread_kill
);
2917 TSAN_INTERCEPT(sleep
);
2918 TSAN_INTERCEPT(usleep
);
2919 TSAN_INTERCEPT(nanosleep
);
2920 TSAN_INTERCEPT(pause
);
2921 TSAN_INTERCEPT(gettimeofday
);
2922 TSAN_INTERCEPT(getaddrinfo
);
2924 TSAN_INTERCEPT(fork
);
2925 TSAN_INTERCEPT(vfork
);
2927 TSAN_INTERCEPT(clone
);
2929 #if !SANITIZER_ANDROID
2930 TSAN_INTERCEPT(dl_iterate_phdr
);
2932 TSAN_MAYBE_INTERCEPT_ON_EXIT
;
2933 TSAN_INTERCEPT(__cxa_atexit
);
2934 TSAN_INTERCEPT(_exit
);
2936 #ifdef NEED_TLS_GET_ADDR
2938 TSAN_INTERCEPT(__tls_get_addr
);
2940 TSAN_INTERCEPT(__tls_get_addr_internal
);
2941 TSAN_INTERCEPT(__tls_get_offset
);
2945 TSAN_MAYBE_INTERCEPT__LWP_EXIT
;
2946 TSAN_MAYBE_INTERCEPT_THR_EXIT
;
2948 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2949 // Need to setup it, because interceptors check that the function is resolved.
2950 // But atexit is emitted directly into the module, so can't be resolved.
2951 REAL(atexit
) = (int(*)(void(*)()))unreachable
;
2954 if (REAL(__cxa_atexit
)(&finalize
, 0, 0)) {
2955 Printf("ThreadSanitizer: failed to setup atexit callback\n");
2958 if (pthread_atfork(atfork_prepare
, atfork_parent
, atfork_child
)) {
2959 Printf("ThreadSanitizer: failed to setup atfork callbacks\n");
2963 #if !SANITIZER_MAC && !SANITIZER_NETBSD && !SANITIZER_FREEBSD
2964 if (pthread_key_create(&interceptor_ctx()->finalize_key
, &thread_finalize
)) {
2965 Printf("ThreadSanitizer: failed to create thread key\n");
2970 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(cond_init
);
2971 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(cond_destroy
);
2972 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(cond_signal
);
2973 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(cond_broadcast
);
2974 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(cond_wait
);
2975 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(mutex_init
);
2976 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(mutex_destroy
);
2977 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(mutex_lock
);
2978 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(mutex_trylock
);
2979 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(mutex_unlock
);
2980 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(rwlock_init
);
2981 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(rwlock_destroy
);
2982 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(rwlock_rdlock
);
2983 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(rwlock_tryrdlock
);
2984 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(rwlock_wrlock
);
2985 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(rwlock_trywrlock
);
2986 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(rwlock_unlock
);
2987 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(once
);
2988 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(sigmask
);
2990 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_init
);
2991 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_signal
);
2992 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_broadcast
);
2993 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_wait
);
2994 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_destroy
);
2995 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_init
);
2996 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_destroy
);
2997 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_trylock
);
2998 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_init
);
2999 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_destroy
);
3000 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_rdlock
);
3001 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_tryrdlock
);
3002 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_wrlock
);
3003 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_trywrlock
);
3004 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_unlock
);
3005 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(once
);
3006 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(sigsetmask
);
3011 } // namespace __tsan
3013 // Invisible barrier for tests.
3014 // There were several unsuccessful iterations for this functionality:
3015 // 1. Initially it was implemented in user code using
3016 // REAL(pthread_barrier_wait). But pthread_barrier_wait is not supported on
3017 // MacOS. Futexes are linux-specific for this matter.
3018 // 2. Then we switched to atomics+usleep(10). But usleep produced parasitic
3019 // "as-if synchronized via sleep" messages in reports which failed some
3021 // 3. Then we switched to atomics+sched_yield. But this produced tons of tsan-
3022 // visible events, which lead to "failed to restore stack trace" failures.
3023 // Note that no_sanitize_thread attribute does not turn off atomic interception
3024 // so attaching it to the function defined in user code does not help.
3025 // That's why we now have what we have.
3026 constexpr u32 kBarrierThreadBits
= 10;
3027 constexpr u32 kBarrierThreads
= 1 << kBarrierThreadBits
;
3029 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
void __tsan_testonly_barrier_init(
3030 atomic_uint32_t
*barrier
, u32 num_threads
) {
3031 if (num_threads
>= kBarrierThreads
) {
3032 Printf("barrier_init: count is too large (%d)\n", num_threads
);
3035 // kBarrierThreadBits lsb is thread count,
3036 // the remaining are count of entered threads.
3037 atomic_store(barrier
, num_threads
, memory_order_relaxed
);
3040 static u32
barrier_epoch(u32 value
) {
3041 return (value
>> kBarrierThreadBits
) / (value
& (kBarrierThreads
- 1));
3044 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
void __tsan_testonly_barrier_wait(
3045 atomic_uint32_t
*barrier
) {
3046 u32 old
= atomic_fetch_add(barrier
, kBarrierThreads
, memory_order_relaxed
);
3047 u32 old_epoch
= barrier_epoch(old
);
3048 if (barrier_epoch(old
+ kBarrierThreads
) != old_epoch
) {
3049 FutexWake(barrier
, (1 << 30));
3053 u32 cur
= atomic_load(barrier
, memory_order_relaxed
);
3054 if (barrier_epoch(cur
) != old_epoch
)
3056 FutexWait(barrier
, cur
);