Daily bump.
[official-gcc.git] / libsanitizer / tsan / tsan_interceptors_posix.cpp
blob80f86ca98ed9cd98804a9ae7ffe09f7b6390bae2
1 //===-- tsan_interceptors_posix.cpp ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is a part of ThreadSanitizer (TSan), a race detector.
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"
30 #include "tsan_rtl.h"
31 #include "tsan_mman.h"
32 #include "tsan_fd.h"
34 #include <stdarg.h>
36 using namespace __tsan;
38 DECLARE_REAL(void *, memcpy, void *to, const void *from, SIZE_T size)
39 DECLARE_REAL(void *, memset, void *block, int c, SIZE_T size)
41 #if SANITIZER_FREEBSD || SANITIZER_APPLE
42 #define stdout __stdoutp
43 #define stderr __stderrp
44 #endif
46 #if SANITIZER_NETBSD
47 #define dirfd(dirp) (*(int *)(dirp))
48 #define fileno_unlocked(fp) \
49 (((__sanitizer_FILE *)fp)->_file == -1 \
50 ? -1 \
51 : (int)(unsigned short)(((__sanitizer_FILE *)fp)->_file))
53 #define stdout ((__sanitizer_FILE*)&__sF[1])
54 #define stderr ((__sanitizer_FILE*)&__sF[2])
56 #define nanosleep __nanosleep50
57 #define vfork __vfork14
58 #endif
60 #ifdef __mips__
61 const int kSigCount = 129;
62 #else
63 const int kSigCount = 65;
64 #endif
66 #ifdef __mips__
67 struct ucontext_t {
68 u64 opaque[768 / sizeof(u64) + 1];
70 #else
71 struct ucontext_t {
72 // The size is determined by looking at sizeof of real ucontext_t on linux.
73 u64 opaque[936 / sizeof(u64) + 1];
75 #endif
77 #if defined(__x86_64__) || defined(__mips__) || SANITIZER_PPC64V1 || \
78 defined(__s390x__)
79 #define PTHREAD_ABI_BASE "GLIBC_2.3.2"
80 #elif defined(__aarch64__) || SANITIZER_PPC64V2
81 #define PTHREAD_ABI_BASE "GLIBC_2.17"
82 #elif SANITIZER_LOONGARCH64
83 #define PTHREAD_ABI_BASE "GLIBC_2.36"
84 #elif SANITIZER_RISCV64
85 # define PTHREAD_ABI_BASE "GLIBC_2.27"
86 #endif
88 extern "C" int pthread_attr_init(void *attr);
89 extern "C" int pthread_attr_destroy(void *attr);
90 DECLARE_REAL(int, pthread_attr_getdetachstate, void *, void *)
91 extern "C" int pthread_attr_setstacksize(void *attr, uptr stacksize);
92 extern "C" int pthread_atfork(void (*prepare)(void), void (*parent)(void),
93 void (*child)(void));
94 extern "C" int pthread_key_create(unsigned *key, void (*destructor)(void* v));
95 extern "C" int pthread_setspecific(unsigned key, const void *v);
96 DECLARE_REAL(int, pthread_mutexattr_gettype, void *, void *)
97 DECLARE_REAL(int, fflush, __sanitizer_FILE *fp)
98 DECLARE_REAL_AND_INTERCEPTOR(void *, malloc, uptr size)
99 DECLARE_REAL_AND_INTERCEPTOR(void, free, void *ptr)
100 extern "C" int pthread_equal(void *t1, void *t2);
101 extern "C" void *pthread_self();
102 extern "C" void _exit(int status);
103 #if !SANITIZER_NETBSD
104 extern "C" int fileno_unlocked(void *stream);
105 extern "C" int dirfd(void *dirp);
106 #endif
107 #if SANITIZER_NETBSD
108 extern __sanitizer_FILE __sF[];
109 #else
110 extern __sanitizer_FILE *stdout, *stderr;
111 #endif
112 #if !SANITIZER_FREEBSD && !SANITIZER_APPLE && !SANITIZER_NETBSD
113 const int PTHREAD_MUTEX_RECURSIVE = 1;
114 const int PTHREAD_MUTEX_RECURSIVE_NP = 1;
115 #else
116 const int PTHREAD_MUTEX_RECURSIVE = 2;
117 const int PTHREAD_MUTEX_RECURSIVE_NP = 2;
118 #endif
119 #if !SANITIZER_FREEBSD && !SANITIZER_APPLE && !SANITIZER_NETBSD
120 const int EPOLL_CTL_ADD = 1;
121 #endif
122 const int SIGILL = 4;
123 const int SIGTRAP = 5;
124 const int SIGABRT = 6;
125 const int SIGFPE = 8;
126 const int SIGSEGV = 11;
127 const int SIGPIPE = 13;
128 const int SIGTERM = 15;
129 #if defined(__mips__) || SANITIZER_FREEBSD || SANITIZER_APPLE || SANITIZER_NETBSD
130 const int SIGBUS = 10;
131 const int SIGSYS = 12;
132 #else
133 const int SIGBUS = 7;
134 const int SIGSYS = 31;
135 #endif
136 #if SANITIZER_HAS_SIGINFO
137 const int SI_TIMER = -2;
138 #endif
139 void *const MAP_FAILED = (void*)-1;
140 #if SANITIZER_NETBSD
141 const int PTHREAD_BARRIER_SERIAL_THREAD = 1234567;
142 #elif !SANITIZER_APPLE
143 const int PTHREAD_BARRIER_SERIAL_THREAD = -1;
144 #endif
145 const int MAP_FIXED = 0x10;
146 typedef long long_t;
147 typedef __sanitizer::u16 mode_t;
149 // From /usr/include/unistd.h
150 # define F_ULOCK 0 /* Unlock a previously locked region. */
151 # define F_LOCK 1 /* Lock a region for exclusive use. */
152 # define F_TLOCK 2 /* Test and lock a region for exclusive use. */
153 # define F_TEST 3 /* Test a region for other processes locks. */
155 #if SANITIZER_FREEBSD || SANITIZER_APPLE || SANITIZER_NETBSD
156 const int SA_SIGINFO = 0x40;
157 const int SIG_SETMASK = 3;
158 #elif defined(__mips__)
159 const int SA_SIGINFO = 8;
160 const int SIG_SETMASK = 3;
161 #else
162 const int SA_SIGINFO = 4;
163 const int SIG_SETMASK = 2;
164 #endif
166 namespace __tsan {
167 struct SignalDesc {
168 bool armed;
169 __sanitizer_siginfo siginfo;
170 ucontext_t ctx;
173 struct ThreadSignalContext {
174 int int_signal_send;
175 SignalDesc pending_signals[kSigCount];
176 // emptyset and oldset are too big for stack.
177 __sanitizer_sigset_t emptyset;
178 __sanitizer_sigset_t oldset;
181 void EnterBlockingFunc(ThreadState *thr) {
182 for (;;) {
183 // The order is important to not delay a signal infinitely if it's
184 // delivered right before we set in_blocking_func. Note: we can't call
185 // ProcessPendingSignals when in_blocking_func is set, or we can handle
186 // a signal synchronously when we are already handling a signal.
187 atomic_store(&thr->in_blocking_func, 1, memory_order_relaxed);
188 if (atomic_load(&thr->pending_signals, memory_order_relaxed) == 0)
189 break;
190 atomic_store(&thr->in_blocking_func, 0, memory_order_relaxed);
191 ProcessPendingSignals(thr);
195 // The sole reason tsan wraps atexit callbacks is to establish synchronization
196 // between callback setup and callback execution.
197 struct AtExitCtx {
198 void (*f)();
199 void *arg;
200 uptr pc;
203 // InterceptorContext holds all global data required for interceptors.
204 // It's explicitly constructed in InitializeInterceptors with placement new
205 // and is never destroyed. This allows usage of members with non-trivial
206 // constructors and destructors.
207 struct InterceptorContext {
208 // The object is 64-byte aligned, because we want hot data to be located
209 // in a single cache line if possible (it's accessed in every interceptor).
210 ALIGNED(64) LibIgnore libignore;
211 __sanitizer_sigaction sigactions[kSigCount];
212 #if !SANITIZER_APPLE && !SANITIZER_NETBSD
213 unsigned finalize_key;
214 #endif
216 Mutex atexit_mu;
217 Vector<struct AtExitCtx *> AtExitStack;
219 InterceptorContext() : libignore(LINKER_INITIALIZED), atexit_mu(MutexTypeAtExit), AtExitStack() {}
222 static ALIGNED(64) char interceptor_placeholder[sizeof(InterceptorContext)];
223 InterceptorContext *interceptor_ctx() {
224 return reinterpret_cast<InterceptorContext*>(&interceptor_placeholder[0]);
227 LibIgnore *libignore() {
228 return &interceptor_ctx()->libignore;
231 void InitializeLibIgnore() {
232 const SuppressionContext &supp = *Suppressions();
233 const uptr n = supp.SuppressionCount();
234 for (uptr i = 0; i < n; i++) {
235 const Suppression *s = supp.SuppressionAt(i);
236 if (0 == internal_strcmp(s->type, kSuppressionLib))
237 libignore()->AddIgnoredLibrary(s->templ);
239 if (flags()->ignore_noninstrumented_modules)
240 libignore()->IgnoreNoninstrumentedModules(true);
241 libignore()->OnLibraryLoaded(0);
244 // The following two hooks can be used by for cooperative scheduling when
245 // locking.
246 #ifdef TSAN_EXTERNAL_HOOKS
247 void OnPotentiallyBlockingRegionBegin();
248 void OnPotentiallyBlockingRegionEnd();
249 #else
250 SANITIZER_WEAK_CXX_DEFAULT_IMPL void OnPotentiallyBlockingRegionBegin() {}
251 SANITIZER_WEAK_CXX_DEFAULT_IMPL void OnPotentiallyBlockingRegionEnd() {}
252 #endif
254 } // namespace __tsan
256 static ThreadSignalContext *SigCtx(ThreadState *thr) {
257 // This function may be called reentrantly if it is interrupted by a signal
258 // handler. Use CAS to handle the race.
259 uptr ctx = atomic_load(&thr->signal_ctx, memory_order_relaxed);
260 if (ctx == 0 && !thr->is_dead) {
261 uptr pctx =
262 (uptr)MmapOrDie(sizeof(ThreadSignalContext), "ThreadSignalContext");
263 MemoryResetRange(thr, (uptr)&SigCtx, pctx, sizeof(ThreadSignalContext));
264 if (atomic_compare_exchange_strong(&thr->signal_ctx, &ctx, pctx,
265 memory_order_relaxed)) {
266 ctx = pctx;
267 } else {
268 UnmapOrDie((ThreadSignalContext *)pctx, sizeof(ThreadSignalContext));
271 return (ThreadSignalContext *)ctx;
274 ScopedInterceptor::ScopedInterceptor(ThreadState *thr, const char *fname,
275 uptr pc)
276 : thr_(thr) {
277 LazyInitialize(thr);
278 if (UNLIKELY(atomic_load(&thr->in_blocking_func, memory_order_relaxed))) {
279 // pthread_join is marked as blocking, but it's also known to call other
280 // intercepted functions (mmap, free). If we don't reset in_blocking_func
281 // we can get deadlocks and memory corruptions if we deliver a synchronous
282 // signal inside of an mmap/free interceptor.
283 // So reset it and restore it back in the destructor.
284 // See https://github.com/google/sanitizers/issues/1540
285 atomic_store(&thr->in_blocking_func, 0, memory_order_relaxed);
286 in_blocking_func_ = true;
288 if (!thr_->is_inited) return;
289 if (!thr_->ignore_interceptors) FuncEntry(thr, pc);
290 DPrintf("#%d: intercept %s()\n", thr_->tid, fname);
291 ignoring_ =
292 !thr_->in_ignored_lib && (flags()->ignore_interceptors_accesses ||
293 libignore()->IsIgnored(pc, &in_ignored_lib_));
294 EnableIgnores();
297 ScopedInterceptor::~ScopedInterceptor() {
298 if (!thr_->is_inited) return;
299 DisableIgnores();
300 if (UNLIKELY(in_blocking_func_))
301 EnterBlockingFunc(thr_);
302 if (!thr_->ignore_interceptors) {
303 ProcessPendingSignals(thr_);
304 FuncExit(thr_);
305 CheckedMutex::CheckNoLocks();
309 NOINLINE
310 void ScopedInterceptor::EnableIgnoresImpl() {
311 ThreadIgnoreBegin(thr_, 0);
312 if (flags()->ignore_noninstrumented_modules)
313 thr_->suppress_reports++;
314 if (in_ignored_lib_) {
315 DCHECK(!thr_->in_ignored_lib);
316 thr_->in_ignored_lib = true;
320 NOINLINE
321 void ScopedInterceptor::DisableIgnoresImpl() {
322 ThreadIgnoreEnd(thr_);
323 if (flags()->ignore_noninstrumented_modules)
324 thr_->suppress_reports--;
325 if (in_ignored_lib_) {
326 DCHECK(thr_->in_ignored_lib);
327 thr_->in_ignored_lib = false;
331 #define TSAN_INTERCEPT(func) INTERCEPT_FUNCTION(func)
332 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
333 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION(func)
334 #else
335 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION_VER(func, ver)
336 #endif
337 #if SANITIZER_FREEBSD
338 # define TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(func) \
339 INTERCEPT_FUNCTION(_pthread_##func)
340 #else
341 # define TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(func)
342 #endif
343 #if SANITIZER_NETBSD
344 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(func) \
345 INTERCEPT_FUNCTION(__libc_##func)
346 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(func) \
347 INTERCEPT_FUNCTION(__libc_thr_##func)
348 #else
349 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(func)
350 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(func)
351 #endif
353 #define READ_STRING_OF_LEN(thr, pc, s, len, n) \
354 MemoryAccessRange((thr), (pc), (uptr)(s), \
355 common_flags()->strict_string_checks ? (len) + 1 : (n), false)
357 #define READ_STRING(thr, pc, s, n) \
358 READ_STRING_OF_LEN((thr), (pc), (s), internal_strlen(s), (n))
360 #define BLOCK_REAL(name) (BlockingCall(thr), REAL(name))
362 struct BlockingCall {
363 explicit BlockingCall(ThreadState *thr)
364 : thr(thr) {
365 EnterBlockingFunc(thr);
366 // When we are in a "blocking call", we process signals asynchronously
367 // (right when they arrive). In this context we do not expect to be
368 // executing any user/runtime code. The known interceptor sequence when
369 // this is not true is: pthread_join -> munmap(stack). It's fine
370 // to ignore munmap in this case -- we handle stack shadow separately.
371 thr->ignore_interceptors++;
374 ~BlockingCall() {
375 thr->ignore_interceptors--;
376 atomic_store(&thr->in_blocking_func, 0, memory_order_relaxed);
379 ThreadState *thr;
382 TSAN_INTERCEPTOR(unsigned, sleep, unsigned sec) {
383 SCOPED_TSAN_INTERCEPTOR(sleep, sec);
384 unsigned res = BLOCK_REAL(sleep)(sec);
385 AfterSleep(thr, pc);
386 return res;
389 TSAN_INTERCEPTOR(int, usleep, long_t usec) {
390 SCOPED_TSAN_INTERCEPTOR(usleep, usec);
391 int res = BLOCK_REAL(usleep)(usec);
392 AfterSleep(thr, pc);
393 return res;
396 TSAN_INTERCEPTOR(int, nanosleep, void *req, void *rem) {
397 SCOPED_TSAN_INTERCEPTOR(nanosleep, req, rem);
398 int res = BLOCK_REAL(nanosleep)(req, rem);
399 AfterSleep(thr, pc);
400 return res;
403 TSAN_INTERCEPTOR(int, pause, int fake) {
404 SCOPED_TSAN_INTERCEPTOR(pause, fake);
405 return BLOCK_REAL(pause)(fake);
408 // Note: we specifically call the function in such strange way
409 // with "installed_at" because in reports it will appear between
410 // callback frames and the frame that installed the callback.
411 static void at_exit_callback_installed_at() {
412 AtExitCtx *ctx;
414 // Ensure thread-safety.
415 Lock l(&interceptor_ctx()->atexit_mu);
417 // Pop AtExitCtx from the top of the stack of callback functions
418 uptr element = interceptor_ctx()->AtExitStack.Size() - 1;
419 ctx = interceptor_ctx()->AtExitStack[element];
420 interceptor_ctx()->AtExitStack.PopBack();
423 ThreadState *thr = cur_thread();
424 Acquire(thr, ctx->pc, (uptr)ctx);
425 FuncEntry(thr, ctx->pc);
426 ((void(*)())ctx->f)();
427 FuncExit(thr);
428 Free(ctx);
431 static void cxa_at_exit_callback_installed_at(void *arg) {
432 ThreadState *thr = cur_thread();
433 AtExitCtx *ctx = (AtExitCtx*)arg;
434 Acquire(thr, ctx->pc, (uptr)arg);
435 FuncEntry(thr, ctx->pc);
436 ((void(*)(void *arg))ctx->f)(ctx->arg);
437 FuncExit(thr);
438 Free(ctx);
441 static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(),
442 void *arg, void *dso);
444 #if !SANITIZER_ANDROID
445 TSAN_INTERCEPTOR(int, atexit, void (*f)()) {
446 if (in_symbolizer())
447 return 0;
448 // We want to setup the atexit callback even if we are in ignored lib
449 // or after fork.
450 SCOPED_INTERCEPTOR_RAW(atexit, f);
451 return setup_at_exit_wrapper(thr, GET_CALLER_PC(), (void (*)())f, 0, 0);
453 #endif
455 TSAN_INTERCEPTOR(int, __cxa_atexit, void (*f)(void *a), void *arg, void *dso) {
456 if (in_symbolizer())
457 return 0;
458 SCOPED_TSAN_INTERCEPTOR(__cxa_atexit, f, arg, dso);
459 return setup_at_exit_wrapper(thr, GET_CALLER_PC(), (void (*)())f, arg, dso);
462 static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(),
463 void *arg, void *dso) {
464 auto *ctx = New<AtExitCtx>();
465 ctx->f = f;
466 ctx->arg = arg;
467 ctx->pc = pc;
468 Release(thr, pc, (uptr)ctx);
469 // Memory allocation in __cxa_atexit will race with free during exit,
470 // because we do not see synchronization around atexit callback list.
471 ThreadIgnoreBegin(thr, pc);
472 int res;
473 if (!dso) {
474 // NetBSD does not preserve the 2nd argument if dso is equal to 0
475 // Store ctx in a local stack-like structure
477 // Ensure thread-safety.
478 Lock l(&interceptor_ctx()->atexit_mu);
479 // __cxa_atexit calls calloc. If we don't ignore interceptors, we will fail
480 // due to atexit_mu held on exit from the calloc interceptor.
481 ScopedIgnoreInterceptors ignore;
483 res = REAL(__cxa_atexit)((void (*)(void *a))at_exit_callback_installed_at,
484 0, 0);
485 // Push AtExitCtx on the top of the stack of callback functions
486 if (!res) {
487 interceptor_ctx()->AtExitStack.PushBack(ctx);
489 } else {
490 res = REAL(__cxa_atexit)(cxa_at_exit_callback_installed_at, ctx, dso);
492 ThreadIgnoreEnd(thr);
493 return res;
496 #if !SANITIZER_APPLE && !SANITIZER_NETBSD
497 static void on_exit_callback_installed_at(int status, void *arg) {
498 ThreadState *thr = cur_thread();
499 AtExitCtx *ctx = (AtExitCtx*)arg;
500 Acquire(thr, ctx->pc, (uptr)arg);
501 FuncEntry(thr, ctx->pc);
502 ((void(*)(int status, void *arg))ctx->f)(status, ctx->arg);
503 FuncExit(thr);
504 Free(ctx);
507 TSAN_INTERCEPTOR(int, on_exit, void(*f)(int, void*), void *arg) {
508 if (in_symbolizer())
509 return 0;
510 SCOPED_TSAN_INTERCEPTOR(on_exit, f, arg);
511 auto *ctx = New<AtExitCtx>();
512 ctx->f = (void(*)())f;
513 ctx->arg = arg;
514 ctx->pc = GET_CALLER_PC();
515 Release(thr, pc, (uptr)ctx);
516 // Memory allocation in __cxa_atexit will race with free during exit,
517 // because we do not see synchronization around atexit callback list.
518 ThreadIgnoreBegin(thr, pc);
519 int res = REAL(on_exit)(on_exit_callback_installed_at, ctx);
520 ThreadIgnoreEnd(thr);
521 return res;
523 #define TSAN_MAYBE_INTERCEPT_ON_EXIT TSAN_INTERCEPT(on_exit)
524 #else
525 #define TSAN_MAYBE_INTERCEPT_ON_EXIT
526 #endif
528 // Cleanup old bufs.
529 static void JmpBufGarbageCollect(ThreadState *thr, uptr sp) {
530 for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) {
531 JmpBuf *buf = &thr->jmp_bufs[i];
532 if (buf->sp <= sp) {
533 uptr sz = thr->jmp_bufs.Size();
534 internal_memcpy(buf, &thr->jmp_bufs[sz - 1], sizeof(*buf));
535 thr->jmp_bufs.PopBack();
536 i--;
541 static void SetJmp(ThreadState *thr, uptr sp) {
542 if (!thr->is_inited) // called from libc guts during bootstrap
543 return;
544 // Cleanup old bufs.
545 JmpBufGarbageCollect(thr, sp);
546 // Remember the buf.
547 JmpBuf *buf = thr->jmp_bufs.PushBack();
548 buf->sp = sp;
549 buf->shadow_stack_pos = thr->shadow_stack_pos;
550 ThreadSignalContext *sctx = SigCtx(thr);
551 buf->int_signal_send = sctx ? sctx->int_signal_send : 0;
552 buf->in_blocking_func = atomic_load(&thr->in_blocking_func, memory_order_relaxed);
553 buf->in_signal_handler = atomic_load(&thr->in_signal_handler,
554 memory_order_relaxed);
557 static void LongJmp(ThreadState *thr, uptr *env) {
558 uptr sp = ExtractLongJmpSp(env);
559 // Find the saved buf with matching sp.
560 for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) {
561 JmpBuf *buf = &thr->jmp_bufs[i];
562 if (buf->sp == sp) {
563 CHECK_GE(thr->shadow_stack_pos, buf->shadow_stack_pos);
564 // Unwind the stack.
565 while (thr->shadow_stack_pos > buf->shadow_stack_pos)
566 FuncExit(thr);
567 ThreadSignalContext *sctx = SigCtx(thr);
568 if (sctx)
569 sctx->int_signal_send = buf->int_signal_send;
570 atomic_store(&thr->in_blocking_func, buf->in_blocking_func,
571 memory_order_relaxed);
572 atomic_store(&thr->in_signal_handler, buf->in_signal_handler,
573 memory_order_relaxed);
574 JmpBufGarbageCollect(thr, buf->sp - 1); // do not collect buf->sp
575 return;
578 Printf("ThreadSanitizer: can't find longjmp buf\n");
579 CHECK(0);
582 // FIXME: put everything below into a common extern "C" block?
583 extern "C" void __tsan_setjmp(uptr sp) { SetJmp(cur_thread_init(), sp); }
585 #if SANITIZER_APPLE
586 TSAN_INTERCEPTOR(int, setjmp, void *env);
587 TSAN_INTERCEPTOR(int, _setjmp, void *env);
588 TSAN_INTERCEPTOR(int, sigsetjmp, void *env);
589 #else // SANITIZER_APPLE
591 #if SANITIZER_NETBSD
592 #define setjmp_symname __setjmp14
593 #define sigsetjmp_symname __sigsetjmp14
594 #else
595 #define setjmp_symname setjmp
596 #define sigsetjmp_symname sigsetjmp
597 #endif
599 DEFINE_REAL(int, setjmp_symname, void *env)
600 DEFINE_REAL(int, _setjmp, void *env)
601 DEFINE_REAL(int, sigsetjmp_symname, void *env)
602 #if !SANITIZER_NETBSD
603 DEFINE_REAL(int, __sigsetjmp, void *env)
604 #endif
606 // The real interceptor for setjmp is special, and implemented in pure asm. We
607 // just need to initialize the REAL functions so that they can be used in asm.
608 static void InitializeSetjmpInterceptors() {
609 // We can not use TSAN_INTERCEPT to get setjmp addr, because it does &setjmp and
610 // setjmp is not present in some versions of libc.
611 using __interception::InterceptFunction;
612 InterceptFunction(SANITIZER_STRINGIFY(setjmp_symname), (uptr*)&REAL(setjmp_symname), 0, 0);
613 InterceptFunction("_setjmp", (uptr*)&REAL(_setjmp), 0, 0);
614 InterceptFunction(SANITIZER_STRINGIFY(sigsetjmp_symname), (uptr*)&REAL(sigsetjmp_symname), 0,
616 #if !SANITIZER_NETBSD
617 InterceptFunction("__sigsetjmp", (uptr*)&REAL(__sigsetjmp), 0, 0);
618 #endif
620 #endif // SANITIZER_APPLE
622 #if SANITIZER_NETBSD
623 #define longjmp_symname __longjmp14
624 #define siglongjmp_symname __siglongjmp14
625 #else
626 #define longjmp_symname longjmp
627 #define siglongjmp_symname siglongjmp
628 #endif
630 TSAN_INTERCEPTOR(void, longjmp_symname, uptr *env, int val) {
631 // Note: if we call REAL(longjmp) in the context of ScopedInterceptor,
632 // bad things will happen. We will jump over ScopedInterceptor dtor and can
633 // leave thr->in_ignored_lib set.
635 SCOPED_INTERCEPTOR_RAW(longjmp_symname, env, val);
637 LongJmp(cur_thread(), env);
638 REAL(longjmp_symname)(env, val);
641 TSAN_INTERCEPTOR(void, siglongjmp_symname, uptr *env, int val) {
643 SCOPED_INTERCEPTOR_RAW(siglongjmp_symname, env, val);
645 LongJmp(cur_thread(), env);
646 REAL(siglongjmp_symname)(env, val);
649 #if SANITIZER_NETBSD
650 TSAN_INTERCEPTOR(void, _longjmp, uptr *env, int val) {
652 SCOPED_INTERCEPTOR_RAW(_longjmp, env, val);
654 LongJmp(cur_thread(), env);
655 REAL(_longjmp)(env, val);
657 #endif
659 #if !SANITIZER_APPLE
660 TSAN_INTERCEPTOR(void*, malloc, uptr size) {
661 if (in_symbolizer())
662 return InternalAlloc(size);
663 void *p = 0;
665 SCOPED_INTERCEPTOR_RAW(malloc, size);
666 p = user_alloc(thr, pc, size);
668 invoke_malloc_hook(p, size);
669 return p;
672 // In glibc<2.25, dynamic TLS blocks are allocated by __libc_memalign. Intercept
673 // __libc_memalign so that (1) we can detect races (2) free will not be called
674 // on libc internally allocated blocks.
675 TSAN_INTERCEPTOR(void*, __libc_memalign, uptr align, uptr sz) {
676 SCOPED_INTERCEPTOR_RAW(__libc_memalign, align, sz);
677 return user_memalign(thr, pc, align, sz);
680 TSAN_INTERCEPTOR(void*, calloc, uptr size, uptr n) {
681 if (in_symbolizer())
682 return InternalCalloc(size, n);
683 void *p = 0;
685 SCOPED_INTERCEPTOR_RAW(calloc, size, n);
686 p = user_calloc(thr, pc, size, n);
688 invoke_malloc_hook(p, n * size);
689 return p;
692 TSAN_INTERCEPTOR(void*, realloc, void *p, uptr size) {
693 if (in_symbolizer())
694 return InternalRealloc(p, size);
695 if (p)
696 invoke_free_hook(p);
698 SCOPED_INTERCEPTOR_RAW(realloc, p, size);
699 p = user_realloc(thr, pc, p, size);
701 invoke_malloc_hook(p, size);
702 return p;
705 TSAN_INTERCEPTOR(void*, reallocarray, void *p, uptr size, uptr n) {
706 if (in_symbolizer())
707 return InternalReallocArray(p, size, n);
708 if (p)
709 invoke_free_hook(p);
711 SCOPED_INTERCEPTOR_RAW(reallocarray, p, size, n);
712 p = user_reallocarray(thr, pc, p, size, n);
714 invoke_malloc_hook(p, size);
715 return p;
718 TSAN_INTERCEPTOR(void, free, void *p) {
719 if (p == 0)
720 return;
721 if (in_symbolizer())
722 return InternalFree(p);
723 invoke_free_hook(p);
724 SCOPED_INTERCEPTOR_RAW(free, p);
725 user_free(thr, pc, p);
728 TSAN_INTERCEPTOR(void, cfree, void *p) {
729 if (p == 0)
730 return;
731 if (in_symbolizer())
732 return InternalFree(p);
733 invoke_free_hook(p);
734 SCOPED_INTERCEPTOR_RAW(cfree, p);
735 user_free(thr, pc, p);
738 TSAN_INTERCEPTOR(uptr, malloc_usable_size, void *p) {
739 SCOPED_INTERCEPTOR_RAW(malloc_usable_size, p);
740 return user_alloc_usable_size(p);
742 #endif
744 TSAN_INTERCEPTOR(char *, strcpy, char *dst, const char *src) {
745 SCOPED_TSAN_INTERCEPTOR(strcpy, dst, src);
746 uptr srclen = internal_strlen(src);
747 MemoryAccessRange(thr, pc, (uptr)dst, srclen + 1, true);
748 MemoryAccessRange(thr, pc, (uptr)src, srclen + 1, false);
749 return REAL(strcpy)(dst, src);
752 TSAN_INTERCEPTOR(char*, strncpy, char *dst, char *src, uptr n) {
753 SCOPED_TSAN_INTERCEPTOR(strncpy, dst, src, n);
754 uptr srclen = internal_strnlen(src, n);
755 MemoryAccessRange(thr, pc, (uptr)dst, n, true);
756 MemoryAccessRange(thr, pc, (uptr)src, min(srclen + 1, n), false);
757 return REAL(strncpy)(dst, src, n);
760 TSAN_INTERCEPTOR(char*, strdup, const char *str) {
761 SCOPED_TSAN_INTERCEPTOR(strdup, str);
762 // strdup will call malloc, so no instrumentation is required here.
763 return REAL(strdup)(str);
766 // Zero out addr if it points into shadow memory and was provided as a hint
767 // only, i.e., MAP_FIXED is not set.
768 static bool fix_mmap_addr(void **addr, long_t sz, int flags) {
769 if (*addr) {
770 if (!IsAppMem((uptr)*addr) || !IsAppMem((uptr)*addr + sz - 1)) {
771 if (flags & MAP_FIXED) {
772 errno = errno_EINVAL;
773 return false;
774 } else {
775 *addr = 0;
779 return true;
782 template <class Mmap>
783 static void *mmap_interceptor(ThreadState *thr, uptr pc, Mmap real_mmap,
784 void *addr, SIZE_T sz, int prot, int flags,
785 int fd, OFF64_T off) {
786 if (!fix_mmap_addr(&addr, sz, flags)) return MAP_FAILED;
787 void *res = real_mmap(addr, sz, prot, flags, fd, off);
788 if (res != MAP_FAILED) {
789 if (!IsAppMem((uptr)res) || !IsAppMem((uptr)res + sz - 1)) {
790 Report("ThreadSanitizer: mmap at bad address: addr=%p size=%p res=%p\n",
791 addr, (void*)sz, res);
792 Die();
794 if (fd > 0) FdAccess(thr, pc, fd);
795 MemoryRangeImitateWriteOrResetRange(thr, pc, (uptr)res, sz);
797 return res;
800 template <class Munmap>
801 static int munmap_interceptor(ThreadState *thr, uptr pc, Munmap real_munmap,
802 void *addr, SIZE_T sz) {
803 UnmapShadow(thr, (uptr)addr, sz);
804 int res = real_munmap(addr, sz);
805 return res;
808 #if SANITIZER_LINUX
809 TSAN_INTERCEPTOR(void*, memalign, uptr align, uptr sz) {
810 SCOPED_INTERCEPTOR_RAW(memalign, align, sz);
811 return user_memalign(thr, pc, align, sz);
813 #define TSAN_MAYBE_INTERCEPT_MEMALIGN TSAN_INTERCEPT(memalign)
814 #else
815 #define TSAN_MAYBE_INTERCEPT_MEMALIGN
816 #endif
818 #if !SANITIZER_APPLE
819 TSAN_INTERCEPTOR(void*, aligned_alloc, uptr align, uptr sz) {
820 if (in_symbolizer())
821 return InternalAlloc(sz, nullptr, align);
822 SCOPED_INTERCEPTOR_RAW(aligned_alloc, align, sz);
823 return user_aligned_alloc(thr, pc, align, sz);
826 TSAN_INTERCEPTOR(void*, valloc, uptr sz) {
827 if (in_symbolizer())
828 return InternalAlloc(sz, nullptr, GetPageSizeCached());
829 SCOPED_INTERCEPTOR_RAW(valloc, sz);
830 return user_valloc(thr, pc, sz);
832 #endif
834 #if SANITIZER_LINUX
835 TSAN_INTERCEPTOR(void*, pvalloc, uptr sz) {
836 if (in_symbolizer()) {
837 uptr PageSize = GetPageSizeCached();
838 sz = sz ? RoundUpTo(sz, PageSize) : PageSize;
839 return InternalAlloc(sz, nullptr, PageSize);
841 SCOPED_INTERCEPTOR_RAW(pvalloc, sz);
842 return user_pvalloc(thr, pc, sz);
844 #define TSAN_MAYBE_INTERCEPT_PVALLOC TSAN_INTERCEPT(pvalloc)
845 #else
846 #define TSAN_MAYBE_INTERCEPT_PVALLOC
847 #endif
849 #if !SANITIZER_APPLE
850 TSAN_INTERCEPTOR(int, posix_memalign, void **memptr, uptr align, uptr sz) {
851 if (in_symbolizer()) {
852 void *p = InternalAlloc(sz, nullptr, align);
853 if (!p)
854 return errno_ENOMEM;
855 *memptr = p;
856 return 0;
858 SCOPED_INTERCEPTOR_RAW(posix_memalign, memptr, align, sz);
859 return user_posix_memalign(thr, pc, memptr, align, sz);
861 #endif
863 // Both __cxa_guard_acquire and pthread_once 0-initialize
864 // the object initially. pthread_once does not have any
865 // other ABI requirements. __cxa_guard_acquire assumes
866 // that any non-0 value in the first byte means that
867 // initialization is completed. Contents of the remaining
868 // bytes are up to us.
869 constexpr u32 kGuardInit = 0;
870 constexpr u32 kGuardDone = 1;
871 constexpr u32 kGuardRunning = 1 << 16;
872 constexpr u32 kGuardWaiter = 1 << 17;
874 static int guard_acquire(ThreadState *thr, uptr pc, atomic_uint32_t *g,
875 bool blocking_hooks = true) {
876 if (blocking_hooks)
877 OnPotentiallyBlockingRegionBegin();
878 auto on_exit = at_scope_exit([blocking_hooks] {
879 if (blocking_hooks)
880 OnPotentiallyBlockingRegionEnd();
883 for (;;) {
884 u32 cmp = atomic_load(g, memory_order_acquire);
885 if (cmp == kGuardInit) {
886 if (atomic_compare_exchange_strong(g, &cmp, kGuardRunning,
887 memory_order_relaxed))
888 return 1;
889 } else if (cmp == kGuardDone) {
890 if (!thr->in_ignored_lib)
891 Acquire(thr, pc, (uptr)g);
892 return 0;
893 } else {
894 if ((cmp & kGuardWaiter) ||
895 atomic_compare_exchange_strong(g, &cmp, cmp | kGuardWaiter,
896 memory_order_relaxed))
897 FutexWait(g, cmp | kGuardWaiter);
902 static void guard_release(ThreadState *thr, uptr pc, atomic_uint32_t *g,
903 u32 v) {
904 if (!thr->in_ignored_lib)
905 Release(thr, pc, (uptr)g);
906 u32 old = atomic_exchange(g, v, memory_order_release);
907 if (old & kGuardWaiter)
908 FutexWake(g, 1 << 30);
911 // __cxa_guard_acquire and friends need to be intercepted in a special way -
912 // regular interceptors will break statically-linked libstdc++. Linux
913 // interceptors are especially defined as weak functions (so that they don't
914 // cause link errors when user defines them as well). So they silently
915 // auto-disable themselves when such symbol is already present in the binary. If
916 // we link libstdc++ statically, it will bring own __cxa_guard_acquire which
917 // will silently replace our interceptor. That's why on Linux we simply export
918 // these interceptors with INTERFACE_ATTRIBUTE.
919 // On OS X, we don't support statically linking, so we just use a regular
920 // interceptor.
921 #if SANITIZER_APPLE
922 #define STDCXX_INTERCEPTOR TSAN_INTERCEPTOR
923 #else
924 #define STDCXX_INTERCEPTOR(rettype, name, ...) \
925 extern "C" rettype INTERFACE_ATTRIBUTE name(__VA_ARGS__)
926 #endif
928 // Used in thread-safe function static initialization.
929 STDCXX_INTERCEPTOR(int, __cxa_guard_acquire, atomic_uint32_t *g) {
930 SCOPED_INTERCEPTOR_RAW(__cxa_guard_acquire, g);
931 return guard_acquire(thr, pc, g);
934 STDCXX_INTERCEPTOR(void, __cxa_guard_release, atomic_uint32_t *g) {
935 SCOPED_INTERCEPTOR_RAW(__cxa_guard_release, g);
936 guard_release(thr, pc, g, kGuardDone);
939 STDCXX_INTERCEPTOR(void, __cxa_guard_abort, atomic_uint32_t *g) {
940 SCOPED_INTERCEPTOR_RAW(__cxa_guard_abort, g);
941 guard_release(thr, pc, g, kGuardInit);
944 namespace __tsan {
945 void DestroyThreadState() {
946 ThreadState *thr = cur_thread();
947 Processor *proc = thr->proc();
948 ThreadFinish(thr);
949 ProcUnwire(proc, thr);
950 ProcDestroy(proc);
951 DTLS_Destroy();
952 cur_thread_finalize();
955 void PlatformCleanUpThreadState(ThreadState *thr) {
956 ThreadSignalContext *sctx = (ThreadSignalContext *)atomic_load(
957 &thr->signal_ctx, memory_order_relaxed);
958 if (sctx) {
959 atomic_store(&thr->signal_ctx, 0, memory_order_relaxed);
960 UnmapOrDie(sctx, sizeof(*sctx));
963 } // namespace __tsan
965 #if !SANITIZER_APPLE && !SANITIZER_NETBSD && !SANITIZER_FREEBSD
966 static void thread_finalize(void *v) {
967 uptr iter = (uptr)v;
968 if (iter > 1) {
969 if (pthread_setspecific(interceptor_ctx()->finalize_key,
970 (void*)(iter - 1))) {
971 Printf("ThreadSanitizer: failed to set thread key\n");
972 Die();
974 return;
976 DestroyThreadState();
978 #endif
981 struct ThreadParam {
982 void* (*callback)(void *arg);
983 void *param;
984 Tid tid;
985 Semaphore created;
986 Semaphore started;
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_APPLE && !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");
1002 Die();
1004 ThreadIgnoreEnd(thr);
1005 #endif
1006 p->created.Wait();
1007 Processor *proc = ProcCreate();
1008 ProcWire(proc, thr);
1009 ThreadStart(thr, p->tid, GetTid(), ThreadType::Regular);
1010 p->started.Post();
1012 void *res = callback(param);
1013 // Prevent the callback from being tail called,
1014 // it mixes up stack traces.
1015 volatile int foo = 42;
1016 foo++;
1017 return res;
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");
1030 Die();
1031 } else {
1032 VPrintf(1,
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",
1036 internal_getpid());
1039 __sanitizer_pthread_attr_t myattr;
1040 if (attr == 0) {
1041 pthread_attr_init(&myattr);
1042 attr = &myattr;
1044 int detached = 0;
1045 REAL(pthread_attr_getdetachstate)(attr, &detached);
1046 AdjustStackSize(attr);
1048 ThreadParam p;
1049 p.callback = callback;
1050 p.param = param;
1051 p.tid = kMainTid;
1052 int res = -1;
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);
1060 if (res == 0) {
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.
1070 p.created.Post();
1071 p.started.Wait();
1073 if (attr == &myattr)
1074 pthread_attr_destroy(&myattr);
1075 return res;
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);
1084 if (res == 0) {
1085 ThreadJoin(thr, pc, tid);
1087 return res;
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);
1096 if (res == 0) {
1097 ThreadDetach(thr, pc, tid);
1099 return res;
1102 TSAN_INTERCEPTOR(void, pthread_exit, void *retval) {
1104 SCOPED_INTERCEPTOR_RAW(pthread_exit, retval);
1105 #if !SANITIZER_APPLE && !SANITIZER_ANDROID
1106 CHECK_EQ(thr, &cur_thread_placeholder);
1107 #endif
1109 REAL(pthread_exit)(retval);
1112 #if SANITIZER_LINUX
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);
1119 if (res == 0)
1120 ThreadJoin(thr, pc, tid);
1121 else
1122 ThreadNotJoined(thr, pc, tid, (uptr)th);
1123 return res;
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);
1133 if (res == 0)
1134 ThreadJoin(thr, pc, tid);
1135 else
1136 ThreadNotJoined(thr, pc, tid, (uptr)th);
1137 return res;
1139 #endif
1141 // Problem:
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
1148 // CLOCK_REALTIME).
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)
1165 return c;
1166 atomic_uintptr_t *p = (atomic_uintptr_t*)c;
1167 uptr cond = atomic_load(p, memory_order_acquire);
1168 if (!force && cond != 0)
1169 return (void*)cond;
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))
1174 return newcond;
1175 WRAP(free)(newcond);
1176 return (void*)cond;
1179 namespace {
1181 template <class Fn>
1182 struct CondMutexUnlockCtx {
1183 ScopedInterceptor *si;
1184 ThreadState *thr;
1185 uptr pc;
1186 void *m;
1187 void *c;
1188 const Fn &fn;
1190 int Cancel() const { return fn(); }
1191 void Unlock() const;
1194 template <class Fn>
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 CHECK_EQ(atomic_load(&thr->in_blocking_func, memory_order_relaxed), 1);
1202 atomic_store(&thr->in_blocking_func, 0, memory_order_relaxed);
1203 MutexPostLock(thr, pc, (uptr)m, MutexFlagDoPreLockOnPostLock);
1204 // Undo BlockingCall ctor effects.
1205 thr->ignore_interceptors--;
1206 si->~ScopedInterceptor();
1208 } // namespace
1210 INTERCEPTOR(int, pthread_cond_init, void *c, void *a) {
1211 void *cond = init_cond(c, true);
1212 SCOPED_TSAN_INTERCEPTOR(pthread_cond_init, cond, a);
1213 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true);
1214 return REAL(pthread_cond_init)(cond, a);
1217 template <class Fn>
1218 int cond_wait(ThreadState *thr, uptr pc, ScopedInterceptor *si, const Fn &fn,
1219 void *c, void *m) {
1220 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1221 MutexUnlock(thr, pc, (uptr)m);
1222 int res = 0;
1223 // This ensures that we handle mutex lock even in case of pthread_cancel.
1224 // See test/tsan/cond_cancel.cpp.
1226 // Enable signal delivery while the thread is blocked.
1227 BlockingCall bc(thr);
1228 CondMutexUnlockCtx<Fn> arg = {si, thr, pc, m, c, fn};
1229 res = call_pthread_cancel_with_cleanup(
1230 [](void *arg) -> int {
1231 return ((const CondMutexUnlockCtx<Fn> *)arg)->Cancel();
1233 [](void *arg) { ((const CondMutexUnlockCtx<Fn> *)arg)->Unlock(); },
1234 &arg);
1236 if (res == errno_EOWNERDEAD) MutexRepair(thr, pc, (uptr)m);
1237 MutexPostLock(thr, pc, (uptr)m, MutexFlagDoPreLockOnPostLock);
1238 return res;
1241 INTERCEPTOR(int, pthread_cond_wait, void *c, void *m) {
1242 void *cond = init_cond(c);
1243 SCOPED_TSAN_INTERCEPTOR(pthread_cond_wait, cond, m);
1244 return cond_wait(
1245 thr, pc, &si, [=]() { return REAL(pthread_cond_wait)(cond, m); }, cond,
1249 INTERCEPTOR(int, pthread_cond_timedwait, void *c, void *m, void *abstime) {
1250 void *cond = init_cond(c);
1251 SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait, cond, m, abstime);
1252 return cond_wait(
1253 thr, pc, &si,
1254 [=]() { return REAL(pthread_cond_timedwait)(cond, m, abstime); }, cond,
1258 #if SANITIZER_LINUX
1259 INTERCEPTOR(int, pthread_cond_clockwait, void *c, void *m,
1260 __sanitizer_clockid_t clock, void *abstime) {
1261 void *cond = init_cond(c);
1262 SCOPED_TSAN_INTERCEPTOR(pthread_cond_clockwait, cond, m, clock, abstime);
1263 return cond_wait(
1264 thr, pc, &si,
1265 [=]() { return REAL(pthread_cond_clockwait)(cond, m, clock, abstime); },
1266 cond, m);
1268 #define TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT TSAN_INTERCEPT(pthread_cond_clockwait)
1269 #else
1270 #define TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT
1271 #endif
1273 #if SANITIZER_APPLE
1274 INTERCEPTOR(int, pthread_cond_timedwait_relative_np, void *c, void *m,
1275 void *reltime) {
1276 void *cond = init_cond(c);
1277 SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait_relative_np, cond, m, reltime);
1278 return cond_wait(
1279 thr, pc, &si,
1280 [=]() {
1281 return REAL(pthread_cond_timedwait_relative_np)(cond, m, reltime);
1283 cond, m);
1285 #endif
1287 INTERCEPTOR(int, pthread_cond_signal, void *c) {
1288 void *cond = init_cond(c);
1289 SCOPED_TSAN_INTERCEPTOR(pthread_cond_signal, cond);
1290 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1291 return REAL(pthread_cond_signal)(cond);
1294 INTERCEPTOR(int, pthread_cond_broadcast, void *c) {
1295 void *cond = init_cond(c);
1296 SCOPED_TSAN_INTERCEPTOR(pthread_cond_broadcast, cond);
1297 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1298 return REAL(pthread_cond_broadcast)(cond);
1301 INTERCEPTOR(int, pthread_cond_destroy, void *c) {
1302 void *cond = init_cond(c);
1303 SCOPED_TSAN_INTERCEPTOR(pthread_cond_destroy, cond);
1304 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true);
1305 int res = REAL(pthread_cond_destroy)(cond);
1306 if (common_flags()->legacy_pthread_cond) {
1307 // Free our aux cond and zero the pointer to not leave dangling pointers.
1308 WRAP(free)(cond);
1309 atomic_store((atomic_uintptr_t*)c, 0, memory_order_relaxed);
1311 return res;
1314 TSAN_INTERCEPTOR(int, pthread_mutex_init, void *m, void *a) {
1315 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_init, m, a);
1316 int res = REAL(pthread_mutex_init)(m, a);
1317 if (res == 0) {
1318 u32 flagz = 0;
1319 if (a) {
1320 int type = 0;
1321 if (REAL(pthread_mutexattr_gettype)(a, &type) == 0)
1322 if (type == PTHREAD_MUTEX_RECURSIVE ||
1323 type == PTHREAD_MUTEX_RECURSIVE_NP)
1324 flagz |= MutexFlagWriteReentrant;
1326 MutexCreate(thr, pc, (uptr)m, flagz);
1328 return res;
1331 TSAN_INTERCEPTOR(int, pthread_mutex_destroy, void *m) {
1332 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_destroy, m);
1333 int res = REAL(pthread_mutex_destroy)(m);
1334 if (res == 0 || res == errno_EBUSY) {
1335 MutexDestroy(thr, pc, (uptr)m);
1337 return res;
1340 TSAN_INTERCEPTOR(int, pthread_mutex_lock, void *m) {
1341 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_lock, m);
1342 MutexPreLock(thr, pc, (uptr)m);
1343 int res = REAL(pthread_mutex_lock)(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);
1348 if (res == errno_EINVAL)
1349 MutexInvalidAccess(thr, pc, (uptr)m);
1350 return res;
1353 TSAN_INTERCEPTOR(int, pthread_mutex_trylock, void *m) {
1354 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_trylock, m);
1355 int res = REAL(pthread_mutex_trylock)(m);
1356 if (res == errno_EOWNERDEAD)
1357 MutexRepair(thr, pc, (uptr)m);
1358 if (res == 0 || res == errno_EOWNERDEAD)
1359 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1360 return res;
1363 #if !SANITIZER_APPLE
1364 TSAN_INTERCEPTOR(int, pthread_mutex_timedlock, void *m, void *abstime) {
1365 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_timedlock, m, abstime);
1366 int res = REAL(pthread_mutex_timedlock)(m, abstime);
1367 if (res == 0) {
1368 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1370 return res;
1372 #endif
1374 TSAN_INTERCEPTOR(int, pthread_mutex_unlock, void *m) {
1375 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_unlock, m);
1376 MutexUnlock(thr, pc, (uptr)m);
1377 int res = REAL(pthread_mutex_unlock)(m);
1378 if (res == errno_EINVAL)
1379 MutexInvalidAccess(thr, pc, (uptr)m);
1380 return res;
1383 #if SANITIZER_GLIBC
1384 # if !__GLIBC_PREREQ(2, 34)
1385 // glibc 2.34 applies a non-default version for the two functions. They are no
1386 // longer expected to be intercepted by programs.
1387 TSAN_INTERCEPTOR(int, __pthread_mutex_lock, void *m) {
1388 SCOPED_TSAN_INTERCEPTOR(__pthread_mutex_lock, m);
1389 MutexPreLock(thr, pc, (uptr)m);
1390 int res = REAL(__pthread_mutex_lock)(m);
1391 if (res == errno_EOWNERDEAD)
1392 MutexRepair(thr, pc, (uptr)m);
1393 if (res == 0 || res == errno_EOWNERDEAD)
1394 MutexPostLock(thr, pc, (uptr)m);
1395 if (res == errno_EINVAL)
1396 MutexInvalidAccess(thr, pc, (uptr)m);
1397 return res;
1400 TSAN_INTERCEPTOR(int, __pthread_mutex_unlock, void *m) {
1401 SCOPED_TSAN_INTERCEPTOR(__pthread_mutex_unlock, m);
1402 MutexUnlock(thr, pc, (uptr)m);
1403 int res = REAL(__pthread_mutex_unlock)(m);
1404 if (res == errno_EINVAL)
1405 MutexInvalidAccess(thr, pc, (uptr)m);
1406 return res;
1408 # endif
1409 #endif
1411 #if !SANITIZER_APPLE
1412 TSAN_INTERCEPTOR(int, pthread_spin_init, void *m, int pshared) {
1413 SCOPED_TSAN_INTERCEPTOR(pthread_spin_init, m, pshared);
1414 int res = REAL(pthread_spin_init)(m, pshared);
1415 if (res == 0) {
1416 MutexCreate(thr, pc, (uptr)m);
1418 return res;
1421 TSAN_INTERCEPTOR(int, pthread_spin_destroy, void *m) {
1422 SCOPED_TSAN_INTERCEPTOR(pthread_spin_destroy, m);
1423 int res = REAL(pthread_spin_destroy)(m);
1424 if (res == 0) {
1425 MutexDestroy(thr, pc, (uptr)m);
1427 return res;
1430 TSAN_INTERCEPTOR(int, pthread_spin_lock, void *m) {
1431 SCOPED_TSAN_INTERCEPTOR(pthread_spin_lock, m);
1432 MutexPreLock(thr, pc, (uptr)m);
1433 int res = REAL(pthread_spin_lock)(m);
1434 if (res == 0) {
1435 MutexPostLock(thr, pc, (uptr)m);
1437 return res;
1440 TSAN_INTERCEPTOR(int, pthread_spin_trylock, void *m) {
1441 SCOPED_TSAN_INTERCEPTOR(pthread_spin_trylock, m);
1442 int res = REAL(pthread_spin_trylock)(m);
1443 if (res == 0) {
1444 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1446 return res;
1449 TSAN_INTERCEPTOR(int, pthread_spin_unlock, void *m) {
1450 SCOPED_TSAN_INTERCEPTOR(pthread_spin_unlock, m);
1451 MutexUnlock(thr, pc, (uptr)m);
1452 int res = REAL(pthread_spin_unlock)(m);
1453 return res;
1455 #endif
1457 TSAN_INTERCEPTOR(int, pthread_rwlock_init, void *m, void *a) {
1458 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_init, m, a);
1459 int res = REAL(pthread_rwlock_init)(m, a);
1460 if (res == 0) {
1461 MutexCreate(thr, pc, (uptr)m);
1463 return res;
1466 TSAN_INTERCEPTOR(int, pthread_rwlock_destroy, void *m) {
1467 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_destroy, m);
1468 int res = REAL(pthread_rwlock_destroy)(m);
1469 if (res == 0) {
1470 MutexDestroy(thr, pc, (uptr)m);
1472 return res;
1475 TSAN_INTERCEPTOR(int, pthread_rwlock_rdlock, void *m) {
1476 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_rdlock, m);
1477 MutexPreReadLock(thr, pc, (uptr)m);
1478 int res = REAL(pthread_rwlock_rdlock)(m);
1479 if (res == 0) {
1480 MutexPostReadLock(thr, pc, (uptr)m);
1482 return res;
1485 TSAN_INTERCEPTOR(int, pthread_rwlock_tryrdlock, void *m) {
1486 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_tryrdlock, m);
1487 int res = REAL(pthread_rwlock_tryrdlock)(m);
1488 if (res == 0) {
1489 MutexPostReadLock(thr, pc, (uptr)m, MutexFlagTryLock);
1491 return res;
1494 #if !SANITIZER_APPLE
1495 TSAN_INTERCEPTOR(int, pthread_rwlock_timedrdlock, void *m, void *abstime) {
1496 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedrdlock, m, abstime);
1497 int res = REAL(pthread_rwlock_timedrdlock)(m, abstime);
1498 if (res == 0) {
1499 MutexPostReadLock(thr, pc, (uptr)m);
1501 return res;
1503 #endif
1505 TSAN_INTERCEPTOR(int, pthread_rwlock_wrlock, void *m) {
1506 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_wrlock, m);
1507 MutexPreLock(thr, pc, (uptr)m);
1508 int res = REAL(pthread_rwlock_wrlock)(m);
1509 if (res == 0) {
1510 MutexPostLock(thr, pc, (uptr)m);
1512 return res;
1515 TSAN_INTERCEPTOR(int, pthread_rwlock_trywrlock, void *m) {
1516 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_trywrlock, m);
1517 int res = REAL(pthread_rwlock_trywrlock)(m);
1518 if (res == 0) {
1519 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1521 return res;
1524 #if !SANITIZER_APPLE
1525 TSAN_INTERCEPTOR(int, pthread_rwlock_timedwrlock, void *m, void *abstime) {
1526 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedwrlock, m, abstime);
1527 int res = REAL(pthread_rwlock_timedwrlock)(m, abstime);
1528 if (res == 0) {
1529 MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1531 return res;
1533 #endif
1535 TSAN_INTERCEPTOR(int, pthread_rwlock_unlock, void *m) {
1536 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_unlock, m);
1537 MutexReadOrWriteUnlock(thr, pc, (uptr)m);
1538 int res = REAL(pthread_rwlock_unlock)(m);
1539 return res;
1542 #if !SANITIZER_APPLE
1543 TSAN_INTERCEPTOR(int, pthread_barrier_init, void *b, void *a, unsigned count) {
1544 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_init, b, a, count);
1545 MemoryAccess(thr, pc, (uptr)b, 1, kAccessWrite);
1546 int res = REAL(pthread_barrier_init)(b, a, count);
1547 return res;
1550 TSAN_INTERCEPTOR(int, pthread_barrier_destroy, void *b) {
1551 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_destroy, b);
1552 MemoryAccess(thr, pc, (uptr)b, 1, kAccessWrite);
1553 int res = REAL(pthread_barrier_destroy)(b);
1554 return res;
1557 TSAN_INTERCEPTOR(int, pthread_barrier_wait, void *b) {
1558 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_wait, b);
1559 Release(thr, pc, (uptr)b);
1560 MemoryAccess(thr, pc, (uptr)b, 1, kAccessRead);
1561 int res = REAL(pthread_barrier_wait)(b);
1562 MemoryAccess(thr, pc, (uptr)b, 1, kAccessRead);
1563 if (res == 0 || res == PTHREAD_BARRIER_SERIAL_THREAD) {
1564 Acquire(thr, pc, (uptr)b);
1566 return res;
1568 #endif
1570 TSAN_INTERCEPTOR(int, pthread_once, void *o, void (*f)()) {
1571 SCOPED_INTERCEPTOR_RAW(pthread_once, o, f);
1572 if (o == 0 || f == 0)
1573 return errno_EINVAL;
1574 atomic_uint32_t *a;
1576 if (SANITIZER_APPLE)
1577 a = static_cast<atomic_uint32_t*>((void *)((char *)o + sizeof(long_t)));
1578 else if (SANITIZER_NETBSD)
1579 a = static_cast<atomic_uint32_t*>
1580 ((void *)((char *)o + __sanitizer::pthread_mutex_t_sz));
1581 else
1582 a = static_cast<atomic_uint32_t*>(o);
1584 // Mac OS X appears to use pthread_once() where calling BlockingRegion hooks
1585 // result in crashes due to too little stack space.
1586 if (guard_acquire(thr, pc, a, !SANITIZER_APPLE)) {
1587 (*f)();
1588 guard_release(thr, pc, a, kGuardDone);
1590 return 0;
1593 #if SANITIZER_GLIBC
1594 TSAN_INTERCEPTOR(int, __fxstat, int version, int fd, void *buf) {
1595 SCOPED_TSAN_INTERCEPTOR(__fxstat, version, fd, buf);
1596 if (fd > 0)
1597 FdAccess(thr, pc, fd);
1598 return REAL(__fxstat)(version, fd, buf);
1600 #define TSAN_MAYBE_INTERCEPT___FXSTAT TSAN_INTERCEPT(__fxstat)
1601 #else
1602 #define TSAN_MAYBE_INTERCEPT___FXSTAT
1603 #endif
1605 TSAN_INTERCEPTOR(int, fstat, int fd, void *buf) {
1606 #if SANITIZER_GLIBC
1607 SCOPED_TSAN_INTERCEPTOR(__fxstat, 0, fd, buf);
1608 if (fd > 0)
1609 FdAccess(thr, pc, fd);
1610 return REAL(__fxstat)(0, fd, buf);
1611 #else
1612 SCOPED_TSAN_INTERCEPTOR(fstat, fd, buf);
1613 if (fd > 0)
1614 FdAccess(thr, pc, fd);
1615 return REAL(fstat)(fd, buf);
1616 #endif
1619 #if SANITIZER_GLIBC
1620 TSAN_INTERCEPTOR(int, __fxstat64, int version, int fd, void *buf) {
1621 SCOPED_TSAN_INTERCEPTOR(__fxstat64, version, fd, buf);
1622 if (fd > 0)
1623 FdAccess(thr, pc, fd);
1624 return REAL(__fxstat64)(version, fd, buf);
1626 #define TSAN_MAYBE_INTERCEPT___FXSTAT64 TSAN_INTERCEPT(__fxstat64)
1627 #else
1628 #define TSAN_MAYBE_INTERCEPT___FXSTAT64
1629 #endif
1631 #if SANITIZER_GLIBC
1632 TSAN_INTERCEPTOR(int, fstat64, int fd, void *buf) {
1633 SCOPED_TSAN_INTERCEPTOR(__fxstat64, 0, fd, buf);
1634 if (fd > 0)
1635 FdAccess(thr, pc, fd);
1636 return REAL(__fxstat64)(0, fd, buf);
1638 #define TSAN_MAYBE_INTERCEPT_FSTAT64 TSAN_INTERCEPT(fstat64)
1639 #else
1640 #define TSAN_MAYBE_INTERCEPT_FSTAT64
1641 #endif
1643 TSAN_INTERCEPTOR(int, open, const char *name, int oflag, ...) {
1644 va_list ap;
1645 va_start(ap, oflag);
1646 mode_t mode = va_arg(ap, int);
1647 va_end(ap);
1648 SCOPED_TSAN_INTERCEPTOR(open, name, oflag, mode);
1649 READ_STRING(thr, pc, name, 0);
1650 int fd = REAL(open)(name, oflag, mode);
1651 if (fd >= 0)
1652 FdFileCreate(thr, pc, fd);
1653 return fd;
1656 #if SANITIZER_LINUX
1657 TSAN_INTERCEPTOR(int, open64, const char *name, int oflag, ...) {
1658 va_list ap;
1659 va_start(ap, oflag);
1660 mode_t mode = va_arg(ap, int);
1661 va_end(ap);
1662 SCOPED_TSAN_INTERCEPTOR(open64, name, oflag, mode);
1663 READ_STRING(thr, pc, name, 0);
1664 int fd = REAL(open64)(name, oflag, mode);
1665 if (fd >= 0)
1666 FdFileCreate(thr, pc, fd);
1667 return fd;
1669 #define TSAN_MAYBE_INTERCEPT_OPEN64 TSAN_INTERCEPT(open64)
1670 #else
1671 #define TSAN_MAYBE_INTERCEPT_OPEN64
1672 #endif
1674 TSAN_INTERCEPTOR(int, creat, const char *name, int mode) {
1675 SCOPED_TSAN_INTERCEPTOR(creat, name, mode);
1676 READ_STRING(thr, pc, name, 0);
1677 int fd = REAL(creat)(name, mode);
1678 if (fd >= 0)
1679 FdFileCreate(thr, pc, fd);
1680 return fd;
1683 #if SANITIZER_LINUX
1684 TSAN_INTERCEPTOR(int, creat64, const char *name, int mode) {
1685 SCOPED_TSAN_INTERCEPTOR(creat64, name, mode);
1686 READ_STRING(thr, pc, name, 0);
1687 int fd = REAL(creat64)(name, mode);
1688 if (fd >= 0)
1689 FdFileCreate(thr, pc, fd);
1690 return fd;
1692 #define TSAN_MAYBE_INTERCEPT_CREAT64 TSAN_INTERCEPT(creat64)
1693 #else
1694 #define TSAN_MAYBE_INTERCEPT_CREAT64
1695 #endif
1697 TSAN_INTERCEPTOR(int, dup, int oldfd) {
1698 SCOPED_TSAN_INTERCEPTOR(dup, oldfd);
1699 int newfd = REAL(dup)(oldfd);
1700 if (oldfd >= 0 && newfd >= 0 && newfd != oldfd)
1701 FdDup(thr, pc, oldfd, newfd, true);
1702 return newfd;
1705 TSAN_INTERCEPTOR(int, dup2, int oldfd, int newfd) {
1706 SCOPED_TSAN_INTERCEPTOR(dup2, oldfd, newfd);
1707 int newfd2 = REAL(dup2)(oldfd, newfd);
1708 if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd)
1709 FdDup(thr, pc, oldfd, newfd2, false);
1710 return newfd2;
1713 #if !SANITIZER_APPLE
1714 TSAN_INTERCEPTOR(int, dup3, int oldfd, int newfd, int flags) {
1715 SCOPED_TSAN_INTERCEPTOR(dup3, oldfd, newfd, flags);
1716 int newfd2 = REAL(dup3)(oldfd, newfd, flags);
1717 if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd)
1718 FdDup(thr, pc, oldfd, newfd2, false);
1719 return newfd2;
1721 #endif
1723 #if SANITIZER_LINUX
1724 TSAN_INTERCEPTOR(int, eventfd, unsigned initval, int flags) {
1725 SCOPED_TSAN_INTERCEPTOR(eventfd, initval, flags);
1726 int fd = REAL(eventfd)(initval, flags);
1727 if (fd >= 0)
1728 FdEventCreate(thr, pc, fd);
1729 return fd;
1731 #define TSAN_MAYBE_INTERCEPT_EVENTFD TSAN_INTERCEPT(eventfd)
1732 #else
1733 #define TSAN_MAYBE_INTERCEPT_EVENTFD
1734 #endif
1736 #if SANITIZER_LINUX
1737 TSAN_INTERCEPTOR(int, signalfd, int fd, void *mask, int flags) {
1738 SCOPED_INTERCEPTOR_RAW(signalfd, fd, mask, flags);
1739 FdClose(thr, pc, fd);
1740 fd = REAL(signalfd)(fd, mask, flags);
1741 if (!MustIgnoreInterceptor(thr))
1742 FdSignalCreate(thr, pc, fd);
1743 return fd;
1745 #define TSAN_MAYBE_INTERCEPT_SIGNALFD TSAN_INTERCEPT(signalfd)
1746 #else
1747 #define TSAN_MAYBE_INTERCEPT_SIGNALFD
1748 #endif
1750 #if SANITIZER_LINUX
1751 TSAN_INTERCEPTOR(int, inotify_init, int fake) {
1752 SCOPED_TSAN_INTERCEPTOR(inotify_init, fake);
1753 int fd = REAL(inotify_init)(fake);
1754 if (fd >= 0)
1755 FdInotifyCreate(thr, pc, fd);
1756 return fd;
1758 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT TSAN_INTERCEPT(inotify_init)
1759 #else
1760 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT
1761 #endif
1763 #if SANITIZER_LINUX
1764 TSAN_INTERCEPTOR(int, inotify_init1, int flags) {
1765 SCOPED_TSAN_INTERCEPTOR(inotify_init1, flags);
1766 int fd = REAL(inotify_init1)(flags);
1767 if (fd >= 0)
1768 FdInotifyCreate(thr, pc, fd);
1769 return fd;
1771 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1 TSAN_INTERCEPT(inotify_init1)
1772 #else
1773 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1
1774 #endif
1776 TSAN_INTERCEPTOR(int, socket, int domain, int type, int protocol) {
1777 SCOPED_TSAN_INTERCEPTOR(socket, domain, type, protocol);
1778 int fd = REAL(socket)(domain, type, protocol);
1779 if (fd >= 0)
1780 FdSocketCreate(thr, pc, fd);
1781 return fd;
1784 TSAN_INTERCEPTOR(int, socketpair, int domain, int type, int protocol, int *fd) {
1785 SCOPED_TSAN_INTERCEPTOR(socketpair, domain, type, protocol, fd);
1786 int res = REAL(socketpair)(domain, type, protocol, fd);
1787 if (res == 0 && fd[0] >= 0 && fd[1] >= 0)
1788 FdPipeCreate(thr, pc, fd[0], fd[1]);
1789 return res;
1792 TSAN_INTERCEPTOR(int, connect, int fd, void *addr, unsigned addrlen) {
1793 SCOPED_TSAN_INTERCEPTOR(connect, fd, addr, addrlen);
1794 FdSocketConnecting(thr, pc, fd);
1795 int res = REAL(connect)(fd, addr, addrlen);
1796 if (res == 0 && fd >= 0)
1797 FdSocketConnect(thr, pc, fd);
1798 return res;
1801 TSAN_INTERCEPTOR(int, bind, int fd, void *addr, unsigned addrlen) {
1802 SCOPED_TSAN_INTERCEPTOR(bind, fd, addr, addrlen);
1803 int res = REAL(bind)(fd, addr, addrlen);
1804 if (fd > 0 && res == 0)
1805 FdAccess(thr, pc, fd);
1806 return res;
1809 TSAN_INTERCEPTOR(int, listen, int fd, int backlog) {
1810 SCOPED_TSAN_INTERCEPTOR(listen, fd, backlog);
1811 int res = REAL(listen)(fd, backlog);
1812 if (fd > 0 && res == 0)
1813 FdAccess(thr, pc, fd);
1814 return res;
1817 TSAN_INTERCEPTOR(int, close, int fd) {
1818 SCOPED_INTERCEPTOR_RAW(close, fd);
1819 if (!in_symbolizer())
1820 FdClose(thr, pc, fd);
1821 return REAL(close)(fd);
1824 #if SANITIZER_LINUX
1825 TSAN_INTERCEPTOR(int, __close, int fd) {
1826 SCOPED_INTERCEPTOR_RAW(__close, fd);
1827 FdClose(thr, pc, fd);
1828 return REAL(__close)(fd);
1830 #define TSAN_MAYBE_INTERCEPT___CLOSE TSAN_INTERCEPT(__close)
1831 #else
1832 #define TSAN_MAYBE_INTERCEPT___CLOSE
1833 #endif
1835 // glibc guts
1836 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1837 TSAN_INTERCEPTOR(void, __res_iclose, void *state, bool free_addr) {
1838 SCOPED_INTERCEPTOR_RAW(__res_iclose, state, free_addr);
1839 int fds[64];
1840 int cnt = ExtractResolvFDs(state, fds, ARRAY_SIZE(fds));
1841 for (int i = 0; i < cnt; i++) FdClose(thr, pc, fds[i]);
1842 REAL(__res_iclose)(state, free_addr);
1844 #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE TSAN_INTERCEPT(__res_iclose)
1845 #else
1846 #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE
1847 #endif
1849 TSAN_INTERCEPTOR(int, pipe, int *pipefd) {
1850 SCOPED_TSAN_INTERCEPTOR(pipe, pipefd);
1851 int res = REAL(pipe)(pipefd);
1852 if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0)
1853 FdPipeCreate(thr, pc, pipefd[0], pipefd[1]);
1854 return res;
1857 #if !SANITIZER_APPLE
1858 TSAN_INTERCEPTOR(int, pipe2, int *pipefd, int flags) {
1859 SCOPED_TSAN_INTERCEPTOR(pipe2, pipefd, flags);
1860 int res = REAL(pipe2)(pipefd, flags);
1861 if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0)
1862 FdPipeCreate(thr, pc, pipefd[0], pipefd[1]);
1863 return res;
1865 #endif
1867 TSAN_INTERCEPTOR(int, unlink, char *path) {
1868 SCOPED_TSAN_INTERCEPTOR(unlink, path);
1869 Release(thr, pc, File2addr(path));
1870 int res = REAL(unlink)(path);
1871 return res;
1874 TSAN_INTERCEPTOR(void*, tmpfile, int fake) {
1875 SCOPED_TSAN_INTERCEPTOR(tmpfile, fake);
1876 void *res = REAL(tmpfile)(fake);
1877 if (res) {
1878 int fd = fileno_unlocked(res);
1879 if (fd >= 0)
1880 FdFileCreate(thr, pc, fd);
1882 return res;
1885 #if SANITIZER_LINUX
1886 TSAN_INTERCEPTOR(void*, tmpfile64, int fake) {
1887 SCOPED_TSAN_INTERCEPTOR(tmpfile64, fake);
1888 void *res = REAL(tmpfile64)(fake);
1889 if (res) {
1890 int fd = fileno_unlocked(res);
1891 if (fd >= 0)
1892 FdFileCreate(thr, pc, fd);
1894 return res;
1896 #define TSAN_MAYBE_INTERCEPT_TMPFILE64 TSAN_INTERCEPT(tmpfile64)
1897 #else
1898 #define TSAN_MAYBE_INTERCEPT_TMPFILE64
1899 #endif
1901 static void FlushStreams() {
1902 // Flushing all the streams here may freeze the process if a child thread is
1903 // performing file stream operations at the same time.
1904 REAL(fflush)(stdout);
1905 REAL(fflush)(stderr);
1908 TSAN_INTERCEPTOR(void, abort, int fake) {
1909 SCOPED_TSAN_INTERCEPTOR(abort, fake);
1910 FlushStreams();
1911 REAL(abort)(fake);
1914 TSAN_INTERCEPTOR(int, rmdir, char *path) {
1915 SCOPED_TSAN_INTERCEPTOR(rmdir, path);
1916 Release(thr, pc, Dir2addr(path));
1917 int res = REAL(rmdir)(path);
1918 return res;
1921 TSAN_INTERCEPTOR(int, closedir, void *dirp) {
1922 SCOPED_INTERCEPTOR_RAW(closedir, dirp);
1923 if (dirp) {
1924 int fd = dirfd(dirp);
1925 FdClose(thr, pc, fd);
1927 return REAL(closedir)(dirp);
1930 #if SANITIZER_LINUX
1931 TSAN_INTERCEPTOR(int, epoll_create, int size) {
1932 SCOPED_TSAN_INTERCEPTOR(epoll_create, size);
1933 int fd = REAL(epoll_create)(size);
1934 if (fd >= 0)
1935 FdPollCreate(thr, pc, fd);
1936 return fd;
1939 TSAN_INTERCEPTOR(int, epoll_create1, int flags) {
1940 SCOPED_TSAN_INTERCEPTOR(epoll_create1, flags);
1941 int fd = REAL(epoll_create1)(flags);
1942 if (fd >= 0)
1943 FdPollCreate(thr, pc, fd);
1944 return fd;
1947 TSAN_INTERCEPTOR(int, epoll_ctl, int epfd, int op, int fd, void *ev) {
1948 SCOPED_TSAN_INTERCEPTOR(epoll_ctl, epfd, op, fd, ev);
1949 if (epfd >= 0)
1950 FdAccess(thr, pc, epfd);
1951 if (epfd >= 0 && fd >= 0)
1952 FdAccess(thr, pc, fd);
1953 if (op == EPOLL_CTL_ADD && epfd >= 0) {
1954 FdPollAdd(thr, pc, epfd, fd);
1955 FdRelease(thr, pc, epfd);
1957 int res = REAL(epoll_ctl)(epfd, op, fd, ev);
1958 return res;
1961 TSAN_INTERCEPTOR(int, epoll_wait, int epfd, void *ev, int cnt, int timeout) {
1962 SCOPED_TSAN_INTERCEPTOR(epoll_wait, epfd, ev, cnt, timeout);
1963 if (epfd >= 0)
1964 FdAccess(thr, pc, epfd);
1965 int res = BLOCK_REAL(epoll_wait)(epfd, ev, cnt, timeout);
1966 if (res > 0 && epfd >= 0)
1967 FdAcquire(thr, pc, epfd);
1968 return res;
1971 TSAN_INTERCEPTOR(int, epoll_pwait, int epfd, void *ev, int cnt, int timeout,
1972 void *sigmask) {
1973 SCOPED_TSAN_INTERCEPTOR(epoll_pwait, epfd, ev, cnt, timeout, sigmask);
1974 if (epfd >= 0)
1975 FdAccess(thr, pc, epfd);
1976 int res = BLOCK_REAL(epoll_pwait)(epfd, ev, cnt, timeout, sigmask);
1977 if (res > 0 && epfd >= 0)
1978 FdAcquire(thr, pc, epfd);
1979 return res;
1982 TSAN_INTERCEPTOR(int, epoll_pwait2, int epfd, void *ev, int cnt, void *timeout,
1983 void *sigmask) {
1984 SCOPED_INTERCEPTOR_RAW(epoll_pwait2, epfd, ev, cnt, timeout, sigmask);
1985 // This function is new and may not be present in libc and/or kernel.
1986 // Since we effectively add it to libc (as will be probed by the program
1987 // using dlsym or a weak function pointer) we need to handle the case
1988 // when it's not present in the actual libc.
1989 if (!REAL(epoll_pwait2)) {
1990 errno = errno_ENOSYS;
1991 return -1;
1993 if (MustIgnoreInterceptor(thr))
1994 REAL(epoll_pwait2)(epfd, ev, cnt, timeout, sigmask);
1995 if (epfd >= 0)
1996 FdAccess(thr, pc, epfd);
1997 int res = BLOCK_REAL(epoll_pwait2)(epfd, ev, cnt, timeout, sigmask);
1998 if (res > 0 && epfd >= 0)
1999 FdAcquire(thr, pc, epfd);
2000 return res;
2003 # define TSAN_MAYBE_INTERCEPT_EPOLL \
2004 TSAN_INTERCEPT(epoll_create); \
2005 TSAN_INTERCEPT(epoll_create1); \
2006 TSAN_INTERCEPT(epoll_ctl); \
2007 TSAN_INTERCEPT(epoll_wait); \
2008 TSAN_INTERCEPT(epoll_pwait); \
2009 TSAN_INTERCEPT(epoll_pwait2)
2010 #else
2011 #define TSAN_MAYBE_INTERCEPT_EPOLL
2012 #endif
2014 // The following functions are intercepted merely to process pending signals.
2015 // If program blocks signal X, we must deliver the signal before the function
2016 // returns. Similarly, if program unblocks a signal (or returns from sigsuspend)
2017 // it's better to deliver the signal straight away.
2018 TSAN_INTERCEPTOR(int, sigsuspend, const __sanitizer_sigset_t *mask) {
2019 SCOPED_TSAN_INTERCEPTOR(sigsuspend, mask);
2020 return REAL(sigsuspend)(mask);
2023 TSAN_INTERCEPTOR(int, sigblock, int mask) {
2024 SCOPED_TSAN_INTERCEPTOR(sigblock, mask);
2025 return REAL(sigblock)(mask);
2028 TSAN_INTERCEPTOR(int, sigsetmask, int mask) {
2029 SCOPED_TSAN_INTERCEPTOR(sigsetmask, mask);
2030 return REAL(sigsetmask)(mask);
2033 TSAN_INTERCEPTOR(int, pthread_sigmask, int how, const __sanitizer_sigset_t *set,
2034 __sanitizer_sigset_t *oldset) {
2035 SCOPED_TSAN_INTERCEPTOR(pthread_sigmask, how, set, oldset);
2036 return REAL(pthread_sigmask)(how, set, oldset);
2039 namespace __tsan {
2041 static void ReportErrnoSpoiling(ThreadState *thr, uptr pc, int sig) {
2042 VarSizeStackTrace stack;
2043 // StackTrace::GetNestInstructionPc(pc) is used because return address is
2044 // expected, OutputReport() will undo this.
2045 ObtainCurrentStack(thr, StackTrace::GetNextInstructionPc(pc), &stack);
2046 ThreadRegistryLock l(&ctx->thread_registry);
2047 ScopedReport rep(ReportTypeErrnoInSignal);
2048 rep.SetSigNum(sig);
2049 if (!IsFiredSuppression(ctx, ReportTypeErrnoInSignal, stack)) {
2050 rep.AddStack(stack, true);
2051 OutputReport(thr, rep);
2055 static void CallUserSignalHandler(ThreadState *thr, bool sync, bool acquire,
2056 int sig, __sanitizer_siginfo *info,
2057 void *uctx) {
2058 CHECK(thr->slot);
2059 __sanitizer_sigaction *sigactions = interceptor_ctx()->sigactions;
2060 if (acquire)
2061 Acquire(thr, 0, (uptr)&sigactions[sig]);
2062 // Signals are generally asynchronous, so if we receive a signals when
2063 // ignores are enabled we should disable ignores. This is critical for sync
2064 // and interceptors, because otherwise we can miss synchronization and report
2065 // false races.
2066 int ignore_reads_and_writes = thr->ignore_reads_and_writes;
2067 int ignore_interceptors = thr->ignore_interceptors;
2068 int ignore_sync = thr->ignore_sync;
2069 // For symbolizer we only process SIGSEGVs synchronously
2070 // (bug in symbolizer or in tsan). But we want to reset
2071 // in_symbolizer to fail gracefully. Symbolizer and user code
2072 // use different memory allocators, so if we don't reset
2073 // in_symbolizer we can get memory allocated with one being
2074 // feed with another, which can cause more crashes.
2075 int in_symbolizer = thr->in_symbolizer;
2076 if (!ctx->after_multithreaded_fork) {
2077 thr->ignore_reads_and_writes = 0;
2078 thr->fast_state.ClearIgnoreBit();
2079 thr->ignore_interceptors = 0;
2080 thr->ignore_sync = 0;
2081 thr->in_symbolizer = 0;
2083 // Ensure that the handler does not spoil errno.
2084 const int saved_errno = errno;
2085 errno = 99;
2086 // This code races with sigaction. Be careful to not read sa_sigaction twice.
2087 // Also need to remember pc for reporting before the call,
2088 // because the handler can reset it.
2089 volatile uptr pc = (sigactions[sig].sa_flags & SA_SIGINFO)
2090 ? (uptr)sigactions[sig].sigaction
2091 : (uptr)sigactions[sig].handler;
2092 if (pc != sig_dfl && pc != sig_ign) {
2093 // The callback can be either sa_handler or sa_sigaction.
2094 // They have different signatures, but we assume that passing
2095 // additional arguments to sa_handler works and is harmless.
2096 ((__sanitizer_sigactionhandler_ptr)pc)(sig, info, uctx);
2098 if (!ctx->after_multithreaded_fork) {
2099 thr->ignore_reads_and_writes = ignore_reads_and_writes;
2100 if (ignore_reads_and_writes)
2101 thr->fast_state.SetIgnoreBit();
2102 thr->ignore_interceptors = ignore_interceptors;
2103 thr->ignore_sync = ignore_sync;
2104 thr->in_symbolizer = in_symbolizer;
2106 // We do not detect errno spoiling for SIGTERM,
2107 // because some SIGTERM handlers do spoil errno but reraise SIGTERM,
2108 // tsan reports false positive in such case.
2109 // It's difficult to properly detect this situation (reraise),
2110 // because in async signal processing case (when handler is called directly
2111 // from rtl_generic_sighandler) we have not yet received the reraised
2112 // signal; and it looks too fragile to intercept all ways to reraise a signal.
2113 if (ShouldReport(thr, ReportTypeErrnoInSignal) && !sync && sig != SIGTERM &&
2114 errno != 99)
2115 ReportErrnoSpoiling(thr, pc, sig);
2116 errno = saved_errno;
2119 void ProcessPendingSignalsImpl(ThreadState *thr) {
2120 atomic_store(&thr->pending_signals, 0, memory_order_relaxed);
2121 ThreadSignalContext *sctx = SigCtx(thr);
2122 if (sctx == 0)
2123 return;
2124 atomic_fetch_add(&thr->in_signal_handler, 1, memory_order_relaxed);
2125 internal_sigfillset(&sctx->emptyset);
2126 int res = REAL(pthread_sigmask)(SIG_SETMASK, &sctx->emptyset, &sctx->oldset);
2127 CHECK_EQ(res, 0);
2128 for (int sig = 0; sig < kSigCount; sig++) {
2129 SignalDesc *signal = &sctx->pending_signals[sig];
2130 if (signal->armed) {
2131 signal->armed = false;
2132 CallUserSignalHandler(thr, false, true, sig, &signal->siginfo,
2133 &signal->ctx);
2136 res = REAL(pthread_sigmask)(SIG_SETMASK, &sctx->oldset, 0);
2137 CHECK_EQ(res, 0);
2138 atomic_fetch_add(&thr->in_signal_handler, -1, memory_order_relaxed);
2141 } // namespace __tsan
2143 static bool is_sync_signal(ThreadSignalContext *sctx, int sig,
2144 __sanitizer_siginfo *info) {
2145 // If we are sending signal to ourselves, we must process it now.
2146 if (sctx && sig == sctx->int_signal_send)
2147 return true;
2148 #if SANITIZER_HAS_SIGINFO
2149 // POSIX timers can be configured to send any kind of signal; however, it
2150 // doesn't make any sense to consider a timer signal as synchronous!
2151 if (info->si_code == SI_TIMER)
2152 return false;
2153 #endif
2154 return sig == SIGSEGV || sig == SIGBUS || sig == SIGILL || sig == SIGTRAP ||
2155 sig == SIGABRT || sig == SIGFPE || sig == SIGPIPE || sig == SIGSYS;
2158 void sighandler(int sig, __sanitizer_siginfo *info, void *ctx) {
2159 ThreadState *thr = cur_thread_init();
2160 ThreadSignalContext *sctx = SigCtx(thr);
2161 if (sig < 0 || sig >= kSigCount) {
2162 VPrintf(1, "ThreadSanitizer: ignoring signal %d\n", sig);
2163 return;
2165 // Don't mess with synchronous signals.
2166 const bool sync = is_sync_signal(sctx, sig, info);
2167 if (sync ||
2168 // If we are in blocking function, we can safely process it now
2169 // (but check if we are in a recursive interceptor,
2170 // i.e. pthread_join()->munmap()).
2171 atomic_load(&thr->in_blocking_func, memory_order_relaxed)) {
2172 atomic_fetch_add(&thr->in_signal_handler, 1, memory_order_relaxed);
2173 if (atomic_load(&thr->in_blocking_func, memory_order_relaxed)) {
2174 atomic_store(&thr->in_blocking_func, 0, memory_order_relaxed);
2175 CallUserSignalHandler(thr, sync, true, sig, info, ctx);
2176 atomic_store(&thr->in_blocking_func, 1, memory_order_relaxed);
2177 } else {
2178 // Be very conservative with when we do acquire in this case.
2179 // It's unsafe to do acquire in async handlers, because ThreadState
2180 // can be in inconsistent state.
2181 // SIGSYS looks relatively safe -- it's synchronous and can actually
2182 // need some global state.
2183 bool acq = (sig == SIGSYS);
2184 CallUserSignalHandler(thr, sync, acq, sig, info, ctx);
2186 atomic_fetch_add(&thr->in_signal_handler, -1, memory_order_relaxed);
2187 return;
2190 if (sctx == 0)
2191 return;
2192 SignalDesc *signal = &sctx->pending_signals[sig];
2193 if (signal->armed == false) {
2194 signal->armed = true;
2195 internal_memcpy(&signal->siginfo, info, sizeof(*info));
2196 internal_memcpy(&signal->ctx, ctx, sizeof(signal->ctx));
2197 atomic_store(&thr->pending_signals, 1, memory_order_relaxed);
2201 TSAN_INTERCEPTOR(int, raise, int sig) {
2202 SCOPED_TSAN_INTERCEPTOR(raise, sig);
2203 ThreadSignalContext *sctx = SigCtx(thr);
2204 CHECK_NE(sctx, 0);
2205 int prev = sctx->int_signal_send;
2206 sctx->int_signal_send = sig;
2207 int res = REAL(raise)(sig);
2208 CHECK_EQ(sctx->int_signal_send, sig);
2209 sctx->int_signal_send = prev;
2210 return res;
2213 TSAN_INTERCEPTOR(int, kill, int pid, int sig) {
2214 SCOPED_TSAN_INTERCEPTOR(kill, pid, sig);
2215 ThreadSignalContext *sctx = SigCtx(thr);
2216 CHECK_NE(sctx, 0);
2217 int prev = sctx->int_signal_send;
2218 if (pid == (int)internal_getpid()) {
2219 sctx->int_signal_send = sig;
2221 int res = REAL(kill)(pid, sig);
2222 if (pid == (int)internal_getpid()) {
2223 CHECK_EQ(sctx->int_signal_send, sig);
2224 sctx->int_signal_send = prev;
2226 return res;
2229 TSAN_INTERCEPTOR(int, pthread_kill, void *tid, int sig) {
2230 SCOPED_TSAN_INTERCEPTOR(pthread_kill, tid, sig);
2231 ThreadSignalContext *sctx = SigCtx(thr);
2232 CHECK_NE(sctx, 0);
2233 int prev = sctx->int_signal_send;
2234 bool self = pthread_equal(tid, pthread_self());
2235 if (self)
2236 sctx->int_signal_send = sig;
2237 int res = REAL(pthread_kill)(tid, sig);
2238 if (self) {
2239 CHECK_EQ(sctx->int_signal_send, sig);
2240 sctx->int_signal_send = prev;
2242 return res;
2245 TSAN_INTERCEPTOR(int, gettimeofday, void *tv, void *tz) {
2246 SCOPED_TSAN_INTERCEPTOR(gettimeofday, tv, tz);
2247 // It's intercepted merely to process pending signals.
2248 return REAL(gettimeofday)(tv, tz);
2251 TSAN_INTERCEPTOR(int, getaddrinfo, void *node, void *service,
2252 void *hints, void *rv) {
2253 SCOPED_TSAN_INTERCEPTOR(getaddrinfo, node, service, hints, rv);
2254 // We miss atomic synchronization in getaddrinfo,
2255 // and can report false race between malloc and free
2256 // inside of getaddrinfo. So ignore memory accesses.
2257 ThreadIgnoreBegin(thr, pc);
2258 int res = REAL(getaddrinfo)(node, service, hints, rv);
2259 ThreadIgnoreEnd(thr);
2260 return res;
2263 TSAN_INTERCEPTOR(int, fork, int fake) {
2264 if (in_symbolizer())
2265 return REAL(fork)(fake);
2266 SCOPED_INTERCEPTOR_RAW(fork, fake);
2267 return REAL(fork)(fake);
2270 void atfork_prepare() {
2271 if (in_symbolizer())
2272 return;
2273 ThreadState *thr = cur_thread();
2274 const uptr pc = StackTrace::GetCurrentPc();
2275 ForkBefore(thr, pc);
2278 void atfork_parent() {
2279 if (in_symbolizer())
2280 return;
2281 ThreadState *thr = cur_thread();
2282 const uptr pc = StackTrace::GetCurrentPc();
2283 ForkParentAfter(thr, pc);
2286 void atfork_child() {
2287 if (in_symbolizer())
2288 return;
2289 ThreadState *thr = cur_thread();
2290 const uptr pc = StackTrace::GetCurrentPc();
2291 ForkChildAfter(thr, pc, true);
2292 FdOnFork(thr, pc);
2295 #if !SANITIZER_IOS
2296 TSAN_INTERCEPTOR(int, vfork, int fake) {
2297 // Some programs (e.g. openjdk) call close for all file descriptors
2298 // in the child process. Under tsan it leads to false positives, because
2299 // address space is shared, so the parent process also thinks that
2300 // the descriptors are closed (while they are actually not).
2301 // This leads to false positives due to missed synchronization.
2302 // Strictly saying this is undefined behavior, because vfork child is not
2303 // allowed to call any functions other than exec/exit. But this is what
2304 // openjdk does, so we want to handle it.
2305 // We could disable interceptors in the child process. But it's not possible
2306 // to simply intercept and wrap vfork, because vfork child is not allowed
2307 // to return from the function that calls vfork, and that's exactly what
2308 // we would do. So this would require some assembly trickery as well.
2309 // Instead we simply turn vfork into fork.
2310 return WRAP(fork)(fake);
2312 #endif
2314 #if SANITIZER_LINUX
2315 TSAN_INTERCEPTOR(int, clone, int (*fn)(void *), void *stack, int flags,
2316 void *arg, int *parent_tid, void *tls, pid_t *child_tid) {
2317 SCOPED_INTERCEPTOR_RAW(clone, fn, stack, flags, arg, parent_tid, tls,
2318 child_tid);
2319 struct Arg {
2320 int (*fn)(void *);
2321 void *arg;
2323 auto wrapper = +[](void *p) -> int {
2324 auto *thr = cur_thread();
2325 uptr pc = GET_CURRENT_PC();
2326 // Start the background thread for fork, but not for clone.
2327 // For fork we did this always and it's known to work (or user code has
2328 // adopted). But if we do this for the new clone interceptor some code
2329 // (sandbox2) fails. So model we used to do for years and don't start the
2330 // background thread after clone.
2331 ForkChildAfter(thr, pc, false);
2332 FdOnFork(thr, pc);
2333 auto *arg = static_cast<Arg *>(p);
2334 return arg->fn(arg->arg);
2336 ForkBefore(thr, pc);
2337 Arg arg_wrapper = {fn, arg};
2338 int pid = REAL(clone)(wrapper, stack, flags, &arg_wrapper, parent_tid, tls,
2339 child_tid);
2340 ForkParentAfter(thr, pc);
2341 return pid;
2343 #endif
2345 #if !SANITIZER_APPLE && !SANITIZER_ANDROID
2346 typedef int (*dl_iterate_phdr_cb_t)(__sanitizer_dl_phdr_info *info, SIZE_T size,
2347 void *data);
2348 struct dl_iterate_phdr_data {
2349 ThreadState *thr;
2350 uptr pc;
2351 dl_iterate_phdr_cb_t cb;
2352 void *data;
2355 static bool IsAppNotRodata(uptr addr) {
2356 return IsAppMem(addr) && *MemToShadow(addr) != Shadow::kRodata;
2359 static int dl_iterate_phdr_cb(__sanitizer_dl_phdr_info *info, SIZE_T size,
2360 void *data) {
2361 dl_iterate_phdr_data *cbdata = (dl_iterate_phdr_data *)data;
2362 // dlopen/dlclose allocate/free dynamic-linker-internal memory, which is later
2363 // accessible in dl_iterate_phdr callback. But we don't see synchronization
2364 // inside of dynamic linker, so we "unpoison" it here in order to not
2365 // produce false reports. Ignoring malloc/free in dlopen/dlclose is not enough
2366 // because some libc functions call __libc_dlopen.
2367 if (info && IsAppNotRodata((uptr)info->dlpi_name))
2368 MemoryResetRange(cbdata->thr, cbdata->pc, (uptr)info->dlpi_name,
2369 internal_strlen(info->dlpi_name));
2370 int res = cbdata->cb(info, size, cbdata->data);
2371 // Perform the check one more time in case info->dlpi_name was overwritten
2372 // by user callback.
2373 if (info && IsAppNotRodata((uptr)info->dlpi_name))
2374 MemoryResetRange(cbdata->thr, cbdata->pc, (uptr)info->dlpi_name,
2375 internal_strlen(info->dlpi_name));
2376 return res;
2379 TSAN_INTERCEPTOR(int, dl_iterate_phdr, dl_iterate_phdr_cb_t cb, void *data) {
2380 SCOPED_TSAN_INTERCEPTOR(dl_iterate_phdr, cb, data);
2381 dl_iterate_phdr_data cbdata;
2382 cbdata.thr = thr;
2383 cbdata.pc = pc;
2384 cbdata.cb = cb;
2385 cbdata.data = data;
2386 int res = REAL(dl_iterate_phdr)(dl_iterate_phdr_cb, &cbdata);
2387 return res;
2389 #endif
2391 static int OnExit(ThreadState *thr) {
2392 int status = Finalize(thr);
2393 FlushStreams();
2394 return status;
2397 #if !SANITIZER_APPLE
2398 static void HandleRecvmsg(ThreadState *thr, uptr pc,
2399 __sanitizer_msghdr *msg) {
2400 int fds[64];
2401 int cnt = ExtractRecvmsgFDs(msg, fds, ARRAY_SIZE(fds));
2402 for (int i = 0; i < cnt; i++)
2403 FdEventCreate(thr, pc, fds[i]);
2405 #endif
2407 #include "sanitizer_common/sanitizer_platform_interceptors.h"
2408 // Causes interceptor recursion (getaddrinfo() and fopen())
2409 #undef SANITIZER_INTERCEPT_GETADDRINFO
2410 // We define our own.
2411 #if SANITIZER_INTERCEPT_TLS_GET_ADDR
2412 #define NEED_TLS_GET_ADDR
2413 #endif
2414 #undef SANITIZER_INTERCEPT_TLS_GET_ADDR
2415 #define SANITIZER_INTERCEPT_TLS_GET_OFFSET 1
2416 #undef SANITIZER_INTERCEPT_PTHREAD_SIGMASK
2418 #define COMMON_INTERCEPT_FUNCTION_VER(name, ver) \
2419 INTERCEPT_FUNCTION_VER(name, ver)
2420 #define COMMON_INTERCEPT_FUNCTION_VER_UNVERSIONED_FALLBACK(name, ver) \
2421 (INTERCEPT_FUNCTION_VER(name, ver) || INTERCEPT_FUNCTION(name))
2423 #define COMMON_INTERCEPTOR_ENTER_NOIGNORE(ctx, func, ...) \
2424 SCOPED_INTERCEPTOR_RAW(func, __VA_ARGS__); \
2425 TsanInterceptorContext _ctx = {thr, pc}; \
2426 ctx = (void *)&_ctx; \
2427 (void)ctx;
2429 #define COMMON_INTERCEPTOR_FILE_OPEN(ctx, file, path) \
2430 if (path) \
2431 Acquire(thr, pc, File2addr(path)); \
2432 if (file) { \
2433 int fd = fileno_unlocked(file); \
2434 if (fd >= 0) FdFileCreate(thr, pc, fd); \
2437 #define COMMON_INTERCEPTOR_FILE_CLOSE(ctx, file) \
2438 if (file) { \
2439 int fd = fileno_unlocked(file); \
2440 FdClose(thr, pc, fd); \
2443 #define COMMON_INTERCEPTOR_DLOPEN(filename, flag) \
2444 ({ \
2445 CheckNoDeepBind(filename, flag); \
2446 ThreadIgnoreBegin(thr, 0); \
2447 void *res = REAL(dlopen)(filename, flag); \
2448 ThreadIgnoreEnd(thr); \
2449 res; \
2452 // Ignore interceptors in OnLibraryLoaded()/Unloaded(). These hooks use code
2453 // (ListOfModules::init, MemoryMappingLayout::DumpListOfModules) that make
2454 // intercepted calls, which can cause deadlockes with ReportRace() which also
2455 // uses this code.
2456 #define COMMON_INTERCEPTOR_LIBRARY_LOADED(filename, handle) \
2457 ({ \
2458 ScopedIgnoreInterceptors ignore_interceptors; \
2459 libignore()->OnLibraryLoaded(filename); \
2462 #define COMMON_INTERCEPTOR_LIBRARY_UNLOADED() \
2463 ({ \
2464 ScopedIgnoreInterceptors ignore_interceptors; \
2465 libignore()->OnLibraryUnloaded(); \
2468 #define COMMON_INTERCEPTOR_ACQUIRE(ctx, u) \
2469 Acquire(((TsanInterceptorContext *) ctx)->thr, pc, u)
2471 #define COMMON_INTERCEPTOR_RELEASE(ctx, u) \
2472 Release(((TsanInterceptorContext *) ctx)->thr, pc, u)
2474 #define COMMON_INTERCEPTOR_DIR_ACQUIRE(ctx, path) \
2475 Acquire(((TsanInterceptorContext *) ctx)->thr, pc, Dir2addr(path))
2477 #define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \
2478 FdAcquire(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2480 #define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \
2481 FdRelease(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2483 #define COMMON_INTERCEPTOR_FD_ACCESS(ctx, fd) \
2484 FdAccess(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2486 #define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \
2487 FdSocketAccept(((TsanInterceptorContext *) ctx)->thr, pc, fd, newfd)
2489 #define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) \
2490 ThreadSetName(((TsanInterceptorContext *) ctx)->thr, name)
2492 #define COMMON_INTERCEPTOR_SET_PTHREAD_NAME(ctx, thread, name) \
2493 if (pthread_equal(pthread_self(), reinterpret_cast<void *>(thread))) \
2494 COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name); \
2495 else \
2496 __tsan::ctx->thread_registry.SetThreadNameByUserId(thread, name)
2498 #define COMMON_INTERCEPTOR_BLOCK_REAL(name) BLOCK_REAL(name)
2500 #define COMMON_INTERCEPTOR_ON_EXIT(ctx) \
2501 OnExit(((TsanInterceptorContext *) ctx)->thr)
2503 #define COMMON_INTERCEPTOR_MMAP_IMPL(ctx, mmap, addr, sz, prot, flags, fd, \
2504 off) \
2505 do { \
2506 return mmap_interceptor(thr, pc, REAL(mmap), addr, sz, prot, flags, fd, \
2507 off); \
2508 } while (false)
2510 #define COMMON_INTERCEPTOR_MUNMAP_IMPL(ctx, addr, sz) \
2511 do { \
2512 return munmap_interceptor(thr, pc, REAL(munmap), addr, sz); \
2513 } while (false)
2515 #if !SANITIZER_APPLE
2516 #define COMMON_INTERCEPTOR_HANDLE_RECVMSG(ctx, msg) \
2517 HandleRecvmsg(((TsanInterceptorContext *)ctx)->thr, \
2518 ((TsanInterceptorContext *)ctx)->pc, msg)
2519 #endif
2521 #define COMMON_INTERCEPTOR_GET_TLS_RANGE(begin, end) \
2522 if (TsanThread *t = GetCurrentThread()) { \
2523 *begin = t->tls_begin(); \
2524 *end = t->tls_end(); \
2525 } else { \
2526 *begin = *end = 0; \
2529 #define COMMON_INTERCEPTOR_USER_CALLBACK_START() \
2530 SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_START()
2532 #define COMMON_INTERCEPTOR_USER_CALLBACK_END() \
2533 SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_END()
2535 #include "sanitizer_common/sanitizer_common_interceptors.inc"
2537 static int sigaction_impl(int sig, const __sanitizer_sigaction *act,
2538 __sanitizer_sigaction *old);
2539 static __sanitizer_sighandler_ptr signal_impl(int sig,
2540 __sanitizer_sighandler_ptr h);
2542 #define SIGNAL_INTERCEPTOR_SIGACTION_IMPL(signo, act, oldact) \
2543 { return sigaction_impl(signo, act, oldact); }
2545 #define SIGNAL_INTERCEPTOR_SIGNAL_IMPL(func, signo, handler) \
2546 { return (uptr)signal_impl(signo, (__sanitizer_sighandler_ptr)handler); }
2548 #define SIGNAL_INTERCEPTOR_ENTER() LazyInitialize(cur_thread_init())
2550 #include "sanitizer_common/sanitizer_signal_interceptors.inc"
2552 int sigaction_impl(int sig, const __sanitizer_sigaction *act,
2553 __sanitizer_sigaction *old) {
2554 // Note: if we call REAL(sigaction) directly for any reason without proxying
2555 // the signal handler through sighandler, very bad things will happen.
2556 // The handler will run synchronously and corrupt tsan per-thread state.
2557 SCOPED_INTERCEPTOR_RAW(sigaction, sig, act, old);
2558 if (sig <= 0 || sig >= kSigCount) {
2559 errno = errno_EINVAL;
2560 return -1;
2562 __sanitizer_sigaction *sigactions = interceptor_ctx()->sigactions;
2563 __sanitizer_sigaction old_stored;
2564 if (old) internal_memcpy(&old_stored, &sigactions[sig], sizeof(old_stored));
2565 __sanitizer_sigaction newact;
2566 if (act) {
2567 // Copy act into sigactions[sig].
2568 // Can't use struct copy, because compiler can emit call to memcpy.
2569 // Can't use internal_memcpy, because it copies byte-by-byte,
2570 // and signal handler reads the handler concurrently. It can read
2571 // some bytes from old value and some bytes from new value.
2572 // Use volatile to prevent insertion of memcpy.
2573 sigactions[sig].handler =
2574 *(volatile __sanitizer_sighandler_ptr const *)&act->handler;
2575 sigactions[sig].sa_flags = *(volatile int const *)&act->sa_flags;
2576 internal_memcpy(&sigactions[sig].sa_mask, &act->sa_mask,
2577 sizeof(sigactions[sig].sa_mask));
2578 #if !SANITIZER_FREEBSD && !SANITIZER_APPLE && !SANITIZER_NETBSD
2579 sigactions[sig].sa_restorer = act->sa_restorer;
2580 #endif
2581 internal_memcpy(&newact, act, sizeof(newact));
2582 internal_sigfillset(&newact.sa_mask);
2583 if ((act->sa_flags & SA_SIGINFO) ||
2584 ((uptr)act->handler != sig_ign && (uptr)act->handler != sig_dfl)) {
2585 newact.sa_flags |= SA_SIGINFO;
2586 newact.sigaction = sighandler;
2588 ReleaseStore(thr, pc, (uptr)&sigactions[sig]);
2589 act = &newact;
2591 int res = REAL(sigaction)(sig, act, old);
2592 if (res == 0 && old && old->sigaction == sighandler)
2593 internal_memcpy(old, &old_stored, sizeof(*old));
2594 return res;
2597 static __sanitizer_sighandler_ptr signal_impl(int sig,
2598 __sanitizer_sighandler_ptr h) {
2599 __sanitizer_sigaction act;
2600 act.handler = h;
2601 internal_memset(&act.sa_mask, -1, sizeof(act.sa_mask));
2602 act.sa_flags = 0;
2603 __sanitizer_sigaction old;
2604 int res = sigaction_symname(sig, &act, &old);
2605 if (res) return (__sanitizer_sighandler_ptr)sig_err;
2606 return old.handler;
2609 #define TSAN_SYSCALL() \
2610 ThreadState *thr = cur_thread(); \
2611 if (thr->ignore_interceptors) \
2612 return; \
2613 ScopedSyscall scoped_syscall(thr)
2615 struct ScopedSyscall {
2616 ThreadState *thr;
2618 explicit ScopedSyscall(ThreadState *thr) : thr(thr) { LazyInitialize(thr); }
2620 ~ScopedSyscall() {
2621 ProcessPendingSignals(thr);
2625 #if !SANITIZER_FREEBSD && !SANITIZER_APPLE
2626 static void syscall_access_range(uptr pc, uptr p, uptr s, bool write) {
2627 TSAN_SYSCALL();
2628 MemoryAccessRange(thr, pc, p, s, write);
2631 static USED void syscall_acquire(uptr pc, uptr addr) {
2632 TSAN_SYSCALL();
2633 Acquire(thr, pc, addr);
2634 DPrintf("syscall_acquire(0x%zx))\n", addr);
2637 static USED void syscall_release(uptr pc, uptr addr) {
2638 TSAN_SYSCALL();
2639 DPrintf("syscall_release(0x%zx)\n", addr);
2640 Release(thr, pc, addr);
2643 static void syscall_fd_close(uptr pc, int fd) {
2644 auto *thr = cur_thread();
2645 FdClose(thr, pc, fd);
2648 static USED void syscall_fd_acquire(uptr pc, int fd) {
2649 TSAN_SYSCALL();
2650 FdAcquire(thr, pc, fd);
2651 DPrintf("syscall_fd_acquire(%d)\n", fd);
2654 static USED void syscall_fd_release(uptr pc, int fd) {
2655 TSAN_SYSCALL();
2656 DPrintf("syscall_fd_release(%d)\n", fd);
2657 FdRelease(thr, pc, fd);
2660 static void syscall_pre_fork(uptr pc) { ForkBefore(cur_thread(), pc); }
2662 static void syscall_post_fork(uptr pc, int pid) {
2663 ThreadState *thr = cur_thread();
2664 if (pid == 0) {
2665 // child
2666 ForkChildAfter(thr, pc, true);
2667 FdOnFork(thr, pc);
2668 } else if (pid > 0) {
2669 // parent
2670 ForkParentAfter(thr, pc);
2671 } else {
2672 // error
2673 ForkParentAfter(thr, pc);
2676 #endif
2678 #define COMMON_SYSCALL_PRE_READ_RANGE(p, s) \
2679 syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), false)
2681 #define COMMON_SYSCALL_PRE_WRITE_RANGE(p, s) \
2682 syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), true)
2684 #define COMMON_SYSCALL_POST_READ_RANGE(p, s) \
2685 do { \
2686 (void)(p); \
2687 (void)(s); \
2688 } while (false)
2690 #define COMMON_SYSCALL_POST_WRITE_RANGE(p, s) \
2691 do { \
2692 (void)(p); \
2693 (void)(s); \
2694 } while (false)
2696 #define COMMON_SYSCALL_ACQUIRE(addr) \
2697 syscall_acquire(GET_CALLER_PC(), (uptr)(addr))
2699 #define COMMON_SYSCALL_RELEASE(addr) \
2700 syscall_release(GET_CALLER_PC(), (uptr)(addr))
2702 #define COMMON_SYSCALL_FD_CLOSE(fd) syscall_fd_close(GET_CALLER_PC(), fd)
2704 #define COMMON_SYSCALL_FD_ACQUIRE(fd) syscall_fd_acquire(GET_CALLER_PC(), fd)
2706 #define COMMON_SYSCALL_FD_RELEASE(fd) syscall_fd_release(GET_CALLER_PC(), fd)
2708 #define COMMON_SYSCALL_PRE_FORK() \
2709 syscall_pre_fork(GET_CALLER_PC())
2711 #define COMMON_SYSCALL_POST_FORK(res) \
2712 syscall_post_fork(GET_CALLER_PC(), res)
2714 #include "sanitizer_common/sanitizer_common_syscalls.inc"
2715 #include "sanitizer_common/sanitizer_syscalls_netbsd.inc"
2717 #ifdef NEED_TLS_GET_ADDR
2719 static void handle_tls_addr(void *arg, void *res) {
2720 ThreadState *thr = cur_thread();
2721 if (!thr)
2722 return;
2723 DTLS::DTV *dtv = DTLS_on_tls_get_addr(arg, res, thr->tls_addr,
2724 thr->tls_addr + thr->tls_size);
2725 if (!dtv)
2726 return;
2727 // New DTLS block has been allocated.
2728 MemoryResetRange(thr, 0, dtv->beg, dtv->size);
2731 #if !SANITIZER_S390
2732 // Define own interceptor instead of sanitizer_common's for three reasons:
2733 // 1. It must not process pending signals.
2734 // Signal handlers may contain MOVDQA instruction (see below).
2735 // 2. It must be as simple as possible to not contain MOVDQA.
2736 // 3. Sanitizer_common version uses COMMON_INTERCEPTOR_INITIALIZE_RANGE which
2737 // is empty for tsan (meant only for msan).
2738 // Note: __tls_get_addr can be called with mis-aligned stack due to:
2739 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58066
2740 // So the interceptor must work with mis-aligned stack, in particular, does not
2741 // execute MOVDQA with stack addresses.
2742 TSAN_INTERCEPTOR(void *, __tls_get_addr, void *arg) {
2743 void *res = REAL(__tls_get_addr)(arg);
2744 handle_tls_addr(arg, res);
2745 return res;
2747 #else // SANITIZER_S390
2748 TSAN_INTERCEPTOR(uptr, __tls_get_addr_internal, void *arg) {
2749 uptr res = __tls_get_offset_wrapper(arg, REAL(__tls_get_offset));
2750 char *tp = static_cast<char *>(__builtin_thread_pointer());
2751 handle_tls_addr(arg, res + tp);
2752 return res;
2754 #endif
2755 #endif
2757 #if SANITIZER_NETBSD
2758 TSAN_INTERCEPTOR(void, _lwp_exit) {
2759 SCOPED_TSAN_INTERCEPTOR(_lwp_exit);
2760 DestroyThreadState();
2761 REAL(_lwp_exit)();
2763 #define TSAN_MAYBE_INTERCEPT__LWP_EXIT TSAN_INTERCEPT(_lwp_exit)
2764 #else
2765 #define TSAN_MAYBE_INTERCEPT__LWP_EXIT
2766 #endif
2768 #if SANITIZER_FREEBSD
2769 TSAN_INTERCEPTOR(void, thr_exit, tid_t *state) {
2770 SCOPED_TSAN_INTERCEPTOR(thr_exit, state);
2771 DestroyThreadState();
2772 REAL(thr_exit(state));
2774 #define TSAN_MAYBE_INTERCEPT_THR_EXIT TSAN_INTERCEPT(thr_exit)
2775 #else
2776 #define TSAN_MAYBE_INTERCEPT_THR_EXIT
2777 #endif
2779 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, cond_init, void *c, void *a)
2780 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, cond_destroy, void *c)
2781 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, cond_signal, void *c)
2782 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, cond_broadcast, void *c)
2783 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, cond_wait, void *c, void *m)
2784 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, mutex_init, void *m, void *a)
2785 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, mutex_destroy, void *m)
2786 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, mutex_lock, void *m)
2787 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, mutex_trylock, void *m)
2788 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, mutex_unlock, void *m)
2789 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, rwlock_init, void *l, void *a)
2790 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, rwlock_destroy, void *l)
2791 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, rwlock_rdlock, void *l)
2792 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, rwlock_tryrdlock, void *l)
2793 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, rwlock_wrlock, void *l)
2794 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, rwlock_trywrlock, void *l)
2795 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, rwlock_unlock, void *l)
2796 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, once, void *o, void (*i)())
2797 TSAN_INTERCEPTOR_FREEBSD_ALIAS(int, sigmask, int f, void *n, void *o)
2799 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_init, void *c, void *a)
2800 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_signal, void *c)
2801 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_broadcast, void *c)
2802 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_wait, void *c, void *m)
2803 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_destroy, void *c)
2804 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_init, void *m, void *a)
2805 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_destroy, void *m)
2806 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_lock, void *m)
2807 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_trylock, void *m)
2808 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_unlock, void *m)
2809 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_init, void *m, void *a)
2810 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_destroy, void *m)
2811 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_rdlock, void *m)
2812 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_tryrdlock, void *m)
2813 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_wrlock, void *m)
2814 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_trywrlock, void *m)
2815 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_unlock, void *m)
2816 TSAN_INTERCEPTOR_NETBSD_ALIAS_THR(int, once, void *o, void (*f)())
2817 TSAN_INTERCEPTOR_NETBSD_ALIAS_THR2(int, sigsetmask, sigmask, int a, void *b,
2818 void *c)
2820 namespace __tsan {
2822 static void finalize(void *arg) {
2823 ThreadState *thr = cur_thread();
2824 int status = Finalize(thr);
2825 // Make sure the output is not lost.
2826 FlushStreams();
2827 if (status)
2828 Die();
2831 #if !SANITIZER_APPLE && !SANITIZER_ANDROID
2832 static void unreachable() {
2833 Report("FATAL: ThreadSanitizer: unreachable called\n");
2834 Die();
2836 #endif
2838 // Define default implementation since interception of libdispatch is optional.
2839 SANITIZER_WEAK_ATTRIBUTE void InitializeLibdispatchInterceptors() {}
2841 void InitializeInterceptors() {
2842 #if !SANITIZER_APPLE
2843 // We need to setup it early, because functions like dlsym() can call it.
2844 REAL(memset) = internal_memset;
2845 REAL(memcpy) = internal_memcpy;
2846 #endif
2848 new(interceptor_ctx()) InterceptorContext();
2850 InitializeCommonInterceptors();
2851 InitializeSignalInterceptors();
2852 InitializeLibdispatchInterceptors();
2854 #if !SANITIZER_APPLE
2855 InitializeSetjmpInterceptors();
2856 #endif
2858 TSAN_INTERCEPT(longjmp_symname);
2859 TSAN_INTERCEPT(siglongjmp_symname);
2860 #if SANITIZER_NETBSD
2861 TSAN_INTERCEPT(_longjmp);
2862 #endif
2864 TSAN_INTERCEPT(malloc);
2865 TSAN_INTERCEPT(__libc_memalign);
2866 TSAN_INTERCEPT(calloc);
2867 TSAN_INTERCEPT(realloc);
2868 TSAN_INTERCEPT(reallocarray);
2869 TSAN_INTERCEPT(free);
2870 TSAN_INTERCEPT(cfree);
2871 TSAN_INTERCEPT(munmap);
2872 TSAN_MAYBE_INTERCEPT_MEMALIGN;
2873 TSAN_INTERCEPT(valloc);
2874 TSAN_MAYBE_INTERCEPT_PVALLOC;
2875 TSAN_INTERCEPT(posix_memalign);
2877 TSAN_INTERCEPT(strcpy);
2878 TSAN_INTERCEPT(strncpy);
2879 TSAN_INTERCEPT(strdup);
2881 TSAN_INTERCEPT(pthread_create);
2882 TSAN_INTERCEPT(pthread_join);
2883 TSAN_INTERCEPT(pthread_detach);
2884 TSAN_INTERCEPT(pthread_exit);
2885 #if SANITIZER_LINUX
2886 TSAN_INTERCEPT(pthread_tryjoin_np);
2887 TSAN_INTERCEPT(pthread_timedjoin_np);
2888 #endif
2890 TSAN_INTERCEPT_VER(pthread_cond_init, PTHREAD_ABI_BASE);
2891 TSAN_INTERCEPT_VER(pthread_cond_signal, PTHREAD_ABI_BASE);
2892 TSAN_INTERCEPT_VER(pthread_cond_broadcast, PTHREAD_ABI_BASE);
2893 TSAN_INTERCEPT_VER(pthread_cond_wait, PTHREAD_ABI_BASE);
2894 TSAN_INTERCEPT_VER(pthread_cond_timedwait, PTHREAD_ABI_BASE);
2895 TSAN_INTERCEPT_VER(pthread_cond_destroy, PTHREAD_ABI_BASE);
2897 TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT;
2899 TSAN_INTERCEPT(pthread_mutex_init);
2900 TSAN_INTERCEPT(pthread_mutex_destroy);
2901 TSAN_INTERCEPT(pthread_mutex_lock);
2902 TSAN_INTERCEPT(pthread_mutex_trylock);
2903 TSAN_INTERCEPT(pthread_mutex_timedlock);
2904 TSAN_INTERCEPT(pthread_mutex_unlock);
2905 #if SANITIZER_GLIBC
2906 # if !__GLIBC_PREREQ(2, 34)
2907 TSAN_INTERCEPT(__pthread_mutex_lock);
2908 TSAN_INTERCEPT(__pthread_mutex_unlock);
2909 # endif
2910 #endif
2912 TSAN_INTERCEPT(pthread_spin_init);
2913 TSAN_INTERCEPT(pthread_spin_destroy);
2914 TSAN_INTERCEPT(pthread_spin_lock);
2915 TSAN_INTERCEPT(pthread_spin_trylock);
2916 TSAN_INTERCEPT(pthread_spin_unlock);
2918 TSAN_INTERCEPT(pthread_rwlock_init);
2919 TSAN_INTERCEPT(pthread_rwlock_destroy);
2920 TSAN_INTERCEPT(pthread_rwlock_rdlock);
2921 TSAN_INTERCEPT(pthread_rwlock_tryrdlock);
2922 TSAN_INTERCEPT(pthread_rwlock_timedrdlock);
2923 TSAN_INTERCEPT(pthread_rwlock_wrlock);
2924 TSAN_INTERCEPT(pthread_rwlock_trywrlock);
2925 TSAN_INTERCEPT(pthread_rwlock_timedwrlock);
2926 TSAN_INTERCEPT(pthread_rwlock_unlock);
2928 TSAN_INTERCEPT(pthread_barrier_init);
2929 TSAN_INTERCEPT(pthread_barrier_destroy);
2930 TSAN_INTERCEPT(pthread_barrier_wait);
2932 TSAN_INTERCEPT(pthread_once);
2934 TSAN_INTERCEPT(fstat);
2935 TSAN_MAYBE_INTERCEPT___FXSTAT;
2936 TSAN_MAYBE_INTERCEPT_FSTAT64;
2937 TSAN_MAYBE_INTERCEPT___FXSTAT64;
2938 TSAN_INTERCEPT(open);
2939 TSAN_MAYBE_INTERCEPT_OPEN64;
2940 TSAN_INTERCEPT(creat);
2941 TSAN_MAYBE_INTERCEPT_CREAT64;
2942 TSAN_INTERCEPT(dup);
2943 TSAN_INTERCEPT(dup2);
2944 TSAN_INTERCEPT(dup3);
2945 TSAN_MAYBE_INTERCEPT_EVENTFD;
2946 TSAN_MAYBE_INTERCEPT_SIGNALFD;
2947 TSAN_MAYBE_INTERCEPT_INOTIFY_INIT;
2948 TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1;
2949 TSAN_INTERCEPT(socket);
2950 TSAN_INTERCEPT(socketpair);
2951 TSAN_INTERCEPT(connect);
2952 TSAN_INTERCEPT(bind);
2953 TSAN_INTERCEPT(listen);
2954 TSAN_MAYBE_INTERCEPT_EPOLL;
2955 TSAN_INTERCEPT(close);
2956 TSAN_MAYBE_INTERCEPT___CLOSE;
2957 TSAN_MAYBE_INTERCEPT___RES_ICLOSE;
2958 TSAN_INTERCEPT(pipe);
2959 TSAN_INTERCEPT(pipe2);
2961 TSAN_INTERCEPT(unlink);
2962 TSAN_INTERCEPT(tmpfile);
2963 TSAN_MAYBE_INTERCEPT_TMPFILE64;
2964 TSAN_INTERCEPT(abort);
2965 TSAN_INTERCEPT(rmdir);
2966 TSAN_INTERCEPT(closedir);
2968 TSAN_INTERCEPT(sigsuspend);
2969 TSAN_INTERCEPT(sigblock);
2970 TSAN_INTERCEPT(sigsetmask);
2971 TSAN_INTERCEPT(pthread_sigmask);
2972 TSAN_INTERCEPT(raise);
2973 TSAN_INTERCEPT(kill);
2974 TSAN_INTERCEPT(pthread_kill);
2975 TSAN_INTERCEPT(sleep);
2976 TSAN_INTERCEPT(usleep);
2977 TSAN_INTERCEPT(nanosleep);
2978 TSAN_INTERCEPT(pause);
2979 TSAN_INTERCEPT(gettimeofday);
2980 TSAN_INTERCEPT(getaddrinfo);
2982 TSAN_INTERCEPT(fork);
2983 TSAN_INTERCEPT(vfork);
2984 #if SANITIZER_LINUX
2985 TSAN_INTERCEPT(clone);
2986 #endif
2987 #if !SANITIZER_ANDROID
2988 TSAN_INTERCEPT(dl_iterate_phdr);
2989 #endif
2990 TSAN_MAYBE_INTERCEPT_ON_EXIT;
2991 TSAN_INTERCEPT(__cxa_atexit);
2992 TSAN_INTERCEPT(_exit);
2994 #ifdef NEED_TLS_GET_ADDR
2995 #if !SANITIZER_S390
2996 TSAN_INTERCEPT(__tls_get_addr);
2997 #else
2998 TSAN_INTERCEPT(__tls_get_addr_internal);
2999 TSAN_INTERCEPT(__tls_get_offset);
3000 #endif
3001 #endif
3003 TSAN_MAYBE_INTERCEPT__LWP_EXIT;
3004 TSAN_MAYBE_INTERCEPT_THR_EXIT;
3006 #if !SANITIZER_APPLE && !SANITIZER_ANDROID
3007 // Need to setup it, because interceptors check that the function is resolved.
3008 // But atexit is emitted directly into the module, so can't be resolved.
3009 REAL(atexit) = (int(*)(void(*)()))unreachable;
3010 #endif
3012 if (REAL(__cxa_atexit)(&finalize, 0, 0)) {
3013 Printf("ThreadSanitizer: failed to setup atexit callback\n");
3014 Die();
3016 if (pthread_atfork(atfork_prepare, atfork_parent, atfork_child)) {
3017 Printf("ThreadSanitizer: failed to setup atfork callbacks\n");
3018 Die();
3021 #if !SANITIZER_APPLE && !SANITIZER_NETBSD && !SANITIZER_FREEBSD
3022 if (pthread_key_create(&interceptor_ctx()->finalize_key, &thread_finalize)) {
3023 Printf("ThreadSanitizer: failed to create thread key\n");
3024 Die();
3026 #endif
3028 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(cond_init);
3029 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(cond_destroy);
3030 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(cond_signal);
3031 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(cond_broadcast);
3032 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(cond_wait);
3033 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(mutex_init);
3034 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(mutex_destroy);
3035 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(mutex_lock);
3036 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(mutex_trylock);
3037 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(mutex_unlock);
3038 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(rwlock_init);
3039 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(rwlock_destroy);
3040 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(rwlock_rdlock);
3041 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(rwlock_tryrdlock);
3042 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(rwlock_wrlock);
3043 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(rwlock_trywrlock);
3044 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(rwlock_unlock);
3045 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(once);
3046 TSAN_MAYBE_INTERCEPT_FREEBSD_ALIAS(sigmask);
3048 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_init);
3049 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_signal);
3050 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_broadcast);
3051 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_wait);
3052 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_destroy);
3053 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_init);
3054 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_destroy);
3055 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_lock);
3056 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_trylock);
3057 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_unlock);
3058 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_init);
3059 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_destroy);
3060 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_rdlock);
3061 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_tryrdlock);
3062 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_wrlock);
3063 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_trywrlock);
3064 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_unlock);
3065 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(once);
3066 TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(sigsetmask);
3068 FdInit();
3071 } // namespace __tsan
3073 // Invisible barrier for tests.
3074 // There were several unsuccessful iterations for this functionality:
3075 // 1. Initially it was implemented in user code using
3076 // REAL(pthread_barrier_wait). But pthread_barrier_wait is not supported on
3077 // MacOS. Futexes are linux-specific for this matter.
3078 // 2. Then we switched to atomics+usleep(10). But usleep produced parasitic
3079 // "as-if synchronized via sleep" messages in reports which failed some
3080 // output tests.
3081 // 3. Then we switched to atomics+sched_yield. But this produced tons of tsan-
3082 // visible events, which lead to "failed to restore stack trace" failures.
3083 // Note that no_sanitize_thread attribute does not turn off atomic interception
3084 // so attaching it to the function defined in user code does not help.
3085 // That's why we now have what we have.
3086 constexpr u32 kBarrierThreadBits = 10;
3087 constexpr u32 kBarrierThreads = 1 << kBarrierThreadBits;
3089 extern "C" {
3091 SANITIZER_INTERFACE_ATTRIBUTE void __tsan_testonly_barrier_init(
3092 atomic_uint32_t *barrier, u32 num_threads) {
3093 if (num_threads >= kBarrierThreads) {
3094 Printf("barrier_init: count is too large (%d)\n", num_threads);
3095 Die();
3097 // kBarrierThreadBits lsb is thread count,
3098 // the remaining are count of entered threads.
3099 atomic_store(barrier, num_threads, memory_order_relaxed);
3102 static u32 barrier_epoch(u32 value) {
3103 return (value >> kBarrierThreadBits) / (value & (kBarrierThreads - 1));
3106 SANITIZER_INTERFACE_ATTRIBUTE void __tsan_testonly_barrier_wait(
3107 atomic_uint32_t *barrier) {
3108 u32 old = atomic_fetch_add(barrier, kBarrierThreads, memory_order_relaxed);
3109 u32 old_epoch = barrier_epoch(old);
3110 if (barrier_epoch(old + kBarrierThreads) != old_epoch) {
3111 FutexWake(barrier, (1 << 30));
3112 return;
3114 for (;;) {
3115 u32 cur = atomic_load(barrier, memory_order_relaxed);
3116 if (barrier_epoch(cur) != old_epoch)
3117 return;
3118 FutexWait(barrier, cur);
3122 } // extern "C"