Daily bump.
[official-gcc.git] / libsanitizer / tsan / tsan_interceptors.cc
blob19a3b7b0643a2745b6c0493afff9d77416d2dd65
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 "interception/interception.h"
21 #include "tsan_interface.h"
22 #include "tsan_platform.h"
23 #include "tsan_suppressions.h"
24 #include "tsan_rtl.h"
25 #include "tsan_mman.h"
26 #include "tsan_fd.h"
28 using namespace __tsan; // NOLINT
30 const int kSigCount = 65;
32 struct my_siginfo_t {
33 // The size is determined by looking at sizeof of real siginfo_t on linux.
34 u64 opaque[128 / sizeof(u64)];
37 struct ucontext_t {
38 // The size is determined by looking at sizeof of real ucontext_t on linux.
39 u64 opaque[936 / sizeof(u64) + 1];
42 extern "C" int pthread_attr_init(void *attr);
43 extern "C" int pthread_attr_destroy(void *attr);
44 DECLARE_REAL(int, pthread_attr_getdetachstate, void *, void *)
45 extern "C" int pthread_attr_setstacksize(void *attr, uptr stacksize);
46 extern "C" int pthread_key_create(unsigned *key, void (*destructor)(void* v));
47 extern "C" int pthread_setspecific(unsigned key, const void *v);
48 extern "C" int pthread_mutexattr_gettype(void *a, int *type);
49 extern "C" int pthread_yield();
50 extern "C" int pthread_sigmask(int how, const __sanitizer_sigset_t *set,
51 __sanitizer_sigset_t *oldset);
52 // REAL(sigfillset) defined in common interceptors.
53 DECLARE_REAL(int, sigfillset, __sanitizer_sigset_t *set)
54 DECLARE_REAL(int, fflush, __sanitizer_FILE *fp)
55 extern "C" void *pthread_self();
56 extern "C" void _exit(int status);
57 extern "C" int *__errno_location();
58 extern "C" int fileno_unlocked(void *stream);
59 extern "C" void *__libc_malloc(uptr size);
60 extern "C" void *__libc_calloc(uptr size, uptr n);
61 extern "C" void *__libc_realloc(void *ptr, uptr size);
62 extern "C" void __libc_free(void *ptr);
63 extern "C" int mallopt(int param, int value);
64 extern __sanitizer_FILE *stdout, *stderr;
65 const int PTHREAD_MUTEX_RECURSIVE = 1;
66 const int PTHREAD_MUTEX_RECURSIVE_NP = 1;
67 const int EINVAL = 22;
68 const int EBUSY = 16;
69 const int EOWNERDEAD = 130;
70 const int EPOLL_CTL_ADD = 1;
71 const int SIGILL = 4;
72 const int SIGABRT = 6;
73 const int SIGFPE = 8;
74 const int SIGSEGV = 11;
75 const int SIGPIPE = 13;
76 const int SIGTERM = 15;
77 const int SIGBUS = 7;
78 const int SIGSYS = 31;
79 void *const MAP_FAILED = (void*)-1;
80 const int PTHREAD_BARRIER_SERIAL_THREAD = -1;
81 const int MAP_FIXED = 0x10;
82 typedef long long_t; // NOLINT
84 // From /usr/include/unistd.h
85 # define F_ULOCK 0 /* Unlock a previously locked region. */
86 # define F_LOCK 1 /* Lock a region for exclusive use. */
87 # define F_TLOCK 2 /* Test and lock a region for exclusive use. */
88 # define F_TEST 3 /* Test a region for other processes locks. */
90 typedef void (*sighandler_t)(int sig);
92 #define errno (*__errno_location())
94 struct sigaction_t {
95 union {
96 sighandler_t sa_handler;
97 void (*sa_sigaction)(int sig, my_siginfo_t *siginfo, void *uctx);
99 __sanitizer_sigset_t sa_mask;
100 int sa_flags;
101 void (*sa_restorer)();
104 const sighandler_t SIG_DFL = (sighandler_t)0;
105 const sighandler_t SIG_IGN = (sighandler_t)1;
106 const sighandler_t SIG_ERR = (sighandler_t)-1;
107 const int SA_SIGINFO = 4;
108 const int SIG_SETMASK = 2;
110 namespace std {
111 struct nothrow_t {};
112 } // namespace std
114 static sigaction_t sigactions[kSigCount];
116 namespace __tsan {
117 struct SignalDesc {
118 bool armed;
119 bool sigaction;
120 my_siginfo_t siginfo;
121 ucontext_t ctx;
124 struct SignalContext {
125 int in_blocking_func;
126 int int_signal_send;
127 int pending_signal_count;
128 SignalDesc pending_signals[kSigCount];
131 // The object is 64-byte aligned, because we want hot data to be located in
132 // a single cache line if possible (it's accessed in every interceptor).
133 static ALIGNED(64) char libignore_placeholder[sizeof(LibIgnore)];
134 static LibIgnore *libignore() {
135 return reinterpret_cast<LibIgnore*>(&libignore_placeholder[0]);
138 void InitializeLibIgnore() {
139 libignore()->Init(*GetSuppressionContext());
140 libignore()->OnLibraryLoaded(0);
143 } // namespace __tsan
145 static SignalContext *SigCtx(ThreadState *thr) {
146 SignalContext *ctx = (SignalContext*)thr->signal_ctx;
147 if (ctx == 0 && thr->is_alive) {
148 ctx = (SignalContext*)MmapOrDie(sizeof(*ctx), "SignalContext");
149 MemoryResetRange(thr, (uptr)&SigCtx, (uptr)ctx, sizeof(*ctx));
150 thr->signal_ctx = ctx;
152 return ctx;
155 static unsigned g_thread_finalize_key;
157 class ScopedInterceptor {
158 public:
159 ScopedInterceptor(ThreadState *thr, const char *fname, uptr pc);
160 ~ScopedInterceptor();
161 private:
162 ThreadState *const thr_;
163 const uptr pc_;
164 bool in_ignored_lib_;
167 ScopedInterceptor::ScopedInterceptor(ThreadState *thr, const char *fname,
168 uptr pc)
169 : thr_(thr)
170 , pc_(pc)
171 , in_ignored_lib_(false) {
172 if (!thr_->ignore_interceptors) {
173 Initialize(thr);
174 FuncEntry(thr, pc);
176 DPrintf("#%d: intercept %s()\n", thr_->tid, fname);
177 if (!thr_->in_ignored_lib && libignore()->IsIgnored(pc)) {
178 in_ignored_lib_ = true;
179 thr_->in_ignored_lib = true;
180 ThreadIgnoreBegin(thr_, pc_);
184 ScopedInterceptor::~ScopedInterceptor() {
185 if (in_ignored_lib_) {
186 thr_->in_ignored_lib = false;
187 ThreadIgnoreEnd(thr_, pc_);
189 if (!thr_->ignore_interceptors) {
190 ProcessPendingSignals(thr_);
191 FuncExit(thr_);
195 #define SCOPED_INTERCEPTOR_RAW(func, ...) \
196 ThreadState *thr = cur_thread(); \
197 const uptr caller_pc = GET_CALLER_PC(); \
198 ScopedInterceptor si(thr, #func, caller_pc); \
199 const uptr pc = __sanitizer::StackTrace::GetCurrentPc(); \
200 (void)pc; \
201 /**/
203 #define SCOPED_TSAN_INTERCEPTOR(func, ...) \
204 SCOPED_INTERCEPTOR_RAW(func, __VA_ARGS__); \
205 if (REAL(func) == 0) { \
206 Report("FATAL: ThreadSanitizer: failed to intercept %s\n", #func); \
207 Die(); \
209 if (thr->ignore_interceptors || thr->in_ignored_lib) \
210 return REAL(func)(__VA_ARGS__); \
211 /**/
213 #define TSAN_INTERCEPTOR(ret, func, ...) INTERCEPTOR(ret, func, __VA_ARGS__)
214 #define TSAN_INTERCEPT(func) INTERCEPT_FUNCTION(func)
215 #define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION_VER(func, ver)
217 #define BLOCK_REAL(name) (BlockingCall(thr), REAL(name))
219 struct BlockingCall {
220 explicit BlockingCall(ThreadState *thr)
221 : ctx(SigCtx(thr)) {
222 ctx->in_blocking_func++;
225 ~BlockingCall() {
226 ctx->in_blocking_func--;
229 SignalContext *ctx;
231 // When we are in a "blocking call", we process signals asynchronously
232 // (right when they arrive). In this context we do not expect to be
233 // executing any user/runtime code. The known interceptor sequence when
234 // this is not true is: pthread_join -> munmap(stack). It's fine
235 // to ignore munmap in this case -- we handle stack shadow separately.
236 ScopedIgnoreInterceptors ignore_interceptors;
239 TSAN_INTERCEPTOR(unsigned, sleep, unsigned sec) {
240 SCOPED_TSAN_INTERCEPTOR(sleep, sec);
241 unsigned res = BLOCK_REAL(sleep)(sec);
242 AfterSleep(thr, pc);
243 return res;
246 TSAN_INTERCEPTOR(int, usleep, long_t usec) {
247 SCOPED_TSAN_INTERCEPTOR(usleep, usec);
248 int res = BLOCK_REAL(usleep)(usec);
249 AfterSleep(thr, pc);
250 return res;
253 TSAN_INTERCEPTOR(int, nanosleep, void *req, void *rem) {
254 SCOPED_TSAN_INTERCEPTOR(nanosleep, req, rem);
255 int res = BLOCK_REAL(nanosleep)(req, rem);
256 AfterSleep(thr, pc);
257 return res;
260 TSAN_INTERCEPTOR(void*, dlopen, const char *filename, int flag) {
261 SCOPED_INTERCEPTOR_RAW(dlopen, filename, flag);
262 void *res = REAL(dlopen)(filename, flag);
263 libignore()->OnLibraryLoaded(filename);
264 return res;
267 TSAN_INTERCEPTOR(int, dlclose, void *handle) {
268 SCOPED_INTERCEPTOR_RAW(dlclose, handle);
269 int res = REAL(dlclose)(handle);
270 libignore()->OnLibraryUnloaded();
271 return res;
274 class AtExitContext {
275 public:
276 AtExitContext()
277 : mtx_(MutexTypeAtExit, StatMtxAtExit)
278 , pos_() {
281 typedef void(*atexit_t)();
283 int atexit(ThreadState *thr, uptr pc, bool is_on_exit,
284 atexit_t f, void *arg) {
285 Lock l(&mtx_);
286 if (pos_ == kMaxAtExit)
287 return 1;
288 Release(thr, pc, (uptr)this);
289 stack_[pos_] = f;
290 args_[pos_] = arg;
291 is_on_exits_[pos_] = is_on_exit;
292 pos_++;
293 return 0;
296 void exit(ThreadState *thr, uptr pc) {
297 for (;;) {
298 atexit_t f = 0;
299 void *arg = 0;
300 bool is_on_exit = false;
302 Lock l(&mtx_);
303 if (pos_) {
304 pos_--;
305 f = stack_[pos_];
306 arg = args_[pos_];
307 is_on_exit = is_on_exits_[pos_];
308 Acquire(thr, pc, (uptr)this);
311 if (f == 0)
312 break;
313 DPrintf("#%d: executing atexit func %p\n", thr->tid, f);
314 if (is_on_exit)
315 ((void(*)(int status, void *arg))f)(0, arg);
316 else
317 ((void(*)(void *arg, void *dso))f)(arg, 0);
321 private:
322 static const int kMaxAtExit = 128;
323 Mutex mtx_;
324 atexit_t stack_[kMaxAtExit];
325 void *args_[kMaxAtExit];
326 bool is_on_exits_[kMaxAtExit];
327 int pos_;
330 static AtExitContext *atexit_ctx;
332 TSAN_INTERCEPTOR(int, atexit, void (*f)()) {
333 if (cur_thread()->in_symbolizer)
334 return 0;
335 // We want to setup the atexit callback even if we are in ignored lib
336 // or after fork.
337 SCOPED_INTERCEPTOR_RAW(atexit, f);
338 return atexit_ctx->atexit(thr, pc, false, (void(*)())f, 0);
341 TSAN_INTERCEPTOR(int, on_exit, void(*f)(int, void*), void *arg) {
342 if (cur_thread()->in_symbolizer)
343 return 0;
344 SCOPED_TSAN_INTERCEPTOR(on_exit, f, arg);
345 return atexit_ctx->atexit(thr, pc, true, (void(*)())f, arg);
348 TSAN_INTERCEPTOR(int, __cxa_atexit, void (*f)(void *a), void *arg, void *dso) {
349 if (cur_thread()->in_symbolizer)
350 return 0;
351 SCOPED_TSAN_INTERCEPTOR(__cxa_atexit, f, arg, dso);
352 if (dso) {
353 // Memory allocation in __cxa_atexit will race with free during exit,
354 // because we do not see synchronization around atexit callback list.
355 ThreadIgnoreBegin(thr, pc);
356 int res = REAL(__cxa_atexit)(f, arg, dso);
357 ThreadIgnoreEnd(thr, pc);
358 return res;
360 return atexit_ctx->atexit(thr, pc, false, (void(*)())f, arg);
363 // Cleanup old bufs.
364 static void JmpBufGarbageCollect(ThreadState *thr, uptr sp) {
365 for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) {
366 JmpBuf *buf = &thr->jmp_bufs[i];
367 if (buf->sp <= sp) {
368 uptr sz = thr->jmp_bufs.Size();
369 thr->jmp_bufs[i] = thr->jmp_bufs[sz - 1];
370 thr->jmp_bufs.PopBack();
371 i--;
376 static void SetJmp(ThreadState *thr, uptr sp, uptr mangled_sp) {
377 if (thr->shadow_stack_pos == 0) // called from libc guts during bootstrap
378 return;
379 // Cleanup old bufs.
380 JmpBufGarbageCollect(thr, sp);
381 // Remember the buf.
382 JmpBuf *buf = thr->jmp_bufs.PushBack();
383 buf->sp = sp;
384 buf->mangled_sp = mangled_sp;
385 buf->shadow_stack_pos = thr->shadow_stack_pos;
388 static void LongJmp(ThreadState *thr, uptr *env) {
389 uptr mangled_sp = env[6];
390 // Find the saved buf by mangled_sp.
391 for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) {
392 JmpBuf *buf = &thr->jmp_bufs[i];
393 if (buf->mangled_sp == mangled_sp) {
394 CHECK_GE(thr->shadow_stack_pos, buf->shadow_stack_pos);
395 // Unwind the stack.
396 while (thr->shadow_stack_pos > buf->shadow_stack_pos)
397 FuncExit(thr);
398 JmpBufGarbageCollect(thr, buf->sp - 1); // do not collect buf->sp
399 return;
402 Printf("ThreadSanitizer: can't find longjmp buf\n");
403 CHECK(0);
406 // FIXME: put everything below into a common extern "C" block?
407 extern "C" void __tsan_setjmp(uptr sp, uptr mangled_sp) {
408 SetJmp(cur_thread(), sp, mangled_sp);
411 // Not called. Merely to satisfy TSAN_INTERCEPT().
412 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
413 int __interceptor_setjmp(void *env);
414 extern "C" int __interceptor_setjmp(void *env) {
415 CHECK(0);
416 return 0;
419 // FIXME: any reason to have a separate declaration?
420 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
421 int __interceptor__setjmp(void *env);
422 extern "C" int __interceptor__setjmp(void *env) {
423 CHECK(0);
424 return 0;
427 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
428 int __interceptor_sigsetjmp(void *env);
429 extern "C" int __interceptor_sigsetjmp(void *env) {
430 CHECK(0);
431 return 0;
434 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
435 int __interceptor___sigsetjmp(void *env);
436 extern "C" int __interceptor___sigsetjmp(void *env) {
437 CHECK(0);
438 return 0;
441 extern "C" int setjmp(void *env);
442 extern "C" int _setjmp(void *env);
443 extern "C" int sigsetjmp(void *env);
444 extern "C" int __sigsetjmp(void *env);
445 DEFINE_REAL(int, setjmp, void *env)
446 DEFINE_REAL(int, _setjmp, void *env)
447 DEFINE_REAL(int, sigsetjmp, void *env)
448 DEFINE_REAL(int, __sigsetjmp, void *env)
450 TSAN_INTERCEPTOR(void, longjmp, uptr *env, int val) {
452 SCOPED_TSAN_INTERCEPTOR(longjmp, env, val);
454 LongJmp(cur_thread(), env);
455 REAL(longjmp)(env, val);
458 TSAN_INTERCEPTOR(void, siglongjmp, uptr *env, int val) {
460 SCOPED_TSAN_INTERCEPTOR(siglongjmp, env, val);
462 LongJmp(cur_thread(), env);
463 REAL(siglongjmp)(env, val);
466 TSAN_INTERCEPTOR(void*, malloc, uptr size) {
467 if (cur_thread()->in_symbolizer)
468 return __libc_malloc(size);
469 void *p = 0;
471 SCOPED_INTERCEPTOR_RAW(malloc, size);
472 p = user_alloc(thr, pc, size);
474 invoke_malloc_hook(p, size);
475 return p;
478 TSAN_INTERCEPTOR(void*, __libc_memalign, uptr align, uptr sz) {
479 SCOPED_TSAN_INTERCEPTOR(__libc_memalign, align, sz);
480 return user_alloc(thr, pc, sz, align);
483 TSAN_INTERCEPTOR(void*, calloc, uptr size, uptr n) {
484 if (cur_thread()->in_symbolizer)
485 return __libc_calloc(size, n);
486 if (__sanitizer::CallocShouldReturnNullDueToOverflow(size, n))
487 return AllocatorReturnNull();
488 void *p = 0;
490 SCOPED_INTERCEPTOR_RAW(calloc, size, n);
491 p = user_alloc(thr, pc, n * size);
492 if (p)
493 internal_memset(p, 0, n * size);
495 invoke_malloc_hook(p, n * size);
496 return p;
499 TSAN_INTERCEPTOR(void*, realloc, void *p, uptr size) {
500 if (cur_thread()->in_symbolizer)
501 return __libc_realloc(p, size);
502 if (p)
503 invoke_free_hook(p);
505 SCOPED_INTERCEPTOR_RAW(realloc, p, size);
506 p = user_realloc(thr, pc, p, size);
508 invoke_malloc_hook(p, size);
509 return p;
512 TSAN_INTERCEPTOR(void, free, void *p) {
513 if (p == 0)
514 return;
515 if (cur_thread()->in_symbolizer)
516 return __libc_free(p);
517 invoke_free_hook(p);
518 SCOPED_INTERCEPTOR_RAW(free, p);
519 user_free(thr, pc, p);
522 TSAN_INTERCEPTOR(void, cfree, void *p) {
523 if (p == 0)
524 return;
525 if (cur_thread()->in_symbolizer)
526 return __libc_free(p);
527 invoke_free_hook(p);
528 SCOPED_INTERCEPTOR_RAW(cfree, p);
529 user_free(thr, pc, p);
532 TSAN_INTERCEPTOR(uptr, malloc_usable_size, void *p) {
533 SCOPED_INTERCEPTOR_RAW(malloc_usable_size, p);
534 return user_alloc_usable_size(thr, pc, p);
537 #define OPERATOR_NEW_BODY(mangled_name) \
538 if (cur_thread()->in_symbolizer) \
539 return __libc_malloc(size); \
540 void *p = 0; \
542 SCOPED_INTERCEPTOR_RAW(mangled_name, size); \
543 p = user_alloc(thr, pc, size); \
545 invoke_malloc_hook(p, size); \
546 return p;
548 SANITIZER_INTERFACE_ATTRIBUTE
549 void *operator new(__sanitizer::uptr size);
550 void *operator new(__sanitizer::uptr size) {
551 OPERATOR_NEW_BODY(_Znwm);
554 SANITIZER_INTERFACE_ATTRIBUTE
555 void *operator new[](__sanitizer::uptr size);
556 void *operator new[](__sanitizer::uptr size) {
557 OPERATOR_NEW_BODY(_Znam);
560 SANITIZER_INTERFACE_ATTRIBUTE
561 void *operator new(__sanitizer::uptr size, std::nothrow_t const&);
562 void *operator new(__sanitizer::uptr size, std::nothrow_t const&) {
563 OPERATOR_NEW_BODY(_ZnwmRKSt9nothrow_t);
566 SANITIZER_INTERFACE_ATTRIBUTE
567 void *operator new[](__sanitizer::uptr size, std::nothrow_t const&);
568 void *operator new[](__sanitizer::uptr size, std::nothrow_t const&) {
569 OPERATOR_NEW_BODY(_ZnamRKSt9nothrow_t);
572 #define OPERATOR_DELETE_BODY(mangled_name) \
573 if (ptr == 0) return; \
574 if (cur_thread()->in_symbolizer) \
575 return __libc_free(ptr); \
576 invoke_free_hook(ptr); \
577 SCOPED_INTERCEPTOR_RAW(mangled_name, ptr); \
578 user_free(thr, pc, ptr);
580 SANITIZER_INTERFACE_ATTRIBUTE
581 void operator delete(void *ptr) throw();
582 void operator delete(void *ptr) throw() {
583 OPERATOR_DELETE_BODY(_ZdlPv);
586 SANITIZER_INTERFACE_ATTRIBUTE
587 void operator delete[](void *ptr) throw();
588 void operator delete[](void *ptr) throw() {
589 OPERATOR_DELETE_BODY(_ZdaPv);
592 SANITIZER_INTERFACE_ATTRIBUTE
593 void operator delete(void *ptr, std::nothrow_t const&);
594 void operator delete(void *ptr, std::nothrow_t const&) {
595 OPERATOR_DELETE_BODY(_ZdlPvRKSt9nothrow_t);
598 SANITIZER_INTERFACE_ATTRIBUTE
599 void operator delete[](void *ptr, std::nothrow_t const&);
600 void operator delete[](void *ptr, std::nothrow_t const&) {
601 OPERATOR_DELETE_BODY(_ZdaPvRKSt9nothrow_t);
604 TSAN_INTERCEPTOR(uptr, strlen, const char *s) {
605 SCOPED_TSAN_INTERCEPTOR(strlen, s);
606 uptr len = internal_strlen(s);
607 MemoryAccessRange(thr, pc, (uptr)s, len + 1, false);
608 return len;
611 TSAN_INTERCEPTOR(void*, memset, void *dst, int v, uptr size) {
612 SCOPED_TSAN_INTERCEPTOR(memset, dst, v, size);
613 MemoryAccessRange(thr, pc, (uptr)dst, size, true);
614 return internal_memset(dst, v, size);
617 TSAN_INTERCEPTOR(void*, memcpy, void *dst, const void *src, uptr size) {
618 SCOPED_TSAN_INTERCEPTOR(memcpy, dst, src, size);
619 MemoryAccessRange(thr, pc, (uptr)dst, size, true);
620 MemoryAccessRange(thr, pc, (uptr)src, size, false);
621 return internal_memcpy(dst, src, size);
624 TSAN_INTERCEPTOR(int, memcmp, const void *s1, const void *s2, uptr n) {
625 SCOPED_TSAN_INTERCEPTOR(memcmp, s1, s2, n);
626 int res = 0;
627 uptr len = 0;
628 for (; len < n; len++) {
629 if ((res = ((unsigned char*)s1)[len] - ((unsigned char*)s2)[len]))
630 break;
632 MemoryAccessRange(thr, pc, (uptr)s1, len < n ? len + 1 : n, false);
633 MemoryAccessRange(thr, pc, (uptr)s2, len < n ? len + 1 : n, false);
634 return res;
637 TSAN_INTERCEPTOR(void*, memmove, void *dst, void *src, uptr n) {
638 SCOPED_TSAN_INTERCEPTOR(memmove, dst, src, n);
639 MemoryAccessRange(thr, pc, (uptr)dst, n, true);
640 MemoryAccessRange(thr, pc, (uptr)src, n, false);
641 return REAL(memmove)(dst, src, n);
644 TSAN_INTERCEPTOR(char*, strchr, char *s, int c) {
645 SCOPED_TSAN_INTERCEPTOR(strchr, s, c);
646 char *res = REAL(strchr)(s, c);
647 uptr len = res ? (char*)res - (char*)s + 1 : internal_strlen(s) + 1;
648 MemoryAccessRange(thr, pc, (uptr)s, len, false);
649 return res;
652 TSAN_INTERCEPTOR(char*, strchrnul, char *s, int c) {
653 SCOPED_TSAN_INTERCEPTOR(strchrnul, s, c);
654 char *res = REAL(strchrnul)(s, c);
655 uptr len = (char*)res - (char*)s + 1;
656 MemoryAccessRange(thr, pc, (uptr)s, len, false);
657 return res;
660 TSAN_INTERCEPTOR(char*, strrchr, char *s, int c) {
661 SCOPED_TSAN_INTERCEPTOR(strrchr, s, c);
662 MemoryAccessRange(thr, pc, (uptr)s, internal_strlen(s) + 1, false);
663 return REAL(strrchr)(s, c);
666 TSAN_INTERCEPTOR(char*, strcpy, char *dst, const char *src) { // NOLINT
667 SCOPED_TSAN_INTERCEPTOR(strcpy, dst, src); // NOLINT
668 uptr srclen = internal_strlen(src);
669 MemoryAccessRange(thr, pc, (uptr)dst, srclen + 1, true);
670 MemoryAccessRange(thr, pc, (uptr)src, srclen + 1, false);
671 return REAL(strcpy)(dst, src); // NOLINT
674 TSAN_INTERCEPTOR(char*, strncpy, char *dst, char *src, uptr n) {
675 SCOPED_TSAN_INTERCEPTOR(strncpy, dst, src, n);
676 uptr srclen = internal_strnlen(src, n);
677 MemoryAccessRange(thr, pc, (uptr)dst, n, true);
678 MemoryAccessRange(thr, pc, (uptr)src, min(srclen + 1, n), false);
679 return REAL(strncpy)(dst, src, n);
682 TSAN_INTERCEPTOR(const char*, strstr, const char *s1, const char *s2) {
683 SCOPED_TSAN_INTERCEPTOR(strstr, s1, s2);
684 const char *res = REAL(strstr)(s1, s2);
685 uptr len1 = internal_strlen(s1);
686 uptr len2 = internal_strlen(s2);
687 MemoryAccessRange(thr, pc, (uptr)s1, len1 + 1, false);
688 MemoryAccessRange(thr, pc, (uptr)s2, len2 + 1, false);
689 return res;
692 TSAN_INTERCEPTOR(char*, strdup, const char *str) {
693 SCOPED_TSAN_INTERCEPTOR(strdup, str);
694 // strdup will call malloc, so no instrumentation is required here.
695 return REAL(strdup)(str);
698 static bool fix_mmap_addr(void **addr, long_t sz, int flags) {
699 if (*addr) {
700 if (!IsAppMem((uptr)*addr) || !IsAppMem((uptr)*addr + sz - 1)) {
701 if (flags & MAP_FIXED) {
702 errno = EINVAL;
703 return false;
704 } else {
705 *addr = 0;
709 return true;
712 TSAN_INTERCEPTOR(void*, mmap, void *addr, long_t sz, int prot,
713 int flags, int fd, unsigned off) {
714 SCOPED_TSAN_INTERCEPTOR(mmap, addr, sz, prot, flags, fd, off);
715 if (!fix_mmap_addr(&addr, sz, flags))
716 return MAP_FAILED;
717 void *res = REAL(mmap)(addr, sz, prot, flags, fd, off);
718 if (res != MAP_FAILED) {
719 if (fd > 0)
720 FdAccess(thr, pc, fd);
721 MemoryRangeImitateWrite(thr, pc, (uptr)res, sz);
723 return res;
726 TSAN_INTERCEPTOR(void*, mmap64, void *addr, long_t sz, int prot,
727 int flags, int fd, u64 off) {
728 SCOPED_TSAN_INTERCEPTOR(mmap64, addr, sz, prot, flags, fd, off);
729 if (!fix_mmap_addr(&addr, sz, flags))
730 return MAP_FAILED;
731 void *res = REAL(mmap64)(addr, sz, prot, flags, fd, off);
732 if (res != MAP_FAILED) {
733 if (fd > 0)
734 FdAccess(thr, pc, fd);
735 MemoryRangeImitateWrite(thr, pc, (uptr)res, sz);
737 return res;
740 TSAN_INTERCEPTOR(int, munmap, void *addr, long_t sz) {
741 SCOPED_TSAN_INTERCEPTOR(munmap, addr, sz);
742 DontNeedShadowFor((uptr)addr, sz);
743 int res = REAL(munmap)(addr, sz);
744 return res;
747 TSAN_INTERCEPTOR(void*, memalign, uptr align, uptr sz) {
748 SCOPED_INTERCEPTOR_RAW(memalign, align, sz);
749 return user_alloc(thr, pc, sz, align);
752 TSAN_INTERCEPTOR(void*, valloc, uptr sz) {
753 SCOPED_INTERCEPTOR_RAW(valloc, sz);
754 return user_alloc(thr, pc, sz, GetPageSizeCached());
757 TSAN_INTERCEPTOR(void*, pvalloc, uptr sz) {
758 SCOPED_INTERCEPTOR_RAW(pvalloc, sz);
759 sz = RoundUp(sz, GetPageSizeCached());
760 return user_alloc(thr, pc, sz, GetPageSizeCached());
763 TSAN_INTERCEPTOR(int, posix_memalign, void **memptr, uptr align, uptr sz) {
764 SCOPED_INTERCEPTOR_RAW(posix_memalign, memptr, align, sz);
765 *memptr = user_alloc(thr, pc, sz, align);
766 return 0;
769 // Used in thread-safe function static initialization.
770 extern "C" int INTERFACE_ATTRIBUTE __cxa_guard_acquire(atomic_uint32_t *g) {
771 SCOPED_INTERCEPTOR_RAW(__cxa_guard_acquire, g);
772 for (;;) {
773 u32 cmp = atomic_load(g, memory_order_acquire);
774 if (cmp == 0) {
775 if (atomic_compare_exchange_strong(g, &cmp, 1<<16, memory_order_relaxed))
776 return 1;
777 } else if (cmp == 1) {
778 Acquire(thr, pc, (uptr)g);
779 return 0;
780 } else {
781 internal_sched_yield();
786 extern "C" void INTERFACE_ATTRIBUTE __cxa_guard_release(atomic_uint32_t *g) {
787 SCOPED_INTERCEPTOR_RAW(__cxa_guard_release, g);
788 Release(thr, pc, (uptr)g);
789 atomic_store(g, 1, memory_order_release);
792 extern "C" void INTERFACE_ATTRIBUTE __cxa_guard_abort(atomic_uint32_t *g) {
793 SCOPED_INTERCEPTOR_RAW(__cxa_guard_abort, g);
794 atomic_store(g, 0, memory_order_relaxed);
797 static void thread_finalize(void *v) {
798 uptr iter = (uptr)v;
799 if (iter > 1) {
800 if (pthread_setspecific(g_thread_finalize_key, (void*)(iter - 1))) {
801 Printf("ThreadSanitizer: failed to set thread key\n");
802 Die();
804 return;
807 ThreadState *thr = cur_thread();
808 ThreadFinish(thr);
809 SignalContext *sctx = thr->signal_ctx;
810 if (sctx) {
811 thr->signal_ctx = 0;
812 UnmapOrDie(sctx, sizeof(*sctx));
818 struct ThreadParam {
819 void* (*callback)(void *arg);
820 void *param;
821 atomic_uintptr_t tid;
824 extern "C" void *__tsan_thread_start_func(void *arg) {
825 ThreadParam *p = (ThreadParam*)arg;
826 void* (*callback)(void *arg) = p->callback;
827 void *param = p->param;
828 int tid = 0;
830 ThreadState *thr = cur_thread();
831 // Thread-local state is not initialized yet.
832 ScopedIgnoreInterceptors ignore;
833 if (pthread_setspecific(g_thread_finalize_key,
834 (void *)kPthreadDestructorIterations)) {
835 Printf("ThreadSanitizer: failed to set thread key\n");
836 Die();
838 while ((tid = atomic_load(&p->tid, memory_order_acquire)) == 0)
839 pthread_yield();
840 atomic_store(&p->tid, 0, memory_order_release);
841 ThreadStart(thr, tid, GetTid());
843 void *res = callback(param);
844 // Prevent the callback from being tail called,
845 // it mixes up stack traces.
846 volatile int foo = 42;
847 foo++;
848 return res;
851 TSAN_INTERCEPTOR(int, pthread_create,
852 void *th, void *attr, void *(*callback)(void*), void * param) {
853 SCOPED_INTERCEPTOR_RAW(pthread_create, th, attr, callback, param);
854 if (ctx->after_multithreaded_fork) {
855 if (flags()->die_after_fork) {
856 Report("ThreadSanitizer: starting new threads after multi-threaded "
857 "fork is not supported. Dying (set die_after_fork=0 to override)\n");
858 Die();
859 } else {
860 VPrintf(1, "ThreadSanitizer: starting new threads after multi-threaded "
861 "fork is not supported (pid %d). Continuing because of "
862 "die_after_fork=0, but you are on your own\n", internal_getpid());
865 __sanitizer_pthread_attr_t myattr;
866 if (attr == 0) {
867 pthread_attr_init(&myattr);
868 attr = &myattr;
870 int detached = 0;
871 REAL(pthread_attr_getdetachstate)(attr, &detached);
872 AdjustStackSize(attr);
874 ThreadParam p;
875 p.callback = callback;
876 p.param = param;
877 atomic_store(&p.tid, 0, memory_order_relaxed);
878 int res = -1;
880 // Otherwise we see false positives in pthread stack manipulation.
881 ScopedIgnoreInterceptors ignore;
882 ThreadIgnoreBegin(thr, pc);
883 res = REAL(pthread_create)(th, attr, __tsan_thread_start_func, &p);
884 ThreadIgnoreEnd(thr, pc);
886 if (res == 0) {
887 int tid = ThreadCreate(thr, pc, *(uptr*)th, detached);
888 CHECK_NE(tid, 0);
889 atomic_store(&p.tid, tid, memory_order_release);
890 while (atomic_load(&p.tid, memory_order_acquire) != 0)
891 pthread_yield();
893 if (attr == &myattr)
894 pthread_attr_destroy(&myattr);
895 return res;
898 TSAN_INTERCEPTOR(int, pthread_join, void *th, void **ret) {
899 SCOPED_INTERCEPTOR_RAW(pthread_join, th, ret);
900 int tid = ThreadTid(thr, pc, (uptr)th);
901 ThreadIgnoreBegin(thr, pc);
902 int res = BLOCK_REAL(pthread_join)(th, ret);
903 ThreadIgnoreEnd(thr, pc);
904 if (res == 0) {
905 ThreadJoin(thr, pc, tid);
907 return res;
910 TSAN_INTERCEPTOR(int, pthread_detach, void *th) {
911 SCOPED_TSAN_INTERCEPTOR(pthread_detach, th);
912 int tid = ThreadTid(thr, pc, (uptr)th);
913 int res = REAL(pthread_detach)(th);
914 if (res == 0) {
915 ThreadDetach(thr, pc, tid);
917 return res;
920 // Problem:
921 // NPTL implementation of pthread_cond has 2 versions (2.2.5 and 2.3.2).
922 // pthread_cond_t has different size in the different versions.
923 // If call new REAL functions for old pthread_cond_t, they will corrupt memory
924 // after pthread_cond_t (old cond is smaller).
925 // If we call old REAL functions for new pthread_cond_t, we will lose some
926 // functionality (e.g. old functions do not support waiting against
927 // CLOCK_REALTIME).
928 // Proper handling would require to have 2 versions of interceptors as well.
929 // But this is messy, in particular requires linker scripts when sanitizer
930 // runtime is linked into a shared library.
931 // Instead we assume we don't have dynamic libraries built against old
932 // pthread (2.2.5 is dated by 2002). And provide legacy_pthread_cond flag
933 // that allows to work with old libraries (but this mode does not support
934 // some features, e.g. pthread_condattr_getpshared).
935 static void *init_cond(void *c, bool force = false) {
936 // sizeof(pthread_cond_t) >= sizeof(uptr) in both versions.
937 // So we allocate additional memory on the side large enough to hold
938 // any pthread_cond_t object. Always call new REAL functions, but pass
939 // the aux object to them.
940 // Note: the code assumes that PTHREAD_COND_INITIALIZER initializes
941 // first word of pthread_cond_t to zero.
942 // It's all relevant only for linux.
943 if (!common_flags()->legacy_pthread_cond)
944 return c;
945 atomic_uintptr_t *p = (atomic_uintptr_t*)c;
946 uptr cond = atomic_load(p, memory_order_acquire);
947 if (!force && cond != 0)
948 return (void*)cond;
949 void *newcond = WRAP(malloc)(pthread_cond_t_sz);
950 internal_memset(newcond, 0, pthread_cond_t_sz);
951 if (atomic_compare_exchange_strong(p, &cond, (uptr)newcond,
952 memory_order_acq_rel))
953 return newcond;
954 WRAP(free)(newcond);
955 return (void*)cond;
958 struct CondMutexUnlockCtx {
959 ThreadState *thr;
960 uptr pc;
961 void *m;
964 static void cond_mutex_unlock(CondMutexUnlockCtx *arg) {
965 MutexLock(arg->thr, arg->pc, (uptr)arg->m);
968 INTERCEPTOR(int, pthread_cond_init, void *c, void *a) {
969 void *cond = init_cond(c, true);
970 SCOPED_TSAN_INTERCEPTOR(pthread_cond_init, cond, a);
971 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true);
972 return REAL(pthread_cond_init)(cond, a);
975 INTERCEPTOR(int, pthread_cond_wait, void *c, void *m) {
976 void *cond = init_cond(c);
977 SCOPED_TSAN_INTERCEPTOR(pthread_cond_wait, cond, m);
978 MutexUnlock(thr, pc, (uptr)m);
979 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
980 CondMutexUnlockCtx arg = {thr, pc, m};
981 // This ensures that we handle mutex lock even in case of pthread_cancel.
982 // See test/tsan/cond_cancel.cc.
983 int res = call_pthread_cancel_with_cleanup(
984 (int(*)(void *c, void *m, void *abstime))REAL(pthread_cond_wait),
985 cond, m, 0, (void(*)(void *arg))cond_mutex_unlock, &arg);
986 if (res == errno_EOWNERDEAD)
987 MutexRepair(thr, pc, (uptr)m);
988 MutexLock(thr, pc, (uptr)m);
989 return res;
992 INTERCEPTOR(int, pthread_cond_timedwait, void *c, void *m, void *abstime) {
993 void *cond = init_cond(c);
994 SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait, cond, m, abstime);
995 MutexUnlock(thr, pc, (uptr)m);
996 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
997 CondMutexUnlockCtx arg = {thr, pc, m};
998 // This ensures that we handle mutex lock even in case of pthread_cancel.
999 // See test/tsan/cond_cancel.cc.
1000 int res = call_pthread_cancel_with_cleanup(
1001 REAL(pthread_cond_timedwait), cond, m, abstime,
1002 (void(*)(void *arg))cond_mutex_unlock, &arg);
1003 if (res == errno_EOWNERDEAD)
1004 MutexRepair(thr, pc, (uptr)m);
1005 MutexLock(thr, pc, (uptr)m);
1006 return res;
1009 INTERCEPTOR(int, pthread_cond_signal, void *c) {
1010 void *cond = init_cond(c);
1011 SCOPED_TSAN_INTERCEPTOR(pthread_cond_signal, cond);
1012 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1013 return REAL(pthread_cond_signal)(cond);
1016 INTERCEPTOR(int, pthread_cond_broadcast, void *c) {
1017 void *cond = init_cond(c);
1018 SCOPED_TSAN_INTERCEPTOR(pthread_cond_broadcast, cond);
1019 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1020 return REAL(pthread_cond_broadcast)(cond);
1023 INTERCEPTOR(int, pthread_cond_destroy, void *c) {
1024 void *cond = init_cond(c);
1025 SCOPED_TSAN_INTERCEPTOR(pthread_cond_destroy, cond);
1026 MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true);
1027 int res = REAL(pthread_cond_destroy)(cond);
1028 if (common_flags()->legacy_pthread_cond) {
1029 // Free our aux cond and zero the pointer to not leave dangling pointers.
1030 WRAP(free)(cond);
1031 atomic_store((atomic_uintptr_t*)c, 0, memory_order_relaxed);
1033 return res;
1036 TSAN_INTERCEPTOR(int, pthread_mutex_init, void *m, void *a) {
1037 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_init, m, a);
1038 int res = REAL(pthread_mutex_init)(m, a);
1039 if (res == 0) {
1040 bool recursive = false;
1041 if (a) {
1042 int type = 0;
1043 if (pthread_mutexattr_gettype(a, &type) == 0)
1044 recursive = (type == PTHREAD_MUTEX_RECURSIVE
1045 || type == PTHREAD_MUTEX_RECURSIVE_NP);
1047 MutexCreate(thr, pc, (uptr)m, false, recursive, false);
1049 return res;
1052 TSAN_INTERCEPTOR(int, pthread_mutex_destroy, void *m) {
1053 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_destroy, m);
1054 int res = REAL(pthread_mutex_destroy)(m);
1055 if (res == 0 || res == EBUSY) {
1056 MutexDestroy(thr, pc, (uptr)m);
1058 return res;
1061 TSAN_INTERCEPTOR(int, pthread_mutex_trylock, void *m) {
1062 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_trylock, m);
1063 int res = REAL(pthread_mutex_trylock)(m);
1064 if (res == EOWNERDEAD)
1065 MutexRepair(thr, pc, (uptr)m);
1066 if (res == 0 || res == EOWNERDEAD)
1067 MutexLock(thr, pc, (uptr)m, /*rec=*/1, /*try_lock=*/true);
1068 return res;
1071 TSAN_INTERCEPTOR(int, pthread_mutex_timedlock, void *m, void *abstime) {
1072 SCOPED_TSAN_INTERCEPTOR(pthread_mutex_timedlock, m, abstime);
1073 int res = REAL(pthread_mutex_timedlock)(m, abstime);
1074 if (res == 0) {
1075 MutexLock(thr, pc, (uptr)m);
1077 return res;
1080 TSAN_INTERCEPTOR(int, pthread_spin_init, void *m, int pshared) {
1081 SCOPED_TSAN_INTERCEPTOR(pthread_spin_init, m, pshared);
1082 int res = REAL(pthread_spin_init)(m, pshared);
1083 if (res == 0) {
1084 MutexCreate(thr, pc, (uptr)m, false, false, false);
1086 return res;
1089 TSAN_INTERCEPTOR(int, pthread_spin_destroy, void *m) {
1090 SCOPED_TSAN_INTERCEPTOR(pthread_spin_destroy, m);
1091 int res = REAL(pthread_spin_destroy)(m);
1092 if (res == 0) {
1093 MutexDestroy(thr, pc, (uptr)m);
1095 return res;
1098 TSAN_INTERCEPTOR(int, pthread_spin_lock, void *m) {
1099 SCOPED_TSAN_INTERCEPTOR(pthread_spin_lock, m);
1100 int res = REAL(pthread_spin_lock)(m);
1101 if (res == 0) {
1102 MutexLock(thr, pc, (uptr)m);
1104 return res;
1107 TSAN_INTERCEPTOR(int, pthread_spin_trylock, void *m) {
1108 SCOPED_TSAN_INTERCEPTOR(pthread_spin_trylock, m);
1109 int res = REAL(pthread_spin_trylock)(m);
1110 if (res == 0) {
1111 MutexLock(thr, pc, (uptr)m, /*rec=*/1, /*try_lock=*/true);
1113 return res;
1116 TSAN_INTERCEPTOR(int, pthread_spin_unlock, void *m) {
1117 SCOPED_TSAN_INTERCEPTOR(pthread_spin_unlock, m);
1118 MutexUnlock(thr, pc, (uptr)m);
1119 int res = REAL(pthread_spin_unlock)(m);
1120 return res;
1123 TSAN_INTERCEPTOR(int, pthread_rwlock_init, void *m, void *a) {
1124 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_init, m, a);
1125 int res = REAL(pthread_rwlock_init)(m, a);
1126 if (res == 0) {
1127 MutexCreate(thr, pc, (uptr)m, true, false, false);
1129 return res;
1132 TSAN_INTERCEPTOR(int, pthread_rwlock_destroy, void *m) {
1133 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_destroy, m);
1134 int res = REAL(pthread_rwlock_destroy)(m);
1135 if (res == 0) {
1136 MutexDestroy(thr, pc, (uptr)m);
1138 return res;
1141 TSAN_INTERCEPTOR(int, pthread_rwlock_rdlock, void *m) {
1142 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_rdlock, m);
1143 int res = REAL(pthread_rwlock_rdlock)(m);
1144 if (res == 0) {
1145 MutexReadLock(thr, pc, (uptr)m);
1147 return res;
1150 TSAN_INTERCEPTOR(int, pthread_rwlock_tryrdlock, void *m) {
1151 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_tryrdlock, m);
1152 int res = REAL(pthread_rwlock_tryrdlock)(m);
1153 if (res == 0) {
1154 MutexLock(thr, pc, (uptr)m, /*rec=*/1, /*try_lock=*/true);
1156 return res;
1159 TSAN_INTERCEPTOR(int, pthread_rwlock_timedrdlock, void *m, void *abstime) {
1160 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedrdlock, m, abstime);
1161 int res = REAL(pthread_rwlock_timedrdlock)(m, abstime);
1162 if (res == 0) {
1163 MutexReadLock(thr, pc, (uptr)m);
1165 return res;
1168 TSAN_INTERCEPTOR(int, pthread_rwlock_wrlock, void *m) {
1169 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_wrlock, m);
1170 int res = REAL(pthread_rwlock_wrlock)(m);
1171 if (res == 0) {
1172 MutexLock(thr, pc, (uptr)m);
1174 return res;
1177 TSAN_INTERCEPTOR(int, pthread_rwlock_trywrlock, void *m) {
1178 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_trywrlock, m);
1179 int res = REAL(pthread_rwlock_trywrlock)(m);
1180 if (res == 0) {
1181 MutexLock(thr, pc, (uptr)m, /*rec=*/1, /*try_lock=*/true);
1183 return res;
1186 TSAN_INTERCEPTOR(int, pthread_rwlock_timedwrlock, void *m, void *abstime) {
1187 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedwrlock, m, abstime);
1188 int res = REAL(pthread_rwlock_timedwrlock)(m, abstime);
1189 if (res == 0) {
1190 MutexLock(thr, pc, (uptr)m);
1192 return res;
1195 TSAN_INTERCEPTOR(int, pthread_rwlock_unlock, void *m) {
1196 SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_unlock, m);
1197 MutexReadOrWriteUnlock(thr, pc, (uptr)m);
1198 int res = REAL(pthread_rwlock_unlock)(m);
1199 return res;
1202 TSAN_INTERCEPTOR(int, pthread_barrier_init, void *b, void *a, unsigned count) {
1203 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_init, b, a, count);
1204 MemoryWrite(thr, pc, (uptr)b, kSizeLog1);
1205 int res = REAL(pthread_barrier_init)(b, a, count);
1206 return res;
1209 TSAN_INTERCEPTOR(int, pthread_barrier_destroy, void *b) {
1210 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_destroy, b);
1211 MemoryWrite(thr, pc, (uptr)b, kSizeLog1);
1212 int res = REAL(pthread_barrier_destroy)(b);
1213 return res;
1216 TSAN_INTERCEPTOR(int, pthread_barrier_wait, void *b) {
1217 SCOPED_TSAN_INTERCEPTOR(pthread_barrier_wait, b);
1218 Release(thr, pc, (uptr)b);
1219 MemoryRead(thr, pc, (uptr)b, kSizeLog1);
1220 int res = REAL(pthread_barrier_wait)(b);
1221 MemoryRead(thr, pc, (uptr)b, kSizeLog1);
1222 if (res == 0 || res == PTHREAD_BARRIER_SERIAL_THREAD) {
1223 Acquire(thr, pc, (uptr)b);
1225 return res;
1228 TSAN_INTERCEPTOR(int, pthread_once, void *o, void (*f)()) {
1229 SCOPED_INTERCEPTOR_RAW(pthread_once, o, f);
1230 if (o == 0 || f == 0)
1231 return EINVAL;
1232 atomic_uint32_t *a = static_cast<atomic_uint32_t*>(o);
1233 u32 v = atomic_load(a, memory_order_acquire);
1234 if (v == 0 && atomic_compare_exchange_strong(a, &v, 1,
1235 memory_order_relaxed)) {
1236 (*f)();
1237 if (!thr->in_ignored_lib)
1238 Release(thr, pc, (uptr)o);
1239 atomic_store(a, 2, memory_order_release);
1240 } else {
1241 while (v != 2) {
1242 pthread_yield();
1243 v = atomic_load(a, memory_order_acquire);
1245 if (!thr->in_ignored_lib)
1246 Acquire(thr, pc, (uptr)o);
1248 return 0;
1251 TSAN_INTERCEPTOR(int, sem_init, void *s, int pshared, unsigned value) {
1252 SCOPED_TSAN_INTERCEPTOR(sem_init, s, pshared, value);
1253 int res = REAL(sem_init)(s, pshared, value);
1254 return res;
1257 TSAN_INTERCEPTOR(int, sem_destroy, void *s) {
1258 SCOPED_TSAN_INTERCEPTOR(sem_destroy, s);
1259 int res = REAL(sem_destroy)(s);
1260 return res;
1263 TSAN_INTERCEPTOR(int, sem_wait, void *s) {
1264 SCOPED_TSAN_INTERCEPTOR(sem_wait, s);
1265 int res = BLOCK_REAL(sem_wait)(s);
1266 if (res == 0) {
1267 Acquire(thr, pc, (uptr)s);
1269 return res;
1272 TSAN_INTERCEPTOR(int, sem_trywait, void *s) {
1273 SCOPED_TSAN_INTERCEPTOR(sem_trywait, s);
1274 int res = BLOCK_REAL(sem_trywait)(s);
1275 if (res == 0) {
1276 Acquire(thr, pc, (uptr)s);
1278 return res;
1281 TSAN_INTERCEPTOR(int, sem_timedwait, void *s, void *abstime) {
1282 SCOPED_TSAN_INTERCEPTOR(sem_timedwait, s, abstime);
1283 int res = BLOCK_REAL(sem_timedwait)(s, abstime);
1284 if (res == 0) {
1285 Acquire(thr, pc, (uptr)s);
1287 return res;
1290 TSAN_INTERCEPTOR(int, sem_post, void *s) {
1291 SCOPED_TSAN_INTERCEPTOR(sem_post, s);
1292 Release(thr, pc, (uptr)s);
1293 int res = REAL(sem_post)(s);
1294 return res;
1297 TSAN_INTERCEPTOR(int, sem_getvalue, void *s, int *sval) {
1298 SCOPED_TSAN_INTERCEPTOR(sem_getvalue, s, sval);
1299 int res = REAL(sem_getvalue)(s, sval);
1300 if (res == 0) {
1301 Acquire(thr, pc, (uptr)s);
1303 return res;
1306 TSAN_INTERCEPTOR(int, __xstat, int version, const char *path, void *buf) {
1307 SCOPED_TSAN_INTERCEPTOR(__xstat, version, path, buf);
1308 return REAL(__xstat)(version, path, buf);
1311 TSAN_INTERCEPTOR(int, stat, const char *path, void *buf) {
1312 SCOPED_TSAN_INTERCEPTOR(__xstat, 0, path, buf);
1313 return REAL(__xstat)(0, path, buf);
1316 TSAN_INTERCEPTOR(int, __xstat64, int version, const char *path, void *buf) {
1317 SCOPED_TSAN_INTERCEPTOR(__xstat64, version, path, buf);
1318 return REAL(__xstat64)(version, path, buf);
1321 TSAN_INTERCEPTOR(int, stat64, const char *path, void *buf) {
1322 SCOPED_TSAN_INTERCEPTOR(__xstat64, 0, path, buf);
1323 return REAL(__xstat64)(0, path, buf);
1326 TSAN_INTERCEPTOR(int, __lxstat, int version, const char *path, void *buf) {
1327 SCOPED_TSAN_INTERCEPTOR(__lxstat, version, path, buf);
1328 return REAL(__lxstat)(version, path, buf);
1331 TSAN_INTERCEPTOR(int, lstat, const char *path, void *buf) {
1332 SCOPED_TSAN_INTERCEPTOR(__lxstat, 0, path, buf);
1333 return REAL(__lxstat)(0, path, buf);
1336 TSAN_INTERCEPTOR(int, __lxstat64, int version, const char *path, void *buf) {
1337 SCOPED_TSAN_INTERCEPTOR(__lxstat64, version, path, buf);
1338 return REAL(__lxstat64)(version, path, buf);
1341 TSAN_INTERCEPTOR(int, lstat64, const char *path, void *buf) {
1342 SCOPED_TSAN_INTERCEPTOR(__lxstat64, 0, path, buf);
1343 return REAL(__lxstat64)(0, path, buf);
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);
1353 TSAN_INTERCEPTOR(int, fstat, int fd, void *buf) {
1354 SCOPED_TSAN_INTERCEPTOR(__fxstat, 0, fd, buf);
1355 if (fd > 0)
1356 FdAccess(thr, pc, fd);
1357 return REAL(__fxstat)(0, fd, buf);
1360 TSAN_INTERCEPTOR(int, __fxstat64, int version, int fd, void *buf) {
1361 SCOPED_TSAN_INTERCEPTOR(__fxstat64, version, fd, buf);
1362 if (fd > 0)
1363 FdAccess(thr, pc, fd);
1364 return REAL(__fxstat64)(version, fd, buf);
1367 TSAN_INTERCEPTOR(int, fstat64, int fd, void *buf) {
1368 SCOPED_TSAN_INTERCEPTOR(__fxstat64, 0, fd, buf);
1369 if (fd > 0)
1370 FdAccess(thr, pc, fd);
1371 return REAL(__fxstat64)(0, fd, buf);
1374 TSAN_INTERCEPTOR(int, open, const char *name, int flags, int mode) {
1375 SCOPED_TSAN_INTERCEPTOR(open, name, flags, mode);
1376 int fd = REAL(open)(name, flags, mode);
1377 if (fd >= 0)
1378 FdFileCreate(thr, pc, fd);
1379 return fd;
1382 TSAN_INTERCEPTOR(int, open64, const char *name, int flags, int mode) {
1383 SCOPED_TSAN_INTERCEPTOR(open64, name, flags, mode);
1384 int fd = REAL(open64)(name, flags, mode);
1385 if (fd >= 0)
1386 FdFileCreate(thr, pc, fd);
1387 return fd;
1390 TSAN_INTERCEPTOR(int, creat, const char *name, int mode) {
1391 SCOPED_TSAN_INTERCEPTOR(creat, name, mode);
1392 int fd = REAL(creat)(name, mode);
1393 if (fd >= 0)
1394 FdFileCreate(thr, pc, fd);
1395 return fd;
1398 TSAN_INTERCEPTOR(int, creat64, const char *name, int mode) {
1399 SCOPED_TSAN_INTERCEPTOR(creat64, name, mode);
1400 int fd = REAL(creat64)(name, mode);
1401 if (fd >= 0)
1402 FdFileCreate(thr, pc, fd);
1403 return fd;
1406 TSAN_INTERCEPTOR(int, dup, int oldfd) {
1407 SCOPED_TSAN_INTERCEPTOR(dup, oldfd);
1408 int newfd = REAL(dup)(oldfd);
1409 if (oldfd >= 0 && newfd >= 0 && newfd != oldfd)
1410 FdDup(thr, pc, oldfd, newfd);
1411 return newfd;
1414 TSAN_INTERCEPTOR(int, dup2, int oldfd, int newfd) {
1415 SCOPED_TSAN_INTERCEPTOR(dup2, oldfd, newfd);
1416 int newfd2 = REAL(dup2)(oldfd, newfd);
1417 if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd)
1418 FdDup(thr, pc, oldfd, newfd2);
1419 return newfd2;
1422 TSAN_INTERCEPTOR(int, dup3, int oldfd, int newfd, int flags) {
1423 SCOPED_TSAN_INTERCEPTOR(dup3, oldfd, newfd, flags);
1424 int newfd2 = REAL(dup3)(oldfd, newfd, flags);
1425 if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd)
1426 FdDup(thr, pc, oldfd, newfd2);
1427 return newfd2;
1430 TSAN_INTERCEPTOR(int, eventfd, unsigned initval, int flags) {
1431 SCOPED_TSAN_INTERCEPTOR(eventfd, initval, flags);
1432 int fd = REAL(eventfd)(initval, flags);
1433 if (fd >= 0)
1434 FdEventCreate(thr, pc, fd);
1435 return fd;
1438 TSAN_INTERCEPTOR(int, signalfd, int fd, void *mask, int flags) {
1439 SCOPED_TSAN_INTERCEPTOR(signalfd, fd, mask, flags);
1440 if (fd >= 0)
1441 FdClose(thr, pc, fd);
1442 fd = REAL(signalfd)(fd, mask, flags);
1443 if (fd >= 0)
1444 FdSignalCreate(thr, pc, fd);
1445 return fd;
1448 TSAN_INTERCEPTOR(int, inotify_init, int fake) {
1449 SCOPED_TSAN_INTERCEPTOR(inotify_init, fake);
1450 int fd = REAL(inotify_init)(fake);
1451 if (fd >= 0)
1452 FdInotifyCreate(thr, pc, fd);
1453 return fd;
1456 TSAN_INTERCEPTOR(int, inotify_init1, int flags) {
1457 SCOPED_TSAN_INTERCEPTOR(inotify_init1, flags);
1458 int fd = REAL(inotify_init1)(flags);
1459 if (fd >= 0)
1460 FdInotifyCreate(thr, pc, fd);
1461 return fd;
1464 TSAN_INTERCEPTOR(int, socket, int domain, int type, int protocol) {
1465 SCOPED_TSAN_INTERCEPTOR(socket, domain, type, protocol);
1466 int fd = REAL(socket)(domain, type, protocol);
1467 if (fd >= 0)
1468 FdSocketCreate(thr, pc, fd);
1469 return fd;
1472 TSAN_INTERCEPTOR(int, socketpair, int domain, int type, int protocol, int *fd) {
1473 SCOPED_TSAN_INTERCEPTOR(socketpair, domain, type, protocol, fd);
1474 int res = REAL(socketpair)(domain, type, protocol, fd);
1475 if (res == 0 && fd[0] >= 0 && fd[1] >= 0)
1476 FdPipeCreate(thr, pc, fd[0], fd[1]);
1477 return res;
1480 TSAN_INTERCEPTOR(int, connect, int fd, void *addr, unsigned addrlen) {
1481 SCOPED_TSAN_INTERCEPTOR(connect, fd, addr, addrlen);
1482 FdSocketConnecting(thr, pc, fd);
1483 int res = REAL(connect)(fd, addr, addrlen);
1484 if (res == 0 && fd >= 0)
1485 FdSocketConnect(thr, pc, fd);
1486 return res;
1489 TSAN_INTERCEPTOR(int, bind, int fd, void *addr, unsigned addrlen) {
1490 SCOPED_TSAN_INTERCEPTOR(bind, fd, addr, addrlen);
1491 int res = REAL(bind)(fd, addr, addrlen);
1492 if (fd > 0 && res == 0)
1493 FdAccess(thr, pc, fd);
1494 return res;
1497 TSAN_INTERCEPTOR(int, listen, int fd, int backlog) {
1498 SCOPED_TSAN_INTERCEPTOR(listen, fd, backlog);
1499 int res = REAL(listen)(fd, backlog);
1500 if (fd > 0 && res == 0)
1501 FdAccess(thr, pc, fd);
1502 return res;
1505 TSAN_INTERCEPTOR(int, epoll_create, int size) {
1506 SCOPED_TSAN_INTERCEPTOR(epoll_create, size);
1507 int fd = REAL(epoll_create)(size);
1508 if (fd >= 0)
1509 FdPollCreate(thr, pc, fd);
1510 return fd;
1513 TSAN_INTERCEPTOR(int, epoll_create1, int flags) {
1514 SCOPED_TSAN_INTERCEPTOR(epoll_create1, flags);
1515 int fd = REAL(epoll_create1)(flags);
1516 if (fd >= 0)
1517 FdPollCreate(thr, pc, fd);
1518 return fd;
1521 TSAN_INTERCEPTOR(int, close, int fd) {
1522 SCOPED_TSAN_INTERCEPTOR(close, fd);
1523 if (fd >= 0)
1524 FdClose(thr, pc, fd);
1525 return REAL(close)(fd);
1528 TSAN_INTERCEPTOR(int, __close, int fd) {
1529 SCOPED_TSAN_INTERCEPTOR(__close, fd);
1530 if (fd >= 0)
1531 FdClose(thr, pc, fd);
1532 return REAL(__close)(fd);
1535 // glibc guts
1536 TSAN_INTERCEPTOR(void, __res_iclose, void *state, bool free_addr) {
1537 SCOPED_TSAN_INTERCEPTOR(__res_iclose, state, free_addr);
1538 int fds[64];
1539 int cnt = ExtractResolvFDs(state, fds, ARRAY_SIZE(fds));
1540 for (int i = 0; i < cnt; i++) {
1541 if (fds[i] > 0)
1542 FdClose(thr, pc, fds[i]);
1544 REAL(__res_iclose)(state, free_addr);
1547 TSAN_INTERCEPTOR(int, pipe, int *pipefd) {
1548 SCOPED_TSAN_INTERCEPTOR(pipe, pipefd);
1549 int res = REAL(pipe)(pipefd);
1550 if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0)
1551 FdPipeCreate(thr, pc, pipefd[0], pipefd[1]);
1552 return res;
1555 TSAN_INTERCEPTOR(int, pipe2, int *pipefd, int flags) {
1556 SCOPED_TSAN_INTERCEPTOR(pipe2, pipefd, flags);
1557 int res = REAL(pipe2)(pipefd, flags);
1558 if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0)
1559 FdPipeCreate(thr, pc, pipefd[0], pipefd[1]);
1560 return res;
1563 TSAN_INTERCEPTOR(long_t, send, int fd, void *buf, long_t len, int flags) {
1564 SCOPED_TSAN_INTERCEPTOR(send, fd, buf, len, flags);
1565 if (fd >= 0) {
1566 FdAccess(thr, pc, fd);
1567 FdRelease(thr, pc, fd);
1569 int res = REAL(send)(fd, buf, len, flags);
1570 return res;
1573 TSAN_INTERCEPTOR(long_t, sendmsg, int fd, void *msg, int flags) {
1574 SCOPED_TSAN_INTERCEPTOR(sendmsg, fd, msg, flags);
1575 if (fd >= 0) {
1576 FdAccess(thr, pc, fd);
1577 FdRelease(thr, pc, fd);
1579 int res = REAL(sendmsg)(fd, msg, flags);
1580 return res;
1583 TSAN_INTERCEPTOR(long_t, recv, int fd, void *buf, long_t len, int flags) {
1584 SCOPED_TSAN_INTERCEPTOR(recv, fd, buf, len, flags);
1585 if (fd >= 0)
1586 FdAccess(thr, pc, fd);
1587 int res = REAL(recv)(fd, buf, len, flags);
1588 if (res >= 0 && fd >= 0) {
1589 FdAcquire(thr, pc, fd);
1591 return res;
1594 TSAN_INTERCEPTOR(int, unlink, char *path) {
1595 SCOPED_TSAN_INTERCEPTOR(unlink, path);
1596 Release(thr, pc, File2addr(path));
1597 int res = REAL(unlink)(path);
1598 return res;
1601 TSAN_INTERCEPTOR(void*, tmpfile, int fake) {
1602 SCOPED_TSAN_INTERCEPTOR(tmpfile, fake);
1603 void *res = REAL(tmpfile)(fake);
1604 if (res) {
1605 int fd = fileno_unlocked(res);
1606 if (fd >= 0)
1607 FdFileCreate(thr, pc, fd);
1609 return res;
1612 TSAN_INTERCEPTOR(void*, tmpfile64, int fake) {
1613 SCOPED_TSAN_INTERCEPTOR(tmpfile64, fake);
1614 void *res = REAL(tmpfile64)(fake);
1615 if (res) {
1616 int fd = fileno_unlocked(res);
1617 if (fd >= 0)
1618 FdFileCreate(thr, pc, fd);
1620 return res;
1623 TSAN_INTERCEPTOR(uptr, fread, void *ptr, uptr size, uptr nmemb, void *f) {
1624 // libc file streams can call user-supplied functions, see fopencookie.
1626 SCOPED_TSAN_INTERCEPTOR(fread, ptr, size, nmemb, f);
1627 MemoryAccessRange(thr, pc, (uptr)ptr, size * nmemb, true);
1629 return REAL(fread)(ptr, size, nmemb, f);
1632 TSAN_INTERCEPTOR(uptr, fwrite, const void *p, uptr size, uptr nmemb, void *f) {
1633 // libc file streams can call user-supplied functions, see fopencookie.
1635 SCOPED_TSAN_INTERCEPTOR(fwrite, p, size, nmemb, f);
1636 MemoryAccessRange(thr, pc, (uptr)p, size * nmemb, false);
1638 return REAL(fwrite)(p, size, nmemb, f);
1641 TSAN_INTERCEPTOR(void, abort, int fake) {
1642 SCOPED_TSAN_INTERCEPTOR(abort, fake);
1643 REAL(fflush)(0);
1644 REAL(abort)(fake);
1647 TSAN_INTERCEPTOR(int, puts, const char *s) {
1648 SCOPED_TSAN_INTERCEPTOR(puts, s);
1649 MemoryAccessRange(thr, pc, (uptr)s, internal_strlen(s), false);
1650 return REAL(puts)(s);
1653 TSAN_INTERCEPTOR(int, rmdir, char *path) {
1654 SCOPED_TSAN_INTERCEPTOR(rmdir, path);
1655 Release(thr, pc, Dir2addr(path));
1656 int res = REAL(rmdir)(path);
1657 return res;
1660 TSAN_INTERCEPTOR(void*, opendir, char *path) {
1661 SCOPED_TSAN_INTERCEPTOR(opendir, path);
1662 void *res = REAL(opendir)(path);
1663 if (res != 0)
1664 Acquire(thr, pc, Dir2addr(path));
1665 return res;
1668 TSAN_INTERCEPTOR(int, epoll_ctl, int epfd, int op, int fd, void *ev) {
1669 SCOPED_TSAN_INTERCEPTOR(epoll_ctl, epfd, op, fd, ev);
1670 if (epfd >= 0)
1671 FdAccess(thr, pc, epfd);
1672 if (epfd >= 0 && fd >= 0)
1673 FdAccess(thr, pc, fd);
1674 if (op == EPOLL_CTL_ADD && epfd >= 0)
1675 FdRelease(thr, pc, epfd);
1676 int res = REAL(epoll_ctl)(epfd, op, fd, ev);
1677 return res;
1680 TSAN_INTERCEPTOR(int, epoll_wait, int epfd, void *ev, int cnt, int timeout) {
1681 SCOPED_TSAN_INTERCEPTOR(epoll_wait, epfd, ev, cnt, timeout);
1682 if (epfd >= 0)
1683 FdAccess(thr, pc, epfd);
1684 int res = BLOCK_REAL(epoll_wait)(epfd, ev, cnt, timeout);
1685 if (res > 0 && epfd >= 0)
1686 FdAcquire(thr, pc, epfd);
1687 return res;
1690 namespace __tsan {
1692 static void CallUserSignalHandler(ThreadState *thr, bool sync, bool sigact,
1693 int sig, my_siginfo_t *info, void *uctx) {
1694 // Ensure that the handler does not spoil errno.
1695 const int saved_errno = errno;
1696 errno = 99;
1697 // Need to remember pc before the call, because the handler can reset it.
1698 uptr pc = sigact ?
1699 (uptr)sigactions[sig].sa_sigaction :
1700 (uptr)sigactions[sig].sa_handler;
1701 pc += 1; // return address is expected, OutputReport() will undo this
1702 if (sigact)
1703 sigactions[sig].sa_sigaction(sig, info, uctx);
1704 else
1705 sigactions[sig].sa_handler(sig);
1706 // We do not detect errno spoiling for SIGTERM,
1707 // because some SIGTERM handlers do spoil errno but reraise SIGTERM,
1708 // tsan reports false positive in such case.
1709 // It's difficult to properly detect this situation (reraise),
1710 // because in async signal processing case (when handler is called directly
1711 // from rtl_generic_sighandler) we have not yet received the reraised
1712 // signal; and it looks too fragile to intercept all ways to reraise a signal.
1713 if (flags()->report_bugs && !sync && sig != SIGTERM && errno != 99) {
1714 __tsan::StackTrace stack;
1715 stack.ObtainCurrent(thr, pc);
1716 ThreadRegistryLock l(ctx->thread_registry);
1717 ScopedReport rep(ReportTypeErrnoInSignal);
1718 if (!IsFiredSuppression(ctx, rep, stack)) {
1719 rep.AddStack(&stack);
1720 OutputReport(ctx, rep, rep.GetReport()->stacks[0]);
1723 errno = saved_errno;
1726 void ProcessPendingSignals(ThreadState *thr) {
1727 SignalContext *sctx = SigCtx(thr);
1728 if (sctx == 0 || sctx->pending_signal_count == 0 || thr->in_signal_handler)
1729 return;
1730 thr->in_signal_handler = true;
1731 sctx->pending_signal_count = 0;
1732 // These are too big for stack.
1733 static THREADLOCAL __sanitizer_sigset_t emptyset, oldset;
1734 REAL(sigfillset)(&emptyset);
1735 pthread_sigmask(SIG_SETMASK, &emptyset, &oldset);
1736 for (int sig = 0; sig < kSigCount; sig++) {
1737 SignalDesc *signal = &sctx->pending_signals[sig];
1738 if (signal->armed) {
1739 signal->armed = false;
1740 if (sigactions[sig].sa_handler != SIG_DFL
1741 && sigactions[sig].sa_handler != SIG_IGN) {
1742 CallUserSignalHandler(thr, false, signal->sigaction,
1743 sig, &signal->siginfo, &signal->ctx);
1747 pthread_sigmask(SIG_SETMASK, &oldset, 0);
1748 CHECK_EQ(thr->in_signal_handler, true);
1749 thr->in_signal_handler = false;
1752 } // namespace __tsan
1754 static bool is_sync_signal(SignalContext *sctx, int sig) {
1755 return sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
1756 sig == SIGABRT || sig == SIGFPE || sig == SIGPIPE || sig == SIGSYS ||
1757 // If we are sending signal to ourselves, we must process it now.
1758 (sctx && sig == sctx->int_signal_send);
1761 void ALWAYS_INLINE rtl_generic_sighandler(bool sigact, int sig,
1762 my_siginfo_t *info, void *ctx) {
1763 ThreadState *thr = cur_thread();
1764 SignalContext *sctx = SigCtx(thr);
1765 if (sig < 0 || sig >= kSigCount) {
1766 VPrintf(1, "ThreadSanitizer: ignoring signal %d\n", sig);
1767 return;
1769 // Don't mess with synchronous signals.
1770 const bool sync = is_sync_signal(sctx, sig);
1771 if (sync ||
1772 // If we are in blocking function, we can safely process it now
1773 // (but check if we are in a recursive interceptor,
1774 // i.e. pthread_join()->munmap()).
1775 (sctx && sctx->in_blocking_func == 1)) {
1776 CHECK_EQ(thr->in_signal_handler, false);
1777 thr->in_signal_handler = true;
1778 if (sctx && sctx->in_blocking_func == 1) {
1779 // We ignore interceptors in blocking functions,
1780 // temporary enbled them again while we are calling user function.
1781 int const i = thr->ignore_interceptors;
1782 thr->ignore_interceptors = 0;
1783 CallUserSignalHandler(thr, sync, sigact, sig, info, ctx);
1784 thr->ignore_interceptors = i;
1785 } else {
1786 CallUserSignalHandler(thr, sync, sigact, sig, info, ctx);
1788 CHECK_EQ(thr->in_signal_handler, true);
1789 thr->in_signal_handler = false;
1790 return;
1793 if (sctx == 0)
1794 return;
1795 SignalDesc *signal = &sctx->pending_signals[sig];
1796 if (signal->armed == false) {
1797 signal->armed = true;
1798 signal->sigaction = sigact;
1799 if (info)
1800 internal_memcpy(&signal->siginfo, info, sizeof(*info));
1801 if (ctx)
1802 internal_memcpy(&signal->ctx, ctx, sizeof(signal->ctx));
1803 sctx->pending_signal_count++;
1807 static void rtl_sighandler(int sig) {
1808 rtl_generic_sighandler(false, sig, 0, 0);
1811 static void rtl_sigaction(int sig, my_siginfo_t *info, void *ctx) {
1812 rtl_generic_sighandler(true, sig, info, ctx);
1815 TSAN_INTERCEPTOR(int, sigaction, int sig, sigaction_t *act, sigaction_t *old) {
1816 SCOPED_TSAN_INTERCEPTOR(sigaction, sig, act, old);
1817 if (old)
1818 internal_memcpy(old, &sigactions[sig], sizeof(*old));
1819 if (act == 0)
1820 return 0;
1821 internal_memcpy(&sigactions[sig], act, sizeof(*act));
1822 sigaction_t newact;
1823 internal_memcpy(&newact, act, sizeof(newact));
1824 REAL(sigfillset)(&newact.sa_mask);
1825 if (act->sa_handler != SIG_IGN && act->sa_handler != SIG_DFL) {
1826 if (newact.sa_flags & SA_SIGINFO)
1827 newact.sa_sigaction = rtl_sigaction;
1828 else
1829 newact.sa_handler = rtl_sighandler;
1831 int res = REAL(sigaction)(sig, &newact, 0);
1832 return res;
1835 TSAN_INTERCEPTOR(sighandler_t, signal, int sig, sighandler_t h) {
1836 sigaction_t act;
1837 act.sa_handler = h;
1838 REAL(memset)(&act.sa_mask, -1, sizeof(act.sa_mask));
1839 act.sa_flags = 0;
1840 sigaction_t old;
1841 int res = sigaction(sig, &act, &old);
1842 if (res)
1843 return SIG_ERR;
1844 return old.sa_handler;
1847 TSAN_INTERCEPTOR(int, sigsuspend, const __sanitizer_sigset_t *mask) {
1848 SCOPED_TSAN_INTERCEPTOR(sigsuspend, mask);
1849 return REAL(sigsuspend)(mask);
1852 TSAN_INTERCEPTOR(int, raise, int sig) {
1853 SCOPED_TSAN_INTERCEPTOR(raise, sig);
1854 SignalContext *sctx = SigCtx(thr);
1855 CHECK_NE(sctx, 0);
1856 int prev = sctx->int_signal_send;
1857 sctx->int_signal_send = sig;
1858 int res = REAL(raise)(sig);
1859 CHECK_EQ(sctx->int_signal_send, sig);
1860 sctx->int_signal_send = prev;
1861 return res;
1864 TSAN_INTERCEPTOR(int, kill, int pid, int sig) {
1865 SCOPED_TSAN_INTERCEPTOR(kill, pid, sig);
1866 SignalContext *sctx = SigCtx(thr);
1867 CHECK_NE(sctx, 0);
1868 int prev = sctx->int_signal_send;
1869 if (pid == (int)internal_getpid()) {
1870 sctx->int_signal_send = sig;
1872 int res = REAL(kill)(pid, sig);
1873 if (pid == (int)internal_getpid()) {
1874 CHECK_EQ(sctx->int_signal_send, sig);
1875 sctx->int_signal_send = prev;
1877 return res;
1880 TSAN_INTERCEPTOR(int, pthread_kill, void *tid, int sig) {
1881 SCOPED_TSAN_INTERCEPTOR(pthread_kill, tid, sig);
1882 SignalContext *sctx = SigCtx(thr);
1883 CHECK_NE(sctx, 0);
1884 int prev = sctx->int_signal_send;
1885 if (tid == pthread_self()) {
1886 sctx->int_signal_send = sig;
1888 int res = REAL(pthread_kill)(tid, sig);
1889 if (tid == pthread_self()) {
1890 CHECK_EQ(sctx->int_signal_send, sig);
1891 sctx->int_signal_send = prev;
1893 return res;
1896 TSAN_INTERCEPTOR(int, gettimeofday, void *tv, void *tz) {
1897 SCOPED_TSAN_INTERCEPTOR(gettimeofday, tv, tz);
1898 // It's intercepted merely to process pending signals.
1899 return REAL(gettimeofday)(tv, tz);
1902 TSAN_INTERCEPTOR(int, getaddrinfo, void *node, void *service,
1903 void *hints, void *rv) {
1904 SCOPED_TSAN_INTERCEPTOR(getaddrinfo, node, service, hints, rv);
1905 // We miss atomic synchronization in getaddrinfo,
1906 // and can report false race between malloc and free
1907 // inside of getaddrinfo. So ignore memory accesses.
1908 ThreadIgnoreBegin(thr, pc);
1909 int res = REAL(getaddrinfo)(node, service, hints, rv);
1910 ThreadIgnoreEnd(thr, pc);
1911 return res;
1914 // Linux kernel has a bug that leads to kernel deadlock if a process
1915 // maps TBs of memory and then calls mlock().
1916 static void MlockIsUnsupported() {
1917 static atomic_uint8_t printed;
1918 if (atomic_exchange(&printed, 1, memory_order_relaxed))
1919 return;
1920 VPrintf(1, "INFO: ThreadSanitizer ignores mlock/munlock[all]\n");
1923 TSAN_INTERCEPTOR(int, mlock, const void *addr, uptr len) {
1924 MlockIsUnsupported();
1925 return 0;
1928 TSAN_INTERCEPTOR(int, munlock, const void *addr, uptr len) {
1929 MlockIsUnsupported();
1930 return 0;
1933 TSAN_INTERCEPTOR(int, mlockall, int flags) {
1934 MlockIsUnsupported();
1935 return 0;
1938 TSAN_INTERCEPTOR(int, munlockall, void) {
1939 MlockIsUnsupported();
1940 return 0;
1943 TSAN_INTERCEPTOR(int, fork, int fake) {
1944 if (cur_thread()->in_symbolizer)
1945 return REAL(fork)(fake);
1946 SCOPED_INTERCEPTOR_RAW(fork, fake);
1947 ForkBefore(thr, pc);
1948 int pid = REAL(fork)(fake);
1949 if (pid == 0) {
1950 // child
1951 ForkChildAfter(thr, pc);
1952 FdOnFork(thr, pc);
1953 } else if (pid > 0) {
1954 // parent
1955 ForkParentAfter(thr, pc);
1956 } else {
1957 // error
1958 ForkParentAfter(thr, pc);
1960 return pid;
1963 TSAN_INTERCEPTOR(int, vfork, int fake) {
1964 // Some programs (e.g. openjdk) call close for all file descriptors
1965 // in the child process. Under tsan it leads to false positives, because
1966 // address space is shared, so the parent process also thinks that
1967 // the descriptors are closed (while they are actually not).
1968 // This leads to false positives due to missed synchronization.
1969 // Strictly saying this is undefined behavior, because vfork child is not
1970 // allowed to call any functions other than exec/exit. But this is what
1971 // openjdk does, so we want to handle it.
1972 // We could disable interceptors in the child process. But it's not possible
1973 // to simply intercept and wrap vfork, because vfork child is not allowed
1974 // to return from the function that calls vfork, and that's exactly what
1975 // we would do. So this would require some assembly trickery as well.
1976 // Instead we simply turn vfork into fork.
1977 return WRAP(fork)(fake);
1980 static int OnExit(ThreadState *thr) {
1981 int status = Finalize(thr);
1982 REAL(fflush)(0);
1983 return status;
1986 struct TsanInterceptorContext {
1987 ThreadState *thr;
1988 const uptr caller_pc;
1989 const uptr pc;
1992 static void HandleRecvmsg(ThreadState *thr, uptr pc,
1993 __sanitizer_msghdr *msg) {
1994 int fds[64];
1995 int cnt = ExtractRecvmsgFDs(msg, fds, ARRAY_SIZE(fds));
1996 for (int i = 0; i < cnt; i++)
1997 FdEventCreate(thr, pc, fds[i]);
2000 #include "sanitizer_common/sanitizer_platform_interceptors.h"
2001 // Causes interceptor recursion (getaddrinfo() and fopen())
2002 #undef SANITIZER_INTERCEPT_GETADDRINFO
2004 #define COMMON_INTERCEPT_FUNCTION(name) INTERCEPT_FUNCTION(name)
2006 #define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \
2007 MemoryAccessRange(((TsanInterceptorContext *)ctx)->thr, \
2008 ((TsanInterceptorContext *)ctx)->pc, (uptr)ptr, size, \
2009 true)
2011 #define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) \
2012 MemoryAccessRange(((TsanInterceptorContext *) ctx)->thr, \
2013 ((TsanInterceptorContext *) ctx)->pc, (uptr) ptr, size, \
2014 false)
2016 #define COMMON_INTERCEPTOR_ENTER(ctx, func, ...) \
2017 SCOPED_TSAN_INTERCEPTOR(func, __VA_ARGS__); \
2018 TsanInterceptorContext _ctx = {thr, caller_pc, pc}; \
2019 ctx = (void *)&_ctx; \
2020 (void) ctx;
2022 #define COMMON_INTERCEPTOR_FILE_OPEN(ctx, file, path) \
2023 Acquire(thr, pc, File2addr(path)); \
2024 if (file) { \
2025 int fd = fileno_unlocked(file); \
2026 if (fd >= 0) FdFileCreate(thr, pc, fd); \
2029 #define COMMON_INTERCEPTOR_FILE_CLOSE(ctx, file) \
2030 if (file) { \
2031 int fd = fileno_unlocked(file); \
2032 if (fd >= 0) FdClose(thr, pc, fd); \
2035 #define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \
2036 FdAcquire(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2038 #define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \
2039 FdRelease(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2041 #define COMMON_INTERCEPTOR_FD_ACCESS(ctx, fd) \
2042 FdAccess(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2044 #define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \
2045 FdSocketAccept(((TsanInterceptorContext *) ctx)->thr, pc, fd, newfd)
2047 #define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) \
2048 ThreadSetName(((TsanInterceptorContext *) ctx)->thr, name)
2050 #define COMMON_INTERCEPTOR_SET_PTHREAD_NAME(ctx, thread, name) \
2051 __tsan::ctx->thread_registry->SetThreadNameByUserId(thread, name)
2053 #define COMMON_INTERCEPTOR_BLOCK_REAL(name) BLOCK_REAL(name)
2055 #define COMMON_INTERCEPTOR_ON_EXIT(ctx) \
2056 OnExit(((TsanInterceptorContext *) ctx)->thr)
2058 #define COMMON_INTERCEPTOR_MUTEX_LOCK(ctx, m) \
2059 MutexLock(((TsanInterceptorContext *)ctx)->thr, \
2060 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2062 #define COMMON_INTERCEPTOR_MUTEX_UNLOCK(ctx, m) \
2063 MutexUnlock(((TsanInterceptorContext *)ctx)->thr, \
2064 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2066 #define COMMON_INTERCEPTOR_MUTEX_REPAIR(ctx, m) \
2067 MutexRepair(((TsanInterceptorContext *)ctx)->thr, \
2068 ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2070 #define COMMON_INTERCEPTOR_HANDLE_RECVMSG(ctx, msg) \
2071 HandleRecvmsg(((TsanInterceptorContext *)ctx)->thr, \
2072 ((TsanInterceptorContext *)ctx)->pc, msg)
2074 #include "sanitizer_common/sanitizer_common_interceptors.inc"
2076 #define TSAN_SYSCALL() \
2077 ThreadState *thr = cur_thread(); \
2078 if (thr->ignore_interceptors) \
2079 return; \
2080 ScopedSyscall scoped_syscall(thr) \
2081 /**/
2083 struct ScopedSyscall {
2084 ThreadState *thr;
2086 explicit ScopedSyscall(ThreadState *thr)
2087 : thr(thr) {
2088 Initialize(thr);
2091 ~ScopedSyscall() {
2092 ProcessPendingSignals(thr);
2096 static void syscall_access_range(uptr pc, uptr p, uptr s, bool write) {
2097 TSAN_SYSCALL();
2098 MemoryAccessRange(thr, pc, p, s, write);
2101 static void syscall_acquire(uptr pc, uptr addr) {
2102 TSAN_SYSCALL();
2103 Acquire(thr, pc, addr);
2104 DPrintf("syscall_acquire(%p)\n", addr);
2107 static void syscall_release(uptr pc, uptr addr) {
2108 TSAN_SYSCALL();
2109 DPrintf("syscall_release(%p)\n", addr);
2110 Release(thr, pc, addr);
2113 static void syscall_fd_close(uptr pc, int fd) {
2114 TSAN_SYSCALL();
2115 FdClose(thr, pc, fd);
2118 static USED void syscall_fd_acquire(uptr pc, int fd) {
2119 TSAN_SYSCALL();
2120 FdAcquire(thr, pc, fd);
2121 DPrintf("syscall_fd_acquire(%p)\n", fd);
2124 static USED void syscall_fd_release(uptr pc, int fd) {
2125 TSAN_SYSCALL();
2126 DPrintf("syscall_fd_release(%p)\n", fd);
2127 FdRelease(thr, pc, fd);
2130 static void syscall_pre_fork(uptr pc) {
2131 TSAN_SYSCALL();
2132 ForkBefore(thr, pc);
2135 static void syscall_post_fork(uptr pc, int pid) {
2136 TSAN_SYSCALL();
2137 if (pid == 0) {
2138 // child
2139 ForkChildAfter(thr, pc);
2140 FdOnFork(thr, pc);
2141 } else if (pid > 0) {
2142 // parent
2143 ForkParentAfter(thr, pc);
2144 } else {
2145 // error
2146 ForkParentAfter(thr, pc);
2150 #define COMMON_SYSCALL_PRE_READ_RANGE(p, s) \
2151 syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), false)
2153 #define COMMON_SYSCALL_PRE_WRITE_RANGE(p, s) \
2154 syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), true)
2156 #define COMMON_SYSCALL_POST_READ_RANGE(p, s) \
2157 do { \
2158 (void)(p); \
2159 (void)(s); \
2160 } while (false)
2162 #define COMMON_SYSCALL_POST_WRITE_RANGE(p, s) \
2163 do { \
2164 (void)(p); \
2165 (void)(s); \
2166 } while (false)
2168 #define COMMON_SYSCALL_ACQUIRE(addr) \
2169 syscall_acquire(GET_CALLER_PC(), (uptr)(addr))
2171 #define COMMON_SYSCALL_RELEASE(addr) \
2172 syscall_release(GET_CALLER_PC(), (uptr)(addr))
2174 #define COMMON_SYSCALL_FD_CLOSE(fd) syscall_fd_close(GET_CALLER_PC(), fd)
2176 #define COMMON_SYSCALL_FD_ACQUIRE(fd) syscall_fd_acquire(GET_CALLER_PC(), fd)
2178 #define COMMON_SYSCALL_FD_RELEASE(fd) syscall_fd_release(GET_CALLER_PC(), fd)
2180 #define COMMON_SYSCALL_PRE_FORK() \
2181 syscall_pre_fork(GET_CALLER_PC())
2183 #define COMMON_SYSCALL_POST_FORK(res) \
2184 syscall_post_fork(GET_CALLER_PC(), res)
2186 #include "sanitizer_common/sanitizer_common_syscalls.inc"
2188 namespace __tsan {
2190 static void finalize(void *arg) {
2191 ThreadState *thr = cur_thread();
2192 uptr pc = 0;
2193 atexit_ctx->exit(thr, pc);
2194 int status = Finalize(thr);
2195 // Make sure the output is not lost.
2196 // Flushing all the streams here may freeze the process if a child thread is
2197 // performing file stream operations at the same time.
2198 REAL(fflush)(stdout);
2199 REAL(fflush)(stderr);
2200 if (status)
2201 REAL(_exit)(status);
2204 static void unreachable() {
2205 Report("FATAL: ThreadSanitizer: unreachable called\n");
2206 Die();
2209 void InitializeInterceptors() {
2210 // We need to setup it early, because functions like dlsym() can call it.
2211 REAL(memset) = internal_memset;
2212 REAL(memcpy) = internal_memcpy;
2213 REAL(memcmp) = internal_memcmp;
2215 // Instruct libc malloc to consume less memory.
2216 mallopt(1, 0); // M_MXFAST
2217 mallopt(-3, 32*1024); // M_MMAP_THRESHOLD
2219 InitializeCommonInterceptors();
2221 // We can not use TSAN_INTERCEPT to get setjmp addr,
2222 // because it does &setjmp and setjmp is not present in some versions of libc.
2223 using __interception::GetRealFunctionAddress;
2224 GetRealFunctionAddress("setjmp", (uptr*)&REAL(setjmp), 0, 0);
2225 GetRealFunctionAddress("_setjmp", (uptr*)&REAL(_setjmp), 0, 0);
2226 GetRealFunctionAddress("sigsetjmp", (uptr*)&REAL(sigsetjmp), 0, 0);
2227 GetRealFunctionAddress("__sigsetjmp", (uptr*)&REAL(__sigsetjmp), 0, 0);
2229 TSAN_INTERCEPT(longjmp);
2230 TSAN_INTERCEPT(siglongjmp);
2232 TSAN_INTERCEPT(malloc);
2233 TSAN_INTERCEPT(__libc_memalign);
2234 TSAN_INTERCEPT(calloc);
2235 TSAN_INTERCEPT(realloc);
2236 TSAN_INTERCEPT(free);
2237 TSAN_INTERCEPT(cfree);
2238 TSAN_INTERCEPT(mmap);
2239 TSAN_INTERCEPT(mmap64);
2240 TSAN_INTERCEPT(munmap);
2241 TSAN_INTERCEPT(memalign);
2242 TSAN_INTERCEPT(valloc);
2243 TSAN_INTERCEPT(pvalloc);
2244 TSAN_INTERCEPT(posix_memalign);
2246 TSAN_INTERCEPT(strlen);
2247 TSAN_INTERCEPT(memset);
2248 TSAN_INTERCEPT(memcpy);
2249 TSAN_INTERCEPT(memmove);
2250 TSAN_INTERCEPT(memcmp);
2251 TSAN_INTERCEPT(strchr);
2252 TSAN_INTERCEPT(strchrnul);
2253 TSAN_INTERCEPT(strrchr);
2254 TSAN_INTERCEPT(strcpy); // NOLINT
2255 TSAN_INTERCEPT(strncpy);
2256 TSAN_INTERCEPT(strstr);
2257 TSAN_INTERCEPT(strdup);
2259 TSAN_INTERCEPT(pthread_create);
2260 TSAN_INTERCEPT(pthread_join);
2261 TSAN_INTERCEPT(pthread_detach);
2263 TSAN_INTERCEPT_VER(pthread_cond_init, "GLIBC_2.3.2");
2264 TSAN_INTERCEPT_VER(pthread_cond_signal, "GLIBC_2.3.2");
2265 TSAN_INTERCEPT_VER(pthread_cond_broadcast, "GLIBC_2.3.2");
2266 TSAN_INTERCEPT_VER(pthread_cond_wait, "GLIBC_2.3.2");
2267 TSAN_INTERCEPT_VER(pthread_cond_timedwait, "GLIBC_2.3.2");
2268 TSAN_INTERCEPT_VER(pthread_cond_destroy, "GLIBC_2.3.2");
2270 TSAN_INTERCEPT(pthread_mutex_init);
2271 TSAN_INTERCEPT(pthread_mutex_destroy);
2272 TSAN_INTERCEPT(pthread_mutex_trylock);
2273 TSAN_INTERCEPT(pthread_mutex_timedlock);
2275 TSAN_INTERCEPT(pthread_spin_init);
2276 TSAN_INTERCEPT(pthread_spin_destroy);
2277 TSAN_INTERCEPT(pthread_spin_lock);
2278 TSAN_INTERCEPT(pthread_spin_trylock);
2279 TSAN_INTERCEPT(pthread_spin_unlock);
2281 TSAN_INTERCEPT(pthread_rwlock_init);
2282 TSAN_INTERCEPT(pthread_rwlock_destroy);
2283 TSAN_INTERCEPT(pthread_rwlock_rdlock);
2284 TSAN_INTERCEPT(pthread_rwlock_tryrdlock);
2285 TSAN_INTERCEPT(pthread_rwlock_timedrdlock);
2286 TSAN_INTERCEPT(pthread_rwlock_wrlock);
2287 TSAN_INTERCEPT(pthread_rwlock_trywrlock);
2288 TSAN_INTERCEPT(pthread_rwlock_timedwrlock);
2289 TSAN_INTERCEPT(pthread_rwlock_unlock);
2291 TSAN_INTERCEPT(pthread_barrier_init);
2292 TSAN_INTERCEPT(pthread_barrier_destroy);
2293 TSAN_INTERCEPT(pthread_barrier_wait);
2295 TSAN_INTERCEPT(pthread_once);
2297 TSAN_INTERCEPT(sem_init);
2298 TSAN_INTERCEPT(sem_destroy);
2299 TSAN_INTERCEPT(sem_wait);
2300 TSAN_INTERCEPT(sem_trywait);
2301 TSAN_INTERCEPT(sem_timedwait);
2302 TSAN_INTERCEPT(sem_post);
2303 TSAN_INTERCEPT(sem_getvalue);
2305 TSAN_INTERCEPT(stat);
2306 TSAN_INTERCEPT(__xstat);
2307 TSAN_INTERCEPT(stat64);
2308 TSAN_INTERCEPT(__xstat64);
2309 TSAN_INTERCEPT(lstat);
2310 TSAN_INTERCEPT(__lxstat);
2311 TSAN_INTERCEPT(lstat64);
2312 TSAN_INTERCEPT(__lxstat64);
2313 TSAN_INTERCEPT(fstat);
2314 TSAN_INTERCEPT(__fxstat);
2315 TSAN_INTERCEPT(fstat64);
2316 TSAN_INTERCEPT(__fxstat64);
2317 TSAN_INTERCEPT(open);
2318 TSAN_INTERCEPT(open64);
2319 TSAN_INTERCEPT(creat);
2320 TSAN_INTERCEPT(creat64);
2321 TSAN_INTERCEPT(dup);
2322 TSAN_INTERCEPT(dup2);
2323 TSAN_INTERCEPT(dup3);
2324 TSAN_INTERCEPT(eventfd);
2325 TSAN_INTERCEPT(signalfd);
2326 TSAN_INTERCEPT(inotify_init);
2327 TSAN_INTERCEPT(inotify_init1);
2328 TSAN_INTERCEPT(socket);
2329 TSAN_INTERCEPT(socketpair);
2330 TSAN_INTERCEPT(connect);
2331 TSAN_INTERCEPT(bind);
2332 TSAN_INTERCEPT(listen);
2333 TSAN_INTERCEPT(epoll_create);
2334 TSAN_INTERCEPT(epoll_create1);
2335 TSAN_INTERCEPT(close);
2336 TSAN_INTERCEPT(__close);
2337 TSAN_INTERCEPT(__res_iclose);
2338 TSAN_INTERCEPT(pipe);
2339 TSAN_INTERCEPT(pipe2);
2341 TSAN_INTERCEPT(send);
2342 TSAN_INTERCEPT(sendmsg);
2343 TSAN_INTERCEPT(recv);
2345 TSAN_INTERCEPT(unlink);
2346 TSAN_INTERCEPT(tmpfile);
2347 TSAN_INTERCEPT(tmpfile64);
2348 TSAN_INTERCEPT(fread);
2349 TSAN_INTERCEPT(fwrite);
2350 TSAN_INTERCEPT(abort);
2351 TSAN_INTERCEPT(puts);
2352 TSAN_INTERCEPT(rmdir);
2353 TSAN_INTERCEPT(opendir);
2355 TSAN_INTERCEPT(epoll_ctl);
2356 TSAN_INTERCEPT(epoll_wait);
2358 TSAN_INTERCEPT(sigaction);
2359 TSAN_INTERCEPT(signal);
2360 TSAN_INTERCEPT(sigsuspend);
2361 TSAN_INTERCEPT(raise);
2362 TSAN_INTERCEPT(kill);
2363 TSAN_INTERCEPT(pthread_kill);
2364 TSAN_INTERCEPT(sleep);
2365 TSAN_INTERCEPT(usleep);
2366 TSAN_INTERCEPT(nanosleep);
2367 TSAN_INTERCEPT(gettimeofday);
2368 TSAN_INTERCEPT(getaddrinfo);
2370 TSAN_INTERCEPT(mlock);
2371 TSAN_INTERCEPT(munlock);
2372 TSAN_INTERCEPT(mlockall);
2373 TSAN_INTERCEPT(munlockall);
2375 TSAN_INTERCEPT(fork);
2376 TSAN_INTERCEPT(vfork);
2377 TSAN_INTERCEPT(dlopen);
2378 TSAN_INTERCEPT(dlclose);
2379 TSAN_INTERCEPT(on_exit);
2380 TSAN_INTERCEPT(__cxa_atexit);
2381 TSAN_INTERCEPT(_exit);
2383 // Need to setup it, because interceptors check that the function is resolved.
2384 // But atexit is emitted directly into the module, so can't be resolved.
2385 REAL(atexit) = (int(*)(void(*)()))unreachable;
2386 atexit_ctx = new(internal_alloc(MBlockAtExit, sizeof(AtExitContext)))
2387 AtExitContext();
2389 if (REAL(__cxa_atexit)(&finalize, 0, 0)) {
2390 Printf("ThreadSanitizer: failed to setup atexit callback\n");
2391 Die();
2394 if (pthread_key_create(&g_thread_finalize_key, &thread_finalize)) {
2395 Printf("ThreadSanitizer: failed to create thread key\n");
2396 Die();
2399 FdInit();
2402 void *internal_start_thread(void(*func)(void *arg), void *arg) {
2403 // Start the thread with signals blocked, otherwise it can steal user signals.
2404 __sanitizer_sigset_t set, old;
2405 internal_sigfillset(&set);
2406 internal_sigprocmask(SIG_SETMASK, &set, &old);
2407 void *th;
2408 REAL(pthread_create)(&th, 0, (void*(*)(void *arg))func, arg);
2409 internal_sigprocmask(SIG_SETMASK, &old, 0);
2410 return th;
2413 void internal_join_thread(void *th) {
2414 REAL(pthread_join)(th, 0);
2417 } // namespace __tsan