* testsuite/26_numerics/headers/cmath/hypot.cc: XFAIL on AIX.
[official-gcc.git] / libsanitizer / tsan / tsan_interceptors.cc
blobbf5f2d5b66ce177b27640f554d54a19d38d384c3
1 //===-- tsan_interceptors.cc ----------------------------------------------===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is a part of ThreadSanitizer (TSan), a race detector.
9 //
10 // FIXME: move as many interceptors as possible into
11 // sanitizer_common/sanitizer_common_interceptors.inc
12 //===----------------------------------------------------------------------===//
14 #include "sanitizer_common/sanitizer_atomic.h"
15 #include "sanitizer_common/sanitizer_libc.h"
16 #include "sanitizer_common/sanitizer_linux.h"
17 #include "sanitizer_common/sanitizer_platform_limits_posix.h"
18 #include "sanitizer_common/sanitizer_placement_new.h"
19 #include "sanitizer_common/sanitizer_stacktrace.h"
20 #include "sanitizer_common/sanitizer_tls_get_addr.h"
21 #include "interception/interception.h"
22 #include "tsan_interceptors.h"
23 #include "tsan_interface.h"
24 #include "tsan_platform.h"
25 #include "tsan_suppressions.h"
26 #include "tsan_rtl.h"
27 #include "tsan_mman.h"
28 #include "tsan_fd.h"
30 #if SANITIZER_POSIX
31 #include "sanitizer_common/sanitizer_posix.h"
32 #endif
34 using namespace __tsan; // NOLINT
36 #if SANITIZER_FREEBSD || SANITIZER_MAC
37 #define __errno_location __error
38 #define stdout __stdoutp
39 #define stderr __stderrp
40 #endif
42 #if SANITIZER_ANDROID
43 #define __errno_location __errno
44 #define mallopt(a, b)
45 #endif
47 #if SANITIZER_LINUX || SANITIZER_FREEBSD
48 #define PTHREAD_CREATE_DETACHED 1
49 #elif SANITIZER_MAC
50 #define PTHREAD_CREATE_DETACHED 2
51 #endif
54 #ifdef __mips__
55 const int kSigCount = 129;
56 #else
57 const int kSigCount = 65;
58 #endif
60 struct my_siginfo_t {
61 // The size is determined by looking at sizeof of real siginfo_t on linux.
62 u64 opaque[128 / sizeof(u64)];
65 #ifdef __mips__
66 struct ucontext_t {
67 u64 opaque[768 / sizeof(u64) + 1];
69 #else
70 struct ucontext_t {
71 // The size is determined by looking at sizeof of real ucontext_t on linux.
72 u64 opaque[936 / sizeof(u64) + 1];
74 #endif
76 #if defined(__x86_64__) || defined(__mips__) || SANITIZER_PPC64V1
77 #define PTHREAD_ABI_BASE "GLIBC_2.3.2"
78 #elif defined(__aarch64__) || SANITIZER_PPC64V2
79 #define PTHREAD_ABI_BASE "GLIBC_2.17"
80 #endif
82 extern "C" int pthread_attr_init(void *attr);
83 extern "C" int pthread_attr_destroy(void *attr);
84 DECLARE_REAL(int, pthread_attr_getdetachstate, void *, void *)
85 extern "C" int pthread_attr_setstacksize(void *attr, uptr stacksize);
86 extern "C" int pthread_key_create(unsigned *key, void (*destructor)(void* v));
87 extern "C" int pthread_setspecific(unsigned key, const void *v);
88 DECLARE_REAL(int, pthread_mutexattr_gettype, void *, void *)
89 DECLARE_REAL(int, fflush, __sanitizer_FILE *fp)
90 DECLARE_REAL_AND_INTERCEPTOR(void *, malloc, uptr size)
91 DECLARE_REAL_AND_INTERCEPTOR(void, free, void *ptr)
92 extern "C" void *pthread_self();
93 extern "C" void _exit(int status);
94 extern "C" int *__errno_location();
95 extern "C" int fileno_unlocked(void *stream);
96 extern "C" int dirfd(void *dirp);
97 #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID
98 extern "C" int mallopt(int param, int value);
99 #endif
100 extern __sanitizer_FILE *stdout, *stderr;
101 #if !SANITIZER_FREEBSD && !SANITIZER_MAC
102 const int PTHREAD_MUTEX_RECURSIVE = 1;
103 const int PTHREAD_MUTEX_RECURSIVE_NP = 1;
104 #else
105 const int PTHREAD_MUTEX_RECURSIVE = 2;
106 const int PTHREAD_MUTEX_RECURSIVE_NP = 2;
107 #endif
108 const int EINVAL = 22;
109 const int EBUSY = 16;
110 const int EOWNERDEAD = 130;
111 #if !SANITIZER_FREEBSD && !SANITIZER_MAC
112 const int EPOLL_CTL_ADD = 1;
113 #endif
114 const int SIGILL = 4;
115 const int SIGABRT = 6;
116 const int SIGFPE = 8;
117 const int SIGSEGV = 11;
118 const int SIGPIPE = 13;
119 const int SIGTERM = 15;
120 #if defined(__mips__) || SANITIZER_FREEBSD || SANITIZER_MAC
121 const int SIGBUS = 10;
122 const int SIGSYS = 12;
123 #else
124 const int SIGBUS = 7;
125 const int SIGSYS = 31;
126 #endif
127 void *const MAP_FAILED = (void*)-1;
128 #if !SANITIZER_MAC
129 const int PTHREAD_BARRIER_SERIAL_THREAD = -1;
130 #endif
131 const int MAP_FIXED = 0x10;
132 typedef long long_t; // NOLINT
134 // From /usr/include/unistd.h
135 # define F_ULOCK 0 /* Unlock a previously locked region. */
136 # define F_LOCK 1 /* Lock a region for exclusive use. */
137 # define F_TLOCK 2 /* Test and lock a region for exclusive use. */
138 # define F_TEST 3 /* Test a region for other processes locks. */
140 #define errno (*__errno_location())
142 typedef void (*sighandler_t)(int sig);
143 typedef void (*sigactionhandler_t)(int sig, my_siginfo_t *siginfo, void *uctx);
145 #if SANITIZER_ANDROID
146 struct sigaction_t {
147 u32 sa_flags;
148 union {
149 sighandler_t sa_handler;
150 sigactionhandler_t sa_sigaction;
152 __sanitizer_sigset_t sa_mask;
153 void (*sa_restorer)();
155 #else
156 struct sigaction_t {
157 #ifdef __mips__
158 u32 sa_flags;
159 #endif
160 union {
161 sighandler_t sa_handler;
162 sigactionhandler_t sa_sigaction;
164 #if SANITIZER_FREEBSD
165 int sa_flags;
166 __sanitizer_sigset_t sa_mask;
167 #elif SANITIZER_MAC
168 __sanitizer_sigset_t sa_mask;
169 int sa_flags;
170 #else
171 __sanitizer_sigset_t sa_mask;
172 #ifndef __mips__
173 int sa_flags;
174 #endif
175 void (*sa_restorer)();
176 #endif
178 #endif
180 const sighandler_t SIG_DFL = (sighandler_t)0;
181 const sighandler_t SIG_IGN = (sighandler_t)1;
182 const sighandler_t SIG_ERR = (sighandler_t)-1;
183 #if SANITIZER_FREEBSD || SANITIZER_MAC
184 const int SA_SIGINFO = 0x40;
185 const int SIG_SETMASK = 3;
186 #elif defined(__mips__)
187 const int SA_SIGINFO = 8;
188 const int SIG_SETMASK = 3;
189 #else
190 const int SA_SIGINFO = 4;
191 const int SIG_SETMASK = 2;
192 #endif
194 #define COMMON_INTERCEPTOR_NOTHING_IS_INITIALIZED \
195 (!cur_thread()->is_inited)
197 static sigaction_t sigactions[kSigCount];
199 namespace __tsan {
200 struct SignalDesc {
201 bool armed;
202 bool sigaction;
203 my_siginfo_t siginfo;
204 ucontext_t ctx;
207 struct ThreadSignalContext {
208 int int_signal_send;
209 atomic_uintptr_t in_blocking_func;
210 atomic_uintptr_t have_pending_signals;
211 SignalDesc pending_signals[kSigCount];
212 // emptyset and oldset are too big for stack.
213 __sanitizer_sigset_t emptyset;
214 __sanitizer_sigset_t oldset;
217 // The object is 64-byte aligned, because we want hot data to be located in
218 // a single cache line if possible (it's accessed in every interceptor).
219 static ALIGNED(64) char libignore_placeholder[sizeof(LibIgnore)];
220 static LibIgnore *libignore() {
221 return reinterpret_cast<LibIgnore*>(&libignore_placeholder[0]);
224 void InitializeLibIgnore() {
225 const SuppressionContext &supp = *Suppressions();
226 const uptr n = supp.SuppressionCount();
227 for (uptr i = 0; i < n; i++) {
228 const Suppression *s = supp.SuppressionAt(i);
229 if (0 == internal_strcmp(s->type, kSuppressionLib))
230 libignore()->AddIgnoredLibrary(s->templ);
232 libignore()->OnLibraryLoaded(0);
235 } // namespace __tsan
237 static ThreadSignalContext *SigCtx(ThreadState *thr) {
238 ThreadSignalContext *ctx = (ThreadSignalContext*)thr->signal_ctx;
239 if (ctx == 0 && !thr->is_dead) {
240 ctx = (ThreadSignalContext*)MmapOrDie(sizeof(*ctx), "ThreadSignalContext");
241 MemoryResetRange(thr, (uptr)&SigCtx, (uptr)ctx, sizeof(*ctx));
242 thr->signal_ctx = ctx;
244 return ctx;
247 #if !SANITIZER_MAC
248 static unsigned g_thread_finalize_key;
249 #endif
251 ScopedInterceptor::ScopedInterceptor(ThreadState *thr, const char *fname,
252 uptr pc)
253 : thr_(thr)
254 , pc_(pc)
255 , in_ignored_lib_(false) {
256 Initialize(thr);
257 if (!thr_->is_inited)
258 return;
259 if (!thr_->ignore_interceptors)
260 FuncEntry(thr, pc);
261 DPrintf("#%d: intercept %s()\n", thr_->tid, fname);
262 if (!thr_->in_ignored_lib && libignore()->IsIgnored(pc)) {
263 in_ignored_lib_ = true;
264 thr_->in_ignored_lib = true;
265 ThreadIgnoreBegin(thr_, pc_);
267 if (flags()->ignore_interceptors_accesses) ThreadIgnoreBegin(thr_, pc_);
270 ScopedInterceptor::~ScopedInterceptor() {
271 if (!thr_->is_inited)
272 return;
273 if (flags()->ignore_interceptors_accesses) ThreadIgnoreEnd(thr_, pc_);
274 if (in_ignored_lib_) {
275 thr_->in_ignored_lib = false;
276 ThreadIgnoreEnd(thr_, pc_);
278 if (!thr_->ignore_interceptors) {
279 ProcessPendingSignals(thr_);
280 FuncExit(thr_);
281 CheckNoLocks(thr_);
285 void ScopedInterceptor::UserCallbackStart() {
286 if (flags()->ignore_interceptors_accesses) ThreadIgnoreEnd(thr_, pc_);
287 if (in_ignored_lib_) {
288 thr_->in_ignored_lib = false;
289 ThreadIgnoreEnd(thr_, pc_);
293 void ScopedInterceptor::UserCallbackEnd() {
294 if (in_ignored_lib_) {
295 thr_->in_ignored_lib = true;
296 ThreadIgnoreBegin(thr_, pc_);
298 if (flags()->ignore_interceptors_accesses) ThreadIgnoreBegin(thr_, pc_);
301 #define TSAN_INTERCEPT(func) INTERCEPT_FUNCTION(func)
302 #if SANITIZER_FREEBSD
303 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION(func)
304 #else
305 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION_VER(func, ver)
306 #endif
308 #define READ_STRING_OF_LEN(thr, pc, s, len, n) \
309 MemoryAccessRange((thr), (pc), (uptr)(s), \
310 common_flags()->strict_string_checks ? (len) + 1 : (n), false)
312 #define READ_STRING(thr, pc, s, n) \
313 READ_STRING_OF_LEN((thr), (pc), (s), internal_strlen(s), (n))
315 #define BLOCK_REAL(name) (BlockingCall(thr), REAL(name))
317 struct BlockingCall {
318 explicit BlockingCall(ThreadState *thr)
319 : thr(thr)
320 , ctx(SigCtx(thr)) {
321 for (;;) {
322 atomic_store(&ctx->in_blocking_func, 1, memory_order_relaxed);
323 if (atomic_load(&ctx->have_pending_signals, memory_order_relaxed) == 0)
324 break;
325 atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
326 ProcessPendingSignals(thr);
328 // When we are in a "blocking call", we process signals asynchronously
329 // (right when they arrive). In this context we do not expect to be
330 // executing any user/runtime code. The known interceptor sequence when
331 // this is not true is: pthread_join -> munmap(stack). It's fine
332 // to ignore munmap in this case -- we handle stack shadow separately.
333 thr->ignore_interceptors++;
336 ~BlockingCall() {
337 thr->ignore_interceptors--;
338 atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
341 ThreadState *thr;
342 ThreadSignalContext *ctx;
345 TSAN_INTERCEPTOR(unsigned, sleep, unsigned sec) {
346 SCOPED_TSAN_INTERCEPTOR(sleep, sec);
347 unsigned res = BLOCK_REAL(sleep)(sec);
348 AfterSleep(thr, pc);
349 return res;
352 TSAN_INTERCEPTOR(int, usleep, long_t usec) {
353 SCOPED_TSAN_INTERCEPTOR(usleep, usec);
354 int res = BLOCK_REAL(usleep)(usec);
355 AfterSleep(thr, pc);
356 return res;
359 TSAN_INTERCEPTOR(int, nanosleep, void *req, void *rem) {
360 SCOPED_TSAN_INTERCEPTOR(nanosleep, req, rem);
361 int res = BLOCK_REAL(nanosleep)(req, rem);
362 AfterSleep(thr, pc);
363 return res;
366 // The sole reason tsan wraps atexit callbacks is to establish synchronization
367 // between callback setup and callback execution.
368 struct AtExitCtx {
369 void (*f)();
370 void *arg;
373 static void at_exit_wrapper(void *arg) {
374 ThreadState *thr = cur_thread();
375 uptr pc = 0;
376 Acquire(thr, pc, (uptr)arg);
377 AtExitCtx *ctx = (AtExitCtx*)arg;
378 ((void(*)(void *arg))ctx->f)(ctx->arg);
379 InternalFree(ctx);
382 static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(),
383 void *arg, void *dso);
385 #if !SANITIZER_ANDROID
386 TSAN_INTERCEPTOR(int, atexit, void (*f)()) {
387 if (cur_thread()->in_symbolizer)
388 return 0;
389 // We want to setup the atexit callback even if we are in ignored lib
390 // or after fork.
391 SCOPED_INTERCEPTOR_RAW(atexit, f);
392 return setup_at_exit_wrapper(thr, pc, (void(*)())f, 0, 0);
394 #endif
396 TSAN_INTERCEPTOR(int, __cxa_atexit, void (*f)(void *a), void *arg, void *dso) {
397 if (cur_thread()->in_symbolizer)
398 return 0;
399 SCOPED_TSAN_INTERCEPTOR(__cxa_atexit, f, arg, dso);
400 return setup_at_exit_wrapper(thr, pc, (void(*)())f, arg, dso);
403 static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(),
404 void *arg, void *dso) {
405 AtExitCtx *ctx = (AtExitCtx*)InternalAlloc(sizeof(AtExitCtx));
406 ctx->f = f;
407 ctx->arg = arg;
408 Release(thr, pc, (uptr)ctx);
409 // Memory allocation in __cxa_atexit will race with free during exit,
410 // because we do not see synchronization around atexit callback list.
411 ThreadIgnoreBegin(thr, pc);
412 int res = REAL(__cxa_atexit)(at_exit_wrapper, ctx, dso);
413 ThreadIgnoreEnd(thr, pc);
414 return res;
417 #if !SANITIZER_MAC
418 static void on_exit_wrapper(int status, void *arg) {
419 ThreadState *thr = cur_thread();
420 uptr pc = 0;
421 Acquire(thr, pc, (uptr)arg);
422 AtExitCtx *ctx = (AtExitCtx*)arg;
423 ((void(*)(int status, void *arg))ctx->f)(status, ctx->arg);
424 InternalFree(ctx);
427 TSAN_INTERCEPTOR(int, on_exit, void(*f)(int, void*), void *arg) {
428 if (cur_thread()->in_symbolizer)
429 return 0;
430 SCOPED_TSAN_INTERCEPTOR(on_exit, f, arg);
431 AtExitCtx *ctx = (AtExitCtx*)InternalAlloc(sizeof(AtExitCtx));
432 ctx->f = (void(*)())f;
433 ctx->arg = arg;
434 Release(thr, pc, (uptr)ctx);
435 // Memory allocation in __cxa_atexit will race with free during exit,
436 // because we do not see synchronization around atexit callback list.
437 ThreadIgnoreBegin(thr, pc);
438 int res = REAL(on_exit)(on_exit_wrapper, ctx);
439 ThreadIgnoreEnd(thr, pc);
440 return res;
442 #endif
444 // Cleanup old bufs.
445 static void JmpBufGarbageCollect(ThreadState *thr, uptr sp) {
446 for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) {
447 JmpBuf *buf = &thr->jmp_bufs[i];
448 if (buf->sp <= sp) {
449 uptr sz = thr->jmp_bufs.Size();
450 internal_memcpy(buf, &thr->jmp_bufs[sz - 1], sizeof(*buf));
451 thr->jmp_bufs.PopBack();
452 i--;
457 static void SetJmp(ThreadState *thr, uptr sp, uptr mangled_sp) {
458 if (!thr->is_inited) // called from libc guts during bootstrap
459 return;
460 // Cleanup old bufs.
461 JmpBufGarbageCollect(thr, sp);
462 // Remember the buf.
463 JmpBuf *buf = thr->jmp_bufs.PushBack();
464 buf->sp = sp;
465 buf->mangled_sp = mangled_sp;
466 buf->shadow_stack_pos = thr->shadow_stack_pos;
467 ThreadSignalContext *sctx = SigCtx(thr);
468 buf->int_signal_send = sctx ? sctx->int_signal_send : 0;
469 buf->in_blocking_func = sctx ?
470 atomic_load(&sctx->in_blocking_func, memory_order_relaxed) :
471 false;
472 buf->in_signal_handler = atomic_load(&thr->in_signal_handler,
473 memory_order_relaxed);
476 static void LongJmp(ThreadState *thr, uptr *env) {
477 #ifdef __powerpc__
478 uptr mangled_sp = env[0];
479 #elif SANITIZER_FREEBSD || SANITIZER_MAC
480 uptr mangled_sp = env[2];
481 #elif defined(SANITIZER_LINUX)
482 # ifdef __aarch64__
483 uptr mangled_sp = env[13];
484 # elif defined(__mips64)
485 uptr mangled_sp = env[1];
486 # else
487 uptr mangled_sp = env[6];
488 # endif
489 #endif
490 // Find the saved buf by mangled_sp.
491 for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) {
492 JmpBuf *buf = &thr->jmp_bufs[i];
493 if (buf->mangled_sp == mangled_sp) {
494 CHECK_GE(thr->shadow_stack_pos, buf->shadow_stack_pos);
495 // Unwind the stack.
496 while (thr->shadow_stack_pos > buf->shadow_stack_pos)
497 FuncExit(thr);
498 ThreadSignalContext *sctx = SigCtx(thr);
499 if (sctx) {
500 sctx->int_signal_send = buf->int_signal_send;
501 atomic_store(&sctx->in_blocking_func, buf->in_blocking_func,
502 memory_order_relaxed);
504 atomic_store(&thr->in_signal_handler, buf->in_signal_handler,
505 memory_order_relaxed);
506 JmpBufGarbageCollect(thr, buf->sp - 1); // do not collect buf->sp
507 return;
510 Printf("ThreadSanitizer: can't find longjmp buf\n");
511 CHECK(0);
514 // FIXME: put everything below into a common extern "C" block?
515 extern "C" void __tsan_setjmp(uptr sp, uptr mangled_sp) {
516 SetJmp(cur_thread(), sp, mangled_sp);
519 #if SANITIZER_MAC
520 TSAN_INTERCEPTOR(int, setjmp, void *env);
521 TSAN_INTERCEPTOR(int, _setjmp, void *env);
522 TSAN_INTERCEPTOR(int, sigsetjmp, void *env);
523 #else // SANITIZER_MAC
524 // Not called. Merely to satisfy TSAN_INTERCEPT().
525 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
526 int __interceptor_setjmp(void *env);
527 extern "C" int __interceptor_setjmp(void *env) {
528 CHECK(0);
529 return 0;
532 // FIXME: any reason to have a separate declaration?
533 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
534 int __interceptor__setjmp(void *env);
535 extern "C" int __interceptor__setjmp(void *env) {
536 CHECK(0);
537 return 0;
540 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
541 int __interceptor_sigsetjmp(void *env);
542 extern "C" int __interceptor_sigsetjmp(void *env) {
543 CHECK(0);
544 return 0;
547 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
548 int __interceptor___sigsetjmp(void *env);
549 extern "C" int __interceptor___sigsetjmp(void *env) {
550 CHECK(0);
551 return 0;
554 extern "C" int setjmp(void *env);
555 extern "C" int _setjmp(void *env);
556 extern "C" int sigsetjmp(void *env);
557 extern "C" int __sigsetjmp(void *env);
558 DEFINE_REAL(int, setjmp, void *env)
559 DEFINE_REAL(int, _setjmp, void *env)
560 DEFINE_REAL(int, sigsetjmp, void *env)
561 DEFINE_REAL(int, __sigsetjmp, void *env)
562 #endif // SANITIZER_MAC
564 TSAN_INTERCEPTOR(void, longjmp, uptr *env, int val) {
565 // Note: if we call REAL(longjmp) in the context of ScopedInterceptor,
566 // bad things will happen. We will jump over ScopedInterceptor dtor and can
567 // leave thr->in_ignored_lib set.
569 SCOPED_INTERCEPTOR_RAW(longjmp, env, val);
571 LongJmp(cur_thread(), env);
572 REAL(longjmp)(env, val);
575 TSAN_INTERCEPTOR(void, siglongjmp, uptr *env, int val) {
577 SCOPED_INTERCEPTOR_RAW(siglongjmp, env, val);
579 LongJmp(cur_thread(), env);
580 REAL(siglongjmp)(env, val);
583 #if !SANITIZER_MAC
584 TSAN_INTERCEPTOR(void*, malloc, uptr size) {
585 if (cur_thread()->in_symbolizer)
586 return InternalAlloc(size);
587 void *p = 0;
589 SCOPED_INTERCEPTOR_RAW(malloc, size);
590 p = user_alloc(thr, pc, size);
592 invoke_malloc_hook(p, size);
593 return p;
596 TSAN_INTERCEPTOR(void*, __libc_memalign, uptr align, uptr sz) {
597 SCOPED_TSAN_INTERCEPTOR(__libc_memalign, align, sz);
598 return user_alloc(thr, pc, sz, align);
601 TSAN_INTERCEPTOR(void*, calloc, uptr size, uptr n) {
602 if (cur_thread()->in_symbolizer)
603 return InternalCalloc(size, n);
604 void *p = 0;
606 SCOPED_INTERCEPTOR_RAW(calloc, size, n);
607 p = user_calloc(thr, pc, size, n);
609 invoke_malloc_hook(p, n * size);
610 return p;
613 TSAN_INTERCEPTOR(void*, realloc, void *p, uptr size) {
614 if (cur_thread()->in_symbolizer)
615 return InternalRealloc(p, size);
616 if (p)
617 invoke_free_hook(p);
619 SCOPED_INTERCEPTOR_RAW(realloc, p, size);
620 p = user_realloc(thr, pc, p, size);
622 invoke_malloc_hook(p, size);
623 return p;
626 TSAN_INTERCEPTOR(void, free, void *p) {
627 if (p == 0)
628 return;
629 if (cur_thread()->in_symbolizer)
630 return InternalFree(p);
631 invoke_free_hook(p);
632 SCOPED_INTERCEPTOR_RAW(free, p);
633 user_free(thr, pc, p);
636 TSAN_INTERCEPTOR(void, cfree, void *p) {
637 if (p == 0)
638 return;
639 if (cur_thread()->in_symbolizer)
640 return InternalFree(p);
641 invoke_free_hook(p);
642 SCOPED_INTERCEPTOR_RAW(cfree, p);
643 user_free(thr, pc, p);
646 TSAN_INTERCEPTOR(uptr, malloc_usable_size, void *p) {
647 SCOPED_INTERCEPTOR_RAW(malloc_usable_size, p);
648 return user_alloc_usable_size(p);
650 #endif
652 TSAN_INTERCEPTOR(char*, strcpy, char *dst, const char *src) { // NOLINT
653 SCOPED_TSAN_INTERCEPTOR(strcpy, dst, src); // NOLINT
654 uptr srclen = internal_strlen(src);
655 MemoryAccessRange(thr, pc, (uptr)dst, srclen + 1, true);
656 MemoryAccessRange(thr, pc, (uptr)src, srclen + 1, false);
657 return REAL(strcpy)(dst, src); // NOLINT
660 TSAN_INTERCEPTOR(char*, strncpy, char *dst, char *src, uptr n) {
661 SCOPED_TSAN_INTERCEPTOR(strncpy, dst, src, n);
662 uptr srclen = internal_strnlen(src, n);
663 MemoryAccessRange(thr, pc, (uptr)dst, n, true);
664 MemoryAccessRange(thr, pc, (uptr)src, min(srclen + 1, n), false);
665 return REAL(strncpy)(dst, src, n);
668 TSAN_INTERCEPTOR(char*, strdup, const char *str) {
669 SCOPED_TSAN_INTERCEPTOR(strdup, str);
670 // strdup will call malloc, so no instrumentation is required here.
671 return REAL(strdup)(str);
674 static bool fix_mmap_addr(void **addr, long_t sz, int flags) {
675 if (*addr) {
676 if (!IsAppMem((uptr)*addr) || !IsAppMem((uptr)*addr + sz - 1)) {
677 if (flags & MAP_FIXED) {
678 errno = EINVAL;
679 return false;
680 } else {
681 *addr = 0;
685 return true;
688 TSAN_INTERCEPTOR(void *, mmap, void *addr, SIZE_T sz, int prot, int flags,
689 int fd, OFF_T off) {
690 SCOPED_TSAN_INTERCEPTOR(mmap, addr, sz, prot, flags, fd, off);
691 if (!fix_mmap_addr(&addr, sz, flags))
692 return MAP_FAILED;
693 void *res = REAL(mmap)(addr, sz, prot, flags, fd, off);
694 if (res != MAP_FAILED) {
695 if (fd > 0)
696 FdAccess(thr, pc, fd);
698 if (thr->ignore_reads_and_writes == 0)
699 MemoryRangeImitateWrite(thr, pc, (uptr)res, sz);
700 else
701 MemoryResetRange(thr, pc, (uptr)res, sz);
703 return res;
706 #if SANITIZER_LINUX
707 TSAN_INTERCEPTOR(void *, mmap64, void *addr, SIZE_T sz, int prot, int flags,
708 int fd, OFF64_T off) {
709 SCOPED_TSAN_INTERCEPTOR(mmap64, addr, sz, prot, flags, fd, off);
710 if (!fix_mmap_addr(&addr, sz, flags))
711 return MAP_FAILED;
712 void *res = REAL(mmap64)(addr, sz, prot, flags, fd, off);
713 if (res != MAP_FAILED) {
714 if (fd > 0)
715 FdAccess(thr, pc, fd);
717 if (thr->ignore_reads_and_writes == 0)
718 MemoryRangeImitateWrite(thr, pc, (uptr)res, sz);
719 else
720 MemoryResetRange(thr, pc, (uptr)res, sz);
722 return res;
724 #define TSAN_MAYBE_INTERCEPT_MMAP64 TSAN_INTERCEPT(mmap64)
725 #else
726 #define TSAN_MAYBE_INTERCEPT_MMAP64
727 #endif
729 TSAN_INTERCEPTOR(int, munmap, void *addr, long_t sz) {
730 SCOPED_TSAN_INTERCEPTOR(munmap, addr, sz);
731 if (sz != 0) {
732 // If sz == 0, munmap will return EINVAL and don't unmap any memory.
733 DontNeedShadowFor((uptr)addr, sz);
734 ScopedGlobalProcessor sgp;
735 ctx->metamap.ResetRange(thr->proc(), (uptr)addr, (uptr)sz);
737 int res = REAL(munmap)(addr, sz);
738 return res;
741 #if SANITIZER_LINUX
742 TSAN_INTERCEPTOR(void*, memalign, uptr align, uptr sz) {
743 SCOPED_INTERCEPTOR_RAW(memalign, align, sz);
744 return user_alloc(thr, pc, sz, align);
746 #define TSAN_MAYBE_INTERCEPT_MEMALIGN TSAN_INTERCEPT(memalign)
747 #else
748 #define TSAN_MAYBE_INTERCEPT_MEMALIGN
749 #endif
751 #if !SANITIZER_MAC
752 TSAN_INTERCEPTOR(void*, aligned_alloc, uptr align, uptr sz) {
753 SCOPED_INTERCEPTOR_RAW(memalign, align, sz);
754 return user_alloc(thr, pc, sz, align);
757 TSAN_INTERCEPTOR(void*, valloc, uptr sz) {
758 SCOPED_INTERCEPTOR_RAW(valloc, sz);
759 return user_alloc(thr, pc, sz, GetPageSizeCached());
761 #endif
763 #if SANITIZER_LINUX
764 TSAN_INTERCEPTOR(void*, pvalloc, uptr sz) {
765 SCOPED_INTERCEPTOR_RAW(pvalloc, sz);
766 sz = RoundUp(sz, GetPageSizeCached());
767 return user_alloc(thr, pc, sz, GetPageSizeCached());
769 #define TSAN_MAYBE_INTERCEPT_PVALLOC TSAN_INTERCEPT(pvalloc)
770 #else
771 #define TSAN_MAYBE_INTERCEPT_PVALLOC
772 #endif
774 #if !SANITIZER_MAC
775 TSAN_INTERCEPTOR(int, posix_memalign, void **memptr, uptr align, uptr sz) {
776 SCOPED_INTERCEPTOR_RAW(posix_memalign, memptr, align, sz);
777 *memptr = user_alloc(thr, pc, sz, align);
778 return 0;
780 #endif
782 // __cxa_guard_acquire and friends need to be intercepted in a special way -
783 // regular interceptors will break statically-linked libstdc++. Linux
784 // interceptors are especially defined as weak functions (so that they don't
785 // cause link errors when user defines them as well). So they silently
786 // auto-disable themselves when such symbol is already present in the binary. If
787 // we link libstdc++ statically, it will bring own __cxa_guard_acquire which
788 // will silently replace our interceptor. That's why on Linux we simply export
789 // these interceptors with INTERFACE_ATTRIBUTE.
790 // On OS X, we don't support statically linking, so we just use a regular
791 // interceptor.
792 #if SANITIZER_MAC
793 #define STDCXX_INTERCEPTOR TSAN_INTERCEPTOR
794 #else
795 #define STDCXX_INTERCEPTOR(rettype, name, ...) \
796 extern "C" rettype INTERFACE_ATTRIBUTE name(__VA_ARGS__)
797 #endif
799 // Used in thread-safe function static initialization.
800 STDCXX_INTERCEPTOR(int, __cxa_guard_acquire, atomic_uint32_t *g) {
801 SCOPED_INTERCEPTOR_RAW(__cxa_guard_acquire, g);
802 for (;;) {
803 u32 cmp = atomic_load(g, memory_order_acquire);
804 if (cmp == 0) {
805 if (atomic_compare_exchange_strong(g, &cmp, 1<<16, memory_order_relaxed))
806 return 1;
807 } else if (cmp == 1) {
808 Acquire(thr, pc, (uptr)g);
809 return 0;
810 } else {
811 internal_sched_yield();
816 STDCXX_INTERCEPTOR(void, __cxa_guard_release, atomic_uint32_t *g) {
817 SCOPED_INTERCEPTOR_RAW(__cxa_guard_release, g);
818 Release(thr, pc, (uptr)g);
819 atomic_store(g, 1, memory_order_release);
822 STDCXX_INTERCEPTOR(void, __cxa_guard_abort, atomic_uint32_t *g) {
823 SCOPED_INTERCEPTOR_RAW(__cxa_guard_abort, g);
824 atomic_store(g, 0, memory_order_relaxed);
827 namespace __tsan {
828 void DestroyThreadState() {
829 ThreadState *thr = cur_thread();
830 Processor *proc = thr->proc();
831 ThreadFinish(thr);
832 ProcUnwire(proc, thr);
833 ProcDestroy(proc);
834 ThreadSignalContext *sctx = thr->signal_ctx;
835 if (sctx) {
836 thr->signal_ctx = 0;
837 UnmapOrDie(sctx, sizeof(*sctx));
839 DTLS_Destroy();
840 cur_thread_finalize();
842 } // namespace __tsan
844 #if !SANITIZER_MAC
845 static void thread_finalize(void *v) {
846 uptr iter = (uptr)v;
847 if (iter > 1) {
848 if (pthread_setspecific(g_thread_finalize_key, (void*)(iter - 1))) {
849 Printf("ThreadSanitizer: failed to set thread key\n");
850 Die();
852 return;
854 DestroyThreadState();
856 #endif
859 struct ThreadParam {
860 void* (*callback)(void *arg);
861 void *param;
862 atomic_uintptr_t tid;
865 extern "C" void *__tsan_thread_start_func(void *arg) {
866 ThreadParam *p = (ThreadParam*)arg;
867 void* (*callback)(void *arg) = p->callback;
868 void *param = p->param;
869 int tid = 0;
871 ThreadState *thr = cur_thread();
872 // Thread-local state is not initialized yet.
873 ScopedIgnoreInterceptors ignore;
874 #if !SANITIZER_MAC
875 ThreadIgnoreBegin(thr, 0);
876 if (pthread_setspecific(g_thread_finalize_key,
877 (void *)GetPthreadDestructorIterations())) {
878 Printf("ThreadSanitizer: failed to set thread key\n");
879 Die();
881 ThreadIgnoreEnd(thr, 0);
882 #endif
883 while ((tid = atomic_load(&p->tid, memory_order_acquire)) == 0)
884 internal_sched_yield();
885 Processor *proc = ProcCreate();
886 ProcWire(proc, thr);
887 ThreadStart(thr, tid, GetTid());
888 atomic_store(&p->tid, 0, memory_order_release);
890 void *res = callback(param);
891 // Prevent the callback from being tail called,
892 // it mixes up stack traces.
893 volatile int foo = 42;
894 foo++;
895 return res;
898 TSAN_INTERCEPTOR(int, pthread_create,
899 void *th, void *attr, void *(*callback)(void*), void * param) {
900 SCOPED_INTERCEPTOR_RAW(pthread_create, th, attr, callback, param);
901 if (ctx->after_multithreaded_fork) {
902 if (flags()->die_after_fork) {
903 Report("ThreadSanitizer: starting new threads after multi-threaded "
904 "fork is not supported. Dying (set die_after_fork=0 to override)\n");
905 Die();
906 } else {
907 VPrintf(1, "ThreadSanitizer: starting new threads after multi-threaded "
908 "fork is not supported (pid %d). Continuing because of "
909 "die_after_fork=0, but you are on your own\n", internal_getpid());
912 __sanitizer_pthread_attr_t myattr;
913 if (attr == 0) {
914 pthread_attr_init(&myattr);
915 attr = &myattr;
917 int detached = 0;
918 REAL(pthread_attr_getdetachstate)(attr, &detached);
919 AdjustStackSize(attr);
921 ThreadParam p;
922 p.callback = callback;
923 p.param = param;
924 atomic_store(&p.tid, 0, memory_order_relaxed);
925 int res = -1;
927 // Otherwise we see false positives in pthread stack manipulation.
928 ScopedIgnoreInterceptors ignore;
929 ThreadIgnoreBegin(thr, pc);
930 res = REAL(pthread_create)(th, attr, __tsan_thread_start_func, &p);
931 ThreadIgnoreEnd(thr, pc);
933 if (res == 0) {
934 int tid = ThreadCreate(thr, pc, *(uptr*)th,
935 detached == PTHREAD_CREATE_DETACHED);
936 CHECK_NE(tid, 0);
937 // Synchronization on p.tid serves two purposes:
938 // 1. ThreadCreate must finish before the new thread starts.
939 // Otherwise the new thread can call pthread_detach, but the pthread_t
940 // identifier is not yet registered in ThreadRegistry by ThreadCreate.
941 // 2. ThreadStart must finish before this thread continues.
942 // Otherwise, this thread can call pthread_detach and reset thr->sync
943 // before the new thread got a chance to acquire from it in ThreadStart.
944 atomic_store(&p.tid, tid, memory_order_release);
945 while (atomic_load(&p.tid, memory_order_acquire) != 0)
946 internal_sched_yield();
948 if (attr == &myattr)
949 pthread_attr_destroy(&myattr);
950 return res;
953 TSAN_INTERCEPTOR(int, pthread_join, void *th, void **ret) {
954 SCOPED_INTERCEPTOR_RAW(pthread_join, th, ret);
955 int tid = ThreadTid(thr, pc, (uptr)th);
956 ThreadIgnoreBegin(thr, pc);
957 int res = BLOCK_REAL(pthread_join)(th, ret);
958 ThreadIgnoreEnd(thr, pc);
959 if (res == 0) {
960 ThreadJoin(thr, pc, tid);
962 return res;
965 DEFINE_REAL_PTHREAD_FUNCTIONS
967 TSAN_INTERCEPTOR(int, pthread_detach, void *th) {
968 SCOPED_TSAN_INTERCEPTOR(pthread_detach, th);
969 int tid = ThreadTid(thr, pc, (uptr)th);
970 int res = REAL(pthread_detach)(th);
971 if (res == 0) {
972 ThreadDetach(thr, pc, tid);
974 return res;
977 // Problem:
978 // NPTL implementation of pthread_cond has 2 versions (2.2.5 and 2.3.2).
979 // pthread_cond_t has different size in the different versions.
980 // If call new REAL functions for old pthread_cond_t, they will corrupt memory
981 // after pthread_cond_t (old cond is smaller).
982 // If we call old REAL functions for new pthread_cond_t, we will lose some
983 // functionality (e.g. old functions do not support waiting against
984 // CLOCK_REALTIME).
985 // Proper handling would require to have 2 versions of interceptors as well.
986 // But this is messy, in particular requires linker scripts when sanitizer
987 // runtime is linked into a shared library.
988 // Instead we assume we don't have dynamic libraries built against old
989 // pthread (2.2.5 is dated by 2002). And provide legacy_pthread_cond flag
990 // that allows to work with old libraries (but this mode does not support
991 // some features, e.g. pthread_condattr_getpshared).
992 static void *init_cond(void *c, bool force = false) {
993 // sizeof(pthread_cond_t) >= sizeof(uptr) in both versions.
994 // So we allocate additional memory on the side large enough to hold
995 // any pthread_cond_t object. Always call new REAL functions, but pass
996 // the aux object to them.
997 // Note: the code assumes that PTHREAD_COND_INITIALIZER initializes
998 // first word of pthread_cond_t to zero.
999 // It's all relevant only for linux.
1000 if (!common_flags()->legacy_pthread_cond)
1001 return c;
1002 atomic_uintptr_t *p = (atomic_uintptr_t*)c;
1003 uptr cond = atomic_load(p, memory_order_acquire);
1004 if (!force && cond != 0)
1005 return (void*)cond;
1006 void *newcond = WRAP(malloc)(pthread_cond_t_sz);
1007 internal_memset(newcond, 0, pthread_cond_t_sz);
1008 if (atomic_compare_exchange_strong(p, &cond, (uptr)newcond,
1009 memory_order_acq_rel))
1010 return newcond;
1011 WRAP(free)(newcond);
1012 return (void*)cond;
1015 struct CondMutexUnlockCtx {
1016 ScopedInterceptor *si;
1017 ThreadState *thr;
1018 uptr pc;
1019 void *m;
1022 static void cond_mutex_unlock(CondMutexUnlockCtx *arg) {
1023 // pthread_cond_wait interceptor has enabled async signal delivery
1024 // (see BlockingCall below). Disable async signals since we are running
1025 // tsan code. Also ScopedInterceptor and BlockingCall destructors won't run
1026 // since the thread is cancelled, so we have to manually execute them
1027 // (the thread still can run some user code due to pthread_cleanup_push).
1028 ThreadSignalContext *ctx = SigCtx(arg->thr);
1029 CHECK_EQ(atomic_load(&ctx->in_blocking_func, memory_order_relaxed), 1);
1030 atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
1031 MutexLock(arg->thr, arg->pc, (uptr)arg->m);
1032 // Undo BlockingCall ctor effects.
1033 arg->thr->ignore_interceptors--;
1034 arg->si->~ScopedInterceptor();
1037 INTERCEPTOR(int, pthread_cond_init, void *c, void *a) {
1038 void *cond = init_cond(c, true);
1039 SCOPED_TSAN_INTERCEPTOR(pthread_cond_init, cond, a);
1040 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true);
1041 return REAL(pthread_cond_init)(cond, a);
1044 static int cond_wait(ThreadState *thr, uptr pc, ScopedInterceptor *si,
1045 int (*fn)(void *c, void *m, void *abstime), void *c,
1046 void *m, void *t) {
1047 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1048 MutexUnlock(thr, pc, (uptr)m);
1049 CondMutexUnlockCtx arg = {si, thr, pc, m};
1050 int res = 0;
1051 // This ensures that we handle mutex lock even in case of pthread_cancel.
1052 // See test/tsan/cond_cancel.cc.
1054 // Enable signal delivery while the thread is blocked.
1055 BlockingCall bc(thr);
1056 res = call_pthread_cancel_with_cleanup(
1057 fn, c, m, t, (void (*)(void *arg))cond_mutex_unlock, &arg);
1059 if (res == errno_EOWNERDEAD) MutexRepair(thr, pc, (uptr)m);
1060 MutexLock(thr, pc, (uptr)m);
1061 return res;
1064 INTERCEPTOR(int, pthread_cond_wait, void *c, void *m) {
1065 void *cond = init_cond(c);
1066 SCOPED_TSAN_INTERCEPTOR(pthread_cond_wait, cond, m);
1067 return cond_wait(thr, pc, &si, (int (*)(void *c, void *m, void *abstime))REAL(
1068 pthread_cond_wait),
1069 cond, m, 0);
1072 INTERCEPTOR(int, pthread_cond_timedwait, void *c, void *m, void *abstime) {
1073 void *cond = init_cond(c);
1074 SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait, cond, m, abstime);
1075 return cond_wait(thr, pc, &si, REAL(pthread_cond_timedwait), cond, m,
1076 abstime);
1079 #if SANITIZER_MAC
1080 INTERCEPTOR(int, pthread_cond_timedwait_relative_np, void *c, void *m,
1081 void *reltime) {
1082 void *cond = init_cond(c);
1083 SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait_relative_np, cond, m, reltime);
1084 return cond_wait(thr, pc, &si, REAL(pthread_cond_timedwait_relative_np), cond,
1085 m, reltime);
1087 #endif
1089 INTERCEPTOR(int, pthread_cond_signal, void *c) {
1090 void *cond = init_cond(c);
1091 SCOPED_TSAN_INTERCEPTOR(pthread_cond_signal, cond);
1092 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1093 return REAL(pthread_cond_signal)(cond);
1096 INTERCEPTOR(int, pthread_cond_broadcast, void *c) {
1097 void *cond = init_cond(c);
1098 SCOPED_TSAN_INTERCEPTOR(pthread_cond_broadcast, cond);
1099 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1100 return REAL(pthread_cond_broadcast)(cond);
1103 INTERCEPTOR(int, pthread_cond_destroy, void *c) {
1104 void *cond = init_cond(c);
1105 SCOPED_TSAN_INTERCEPTOR(pthread_cond_destroy, cond);
1106 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true);
1107 int res = REAL(pthread_cond_destroy)(cond);
1108 if (common_flags()->legacy_pthread_cond) {
1109 // Free our aux cond and zero the pointer to not leave dangling pointers.
1110 WRAP(free)(cond);
1111 atomic_store((atomic_uintptr_t*)c, 0, memory_order_relaxed);
1113 return res;
1116 TSAN_INTERCEPTOR(int, pthread_mutex_init, void *m, void *a) {
1117 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_init, m, a);
1118 int res = REAL(pthread_mutex_init)(m, a);
1119 if (res == 0) {
1120 bool recursive = false;
1121 if (a) {
1122 int type = 0;
1123 if (REAL(pthread_mutexattr_gettype)(a, &type) == 0)
1124 recursive = (type == PTHREAD_MUTEX_RECURSIVE
1125 || type == PTHREAD_MUTEX_RECURSIVE_NP);
1127 MutexCreate(thr, pc, (uptr)m, false, recursive, false);
1129 return res;
1132 TSAN_INTERCEPTOR(int, pthread_mutex_destroy, void *m) {
1133 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_destroy, m);
1134 int res = REAL(pthread_mutex_destroy)(m);
1135 if (res == 0 || res == EBUSY) {
1136 MutexDestroy(thr, pc, (uptr)m);
1138 return res;
1141 TSAN_INTERCEPTOR(int, pthread_mutex_trylock, void *m) {
1142 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_trylock, m);
1143 int res = REAL(pthread_mutex_trylock)(m);
1144 if (res == EOWNERDEAD)
1145 MutexRepair(thr, pc, (uptr)m);
1146 if (res == 0 || res == EOWNERDEAD)
1147 MutexLock(thr, pc, (uptr)m, /*rec=*/1, /*try_lock=*/true);
1148 return res;
1151 #if !SANITIZER_MAC
1152 TSAN_INTERCEPTOR(int, pthread_mutex_timedlock, void *m, void *abstime) {
1153 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_timedlock, m, abstime);
1154 int res = REAL(pthread_mutex_timedlock)(m, abstime);
1155 if (res == 0) {
1156 MutexLock(thr, pc, (uptr)m);
1158 return res;
1160 #endif
1162 #if !SANITIZER_MAC
1163 TSAN_INTERCEPTOR(int, pthread_spin_init, void *m, int pshared) {
1164 SCOPED_TSAN_INTERCEPTOR(pthread_spin_init, m, pshared);
1165 int res = REAL(pthread_spin_init)(m, pshared);
1166 if (res == 0) {
1167 MutexCreate(thr, pc, (uptr)m, false, false, false);
1169 return res;
1172 TSAN_INTERCEPTOR(int, pthread_spin_destroy, void *m) {
1173 SCOPED_TSAN_INTERCEPTOR(pthread_spin_destroy, m);
1174 int res = REAL(pthread_spin_destroy)(m);
1175 if (res == 0) {
1176 MutexDestroy(thr, pc, (uptr)m);
1178 return res;
1181 TSAN_INTERCEPTOR(int, pthread_spin_lock, void *m) {
1182 SCOPED_TSAN_INTERCEPTOR(pthread_spin_lock, m);
1183 int res = REAL(pthread_spin_lock)(m);
1184 if (res == 0) {
1185 MutexLock(thr, pc, (uptr)m);
1187 return res;
1190 TSAN_INTERCEPTOR(int, pthread_spin_trylock, void *m) {
1191 SCOPED_TSAN_INTERCEPTOR(pthread_spin_trylock, m);
1192 int res = REAL(pthread_spin_trylock)(m);
1193 if (res == 0) {
1194 MutexLock(thr, pc, (uptr)m, /*rec=*/1, /*try_lock=*/true);
1196 return res;
1199 TSAN_INTERCEPTOR(int, pthread_spin_unlock, void *m) {
1200 SCOPED_TSAN_INTERCEPTOR(pthread_spin_unlock, m);
1201 MutexUnlock(thr, pc, (uptr)m);
1202 int res = REAL(pthread_spin_unlock)(m);
1203 return res;
1205 #endif
1207 TSAN_INTERCEPTOR(int, pthread_rwlock_init, void *m, void *a) {
1208 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_init, m, a);
1209 int res = REAL(pthread_rwlock_init)(m, a);
1210 if (res == 0) {
1211 MutexCreate(thr, pc, (uptr)m, true, false, false);
1213 return res;
1216 TSAN_INTERCEPTOR(int, pthread_rwlock_destroy, void *m) {
1217 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_destroy, m);
1218 int res = REAL(pthread_rwlock_destroy)(m);
1219 if (res == 0) {
1220 MutexDestroy(thr, pc, (uptr)m);
1222 return res;
1225 TSAN_INTERCEPTOR(int, pthread_rwlock_rdlock, void *m) {
1226 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_rdlock, m);
1227 int res = REAL(pthread_rwlock_rdlock)(m);
1228 if (res == 0) {
1229 MutexReadLock(thr, pc, (uptr)m);
1231 return res;
1234 TSAN_INTERCEPTOR(int, pthread_rwlock_tryrdlock, void *m) {
1235 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_tryrdlock, m);
1236 int res = REAL(pthread_rwlock_tryrdlock)(m);
1237 if (res == 0) {
1238 MutexReadLock(thr, pc, (uptr)m, /*try_lock=*/true);
1240 return res;
1243 #if !SANITIZER_MAC
1244 TSAN_INTERCEPTOR(int, pthread_rwlock_timedrdlock, void *m, void *abstime) {
1245 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedrdlock, m, abstime);
1246 int res = REAL(pthread_rwlock_timedrdlock)(m, abstime);
1247 if (res == 0) {
1248 MutexReadLock(thr, pc, (uptr)m);
1250 return res;
1252 #endif
1254 TSAN_INTERCEPTOR(int, pthread_rwlock_wrlock, void *m) {
1255 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_wrlock, m);
1256 int res = REAL(pthread_rwlock_wrlock)(m);
1257 if (res == 0) {
1258 MutexLock(thr, pc, (uptr)m);
1260 return res;
1263 TSAN_INTERCEPTOR(int, pthread_rwlock_trywrlock, void *m) {
1264 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_trywrlock, m);
1265 int res = REAL(pthread_rwlock_trywrlock)(m);
1266 if (res == 0) {
1267 MutexLock(thr, pc, (uptr)m, /*rec=*/1, /*try_lock=*/true);
1269 return res;
1272 #if !SANITIZER_MAC
1273 TSAN_INTERCEPTOR(int, pthread_rwlock_timedwrlock, void *m, void *abstime) {
1274 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedwrlock, m, abstime);
1275 int res = REAL(pthread_rwlock_timedwrlock)(m, abstime);
1276 if (res == 0) {
1277 MutexLock(thr, pc, (uptr)m);
1279 return res;
1281 #endif
1283 TSAN_INTERCEPTOR(int, pthread_rwlock_unlock, void *m) {
1284 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_unlock, m);
1285 MutexReadOrWriteUnlock(thr, pc, (uptr)m);
1286 int res = REAL(pthread_rwlock_unlock)(m);
1287 return res;
1290 #if !SANITIZER_MAC
1291 TSAN_INTERCEPTOR(int, pthread_barrier_init, void *b, void *a, unsigned count) {
1292 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_init, b, a, count);
1293 MemoryWrite(thr, pc, (uptr)b, kSizeLog1);
1294 int res = REAL(pthread_barrier_init)(b, a, count);
1295 return res;
1298 TSAN_INTERCEPTOR(int, pthread_barrier_destroy, void *b) {
1299 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_destroy, b);
1300 MemoryWrite(thr, pc, (uptr)b, kSizeLog1);
1301 int res = REAL(pthread_barrier_destroy)(b);
1302 return res;
1305 TSAN_INTERCEPTOR(int, pthread_barrier_wait, void *b) {
1306 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_wait, b);
1307 Release(thr, pc, (uptr)b);
1308 MemoryRead(thr, pc, (uptr)b, kSizeLog1);
1309 int res = REAL(pthread_barrier_wait)(b);
1310 MemoryRead(thr, pc, (uptr)b, kSizeLog1);
1311 if (res == 0 || res == PTHREAD_BARRIER_SERIAL_THREAD) {
1312 Acquire(thr, pc, (uptr)b);
1314 return res;
1316 #endif
1318 TSAN_INTERCEPTOR(int, pthread_once, void *o, void (*f)()) {
1319 SCOPED_INTERCEPTOR_RAW(pthread_once, o, f);
1320 if (o == 0 || f == 0)
1321 return EINVAL;
1322 atomic_uint32_t *a;
1323 if (!SANITIZER_MAC)
1324 a = static_cast<atomic_uint32_t*>(o);
1325 else // On OS X, pthread_once_t has a header with a long-sized signature.
1326 a = static_cast<atomic_uint32_t*>((void *)((char *)o + sizeof(long_t)));
1327 u32 v = atomic_load(a, memory_order_acquire);
1328 if (v == 0 && atomic_compare_exchange_strong(a, &v, 1,
1329 memory_order_relaxed)) {
1330 (*f)();
1331 if (!thr->in_ignored_lib)
1332 Release(thr, pc, (uptr)o);
1333 atomic_store(a, 2, memory_order_release);
1334 } else {
1335 while (v != 2) {
1336 internal_sched_yield();
1337 v = atomic_load(a, memory_order_acquire);
1339 if (!thr->in_ignored_lib)
1340 Acquire(thr, pc, (uptr)o);
1342 return 0;
1345 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1346 TSAN_INTERCEPTOR(int, __fxstat, int version, int fd, void *buf) {
1347 SCOPED_TSAN_INTERCEPTOR(__fxstat, version, fd, buf);
1348 if (fd > 0)
1349 FdAccess(thr, pc, fd);
1350 return REAL(__fxstat)(version, fd, buf);
1352 #define TSAN_MAYBE_INTERCEPT___FXSTAT TSAN_INTERCEPT(__fxstat)
1353 #else
1354 #define TSAN_MAYBE_INTERCEPT___FXSTAT
1355 #endif
1357 TSAN_INTERCEPTOR(int, fstat, int fd, void *buf) {
1358 #if SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_ANDROID
1359 SCOPED_TSAN_INTERCEPTOR(fstat, fd, buf);
1360 if (fd > 0)
1361 FdAccess(thr, pc, fd);
1362 return REAL(fstat)(fd, buf);
1363 #else
1364 SCOPED_TSAN_INTERCEPTOR(__fxstat, 0, fd, buf);
1365 if (fd > 0)
1366 FdAccess(thr, pc, fd);
1367 return REAL(__fxstat)(0, fd, buf);
1368 #endif
1371 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1372 TSAN_INTERCEPTOR(int, __fxstat64, int version, int fd, void *buf) {
1373 SCOPED_TSAN_INTERCEPTOR(__fxstat64, version, fd, buf);
1374 if (fd > 0)
1375 FdAccess(thr, pc, fd);
1376 return REAL(__fxstat64)(version, fd, buf);
1378 #define TSAN_MAYBE_INTERCEPT___FXSTAT64 TSAN_INTERCEPT(__fxstat64)
1379 #else
1380 #define TSAN_MAYBE_INTERCEPT___FXSTAT64
1381 #endif
1383 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1384 TSAN_INTERCEPTOR(int, fstat64, int fd, void *buf) {
1385 SCOPED_TSAN_INTERCEPTOR(__fxstat64, 0, fd, buf);
1386 if (fd > 0)
1387 FdAccess(thr, pc, fd);
1388 return REAL(__fxstat64)(0, fd, buf);
1390 #define TSAN_MAYBE_INTERCEPT_FSTAT64 TSAN_INTERCEPT(fstat64)
1391 #else
1392 #define TSAN_MAYBE_INTERCEPT_FSTAT64
1393 #endif
1395 TSAN_INTERCEPTOR(int, open, const char *name, int flags, int mode) {
1396 SCOPED_TSAN_INTERCEPTOR(open, name, flags, mode);
1397 READ_STRING(thr, pc, name, 0);
1398 int fd = REAL(open)(name, flags, mode);
1399 if (fd >= 0)
1400 FdFileCreate(thr, pc, fd);
1401 return fd;
1404 #if SANITIZER_LINUX
1405 TSAN_INTERCEPTOR(int, open64, const char *name, int flags, int mode) {
1406 SCOPED_TSAN_INTERCEPTOR(open64, name, flags, mode);
1407 READ_STRING(thr, pc, name, 0);
1408 int fd = REAL(open64)(name, flags, mode);
1409 if (fd >= 0)
1410 FdFileCreate(thr, pc, fd);
1411 return fd;
1413 #define TSAN_MAYBE_INTERCEPT_OPEN64 TSAN_INTERCEPT(open64)
1414 #else
1415 #define TSAN_MAYBE_INTERCEPT_OPEN64
1416 #endif
1418 TSAN_INTERCEPTOR(int, creat, const char *name, int mode) {
1419 SCOPED_TSAN_INTERCEPTOR(creat, name, mode);
1420 READ_STRING(thr, pc, name, 0);
1421 int fd = REAL(creat)(name, mode);
1422 if (fd >= 0)
1423 FdFileCreate(thr, pc, fd);
1424 return fd;
1427 #if SANITIZER_LINUX
1428 TSAN_INTERCEPTOR(int, creat64, const char *name, int mode) {
1429 SCOPED_TSAN_INTERCEPTOR(creat64, name, mode);
1430 READ_STRING(thr, pc, name, 0);
1431 int fd = REAL(creat64)(name, mode);
1432 if (fd >= 0)
1433 FdFileCreate(thr, pc, fd);
1434 return fd;
1436 #define TSAN_MAYBE_INTERCEPT_CREAT64 TSAN_INTERCEPT(creat64)
1437 #else
1438 #define TSAN_MAYBE_INTERCEPT_CREAT64
1439 #endif
1441 TSAN_INTERCEPTOR(int, dup, int oldfd) {
1442 SCOPED_TSAN_INTERCEPTOR(dup, oldfd);
1443 int newfd = REAL(dup)(oldfd);
1444 if (oldfd >= 0 && newfd >= 0 && newfd != oldfd)
1445 FdDup(thr, pc, oldfd, newfd, true);
1446 return newfd;
1449 TSAN_INTERCEPTOR(int, dup2, int oldfd, int newfd) {
1450 SCOPED_TSAN_INTERCEPTOR(dup2, oldfd, newfd);
1451 int newfd2 = REAL(dup2)(oldfd, newfd);
1452 if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd)
1453 FdDup(thr, pc, oldfd, newfd2, false);
1454 return newfd2;
1457 #if !SANITIZER_MAC
1458 TSAN_INTERCEPTOR(int, dup3, int oldfd, int newfd, int flags) {
1459 SCOPED_TSAN_INTERCEPTOR(dup3, oldfd, newfd, flags);
1460 int newfd2 = REAL(dup3)(oldfd, newfd, flags);
1461 if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd)
1462 FdDup(thr, pc, oldfd, newfd2, false);
1463 return newfd2;
1465 #endif
1467 #if SANITIZER_LINUX
1468 TSAN_INTERCEPTOR(int, eventfd, unsigned initval, int flags) {
1469 SCOPED_TSAN_INTERCEPTOR(eventfd, initval, flags);
1470 int fd = REAL(eventfd)(initval, flags);
1471 if (fd >= 0)
1472 FdEventCreate(thr, pc, fd);
1473 return fd;
1475 #define TSAN_MAYBE_INTERCEPT_EVENTFD TSAN_INTERCEPT(eventfd)
1476 #else
1477 #define TSAN_MAYBE_INTERCEPT_EVENTFD
1478 #endif
1480 #if SANITIZER_LINUX
1481 TSAN_INTERCEPTOR(int, signalfd, int fd, void *mask, int flags) {
1482 SCOPED_TSAN_INTERCEPTOR(signalfd, fd, mask, flags);
1483 if (fd >= 0)
1484 FdClose(thr, pc, fd);
1485 fd = REAL(signalfd)(fd, mask, flags);
1486 if (fd >= 0)
1487 FdSignalCreate(thr, pc, fd);
1488 return fd;
1490 #define TSAN_MAYBE_INTERCEPT_SIGNALFD TSAN_INTERCEPT(signalfd)
1491 #else
1492 #define TSAN_MAYBE_INTERCEPT_SIGNALFD
1493 #endif
1495 #if SANITIZER_LINUX
1496 TSAN_INTERCEPTOR(int, inotify_init, int fake) {
1497 SCOPED_TSAN_INTERCEPTOR(inotify_init, fake);
1498 int fd = REAL(inotify_init)(fake);
1499 if (fd >= 0)
1500 FdInotifyCreate(thr, pc, fd);
1501 return fd;
1503 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT TSAN_INTERCEPT(inotify_init)
1504 #else
1505 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT
1506 #endif
1508 #if SANITIZER_LINUX
1509 TSAN_INTERCEPTOR(int, inotify_init1, int flags) {
1510 SCOPED_TSAN_INTERCEPTOR(inotify_init1, flags);
1511 int fd = REAL(inotify_init1)(flags);
1512 if (fd >= 0)
1513 FdInotifyCreate(thr, pc, fd);
1514 return fd;
1516 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1 TSAN_INTERCEPT(inotify_init1)
1517 #else
1518 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1
1519 #endif
1521 TSAN_INTERCEPTOR(int, socket, int domain, int type, int protocol) {
1522 SCOPED_TSAN_INTERCEPTOR(socket, domain, type, protocol);
1523 int fd = REAL(socket)(domain, type, protocol);
1524 if (fd >= 0)
1525 FdSocketCreate(thr, pc, fd);
1526 return fd;
1529 TSAN_INTERCEPTOR(int, socketpair, int domain, int type, int protocol, int *fd) {
1530 SCOPED_TSAN_INTERCEPTOR(socketpair, domain, type, protocol, fd);
1531 int res = REAL(socketpair)(domain, type, protocol, fd);
1532 if (res == 0 && fd[0] >= 0 && fd[1] >= 0)
1533 FdPipeCreate(thr, pc, fd[0], fd[1]);
1534 return res;
1537 TSAN_INTERCEPTOR(int, connect, int fd, void *addr, unsigned addrlen) {
1538 SCOPED_TSAN_INTERCEPTOR(connect, fd, addr, addrlen);
1539 FdSocketConnecting(thr, pc, fd);
1540 int res = REAL(connect)(fd, addr, addrlen);
1541 if (res == 0 && fd >= 0)
1542 FdSocketConnect(thr, pc, fd);
1543 return res;
1546 TSAN_INTERCEPTOR(int, bind, int fd, void *addr, unsigned addrlen) {
1547 SCOPED_TSAN_INTERCEPTOR(bind, fd, addr, addrlen);
1548 int res = REAL(bind)(fd, addr, addrlen);
1549 if (fd > 0 && res == 0)
1550 FdAccess(thr, pc, fd);
1551 return res;
1554 TSAN_INTERCEPTOR(int, listen, int fd, int backlog) {
1555 SCOPED_TSAN_INTERCEPTOR(listen, fd, backlog);
1556 int res = REAL(listen)(fd, backlog);
1557 if (fd > 0 && res == 0)
1558 FdAccess(thr, pc, fd);
1559 return res;
1562 TSAN_INTERCEPTOR(int, close, int fd) {
1563 SCOPED_TSAN_INTERCEPTOR(close, fd);
1564 if (fd >= 0)
1565 FdClose(thr, pc, fd);
1566 return REAL(close)(fd);
1569 #if SANITIZER_LINUX
1570 TSAN_INTERCEPTOR(int, __close, int fd) {
1571 SCOPED_TSAN_INTERCEPTOR(__close, fd);
1572 if (fd >= 0)
1573 FdClose(thr, pc, fd);
1574 return REAL(__close)(fd);
1576 #define TSAN_MAYBE_INTERCEPT___CLOSE TSAN_INTERCEPT(__close)
1577 #else
1578 #define TSAN_MAYBE_INTERCEPT___CLOSE
1579 #endif
1581 // glibc guts
1582 #if SANITIZER_LINUX && !SANITIZER_ANDROID
1583 TSAN_INTERCEPTOR(void, __res_iclose, void *state, bool free_addr) {
1584 SCOPED_TSAN_INTERCEPTOR(__res_iclose, state, free_addr);
1585 int fds[64];
1586 int cnt = ExtractResolvFDs(state, fds, ARRAY_SIZE(fds));
1587 for (int i = 0; i < cnt; i++) {
1588 if (fds[i] > 0)
1589 FdClose(thr, pc, fds[i]);
1591 REAL(__res_iclose)(state, free_addr);
1593 #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE TSAN_INTERCEPT(__res_iclose)
1594 #else
1595 #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE
1596 #endif
1598 TSAN_INTERCEPTOR(int, pipe, int *pipefd) {
1599 SCOPED_TSAN_INTERCEPTOR(pipe, pipefd);
1600 int res = REAL(pipe)(pipefd);
1601 if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0)
1602 FdPipeCreate(thr, pc, pipefd[0], pipefd[1]);
1603 return res;
1606 #if !SANITIZER_MAC
1607 TSAN_INTERCEPTOR(int, pipe2, int *pipefd, int flags) {
1608 SCOPED_TSAN_INTERCEPTOR(pipe2, pipefd, flags);
1609 int res = REAL(pipe2)(pipefd, flags);
1610 if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0)
1611 FdPipeCreate(thr, pc, pipefd[0], pipefd[1]);
1612 return res;
1614 #endif
1616 TSAN_INTERCEPTOR(int, unlink, char *path) {
1617 SCOPED_TSAN_INTERCEPTOR(unlink, path);
1618 Release(thr, pc, File2addr(path));
1619 int res = REAL(unlink)(path);
1620 return res;
1623 TSAN_INTERCEPTOR(void*, tmpfile, int fake) {
1624 SCOPED_TSAN_INTERCEPTOR(tmpfile, fake);
1625 void *res = REAL(tmpfile)(fake);
1626 if (res) {
1627 int fd = fileno_unlocked(res);
1628 if (fd >= 0)
1629 FdFileCreate(thr, pc, fd);
1631 return res;
1634 #if SANITIZER_LINUX
1635 TSAN_INTERCEPTOR(void*, tmpfile64, int fake) {
1636 SCOPED_TSAN_INTERCEPTOR(tmpfile64, fake);
1637 void *res = REAL(tmpfile64)(fake);
1638 if (res) {
1639 int fd = fileno_unlocked(res);
1640 if (fd >= 0)
1641 FdFileCreate(thr, pc, fd);
1643 return res;
1645 #define TSAN_MAYBE_INTERCEPT_TMPFILE64 TSAN_INTERCEPT(tmpfile64)
1646 #else
1647 #define TSAN_MAYBE_INTERCEPT_TMPFILE64
1648 #endif
1650 TSAN_INTERCEPTOR(uptr, fread, void *ptr, uptr size, uptr nmemb, void *f) {
1651 // libc file streams can call user-supplied functions, see fopencookie.
1653 SCOPED_TSAN_INTERCEPTOR(fread, ptr, size, nmemb, f);
1654 MemoryAccessRange(thr, pc, (uptr)ptr, size * nmemb, true);
1656 return REAL(fread)(ptr, size, nmemb, f);
1659 TSAN_INTERCEPTOR(uptr, fwrite, const void *p, uptr size, uptr nmemb, void *f) {
1660 // libc file streams can call user-supplied functions, see fopencookie.
1662 SCOPED_TSAN_INTERCEPTOR(fwrite, p, size, nmemb, f);
1663 MemoryAccessRange(thr, pc, (uptr)p, size * nmemb, false);
1665 return REAL(fwrite)(p, size, nmemb, f);
1668 static void FlushStreams() {
1669 // Flushing all the streams here may freeze the process if a child thread is
1670 // performing file stream operations at the same time.
1671 REAL(fflush)(stdout);
1672 REAL(fflush)(stderr);
1675 TSAN_INTERCEPTOR(void, abort, int fake) {
1676 SCOPED_TSAN_INTERCEPTOR(abort, fake);
1677 FlushStreams();
1678 REAL(abort)(fake);
1681 TSAN_INTERCEPTOR(int, puts, const char *s) {
1682 SCOPED_TSAN_INTERCEPTOR(puts, s);
1683 MemoryAccessRange(thr, pc, (uptr)s, internal_strlen(s), false);
1684 return REAL(puts)(s);
1687 TSAN_INTERCEPTOR(int, rmdir, char *path) {
1688 SCOPED_TSAN_INTERCEPTOR(rmdir, path);
1689 Release(thr, pc, Dir2addr(path));
1690 int res = REAL(rmdir)(path);
1691 return res;
1694 TSAN_INTERCEPTOR(int, closedir, void *dirp) {
1695 SCOPED_TSAN_INTERCEPTOR(closedir, dirp);
1696 if (dirp) {
1697 int fd = dirfd(dirp);
1698 FdClose(thr, pc, fd);
1700 return REAL(closedir)(dirp);
1703 #if SANITIZER_LINUX
1704 TSAN_INTERCEPTOR(int, epoll_create, int size) {
1705 SCOPED_TSAN_INTERCEPTOR(epoll_create, size);
1706 int fd = REAL(epoll_create)(size);
1707 if (fd >= 0)
1708 FdPollCreate(thr, pc, fd);
1709 return fd;
1712 TSAN_INTERCEPTOR(int, epoll_create1, int flags) {
1713 SCOPED_TSAN_INTERCEPTOR(epoll_create1, flags);
1714 int fd = REAL(epoll_create1)(flags);
1715 if (fd >= 0)
1716 FdPollCreate(thr, pc, fd);
1717 return fd;
1720 TSAN_INTERCEPTOR(int, epoll_ctl, int epfd, int op, int fd, void *ev) {
1721 SCOPED_TSAN_INTERCEPTOR(epoll_ctl, epfd, op, fd, ev);
1722 if (epfd >= 0)
1723 FdAccess(thr, pc, epfd);
1724 if (epfd >= 0 && fd >= 0)
1725 FdAccess(thr, pc, fd);
1726 if (op == EPOLL_CTL_ADD && epfd >= 0)
1727 FdRelease(thr, pc, epfd);
1728 int res = REAL(epoll_ctl)(epfd, op, fd, ev);
1729 return res;
1732 TSAN_INTERCEPTOR(int, epoll_wait, int epfd, void *ev, int cnt, int timeout) {
1733 SCOPED_TSAN_INTERCEPTOR(epoll_wait, epfd, ev, cnt, timeout);
1734 if (epfd >= 0)
1735 FdAccess(thr, pc, epfd);
1736 int res = BLOCK_REAL(epoll_wait)(epfd, ev, cnt, timeout);
1737 if (res > 0 && epfd >= 0)
1738 FdAcquire(thr, pc, epfd);
1739 return res;
1742 TSAN_INTERCEPTOR(int, epoll_pwait, int epfd, void *ev, int cnt, int timeout,
1743 void *sigmask) {
1744 SCOPED_TSAN_INTERCEPTOR(epoll_pwait, epfd, ev, cnt, timeout, sigmask);
1745 if (epfd >= 0)
1746 FdAccess(thr, pc, epfd);
1747 int res = BLOCK_REAL(epoll_pwait)(epfd, ev, cnt, timeout, sigmask);
1748 if (res > 0 && epfd >= 0)
1749 FdAcquire(thr, pc, epfd);
1750 return res;
1753 #define TSAN_MAYBE_INTERCEPT_EPOLL \
1754 TSAN_INTERCEPT(epoll_create); \
1755 TSAN_INTERCEPT(epoll_create1); \
1756 TSAN_INTERCEPT(epoll_ctl); \
1757 TSAN_INTERCEPT(epoll_wait); \
1758 TSAN_INTERCEPT(epoll_pwait)
1759 #else
1760 #define TSAN_MAYBE_INTERCEPT_EPOLL
1761 #endif
1763 // The following functions are intercepted merely to process pending signals.
1764 // If program blocks signal X, we must deliver the signal before the function
1765 // returns. Similarly, if program unblocks a signal (or returns from sigsuspend)
1766 // it's better to deliver the signal straight away.
1767 TSAN_INTERCEPTOR(int, sigsuspend, const __sanitizer_sigset_t *mask) {
1768 SCOPED_TSAN_INTERCEPTOR(sigsuspend, mask);
1769 return REAL(sigsuspend)(mask);
1772 TSAN_INTERCEPTOR(int, sigblock, int mask) {
1773 SCOPED_TSAN_INTERCEPTOR(sigblock, mask);
1774 return REAL(sigblock)(mask);
1777 TSAN_INTERCEPTOR(int, sigsetmask, int mask) {
1778 SCOPED_TSAN_INTERCEPTOR(sigsetmask, mask);
1779 return REAL(sigsetmask)(mask);
1782 TSAN_INTERCEPTOR(int, pthread_sigmask, int how, const __sanitizer_sigset_t *set,
1783 __sanitizer_sigset_t *oldset) {
1784 SCOPED_TSAN_INTERCEPTOR(pthread_sigmask, how, set, oldset);
1785 return REAL(pthread_sigmask)(how, set, oldset);
1788 namespace __tsan {
1790 static void CallUserSignalHandler(ThreadState *thr, bool sync, bool acquire,
1791 bool sigact, int sig, my_siginfo_t *info, void *uctx) {
1792 if (acquire)
1793 Acquire(thr, 0, (uptr)&sigactions[sig]);
1794 // Signals are generally asynchronous, so if we receive a signals when
1795 // ignores are enabled we should disable ignores. This is critical for sync
1796 // and interceptors, because otherwise we can miss syncronization and report
1797 // false races.
1798 int ignore_reads_and_writes = thr->ignore_reads_and_writes;
1799 int ignore_interceptors = thr->ignore_interceptors;
1800 int ignore_sync = thr->ignore_sync;
1801 if (!ctx->after_multithreaded_fork) {
1802 thr->ignore_reads_and_writes = 0;
1803 thr->fast_state.ClearIgnoreBit();
1804 thr->ignore_interceptors = 0;
1805 thr->ignore_sync = 0;
1807 // Ensure that the handler does not spoil errno.
1808 const int saved_errno = errno;
1809 errno = 99;
1810 // This code races with sigaction. Be careful to not read sa_sigaction twice.
1811 // Also need to remember pc for reporting before the call,
1812 // because the handler can reset it.
1813 volatile uptr pc = sigact ?
1814 (uptr)sigactions[sig].sa_sigaction :
1815 (uptr)sigactions[sig].sa_handler;
1816 if (pc != (uptr)SIG_DFL && pc != (uptr)SIG_IGN) {
1817 if (sigact)
1818 ((sigactionhandler_t)pc)(sig, info, uctx);
1819 else
1820 ((sighandler_t)pc)(sig);
1822 if (!ctx->after_multithreaded_fork) {
1823 thr->ignore_reads_and_writes = ignore_reads_and_writes;
1824 if (ignore_reads_and_writes)
1825 thr->fast_state.SetIgnoreBit();
1826 thr->ignore_interceptors = ignore_interceptors;
1827 thr->ignore_sync = ignore_sync;
1829 // We do not detect errno spoiling for SIGTERM,
1830 // because some SIGTERM handlers do spoil errno but reraise SIGTERM,
1831 // tsan reports false positive in such case.
1832 // It's difficult to properly detect this situation (reraise),
1833 // because in async signal processing case (when handler is called directly
1834 // from rtl_generic_sighandler) we have not yet received the reraised
1835 // signal; and it looks too fragile to intercept all ways to reraise a signal.
1836 if (flags()->report_bugs && !sync && sig != SIGTERM && errno != 99) {
1837 VarSizeStackTrace stack;
1838 // StackTrace::GetNestInstructionPc(pc) is used because return address is
1839 // expected, OutputReport() will undo this.
1840 ObtainCurrentStack(thr, StackTrace::GetNextInstructionPc(pc), &stack);
1841 ThreadRegistryLock l(ctx->thread_registry);
1842 ScopedReport rep(ReportTypeErrnoInSignal);
1843 if (!IsFiredSuppression(ctx, ReportTypeErrnoInSignal, stack)) {
1844 rep.AddStack(stack, true);
1845 OutputReport(thr, rep);
1848 errno = saved_errno;
1851 void ProcessPendingSignals(ThreadState *thr) {
1852 ThreadSignalContext *sctx = SigCtx(thr);
1853 if (sctx == 0 ||
1854 atomic_load(&sctx->have_pending_signals, memory_order_relaxed) == 0)
1855 return;
1856 atomic_store(&sctx->have_pending_signals, 0, memory_order_relaxed);
1857 atomic_fetch_add(&thr->in_signal_handler, 1, memory_order_relaxed);
1858 internal_sigfillset(&sctx->emptyset);
1859 int res = REAL(pthread_sigmask)(SIG_SETMASK, &sctx->emptyset, &sctx->oldset);
1860 CHECK_EQ(res, 0);
1861 for (int sig = 0; sig < kSigCount; sig++) {
1862 SignalDesc *signal = &sctx->pending_signals[sig];
1863 if (signal->armed) {
1864 signal->armed = false;
1865 CallUserSignalHandler(thr, false, true, signal->sigaction, sig,
1866 &signal->siginfo, &signal->ctx);
1869 res = REAL(pthread_sigmask)(SIG_SETMASK, &sctx->oldset, 0);
1870 CHECK_EQ(res, 0);
1871 atomic_fetch_add(&thr->in_signal_handler, -1, memory_order_relaxed);
1874 } // namespace __tsan
1876 static bool is_sync_signal(ThreadSignalContext *sctx, int sig) {
1877 return sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
1878 sig == SIGABRT || sig == SIGFPE || sig == SIGPIPE || sig == SIGSYS ||
1879 // If we are sending signal to ourselves, we must process it now.
1880 (sctx && sig == sctx->int_signal_send);
1883 void ALWAYS_INLINE rtl_generic_sighandler(bool sigact, int sig,
1884 my_siginfo_t *info, void *ctx) {
1885 ThreadState *thr = cur_thread();
1886 ThreadSignalContext *sctx = SigCtx(thr);
1887 if (sig < 0 || sig >= kSigCount) {
1888 VPrintf(1, "ThreadSanitizer: ignoring signal %d\n", sig);
1889 return;
1891 // Don't mess with synchronous signals.
1892 const bool sync = is_sync_signal(sctx, sig);
1893 if (sync ||
1894 // If we are in blocking function, we can safely process it now
1895 // (but check if we are in a recursive interceptor,
1896 // i.e. pthread_join()->munmap()).
1897 (sctx && atomic_load(&sctx->in_blocking_func, memory_order_relaxed))) {
1898 atomic_fetch_add(&thr->in_signal_handler, 1, memory_order_relaxed);
1899 if (sctx && atomic_load(&sctx->in_blocking_func, memory_order_relaxed)) {
1900 atomic_store(&sctx->in_blocking_func, 0, memory_order_relaxed);
1901 CallUserSignalHandler(thr, sync, true, sigact, sig, info, ctx);
1902 atomic_store(&sctx->in_blocking_func, 1, memory_order_relaxed);
1903 } else {
1904 // Be very conservative with when we do acquire in this case.
1905 // It's unsafe to do acquire in async handlers, because ThreadState
1906 // can be in inconsistent state.
1907 // SIGSYS looks relatively safe -- it's synchronous and can actually
1908 // need some global state.
1909 bool acq = (sig == SIGSYS);
1910 CallUserSignalHandler(thr, sync, acq, sigact, sig, info, ctx);
1912 atomic_fetch_add(&thr->in_signal_handler, -1, memory_order_relaxed);
1913 return;
1916 if (sctx == 0)
1917 return;
1918 SignalDesc *signal = &sctx->pending_signals[sig];
1919 if (signal->armed == false) {
1920 signal->armed = true;
1921 signal->sigaction = sigact;
1922 if (info)
1923 internal_memcpy(&signal->siginfo, info, sizeof(*info));
1924 if (ctx)
1925 internal_memcpy(&signal->ctx, ctx, sizeof(signal->ctx));
1926 atomic_store(&sctx->have_pending_signals, 1, memory_order_relaxed);
1930 static void rtl_sighandler(int sig) {
1931 rtl_generic_sighandler(false, sig, 0, 0);
1934 static void rtl_sigaction(int sig, my_siginfo_t *info, void *ctx) {
1935 rtl_generic_sighandler(true, sig, info, ctx);
1938 TSAN_INTERCEPTOR(int, sigaction, int sig, sigaction_t *act, sigaction_t *old) {
1939 // Note: if we call REAL(sigaction) directly for any reason without proxying
1940 // the signal handler through rtl_sigaction, very bad things will happen.
1941 // The handler will run synchronously and corrupt tsan per-thread state.
1942 SCOPED_INTERCEPTOR_RAW(sigaction, sig, act, old);
1943 if (old)
1944 internal_memcpy(old, &sigactions[sig], sizeof(*old));
1945 if (act == 0)
1946 return 0;
1947 // Copy act into sigactions[sig].
1948 // Can't use struct copy, because compiler can emit call to memcpy.
1949 // Can't use internal_memcpy, because it copies byte-by-byte,
1950 // and signal handler reads the sa_handler concurrently. It it can read
1951 // some bytes from old value and some bytes from new value.
1952 // Use volatile to prevent insertion of memcpy.
1953 sigactions[sig].sa_handler = *(volatile sighandler_t*)&act->sa_handler;
1954 sigactions[sig].sa_flags = *(volatile int*)&act->sa_flags;
1955 internal_memcpy(&sigactions[sig].sa_mask, &act->sa_mask,
1956 sizeof(sigactions[sig].sa_mask));
1957 #if !SANITIZER_FREEBSD && !SANITIZER_MAC
1958 sigactions[sig].sa_restorer = act->sa_restorer;
1959 #endif
1960 sigaction_t newact;
1961 internal_memcpy(&newact, act, sizeof(newact));
1962 internal_sigfillset(&newact.sa_mask);
1963 if (act->sa_handler != SIG_IGN && act->sa_handler != SIG_DFL) {
1964 if (newact.sa_flags & SA_SIGINFO)
1965 newact.sa_sigaction = rtl_sigaction;
1966 else
1967 newact.sa_handler = rtl_sighandler;
1969 ReleaseStore(thr, pc, (uptr)&sigactions[sig]);
1970 int res = REAL(sigaction)(sig, &newact, 0);
1971 return res;
1974 TSAN_INTERCEPTOR(sighandler_t, signal, int sig, sighandler_t h) {
1975 sigaction_t act;
1976 act.sa_handler = h;
1977 internal_memset(&act.sa_mask, -1, sizeof(act.sa_mask));
1978 act.sa_flags = 0;
1979 sigaction_t old;
1980 int res = sigaction(sig, &act, &old);
1981 if (res)
1982 return SIG_ERR;
1983 return old.sa_handler;
1986 TSAN_INTERCEPTOR(int, raise, int sig) {
1987 SCOPED_TSAN_INTERCEPTOR(raise, sig);
1988 ThreadSignalContext *sctx = SigCtx(thr);
1989 CHECK_NE(sctx, 0);
1990 int prev = sctx->int_signal_send;
1991 sctx->int_signal_send = sig;
1992 int res = REAL(raise)(sig);
1993 CHECK_EQ(sctx->int_signal_send, sig);
1994 sctx->int_signal_send = prev;
1995 return res;
1998 TSAN_INTERCEPTOR(int, kill, int pid, int sig) {
1999 SCOPED_TSAN_INTERCEPTOR(kill, pid, sig);
2000 ThreadSignalContext *sctx = SigCtx(thr);
2001 CHECK_NE(sctx, 0);
2002 int prev = sctx->int_signal_send;
2003 if (pid == (int)internal_getpid()) {
2004 sctx->int_signal_send = sig;
2006 int res = REAL(kill)(pid, sig);
2007 if (pid == (int)internal_getpid()) {
2008 CHECK_EQ(sctx->int_signal_send, sig);
2009 sctx->int_signal_send = prev;
2011 return res;
2014 TSAN_INTERCEPTOR(int, pthread_kill, void *tid, int sig) {
2015 SCOPED_TSAN_INTERCEPTOR(pthread_kill, tid, sig);
2016 ThreadSignalContext *sctx = SigCtx(thr);
2017 CHECK_NE(sctx, 0);
2018 int prev = sctx->int_signal_send;
2019 if (tid == pthread_self()) {
2020 sctx->int_signal_send = sig;
2022 int res = REAL(pthread_kill)(tid, sig);
2023 if (tid == pthread_self()) {
2024 CHECK_EQ(sctx->int_signal_send, sig);
2025 sctx->int_signal_send = prev;
2027 return res;
2030 TSAN_INTERCEPTOR(int, gettimeofday, void *tv, void *tz) {
2031 SCOPED_TSAN_INTERCEPTOR(gettimeofday, tv, tz);
2032 // It's intercepted merely to process pending signals.
2033 return REAL(gettimeofday)(tv, tz);
2036 TSAN_INTERCEPTOR(int, getaddrinfo, void *node, void *service,
2037 void *hints, void *rv) {
2038 SCOPED_TSAN_INTERCEPTOR(getaddrinfo, node, service, hints, rv);
2039 // We miss atomic synchronization in getaddrinfo,
2040 // and can report false race between malloc and free
2041 // inside of getaddrinfo. So ignore memory accesses.
2042 ThreadIgnoreBegin(thr, pc);
2043 int res = REAL(getaddrinfo)(node, service, hints, rv);
2044 ThreadIgnoreEnd(thr, pc);
2045 return res;
2048 TSAN_INTERCEPTOR(int, fork, int fake) {
2049 if (cur_thread()->in_symbolizer)
2050 return REAL(fork)(fake);
2051 SCOPED_INTERCEPTOR_RAW(fork, fake);
2052 ForkBefore(thr, pc);
2053 int pid;
2055 // On OS X, REAL(fork) can call intercepted functions (OSSpinLockLock), and
2056 // we'll assert in CheckNoLocks() unless we ignore interceptors.
2057 ScopedIgnoreInterceptors ignore;
2058 pid = REAL(fork)(fake);
2060 if (pid == 0) {
2061 // child
2062 ForkChildAfter(thr, pc);
2063 FdOnFork(thr, pc);
2064 } else if (pid > 0) {
2065 // parent
2066 ForkParentAfter(thr, pc);
2067 } else {
2068 // error
2069 ForkParentAfter(thr, pc);
2071 return pid;
2074 TSAN_INTERCEPTOR(int, vfork, int fake) {
2075 // Some programs (e.g. openjdk) call close for all file descriptors
2076 // in the child process. Under tsan it leads to false positives, because
2077 // address space is shared, so the parent process also thinks that
2078 // the descriptors are closed (while they are actually not).
2079 // This leads to false positives due to missed synchronization.
2080 // Strictly saying this is undefined behavior, because vfork child is not
2081 // allowed to call any functions other than exec/exit. But this is what
2082 // openjdk does, so we want to handle it.
2083 // We could disable interceptors in the child process. But it's not possible
2084 // to simply intercept and wrap vfork, because vfork child is not allowed
2085 // to return from the function that calls vfork, and that's exactly what
2086 // we would do. So this would require some assembly trickery as well.
2087 // Instead we simply turn vfork into fork.
2088 return WRAP(fork)(fake);
2091 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2092 typedef int (*dl_iterate_phdr_cb_t)(__sanitizer_dl_phdr_info *info, SIZE_T size,
2093 void *data);
2094 struct dl_iterate_phdr_data {
2095 ThreadState *thr;
2096 uptr pc;
2097 dl_iterate_phdr_cb_t cb;
2098 void *data;
2101 static bool IsAppNotRodata(uptr addr) {
2102 return IsAppMem(addr) && *(u64*)MemToShadow(addr) != kShadowRodata;
2105 static int dl_iterate_phdr_cb(__sanitizer_dl_phdr_info *info, SIZE_T size,
2106 void *data) {
2107 dl_iterate_phdr_data *cbdata = (dl_iterate_phdr_data *)data;
2108 // dlopen/dlclose allocate/free dynamic-linker-internal memory, which is later
2109 // accessible in dl_iterate_phdr callback. But we don't see synchronization
2110 // inside of dynamic linker, so we "unpoison" it here in order to not
2111 // produce false reports. Ignoring malloc/free in dlopen/dlclose is not enough
2112 // because some libc functions call __libc_dlopen.
2113 if (info && IsAppNotRodata((uptr)info->dlpi_name))
2114 MemoryResetRange(cbdata->thr, cbdata->pc, (uptr)info->dlpi_name,
2115 internal_strlen(info->dlpi_name));
2116 int res = cbdata->cb(info, size, cbdata->data);
2117 // Perform the check one more time in case info->dlpi_name was overwritten
2118 // by user callback.
2119 if (info && IsAppNotRodata((uptr)info->dlpi_name))
2120 MemoryResetRange(cbdata->thr, cbdata->pc, (uptr)info->dlpi_name,
2121 internal_strlen(info->dlpi_name));
2122 return res;
2125 TSAN_INTERCEPTOR(int, dl_iterate_phdr, dl_iterate_phdr_cb_t cb, void *data) {
2126 SCOPED_TSAN_INTERCEPTOR(dl_iterate_phdr, cb, data);
2127 dl_iterate_phdr_data cbdata;
2128 cbdata.thr = thr;
2129 cbdata.pc = pc;
2130 cbdata.cb = cb;
2131 cbdata.data = data;
2132 int res = REAL(dl_iterate_phdr)(dl_iterate_phdr_cb, &cbdata);
2133 return res;
2135 #endif
2137 static int OnExit(ThreadState *thr) {
2138 int status = Finalize(thr);
2139 FlushStreams();
2140 return status;
2143 struct TsanInterceptorContext {
2144 ThreadState *thr;
2145 const uptr caller_pc;
2146 const uptr pc;
2149 #if !SANITIZER_MAC
2150 static void HandleRecvmsg(ThreadState *thr, uptr pc,
2151 __sanitizer_msghdr *msg) {
2152 int fds[64];
2153 int cnt = ExtractRecvmsgFDs(msg, fds, ARRAY_SIZE(fds));
2154 for (int i = 0; i < cnt; i++)
2155 FdEventCreate(thr, pc, fds[i]);
2157 #endif
2159 #include "sanitizer_common/sanitizer_platform_interceptors.h"
2160 // Causes interceptor recursion (getaddrinfo() and fopen())
2161 #undef SANITIZER_INTERCEPT_GETADDRINFO
2162 // There interceptors do not seem to be strictly necessary for tsan.
2163 // But we see cases where the interceptors consume 70% of execution time.
2164 // Memory blocks passed to fgetgrent_r are "written to" by tsan several times.
2165 // First, there is some recursion (getgrnam_r calls fgetgrent_r), and each
2166 // function "writes to" the buffer. Then, the same memory is "written to"
2167 // twice, first as buf and then as pwbufp (both of them refer to the same
2168 // addresses).
2169 #undef SANITIZER_INTERCEPT_GETPWENT
2170 #undef SANITIZER_INTERCEPT_GETPWENT_R
2171 #undef SANITIZER_INTERCEPT_FGETPWENT
2172 #undef SANITIZER_INTERCEPT_GETPWNAM_AND_FRIENDS
2173 #undef SANITIZER_INTERCEPT_GETPWNAM_R_AND_FRIENDS
2174 // We define our own.
2175 #if SANITIZER_INTERCEPT_TLS_GET_ADDR
2176 #define NEED_TLS_GET_ADDR
2177 #endif
2178 #undef SANITIZER_INTERCEPT_TLS_GET_ADDR
2180 #define COMMON_INTERCEPT_FUNCTION(name) INTERCEPT_FUNCTION(name)
2181 #define COMMON_INTERCEPT_FUNCTION_VER(name, ver) \
2182 INTERCEPT_FUNCTION_VER(name, ver)
2184 #define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \
2185 MemoryAccessRange(((TsanInterceptorContext *)ctx)->thr, \
2186 ((TsanInterceptorContext *)ctx)->pc, (uptr)ptr, size, \
2187 true)
2189 #define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) \
2190 MemoryAccessRange(((TsanInterceptorContext *) ctx)->thr, \
2191 ((TsanInterceptorContext *) ctx)->pc, (uptr) ptr, size, \
2192 false)
2194 #define COMMON_INTERCEPTOR_ENTER(ctx, func, ...) \
2195 SCOPED_TSAN_INTERCEPTOR(func, __VA_ARGS__); \
2196 TsanInterceptorContext _ctx = {thr, caller_pc, pc}; \
2197 ctx = (void *)&_ctx; \
2198 (void) ctx;
2200 #define COMMON_INTERCEPTOR_ENTER_NOIGNORE(ctx, func, ...) \
2201 SCOPED_INTERCEPTOR_RAW(func, __VA_ARGS__); \
2202 TsanInterceptorContext _ctx = {thr, caller_pc, pc}; \
2203 ctx = (void *)&_ctx; \
2204 (void) ctx;
2206 #define COMMON_INTERCEPTOR_FILE_OPEN(ctx, file, path) \
2207 Acquire(thr, pc, File2addr(path)); \
2208 if (file) { \
2209 int fd = fileno_unlocked(file); \
2210 if (fd >= 0) FdFileCreate(thr, pc, fd); \
2213 #define COMMON_INTERCEPTOR_FILE_CLOSE(ctx, file) \
2214 if (file) { \
2215 int fd = fileno_unlocked(file); \
2216 if (fd >= 0) FdClose(thr, pc, fd); \
2219 #define COMMON_INTERCEPTOR_LIBRARY_LOADED(filename, handle) \
2220 libignore()->OnLibraryLoaded(filename)
2222 #define COMMON_INTERCEPTOR_LIBRARY_UNLOADED() \
2223 libignore()->OnLibraryUnloaded()
2225 #define COMMON_INTERCEPTOR_ACQUIRE(ctx, u) \
2226 Acquire(((TsanInterceptorContext *) ctx)->thr, pc, u)
2228 #define COMMON_INTERCEPTOR_RELEASE(ctx, u) \
2229 Release(((TsanInterceptorContext *) ctx)->thr, pc, u)
2231 #define COMMON_INTERCEPTOR_DIR_ACQUIRE(ctx, path) \
2232 Acquire(((TsanInterceptorContext *) ctx)->thr, pc, Dir2addr(path))
2234 #define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \
2235 FdAcquire(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2237 #define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \
2238 FdRelease(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2240 #define COMMON_INTERCEPTOR_FD_ACCESS(ctx, fd) \
2241 FdAccess(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2243 #define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \
2244 FdSocketAccept(((TsanInterceptorContext *) ctx)->thr, pc, fd, newfd)
2246 #define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) \
2247 ThreadSetName(((TsanInterceptorContext *) ctx)->thr, name)
2249 #define COMMON_INTERCEPTOR_SET_PTHREAD_NAME(ctx, thread, name) \
2250 __tsan::ctx->thread_registry->SetThreadNameByUserId(thread, name)
2252 #define COMMON_INTERCEPTOR_BLOCK_REAL(name) BLOCK_REAL(name)
2254 #define COMMON_INTERCEPTOR_ON_EXIT(ctx) \
2255 OnExit(((TsanInterceptorContext *) ctx)->thr)
2257 #define COMMON_INTERCEPTOR_MUTEX_LOCK(ctx, m) \
2258 MutexLock(((TsanInterceptorContext *)ctx)->thr, \
2259 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2261 #define COMMON_INTERCEPTOR_MUTEX_UNLOCK(ctx, m) \
2262 MutexUnlock(((TsanInterceptorContext *)ctx)->thr, \
2263 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2265 #define COMMON_INTERCEPTOR_MUTEX_REPAIR(ctx, m) \
2266 MutexRepair(((TsanInterceptorContext *)ctx)->thr, \
2267 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2269 #define COMMON_INTERCEPTOR_MUTEX_INVALID(ctx, m) \
2270 MutexInvalidAccess(((TsanInterceptorContext *)ctx)->thr, \
2271 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2273 #if !SANITIZER_MAC
2274 #define COMMON_INTERCEPTOR_HANDLE_RECVMSG(ctx, msg) \
2275 HandleRecvmsg(((TsanInterceptorContext *)ctx)->thr, \
2276 ((TsanInterceptorContext *)ctx)->pc, msg)
2277 #endif
2279 #define COMMON_INTERCEPTOR_GET_TLS_RANGE(begin, end) \
2280 if (TsanThread *t = GetCurrentThread()) { \
2281 *begin = t->tls_begin(); \
2282 *end = t->tls_end(); \
2283 } else { \
2284 *begin = *end = 0; \
2287 #define COMMON_INTERCEPTOR_USER_CALLBACK_START() \
2288 SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_START()
2290 #define COMMON_INTERCEPTOR_USER_CALLBACK_END() \
2291 SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_END()
2293 #include "sanitizer_common/sanitizer_common_interceptors.inc"
2295 #define TSAN_SYSCALL() \
2296 ThreadState *thr = cur_thread(); \
2297 if (thr->ignore_interceptors) \
2298 return; \
2299 ScopedSyscall scoped_syscall(thr) \
2300 /**/
2302 struct ScopedSyscall {
2303 ThreadState *thr;
2305 explicit ScopedSyscall(ThreadState *thr)
2306 : thr(thr) {
2307 Initialize(thr);
2310 ~ScopedSyscall() {
2311 ProcessPendingSignals(thr);
2315 #if !SANITIZER_FREEBSD && !SANITIZER_MAC
2316 static void syscall_access_range(uptr pc, uptr p, uptr s, bool write) {
2317 TSAN_SYSCALL();
2318 MemoryAccessRange(thr, pc, p, s, write);
2321 static void syscall_acquire(uptr pc, uptr addr) {
2322 TSAN_SYSCALL();
2323 Acquire(thr, pc, addr);
2324 DPrintf("syscall_acquire(%p)\n", addr);
2327 static void syscall_release(uptr pc, uptr addr) {
2328 TSAN_SYSCALL();
2329 DPrintf("syscall_release(%p)\n", addr);
2330 Release(thr, pc, addr);
2333 static void syscall_fd_close(uptr pc, int fd) {
2334 TSAN_SYSCALL();
2335 FdClose(thr, pc, fd);
2338 static USED void syscall_fd_acquire(uptr pc, int fd) {
2339 TSAN_SYSCALL();
2340 FdAcquire(thr, pc, fd);
2341 DPrintf("syscall_fd_acquire(%p)\n", fd);
2344 static USED void syscall_fd_release(uptr pc, int fd) {
2345 TSAN_SYSCALL();
2346 DPrintf("syscall_fd_release(%p)\n", fd);
2347 FdRelease(thr, pc, fd);
2350 static void syscall_pre_fork(uptr pc) {
2351 TSAN_SYSCALL();
2352 ForkBefore(thr, pc);
2355 static void syscall_post_fork(uptr pc, int pid) {
2356 TSAN_SYSCALL();
2357 if (pid == 0) {
2358 // child
2359 ForkChildAfter(thr, pc);
2360 FdOnFork(thr, pc);
2361 } else if (pid > 0) {
2362 // parent
2363 ForkParentAfter(thr, pc);
2364 } else {
2365 // error
2366 ForkParentAfter(thr, pc);
2369 #endif
2371 #define COMMON_SYSCALL_PRE_READ_RANGE(p, s) \
2372 syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), false)
2374 #define COMMON_SYSCALL_PRE_WRITE_RANGE(p, s) \
2375 syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), true)
2377 #define COMMON_SYSCALL_POST_READ_RANGE(p, s) \
2378 do { \
2379 (void)(p); \
2380 (void)(s); \
2381 } while (false)
2383 #define COMMON_SYSCALL_POST_WRITE_RANGE(p, s) \
2384 do { \
2385 (void)(p); \
2386 (void)(s); \
2387 } while (false)
2389 #define COMMON_SYSCALL_ACQUIRE(addr) \
2390 syscall_acquire(GET_CALLER_PC(), (uptr)(addr))
2392 #define COMMON_SYSCALL_RELEASE(addr) \
2393 syscall_release(GET_CALLER_PC(), (uptr)(addr))
2395 #define COMMON_SYSCALL_FD_CLOSE(fd) syscall_fd_close(GET_CALLER_PC(), fd)
2397 #define COMMON_SYSCALL_FD_ACQUIRE(fd) syscall_fd_acquire(GET_CALLER_PC(), fd)
2399 #define COMMON_SYSCALL_FD_RELEASE(fd) syscall_fd_release(GET_CALLER_PC(), fd)
2401 #define COMMON_SYSCALL_PRE_FORK() \
2402 syscall_pre_fork(GET_CALLER_PC())
2404 #define COMMON_SYSCALL_POST_FORK(res) \
2405 syscall_post_fork(GET_CALLER_PC(), res)
2407 #include "sanitizer_common/sanitizer_common_syscalls.inc"
2409 #ifdef NEED_TLS_GET_ADDR
2410 // Define own interceptor instead of sanitizer_common's for three reasons:
2411 // 1. It must not process pending signals.
2412 // Signal handlers may contain MOVDQA instruction (see below).
2413 // 2. It must be as simple as possible to not contain MOVDQA.
2414 // 3. Sanitizer_common version uses COMMON_INTERCEPTOR_INITIALIZE_RANGE which
2415 // is empty for tsan (meant only for msan).
2416 // Note: __tls_get_addr can be called with mis-aligned stack due to:
2417 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58066
2418 // So the interceptor must work with mis-aligned stack, in particular, does not
2419 // execute MOVDQA with stack addresses.
2420 TSAN_INTERCEPTOR(void *, __tls_get_addr, void *arg) {
2421 void *res = REAL(__tls_get_addr)(arg);
2422 ThreadState *thr = cur_thread();
2423 if (!thr)
2424 return res;
2425 DTLS::DTV *dtv = DTLS_on_tls_get_addr(arg, res, thr->tls_addr, thr->tls_size);
2426 if (!dtv)
2427 return res;
2428 // New DTLS block has been allocated.
2429 MemoryResetRange(thr, 0, dtv->beg, dtv->size);
2430 return res;
2432 #endif
2434 namespace __tsan {
2436 static void finalize(void *arg) {
2437 ThreadState *thr = cur_thread();
2438 int status = Finalize(thr);
2439 // Make sure the output is not lost.
2440 FlushStreams();
2441 if (status)
2442 Die();
2445 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2446 static void unreachable() {
2447 Report("FATAL: ThreadSanitizer: unreachable called\n");
2448 Die();
2450 #endif
2452 void InitializeInterceptors() {
2453 #if !SANITIZER_MAC
2454 // We need to setup it early, because functions like dlsym() can call it.
2455 REAL(memset) = internal_memset;
2456 REAL(memcpy) = internal_memcpy;
2457 #endif
2459 // Instruct libc malloc to consume less memory.
2460 #if SANITIZER_LINUX
2461 mallopt(1, 0); // M_MXFAST
2462 mallopt(-3, 32*1024); // M_MMAP_THRESHOLD
2463 #endif
2465 InitializeCommonInterceptors();
2467 #if !SANITIZER_MAC
2468 // We can not use TSAN_INTERCEPT to get setjmp addr,
2469 // because it does &setjmp and setjmp is not present in some versions of libc.
2470 using __interception::GetRealFunctionAddress;
2471 GetRealFunctionAddress("setjmp", (uptr*)&REAL(setjmp), 0, 0);
2472 GetRealFunctionAddress("_setjmp", (uptr*)&REAL(_setjmp), 0, 0);
2473 GetRealFunctionAddress("sigsetjmp", (uptr*)&REAL(sigsetjmp), 0, 0);
2474 GetRealFunctionAddress("__sigsetjmp", (uptr*)&REAL(__sigsetjmp), 0, 0);
2475 #endif
2477 TSAN_INTERCEPT(longjmp);
2478 TSAN_INTERCEPT(siglongjmp);
2480 TSAN_INTERCEPT(malloc);
2481 TSAN_INTERCEPT(__libc_memalign);
2482 TSAN_INTERCEPT(calloc);
2483 TSAN_INTERCEPT(realloc);
2484 TSAN_INTERCEPT(free);
2485 TSAN_INTERCEPT(cfree);
2486 TSAN_INTERCEPT(mmap);
2487 TSAN_MAYBE_INTERCEPT_MMAP64;
2488 TSAN_INTERCEPT(munmap);
2489 TSAN_MAYBE_INTERCEPT_MEMALIGN;
2490 TSAN_INTERCEPT(valloc);
2491 TSAN_MAYBE_INTERCEPT_PVALLOC;
2492 TSAN_INTERCEPT(posix_memalign);
2494 TSAN_INTERCEPT(strcpy); // NOLINT
2495 TSAN_INTERCEPT(strncpy);
2496 TSAN_INTERCEPT(strdup);
2498 TSAN_INTERCEPT(pthread_create);
2499 TSAN_INTERCEPT(pthread_join);
2500 TSAN_INTERCEPT(pthread_detach);
2502 TSAN_INTERCEPT_VER(pthread_cond_init, PTHREAD_ABI_BASE);
2503 TSAN_INTERCEPT_VER(pthread_cond_signal, PTHREAD_ABI_BASE);
2504 TSAN_INTERCEPT_VER(pthread_cond_broadcast, PTHREAD_ABI_BASE);
2505 TSAN_INTERCEPT_VER(pthread_cond_wait, PTHREAD_ABI_BASE);
2506 TSAN_INTERCEPT_VER(pthread_cond_timedwait, PTHREAD_ABI_BASE);
2507 TSAN_INTERCEPT_VER(pthread_cond_destroy, PTHREAD_ABI_BASE);
2509 TSAN_INTERCEPT(pthread_mutex_init);
2510 TSAN_INTERCEPT(pthread_mutex_destroy);
2511 TSAN_INTERCEPT(pthread_mutex_trylock);
2512 TSAN_INTERCEPT(pthread_mutex_timedlock);
2514 TSAN_INTERCEPT(pthread_spin_init);
2515 TSAN_INTERCEPT(pthread_spin_destroy);
2516 TSAN_INTERCEPT(pthread_spin_lock);
2517 TSAN_INTERCEPT(pthread_spin_trylock);
2518 TSAN_INTERCEPT(pthread_spin_unlock);
2520 TSAN_INTERCEPT(pthread_rwlock_init);
2521 TSAN_INTERCEPT(pthread_rwlock_destroy);
2522 TSAN_INTERCEPT(pthread_rwlock_rdlock);
2523 TSAN_INTERCEPT(pthread_rwlock_tryrdlock);
2524 TSAN_INTERCEPT(pthread_rwlock_timedrdlock);
2525 TSAN_INTERCEPT(pthread_rwlock_wrlock);
2526 TSAN_INTERCEPT(pthread_rwlock_trywrlock);
2527 TSAN_INTERCEPT(pthread_rwlock_timedwrlock);
2528 TSAN_INTERCEPT(pthread_rwlock_unlock);
2530 TSAN_INTERCEPT(pthread_barrier_init);
2531 TSAN_INTERCEPT(pthread_barrier_destroy);
2532 TSAN_INTERCEPT(pthread_barrier_wait);
2534 TSAN_INTERCEPT(pthread_once);
2536 TSAN_INTERCEPT(fstat);
2537 TSAN_MAYBE_INTERCEPT___FXSTAT;
2538 TSAN_MAYBE_INTERCEPT_FSTAT64;
2539 TSAN_MAYBE_INTERCEPT___FXSTAT64;
2540 TSAN_INTERCEPT(open);
2541 TSAN_MAYBE_INTERCEPT_OPEN64;
2542 TSAN_INTERCEPT(creat);
2543 TSAN_MAYBE_INTERCEPT_CREAT64;
2544 TSAN_INTERCEPT(dup);
2545 TSAN_INTERCEPT(dup2);
2546 TSAN_INTERCEPT(dup3);
2547 TSAN_MAYBE_INTERCEPT_EVENTFD;
2548 TSAN_MAYBE_INTERCEPT_SIGNALFD;
2549 TSAN_MAYBE_INTERCEPT_INOTIFY_INIT;
2550 TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1;
2551 TSAN_INTERCEPT(socket);
2552 TSAN_INTERCEPT(socketpair);
2553 TSAN_INTERCEPT(connect);
2554 TSAN_INTERCEPT(bind);
2555 TSAN_INTERCEPT(listen);
2556 TSAN_MAYBE_INTERCEPT_EPOLL;
2557 TSAN_INTERCEPT(close);
2558 TSAN_MAYBE_INTERCEPT___CLOSE;
2559 TSAN_MAYBE_INTERCEPT___RES_ICLOSE;
2560 TSAN_INTERCEPT(pipe);
2561 TSAN_INTERCEPT(pipe2);
2563 TSAN_INTERCEPT(unlink);
2564 TSAN_INTERCEPT(tmpfile);
2565 TSAN_MAYBE_INTERCEPT_TMPFILE64;
2566 TSAN_INTERCEPT(fread);
2567 TSAN_INTERCEPT(fwrite);
2568 TSAN_INTERCEPT(abort);
2569 TSAN_INTERCEPT(puts);
2570 TSAN_INTERCEPT(rmdir);
2571 TSAN_INTERCEPT(closedir);
2573 TSAN_INTERCEPT(sigaction);
2574 TSAN_INTERCEPT(signal);
2575 TSAN_INTERCEPT(sigsuspend);
2576 TSAN_INTERCEPT(sigblock);
2577 TSAN_INTERCEPT(sigsetmask);
2578 TSAN_INTERCEPT(pthread_sigmask);
2579 TSAN_INTERCEPT(raise);
2580 TSAN_INTERCEPT(kill);
2581 TSAN_INTERCEPT(pthread_kill);
2582 TSAN_INTERCEPT(sleep);
2583 TSAN_INTERCEPT(usleep);
2584 TSAN_INTERCEPT(nanosleep);
2585 TSAN_INTERCEPT(gettimeofday);
2586 TSAN_INTERCEPT(getaddrinfo);
2588 TSAN_INTERCEPT(fork);
2589 TSAN_INTERCEPT(vfork);
2590 #if !SANITIZER_ANDROID
2591 TSAN_INTERCEPT(dl_iterate_phdr);
2592 #endif
2593 TSAN_INTERCEPT(on_exit);
2594 TSAN_INTERCEPT(__cxa_atexit);
2595 TSAN_INTERCEPT(_exit);
2597 #ifdef NEED_TLS_GET_ADDR
2598 TSAN_INTERCEPT(__tls_get_addr);
2599 #endif
2601 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2602 // Need to setup it, because interceptors check that the function is resolved.
2603 // But atexit is emitted directly into the module, so can't be resolved.
2604 REAL(atexit) = (int(*)(void(*)()))unreachable;
2605 #endif
2607 if (REAL(__cxa_atexit)(&finalize, 0, 0)) {
2608 Printf("ThreadSanitizer: failed to setup atexit callback\n");
2609 Die();
2612 #if !SANITIZER_MAC
2613 if (pthread_key_create(&g_thread_finalize_key, &thread_finalize)) {
2614 Printf("ThreadSanitizer: failed to create thread key\n");
2615 Die();
2617 #endif
2619 FdInit();
2622 } // namespace __tsan
2624 // Invisible barrier for tests.
2625 // There were several unsuccessful iterations for this functionality:
2626 // 1. Initially it was implemented in user code using
2627 // REAL(pthread_barrier_wait). But pthread_barrier_wait is not supported on
2628 // MacOS. Futexes are linux-specific for this matter.
2629 // 2. Then we switched to atomics+usleep(10). But usleep produced parasitic
2630 // "as-if synchronized via sleep" messages in reports which failed some
2631 // output tests.
2632 // 3. Then we switched to atomics+sched_yield. But this produced tons of tsan-
2633 // visible events, which lead to "failed to restore stack trace" failures.
2634 // Note that no_sanitize_thread attribute does not turn off atomic interception
2635 // so attaching it to the function defined in user code does not help.
2636 // That's why we now have what we have.
2637 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
2638 void __tsan_testonly_barrier_init(u64 *barrier, u32 count) {
2639 if (count >= (1 << 8)) {
2640 Printf("barrier_init: count is too large (%d)\n", count);
2641 Die();
2643 // 8 lsb is thread count, the remaining are count of entered threads.
2644 *barrier = count;
2647 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
2648 void __tsan_testonly_barrier_wait(u64 *barrier) {
2649 unsigned old = __atomic_fetch_add(barrier, 1 << 8, __ATOMIC_RELAXED);
2650 unsigned old_epoch = (old >> 8) / (old & 0xff);
2651 for (;;) {
2652 unsigned cur = __atomic_load_n(barrier, __ATOMIC_RELAXED);
2653 unsigned cur_epoch = (cur >> 8) / (cur & 0xff);
2654 if (cur_epoch != old_epoch)
2655 return;
2656 internal_sched_yield();