1 //===-- tsan_interceptors_posix.cpp ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is a part of ThreadSanitizer (TSan), a race detector.
10 //
11 // FIXME: move as many interceptors as possible into
12 // sanitizer_common/sanitizer_common_interceptors.inc
13 //===----------------------------------------------------------------------===//
14 
15 #include "sanitizer_common/sanitizer_atomic.h"
16 #include "sanitizer_common/sanitizer_errno.h"
17 #include "sanitizer_common/sanitizer_libc.h"
18 #include "sanitizer_common/sanitizer_linux.h"
19 #include "sanitizer_common/sanitizer_platform_limits_netbsd.h"
20 #include "sanitizer_common/sanitizer_platform_limits_posix.h"
21 #include "sanitizer_common/sanitizer_placement_new.h"
22 #include "sanitizer_common/sanitizer_posix.h"
23 #include "sanitizer_common/sanitizer_stacktrace.h"
24 #include "sanitizer_common/sanitizer_tls_get_addr.h"
25 #include "interception/interception.h"
26 #include "tsan_interceptors.h"
27 #include "tsan_interface.h"
28 #include "tsan_platform.h"
29 #include "tsan_suppressions.h"
30 #include "tsan_rtl.h"
31 #include "tsan_mman.h"
32 #include "tsan_fd.h"
33 
34 #include <stdarg.h>
35 
36 using namespace __tsan;
37 
38 #if SANITIZER_FREEBSD || SANITIZER_MAC
39 #define stdout __stdoutp
40 #define stderr __stderrp
41 #endif
42 
43 #if SANITIZER_NETBSD
44 #define dirfd(dirp) (*(int *)(dirp))
45 #define fileno_unlocked(fp)              \
46   (((__sanitizer_FILE *)fp)->_file == -1 \
47        ? -1                              \
48        : (int)(unsigned short)(((__sanitizer_FILE *)fp)->_file))
49 
50 #define stdout ((__sanitizer_FILE*)&__sF[1])
51 #define stderr ((__sanitizer_FILE*)&__sF[2])
52 
53 #define nanosleep __nanosleep50
54 #define vfork __vfork14
55 #endif
56 
57 #ifdef __mips__
58 const int kSigCount = 129;
59 #else
60 const int kSigCount = 65;
61 #endif
62 
63 #ifdef __mips__
64 struct ucontext_t {
65   u64 opaque[768 / sizeof(u64) + 1];
66 };
67 #else
68 struct ucontext_t {
69   // The size is determined by looking at sizeof of real ucontext_t on linux.
70   u64 opaque[936 / sizeof(u64) + 1];
71 };
72 #endif
73 
74 #if defined(__x86_64__) || defined(__mips__) || SANITIZER_PPC64V1 || \
75     defined(__s390x__)
76 #define PTHREAD_ABI_BASE  "GLIBC_2.3.2"
77 #elif defined(__aarch64__) || SANITIZER_PPC64V2
78 #define PTHREAD_ABI_BASE  "GLIBC_2.17"
79 #endif
80 
81 extern "C" int pthread_attr_init(void *attr);
82 extern "C" int pthread_attr_destroy(void *attr);
83 DECLARE_REAL(int, pthread_attr_getdetachstate, void *, void *)
84 extern "C" int pthread_attr_setstacksize(void *attr, uptr stacksize);
85 extern "C" int pthread_atfork(void (*prepare)(void), void (*parent)(void),
86                               void (*child)(void));
87 extern "C" int pthread_key_create(unsigned *key, void (*destructor)(void* v));
88 extern "C" int pthread_setspecific(unsigned key, const void *v);
89 DECLARE_REAL(int, pthread_mutexattr_gettype, void *, void *)
90 DECLARE_REAL(int, fflush, __sanitizer_FILE *fp)
91 DECLARE_REAL_AND_INTERCEPTOR(void *, malloc, uptr size)
92 DECLARE_REAL_AND_INTERCEPTOR(void, free, void *ptr)
93 extern "C" void *pthread_self();
94 extern "C" void _exit(int status);
95 #if !SANITIZER_NETBSD
96 extern "C" int fileno_unlocked(void *stream);
97 extern "C" int dirfd(void *dirp);
98 #endif
99 #if SANITIZER_GLIBC
100 extern "C" int mallopt(int param, int value);
101 #endif
102 #if SANITIZER_NETBSD
103 extern __sanitizer_FILE __sF[];
104 #else
105 extern __sanitizer_FILE *stdout, *stderr;
106 #endif
107 #if !SANITIZER_FREEBSD && !SANITIZER_MAC && !SANITIZER_NETBSD
108 const int PTHREAD_MUTEX_RECURSIVE = 1;
109 const int PTHREAD_MUTEX_RECURSIVE_NP = 1;
110 #else
111 const int PTHREAD_MUTEX_RECURSIVE = 2;
112 const int PTHREAD_MUTEX_RECURSIVE_NP = 2;
113 #endif
114 #if !SANITIZER_FREEBSD && !SANITIZER_MAC && !SANITIZER_NETBSD
115 const int EPOLL_CTL_ADD = 1;
116 #endif
117 const int SIGILL = 4;
118 const int SIGTRAP = 5;
119 const int SIGABRT = 6;
120 const int SIGFPE = 8;
121 const int SIGSEGV = 11;
122 const int SIGPIPE = 13;
123 const int SIGTERM = 15;
124 #if defined(__mips__) || SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_NETBSD
125 const int SIGBUS = 10;
126 const int SIGSYS = 12;
127 #else
128 const int SIGBUS = 7;
129 const int SIGSYS = 31;
130 #endif
131 void *const MAP_FAILED = (void*)-1;
132 #if SANITIZER_NETBSD
133 const int PTHREAD_BARRIER_SERIAL_THREAD = 1234567;
134 #elif !SANITIZER_MAC
135 const int PTHREAD_BARRIER_SERIAL_THREAD = -1;
136 #endif
137 const int MAP_FIXED = 0x10;
138 typedef long long_t;
139 typedef __sanitizer::u16 mode_t;
140 
141 // From /usr/include/unistd.h
142 # define F_ULOCK 0      /* Unlock a previously locked region.  */
143 # define F_LOCK  1      /* Lock a region for exclusive use.  */
144 # define F_TLOCK 2      /* Test and lock a region for exclusive use.  */
145 # define F_TEST  3      /* Test a region for other processes locks.  */
146 
147 #if SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_NETBSD
148 const int SA_SIGINFO = 0x40;
149 const int SIG_SETMASK = 3;
150 #elif defined(__mips__)
151 const int SA_SIGINFO = 8;
152 const int SIG_SETMASK = 3;
153 #else
154 const int SA_SIGINFO = 4;
155 const int SIG_SETMASK = 2;
156 #endif
157 
158 #define COMMON_INTERCEPTOR_NOTHING_IS_INITIALIZED \
159   (cur_thread_init(), !cur_thread()->is_inited)
160 
161 namespace __tsan {
162 struct SignalDesc {
163   bool armed;
164   bool sigaction;
165   __sanitizer_siginfo siginfo;
166   ucontext_t ctx;
167 };
168 
169 struct ThreadSignalContext {
170   int int_signal_send;
171   atomic_uintptr_t in_blocking_func;
172   atomic_uintptr_t have_pending_signals;
173   SignalDesc pending_signals[kSigCount];
174   // emptyset and oldset are too big for stack.
175   __sanitizer_sigset_t emptyset;
176   __sanitizer_sigset_t oldset;
177 };
178 
179 // The sole reason tsan wraps atexit callbacks is to establish synchronization
180 // between callback setup and callback execution.
181 struct AtExitCtx {
182   void (*f)();
183   void *arg;
184 };
185 
186 // InterceptorContext holds all global data required for interceptors.
187 // It's explicitly constructed in InitializeInterceptors with placement new
188 // and is never destroyed. This allows usage of members with non-trivial
189 // constructors and destructors.
190 struct InterceptorContext {
191   // The object is 64-byte aligned, because we want hot data to be located
192   // in a single cache line if possible (it's accessed in every interceptor).
193   ALIGNED(64) LibIgnore libignore;
194   __sanitizer_sigaction sigactions[kSigCount];
195 #if !SANITIZER_MAC && !SANITIZER_NETBSD
196   unsigned finalize_key;
197 #endif
198 
199   Mutex atexit_mu;
200   Vector<struct AtExitCtx *> AtExitStack;
201 
InterceptorContext__tsan::InterceptorContext202   InterceptorContext() : libignore(LINKER_INITIALIZED), atexit_mu(MutexTypeAtExit), AtExitStack() {}
203 };
204 
205 static ALIGNED(64) char interceptor_placeholder[sizeof(InterceptorContext)];
interceptor_ctx()206 InterceptorContext *interceptor_ctx() {
207   return reinterpret_cast<InterceptorContext*>(&interceptor_placeholder[0]);
208 }
209 
libignore()210 LibIgnore *libignore() {
211   return &interceptor_ctx()->libignore;
212 }
213 
InitializeLibIgnore()214 void InitializeLibIgnore() {
215   const SuppressionContext &supp = *Suppressions();
216   const uptr n = supp.SuppressionCount();
217   for (uptr i = 0; i < n; i++) {
218     const Suppression *s = supp.SuppressionAt(i);
219     if (0 == internal_strcmp(s->type, kSuppressionLib))
220       libignore()->AddIgnoredLibrary(s->templ);
221   }
222   if (flags()->ignore_noninstrumented_modules)
223     libignore()->IgnoreNoninstrumentedModules(true);
224   libignore()->OnLibraryLoaded(0);
225 }
226 
227 // The following two hooks can be used by for cooperative scheduling when
228 // locking.
229 #ifdef TSAN_EXTERNAL_HOOKS
230 void OnPotentiallyBlockingRegionBegin();
231 void OnPotentiallyBlockingRegionEnd();
232 #else
OnPotentiallyBlockingRegionBegin()233 SANITIZER_WEAK_CXX_DEFAULT_IMPL void OnPotentiallyBlockingRegionBegin() {}
OnPotentiallyBlockingRegionEnd()234 SANITIZER_WEAK_CXX_DEFAULT_IMPL void OnPotentiallyBlockingRegionEnd() {}
235 #endif
236 
237 }  // namespace __tsan
238 
SigCtx(ThreadState * thr)239 static ThreadSignalContext *SigCtx(ThreadState *thr) {
240   ThreadSignalContext *ctx = (ThreadSignalContext*)thr->signal_ctx;
241   if (ctx == 0 && !thr->is_dead) {
242     ctx = (ThreadSignalContext*)MmapOrDie(sizeof(*ctx), "ThreadSignalContext");
243     MemoryResetRange(thr, (uptr)&SigCtx, (uptr)ctx, sizeof(*ctx));
244     thr->signal_ctx = ctx;
245   }
246   return ctx;
247 }
248 
ScopedInterceptor(ThreadState * thr,const char * fname,uptr pc)249 ScopedInterceptor::ScopedInterceptor(ThreadState *thr, const char *fname,
250                                      uptr pc)
251     : thr_(thr), pc_(pc), in_ignored_lib_(false), ignoring_(false) {
252   Initialize(thr);
253   if (!thr_->is_inited) return;
254   if (!thr_->ignore_interceptors) FuncEntry(thr, pc);
255   DPrintf("#%d: intercept %s()\n", thr_->tid, fname);
256   ignoring_ =
257       !thr_->in_ignored_lib && (flags()->ignore_interceptors_accesses ||
258                                 libignore()->IsIgnored(pc, &in_ignored_lib_));
259   EnableIgnores();
260 }
261 
~ScopedInterceptor()262 ScopedInterceptor::~ScopedInterceptor() {
263   if (!thr_->is_inited) return;
264   DisableIgnores();
265   if (!thr_->ignore_interceptors) {
266     ProcessPendingSignals(thr_);
267     FuncExit(thr_);
268     CheckedMutex::CheckNoLocks();
269   }
270 }
271 
EnableIgnores()272 void ScopedInterceptor::EnableIgnores() {
273   if (ignoring_) {
274     ThreadIgnoreBegin(thr_, pc_, /*save_stack=*/false);
275     if (flags()->ignore_noninstrumented_modules) thr_->suppress_reports++;
276     if (in_ignored_lib_) {
277       DCHECK(!thr_->in_ignored_lib);
278       thr_->in_ignored_lib = true;
279     }
280   }
281 }
282 
DisableIgnores()283 void ScopedInterceptor::DisableIgnores() {
284   if (ignoring_) {
285     ThreadIgnoreEnd(thr_, pc_);
286     if (flags()->ignore_noninstrumented_modules) thr_->suppress_reports--;
287     if (in_ignored_lib_) {
288       DCHECK(thr_->in_ignored_lib);
289       thr_->in_ignored_lib = false;
290     }
291   }
292 }
293 
294 #define TSAN_INTERCEPT(func) INTERCEPT_FUNCTION(func)
295 #if SANITIZER_FREEBSD
296 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION(func)
297 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(func)
298 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(func)
299 #elif SANITIZER_NETBSD
300 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION(func)
301 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(func) \
302          INTERCEPT_FUNCTION(__libc_##func)
303 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(func) \
304          INTERCEPT_FUNCTION(__libc_thr_##func)
305 #else
306 # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION_VER(func, ver)
307 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(func)
308 # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(func)
309 #endif
310 
311 #define READ_STRING_OF_LEN(thr, pc, s, len, n)                 \
312   MemoryAccessRange((thr), (pc), (uptr)(s),                         \
313     common_flags()->strict_string_checks ? (len) + 1 : (n), false)
314 
315 #define READ_STRING(thr, pc, s, n)                             \
316     READ_STRING_OF_LEN((thr), (pc), (s), internal_strlen(s), (n))
317 
318 #define BLOCK_REAL(name) (BlockingCall(thr), REAL(name))
319 
320 struct BlockingCall {
BlockingCallBlockingCall321   explicit BlockingCall(ThreadState *thr)
322       : thr(thr)
323       , ctx(SigCtx(thr)) {
324     for (;;) {
325       atomic_store(&ctx->in_blocking_func, 1, memory_order_relaxed);
326       if (atomic_load(&ctx->have_pending_signals, memory_order_relaxed) == 0)
327         break;
328       atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
329       ProcessPendingSignals(thr);
330     }
331     // When we are in a "blocking call", we process signals asynchronously
332     // (right when they arrive). In this context we do not expect to be
333     // executing any user/runtime code. The known interceptor sequence when
334     // this is not true is: pthread_join -> munmap(stack). It's fine
335     // to ignore munmap in this case -- we handle stack shadow separately.
336     thr->ignore_interceptors++;
337   }
338 
~BlockingCallBlockingCall339   ~BlockingCall() {
340     thr->ignore_interceptors--;
341     atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
342   }
343 
344   ThreadState *thr;
345   ThreadSignalContext *ctx;
346 };
347 
TSAN_INTERCEPTOR(unsigned,sleep,unsigned sec)348 TSAN_INTERCEPTOR(unsigned, sleep, unsigned sec) {
349   SCOPED_TSAN_INTERCEPTOR(sleep, sec);
350   unsigned res = BLOCK_REAL(sleep)(sec);
351   AfterSleep(thr, pc);
352   return res;
353 }
354 
TSAN_INTERCEPTOR(int,usleep,long_t usec)355 TSAN_INTERCEPTOR(int, usleep, long_t usec) {
356   SCOPED_TSAN_INTERCEPTOR(usleep, usec);
357   int res = BLOCK_REAL(usleep)(usec);
358   AfterSleep(thr, pc);
359   return res;
360 }
361 
TSAN_INTERCEPTOR(int,nanosleep,void * req,void * rem)362 TSAN_INTERCEPTOR(int, nanosleep, void *req, void *rem) {
363   SCOPED_TSAN_INTERCEPTOR(nanosleep, req, rem);
364   int res = BLOCK_REAL(nanosleep)(req, rem);
365   AfterSleep(thr, pc);
366   return res;
367 }
368 
TSAN_INTERCEPTOR(int,pause,int fake)369 TSAN_INTERCEPTOR(int, pause, int fake) {
370   SCOPED_TSAN_INTERCEPTOR(pause, fake);
371   return BLOCK_REAL(pause)(fake);
372 }
373 
at_exit_wrapper()374 static void at_exit_wrapper() {
375   AtExitCtx *ctx;
376   {
377     // Ensure thread-safety.
378     Lock l(&interceptor_ctx()->atexit_mu);
379 
380     // Pop AtExitCtx from the top of the stack of callback functions
381     uptr element = interceptor_ctx()->AtExitStack.Size() - 1;
382     ctx = interceptor_ctx()->AtExitStack[element];
383     interceptor_ctx()->AtExitStack.PopBack();
384   }
385 
386   Acquire(cur_thread(), (uptr)0, (uptr)ctx);
387   ((void(*)())ctx->f)();
388   InternalFree(ctx);
389 }
390 
cxa_at_exit_wrapper(void * arg)391 static void cxa_at_exit_wrapper(void *arg) {
392   Acquire(cur_thread(), 0, (uptr)arg);
393   AtExitCtx *ctx = (AtExitCtx*)arg;
394   ((void(*)(void *arg))ctx->f)(ctx->arg);
395   InternalFree(ctx);
396 }
397 
398 static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(),
399       void *arg, void *dso);
400 
401 #if !SANITIZER_ANDROID
TSAN_INTERCEPTOR(int,atexit,void (* f)())402 TSAN_INTERCEPTOR(int, atexit, void (*f)()) {
403   if (in_symbolizer())
404     return 0;
405   // We want to setup the atexit callback even if we are in ignored lib
406   // or after fork.
407   SCOPED_INTERCEPTOR_RAW(atexit, f);
408   return setup_at_exit_wrapper(thr, pc, (void(*)())f, 0, 0);
409 }
410 #endif
411 
TSAN_INTERCEPTOR(int,__cxa_atexit,void (* f)(void * a),void * arg,void * dso)412 TSAN_INTERCEPTOR(int, __cxa_atexit, void (*f)(void *a), void *arg, void *dso) {
413   if (in_symbolizer())
414     return 0;
415   SCOPED_TSAN_INTERCEPTOR(__cxa_atexit, f, arg, dso);
416   return setup_at_exit_wrapper(thr, pc, (void(*)())f, arg, dso);
417 }
418 
setup_at_exit_wrapper(ThreadState * thr,uptr pc,void (* f)(),void * arg,void * dso)419 static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(),
420       void *arg, void *dso) {
421   AtExitCtx *ctx = (AtExitCtx*)InternalAlloc(sizeof(AtExitCtx));
422   ctx->f = f;
423   ctx->arg = arg;
424   Release(thr, pc, (uptr)ctx);
425   // Memory allocation in __cxa_atexit will race with free during exit,
426   // because we do not see synchronization around atexit callback list.
427   ThreadIgnoreBegin(thr, pc);
428   int res;
429   if (!dso) {
430     // NetBSD does not preserve the 2nd argument if dso is equal to 0
431     // Store ctx in a local stack-like structure
432 
433     // Ensure thread-safety.
434     Lock l(&interceptor_ctx()->atexit_mu);
435     // __cxa_atexit calls calloc. If we don't ignore interceptors, we will fail
436     // due to atexit_mu held on exit from the calloc interceptor.
437     ScopedIgnoreInterceptors ignore;
438 
439     res = REAL(__cxa_atexit)((void (*)(void *a))at_exit_wrapper, 0, 0);
440     // Push AtExitCtx on the top of the stack of callback functions
441     if (!res) {
442       interceptor_ctx()->AtExitStack.PushBack(ctx);
443     }
444   } else {
445     res = REAL(__cxa_atexit)(cxa_at_exit_wrapper, ctx, dso);
446   }
447   ThreadIgnoreEnd(thr, pc);
448   return res;
449 }
450 
451 #if !SANITIZER_MAC && !SANITIZER_NETBSD
on_exit_wrapper(int status,void * arg)452 static void on_exit_wrapper(int status, void *arg) {
453   ThreadState *thr = cur_thread();
454   uptr pc = 0;
455   Acquire(thr, pc, (uptr)arg);
456   AtExitCtx *ctx = (AtExitCtx*)arg;
457   ((void(*)(int status, void *arg))ctx->f)(status, ctx->arg);
458   InternalFree(ctx);
459 }
460 
TSAN_INTERCEPTOR(int,on_exit,void (* f)(int,void *),void * arg)461 TSAN_INTERCEPTOR(int, on_exit, void(*f)(int, void*), void *arg) {
462   if (in_symbolizer())
463     return 0;
464   SCOPED_TSAN_INTERCEPTOR(on_exit, f, arg);
465   AtExitCtx *ctx = (AtExitCtx*)InternalAlloc(sizeof(AtExitCtx));
466   ctx->f = (void(*)())f;
467   ctx->arg = arg;
468   Release(thr, pc, (uptr)ctx);
469   // Memory allocation in __cxa_atexit will race with free during exit,
470   // because we do not see synchronization around atexit callback list.
471   ThreadIgnoreBegin(thr, pc);
472   int res = REAL(on_exit)(on_exit_wrapper, ctx);
473   ThreadIgnoreEnd(thr, pc);
474   return res;
475 }
476 #define TSAN_MAYBE_INTERCEPT_ON_EXIT TSAN_INTERCEPT(on_exit)
477 #else
478 #define TSAN_MAYBE_INTERCEPT_ON_EXIT
479 #endif
480 
481 // Cleanup old bufs.
JmpBufGarbageCollect(ThreadState * thr,uptr sp)482 static void JmpBufGarbageCollect(ThreadState *thr, uptr sp) {
483   for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) {
484     JmpBuf *buf = &thr->jmp_bufs[i];
485     if (buf->sp <= sp) {
486       uptr sz = thr->jmp_bufs.Size();
487       internal_memcpy(buf, &thr->jmp_bufs[sz - 1], sizeof(*buf));
488       thr->jmp_bufs.PopBack();
489       i--;
490     }
491   }
492 }
493 
SetJmp(ThreadState * thr,uptr sp)494 static void SetJmp(ThreadState *thr, uptr sp) {
495   if (!thr->is_inited)  // called from libc guts during bootstrap
496     return;
497   // Cleanup old bufs.
498   JmpBufGarbageCollect(thr, sp);
499   // Remember the buf.
500   JmpBuf *buf = thr->jmp_bufs.PushBack();
501   buf->sp = sp;
502   buf->shadow_stack_pos = thr->shadow_stack_pos;
503   ThreadSignalContext *sctx = SigCtx(thr);
504   buf->int_signal_send = sctx ? sctx->int_signal_send : 0;
505   buf->in_blocking_func = sctx ?
506       atomic_load(&sctx->in_blocking_func, memory_order_relaxed) :
507       false;
508   buf->in_signal_handler = atomic_load(&thr->in_signal_handler,
509       memory_order_relaxed);
510 }
511 
LongJmp(ThreadState * thr,uptr * env)512 static void LongJmp(ThreadState *thr, uptr *env) {
513   uptr sp = ExtractLongJmpSp(env);
514   // Find the saved buf with matching sp.
515   for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) {
516     JmpBuf *buf = &thr->jmp_bufs[i];
517     if (buf->sp == sp) {
518       CHECK_GE(thr->shadow_stack_pos, buf->shadow_stack_pos);
519       // Unwind the stack.
520       while (thr->shadow_stack_pos > buf->shadow_stack_pos)
521         FuncExit(thr);
522       ThreadSignalContext *sctx = SigCtx(thr);
523       if (sctx) {
524         sctx->int_signal_send = buf->int_signal_send;
525         atomic_store(&sctx->in_blocking_func, buf->in_blocking_func,
526             memory_order_relaxed);
527       }
528       atomic_store(&thr->in_signal_handler, buf->in_signal_handler,
529           memory_order_relaxed);
530       JmpBufGarbageCollect(thr, buf->sp - 1);  // do not collect buf->sp
531       return;
532     }
533   }
534   Printf("ThreadSanitizer: can't find longjmp buf\n");
535   CHECK(0);
536 }
537 
538 // FIXME: put everything below into a common extern "C" block?
__tsan_setjmp(uptr sp)539 extern "C" void __tsan_setjmp(uptr sp) {
540   cur_thread_init();
541   SetJmp(cur_thread(), sp);
542 }
543 
544 #if SANITIZER_MAC
545 TSAN_INTERCEPTOR(int, setjmp, void *env);
546 TSAN_INTERCEPTOR(int, _setjmp, void *env);
547 TSAN_INTERCEPTOR(int, sigsetjmp, void *env);
548 #else  // SANITIZER_MAC
549 
550 #if SANITIZER_NETBSD
551 #define setjmp_symname __setjmp14
552 #define sigsetjmp_symname __sigsetjmp14
553 #else
554 #define setjmp_symname setjmp
555 #define sigsetjmp_symname sigsetjmp
556 #endif
557 
558 #define TSAN_INTERCEPTOR_SETJMP_(x) __interceptor_ ## x
559 #define TSAN_INTERCEPTOR_SETJMP__(x) TSAN_INTERCEPTOR_SETJMP_(x)
560 #define TSAN_INTERCEPTOR_SETJMP TSAN_INTERCEPTOR_SETJMP__(setjmp_symname)
561 #define TSAN_INTERCEPTOR_SIGSETJMP TSAN_INTERCEPTOR_SETJMP__(sigsetjmp_symname)
562 
563 #define TSAN_STRING_SETJMP SANITIZER_STRINGIFY(setjmp_symname)
564 #define TSAN_STRING_SIGSETJMP SANITIZER_STRINGIFY(sigsetjmp_symname)
565 
566 // Not called.  Merely to satisfy TSAN_INTERCEPT().
567 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
568 int TSAN_INTERCEPTOR_SETJMP(void *env);
TSAN_INTERCEPTOR_SETJMP(void * env)569 extern "C" int TSAN_INTERCEPTOR_SETJMP(void *env) {
570   CHECK(0);
571   return 0;
572 }
573 
574 // FIXME: any reason to have a separate declaration?
575 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
576 int __interceptor__setjmp(void *env);
__interceptor__setjmp(void * env)577 extern "C" int __interceptor__setjmp(void *env) {
578   CHECK(0);
579   return 0;
580 }
581 
582 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
583 int TSAN_INTERCEPTOR_SIGSETJMP(void *env);
TSAN_INTERCEPTOR_SIGSETJMP(void * env)584 extern "C" int TSAN_INTERCEPTOR_SIGSETJMP(void *env) {
585   CHECK(0);
586   return 0;
587 }
588 
589 #if !SANITIZER_NETBSD
590 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
591 int __interceptor___sigsetjmp(void *env);
__interceptor___sigsetjmp(void * env)592 extern "C" int __interceptor___sigsetjmp(void *env) {
593   CHECK(0);
594   return 0;
595 }
596 #endif
597 
598 extern "C" int setjmp_symname(void *env);
599 extern "C" int _setjmp(void *env);
600 extern "C" int sigsetjmp_symname(void *env);
601 #if !SANITIZER_NETBSD
602 extern "C" int __sigsetjmp(void *env);
603 #endif
DEFINE_REAL(int,setjmp_symname,void * env)604 DEFINE_REAL(int, setjmp_symname, void *env)
605 DEFINE_REAL(int, _setjmp, void *env)
606 DEFINE_REAL(int, sigsetjmp_symname, void *env)
607 #if !SANITIZER_NETBSD
608 DEFINE_REAL(int, __sigsetjmp, void *env)
609 #endif
610 #endif  // SANITIZER_MAC
611 
612 #if SANITIZER_NETBSD
613 #define longjmp_symname __longjmp14
614 #define siglongjmp_symname __siglongjmp14
615 #else
616 #define longjmp_symname longjmp
617 #define siglongjmp_symname siglongjmp
618 #endif
619 
620 TSAN_INTERCEPTOR(void, longjmp_symname, uptr *env, int val) {
621   // Note: if we call REAL(longjmp) in the context of ScopedInterceptor,
622   // bad things will happen. We will jump over ScopedInterceptor dtor and can
623   // leave thr->in_ignored_lib set.
624   {
625     SCOPED_INTERCEPTOR_RAW(longjmp_symname, env, val);
626   }
627   LongJmp(cur_thread(), env);
628   REAL(longjmp_symname)(env, val);
629 }
630 
TSAN_INTERCEPTOR(void,siglongjmp_symname,uptr * env,int val)631 TSAN_INTERCEPTOR(void, siglongjmp_symname, uptr *env, int val) {
632   {
633     SCOPED_INTERCEPTOR_RAW(siglongjmp_symname, env, val);
634   }
635   LongJmp(cur_thread(), env);
636   REAL(siglongjmp_symname)(env, val);
637 }
638 
639 #if SANITIZER_NETBSD
TSAN_INTERCEPTOR(void,_longjmp,uptr * env,int val)640 TSAN_INTERCEPTOR(void, _longjmp, uptr *env, int val) {
641   {
642     SCOPED_INTERCEPTOR_RAW(_longjmp, env, val);
643   }
644   LongJmp(cur_thread(), env);
645   REAL(_longjmp)(env, val);
646 }
647 #endif
648 
649 #if !SANITIZER_MAC
TSAN_INTERCEPTOR(void *,malloc,uptr size)650 TSAN_INTERCEPTOR(void*, malloc, uptr size) {
651   if (in_symbolizer())
652     return InternalAlloc(size);
653   void *p = 0;
654   {
655     SCOPED_INTERCEPTOR_RAW(malloc, size);
656     p = user_alloc(thr, pc, size);
657   }
658   invoke_malloc_hook(p, size);
659   return p;
660 }
661 
662 // In glibc<2.25, dynamic TLS blocks are allocated by __libc_memalign. Intercept
663 // __libc_memalign so that (1) we can detect races (2) free will not be called
664 // on libc internally allocated blocks.
TSAN_INTERCEPTOR(void *,__libc_memalign,uptr align,uptr sz)665 TSAN_INTERCEPTOR(void*, __libc_memalign, uptr align, uptr sz) {
666   SCOPED_INTERCEPTOR_RAW(__libc_memalign, align, sz);
667   return user_memalign(thr, pc, align, sz);
668 }
669 
TSAN_INTERCEPTOR(void *,calloc,uptr size,uptr n)670 TSAN_INTERCEPTOR(void*, calloc, uptr size, uptr n) {
671   if (in_symbolizer())
672     return InternalCalloc(size, n);
673   void *p = 0;
674   {
675     SCOPED_INTERCEPTOR_RAW(calloc, size, n);
676     p = user_calloc(thr, pc, size, n);
677   }
678   invoke_malloc_hook(p, n * size);
679   return p;
680 }
681 
TSAN_INTERCEPTOR(void *,realloc,void * p,uptr size)682 TSAN_INTERCEPTOR(void*, realloc, void *p, uptr size) {
683   if (in_symbolizer())
684     return InternalRealloc(p, size);
685   if (p)
686     invoke_free_hook(p);
687   {
688     SCOPED_INTERCEPTOR_RAW(realloc, p, size);
689     p = user_realloc(thr, pc, p, size);
690   }
691   invoke_malloc_hook(p, size);
692   return p;
693 }
694 
TSAN_INTERCEPTOR(void *,reallocarray,void * p,uptr size,uptr n)695 TSAN_INTERCEPTOR(void*, reallocarray, void *p, uptr size, uptr n) {
696   if (in_symbolizer())
697     return InternalReallocArray(p, size, n);
698   if (p)
699     invoke_free_hook(p);
700   {
701     SCOPED_INTERCEPTOR_RAW(reallocarray, p, size, n);
702     p = user_reallocarray(thr, pc, p, size, n);
703   }
704   invoke_malloc_hook(p, size);
705   return p;
706 }
707 
TSAN_INTERCEPTOR(void,free,void * p)708 TSAN_INTERCEPTOR(void, free, void *p) {
709   if (p == 0)
710     return;
711   if (in_symbolizer())
712     return InternalFree(p);
713   invoke_free_hook(p);
714   SCOPED_INTERCEPTOR_RAW(free, p);
715   user_free(thr, pc, p);
716 }
717 
TSAN_INTERCEPTOR(void,cfree,void * p)718 TSAN_INTERCEPTOR(void, cfree, void *p) {
719   if (p == 0)
720     return;
721   if (in_symbolizer())
722     return InternalFree(p);
723   invoke_free_hook(p);
724   SCOPED_INTERCEPTOR_RAW(cfree, p);
725   user_free(thr, pc, p);
726 }
727 
TSAN_INTERCEPTOR(uptr,malloc_usable_size,void * p)728 TSAN_INTERCEPTOR(uptr, malloc_usable_size, void *p) {
729   SCOPED_INTERCEPTOR_RAW(malloc_usable_size, p);
730   return user_alloc_usable_size(p);
731 }
732 #endif
733 
TSAN_INTERCEPTOR(char *,strcpy,char * dst,const char * src)734 TSAN_INTERCEPTOR(char *, strcpy, char *dst, const char *src) {
735   SCOPED_TSAN_INTERCEPTOR(strcpy, dst, src);
736   uptr srclen = internal_strlen(src);
737   MemoryAccessRange(thr, pc, (uptr)dst, srclen + 1, true);
738   MemoryAccessRange(thr, pc, (uptr)src, srclen + 1, false);
739   return REAL(strcpy)(dst, src);
740 }
741 
TSAN_INTERCEPTOR(char *,strncpy,char * dst,char * src,uptr n)742 TSAN_INTERCEPTOR(char*, strncpy, char *dst, char *src, uptr n) {
743   SCOPED_TSAN_INTERCEPTOR(strncpy, dst, src, n);
744   uptr srclen = internal_strnlen(src, n);
745   MemoryAccessRange(thr, pc, (uptr)dst, n, true);
746   MemoryAccessRange(thr, pc, (uptr)src, min(srclen + 1, n), false);
747   return REAL(strncpy)(dst, src, n);
748 }
749 
TSAN_INTERCEPTOR(char *,strdup,const char * str)750 TSAN_INTERCEPTOR(char*, strdup, const char *str) {
751   SCOPED_TSAN_INTERCEPTOR(strdup, str);
752   // strdup will call malloc, so no instrumentation is required here.
753   return REAL(strdup)(str);
754 }
755 
756 // Zero out addr if it points into shadow memory and was provided as a hint
757 // only, i.e., MAP_FIXED is not set.
fix_mmap_addr(void ** addr,long_t sz,int flags)758 static bool fix_mmap_addr(void **addr, long_t sz, int flags) {
759   if (*addr) {
760     if (!IsAppMem((uptr)*addr) || !IsAppMem((uptr)*addr + sz - 1)) {
761       if (flags & MAP_FIXED) {
762         errno = errno_EINVAL;
763         return false;
764       } else {
765         *addr = 0;
766       }
767     }
768   }
769   return true;
770 }
771 
772 template <class Mmap>
mmap_interceptor(ThreadState * thr,uptr pc,Mmap real_mmap,void * addr,SIZE_T sz,int prot,int flags,int fd,OFF64_T off)773 static void *mmap_interceptor(ThreadState *thr, uptr pc, Mmap real_mmap,
774                               void *addr, SIZE_T sz, int prot, int flags,
775                               int fd, OFF64_T off) {
776   if (!fix_mmap_addr(&addr, sz, flags)) return MAP_FAILED;
777   void *res = real_mmap(addr, sz, prot, flags, fd, off);
778   if (res != MAP_FAILED) {
779     if (!IsAppMem((uptr)res) || !IsAppMem((uptr)res + sz - 1)) {
780       Report("ThreadSanitizer: mmap at bad address: addr=%p size=%p res=%p\n",
781              addr, (void*)sz, res);
782       Die();
783     }
784     if (fd > 0) FdAccess(thr, pc, fd);
785     MemoryRangeImitateWriteOrResetRange(thr, pc, (uptr)res, sz);
786   }
787   return res;
788 }
789 
TSAN_INTERCEPTOR(int,munmap,void * addr,long_t sz)790 TSAN_INTERCEPTOR(int, munmap, void *addr, long_t sz) {
791   SCOPED_TSAN_INTERCEPTOR(munmap, addr, sz);
792   UnmapShadow(thr, (uptr)addr, sz);
793   int res = REAL(munmap)(addr, sz);
794   return res;
795 }
796 
797 #if SANITIZER_LINUX
TSAN_INTERCEPTOR(void *,memalign,uptr align,uptr sz)798 TSAN_INTERCEPTOR(void*, memalign, uptr align, uptr sz) {
799   SCOPED_INTERCEPTOR_RAW(memalign, align, sz);
800   return user_memalign(thr, pc, align, sz);
801 }
802 #define TSAN_MAYBE_INTERCEPT_MEMALIGN TSAN_INTERCEPT(memalign)
803 #else
804 #define TSAN_MAYBE_INTERCEPT_MEMALIGN
805 #endif
806 
807 #if !SANITIZER_MAC
TSAN_INTERCEPTOR(void *,aligned_alloc,uptr align,uptr sz)808 TSAN_INTERCEPTOR(void*, aligned_alloc, uptr align, uptr sz) {
809   if (in_symbolizer())
810     return InternalAlloc(sz, nullptr, align);
811   SCOPED_INTERCEPTOR_RAW(aligned_alloc, align, sz);
812   return user_aligned_alloc(thr, pc, align, sz);
813 }
814 
TSAN_INTERCEPTOR(void *,valloc,uptr sz)815 TSAN_INTERCEPTOR(void*, valloc, uptr sz) {
816   if (in_symbolizer())
817     return InternalAlloc(sz, nullptr, GetPageSizeCached());
818   SCOPED_INTERCEPTOR_RAW(valloc, sz);
819   return user_valloc(thr, pc, sz);
820 }
821 #endif
822 
823 #if SANITIZER_LINUX
TSAN_INTERCEPTOR(void *,pvalloc,uptr sz)824 TSAN_INTERCEPTOR(void*, pvalloc, uptr sz) {
825   if (in_symbolizer()) {
826     uptr PageSize = GetPageSizeCached();
827     sz = sz ? RoundUpTo(sz, PageSize) : PageSize;
828     return InternalAlloc(sz, nullptr, PageSize);
829   }
830   SCOPED_INTERCEPTOR_RAW(pvalloc, sz);
831   return user_pvalloc(thr, pc, sz);
832 }
833 #define TSAN_MAYBE_INTERCEPT_PVALLOC TSAN_INTERCEPT(pvalloc)
834 #else
835 #define TSAN_MAYBE_INTERCEPT_PVALLOC
836 #endif
837 
838 #if !SANITIZER_MAC
TSAN_INTERCEPTOR(int,posix_memalign,void ** memptr,uptr align,uptr sz)839 TSAN_INTERCEPTOR(int, posix_memalign, void **memptr, uptr align, uptr sz) {
840   if (in_symbolizer()) {
841     void *p = InternalAlloc(sz, nullptr, align);
842     if (!p)
843       return errno_ENOMEM;
844     *memptr = p;
845     return 0;
846   }
847   SCOPED_INTERCEPTOR_RAW(posix_memalign, memptr, align, sz);
848   return user_posix_memalign(thr, pc, memptr, align, sz);
849 }
850 #endif
851 
852 // __cxa_guard_acquire and friends need to be intercepted in a special way -
853 // regular interceptors will break statically-linked libstdc++. Linux
854 // interceptors are especially defined as weak functions (so that they don't
855 // cause link errors when user defines them as well). So they silently
856 // auto-disable themselves when such symbol is already present in the binary. If
857 // we link libstdc++ statically, it will bring own __cxa_guard_acquire which
858 // will silently replace our interceptor.  That's why on Linux we simply export
859 // these interceptors with INTERFACE_ATTRIBUTE.
860 // On OS X, we don't support statically linking, so we just use a regular
861 // interceptor.
862 #if SANITIZER_MAC
863 #define STDCXX_INTERCEPTOR TSAN_INTERCEPTOR
864 #else
865 #define STDCXX_INTERCEPTOR(rettype, name, ...) \
866   extern "C" rettype INTERFACE_ATTRIBUTE name(__VA_ARGS__)
867 #endif
868 
869 // Used in thread-safe function static initialization.
STDCXX_INTERCEPTOR(int,__cxa_guard_acquire,atomic_uint32_t * g)870 STDCXX_INTERCEPTOR(int, __cxa_guard_acquire, atomic_uint32_t *g) {
871   SCOPED_INTERCEPTOR_RAW(__cxa_guard_acquire, g);
872   OnPotentiallyBlockingRegionBegin();
873   auto on_exit = at_scope_exit(&OnPotentiallyBlockingRegionEnd);
874   for (;;) {
875     u32 cmp = atomic_load(g, memory_order_acquire);
876     if (cmp == 0) {
877       if (atomic_compare_exchange_strong(g, &cmp, 1<<16, memory_order_relaxed))
878         return 1;
879     } else if (cmp == 1) {
880       Acquire(thr, pc, (uptr)g);
881       return 0;
882     } else {
883       internal_sched_yield();
884     }
885   }
886 }
887 
STDCXX_INTERCEPTOR(void,__cxa_guard_release,atomic_uint32_t * g)888 STDCXX_INTERCEPTOR(void, __cxa_guard_release, atomic_uint32_t *g) {
889   SCOPED_INTERCEPTOR_RAW(__cxa_guard_release, g);
890   Release(thr, pc, (uptr)g);
891   atomic_store(g, 1, memory_order_release);
892 }
893 
STDCXX_INTERCEPTOR(void,__cxa_guard_abort,atomic_uint32_t * g)894 STDCXX_INTERCEPTOR(void, __cxa_guard_abort, atomic_uint32_t *g) {
895   SCOPED_INTERCEPTOR_RAW(__cxa_guard_abort, g);
896   atomic_store(g, 0, memory_order_relaxed);
897 }
898 
899 namespace __tsan {
DestroyThreadState()900 void DestroyThreadState() {
901   ThreadState *thr = cur_thread();
902   Processor *proc = thr->proc();
903   ThreadFinish(thr);
904   ProcUnwire(proc, thr);
905   ProcDestroy(proc);
906   DTLS_Destroy();
907   cur_thread_finalize();
908 }
909 
PlatformCleanUpThreadState(ThreadState * thr)910 void PlatformCleanUpThreadState(ThreadState *thr) {
911   ThreadSignalContext *sctx = thr->signal_ctx;
912   if (sctx) {
913     thr->signal_ctx = 0;
914     UnmapOrDie(sctx, sizeof(*sctx));
915   }
916 }
917 }  // namespace __tsan
918 
919 #if !SANITIZER_MAC && !SANITIZER_NETBSD && !SANITIZER_FREEBSD
thread_finalize(void * v)920 static void thread_finalize(void *v) {
921   uptr iter = (uptr)v;
922   if (iter > 1) {
923     if (pthread_setspecific(interceptor_ctx()->finalize_key,
924         (void*)(iter - 1))) {
925       Printf("ThreadSanitizer: failed to set thread key\n");
926       Die();
927     }
928     return;
929   }
930   DestroyThreadState();
931 }
932 #endif
933 
934 
935 struct ThreadParam {
936   void* (*callback)(void *arg);
937   void *param;
938   atomic_uintptr_t tid;
939 };
940 
__tsan_thread_start_func(void * arg)941 extern "C" void *__tsan_thread_start_func(void *arg) {
942   ThreadParam *p = (ThreadParam*)arg;
943   void* (*callback)(void *arg) = p->callback;
944   void *param = p->param;
945   int tid = 0;
946   {
947     cur_thread_init();
948     ThreadState *thr = cur_thread();
949     // Thread-local state is not initialized yet.
950     ScopedIgnoreInterceptors ignore;
951 #if !SANITIZER_MAC && !SANITIZER_NETBSD && !SANITIZER_FREEBSD
952     ThreadIgnoreBegin(thr, 0);
953     if (pthread_setspecific(interceptor_ctx()->finalize_key,
954                             (void *)GetPthreadDestructorIterations())) {
955       Printf("ThreadSanitizer: failed to set thread key\n");
956       Die();
957     }
958     ThreadIgnoreEnd(thr, 0);
959 #endif
960     while ((tid = atomic_load(&p->tid, memory_order_acquire)) == 0)
961       internal_sched_yield();
962     Processor *proc = ProcCreate();
963     ProcWire(proc, thr);
964     ThreadStart(thr, tid, GetTid(), ThreadType::Regular);
965     atomic_store(&p->tid, 0, memory_order_release);
966   }
967   void *res = callback(param);
968   // Prevent the callback from being tail called,
969   // it mixes up stack traces.
970   volatile int foo = 42;
971   foo++;
972   return res;
973 }
974 
TSAN_INTERCEPTOR(int,pthread_create,void * th,void * attr,void * (* callback)(void *),void * param)975 TSAN_INTERCEPTOR(int, pthread_create,
976     void *th, void *attr, void *(*callback)(void*), void * param) {
977   SCOPED_INTERCEPTOR_RAW(pthread_create, th, attr, callback, param);
978 
979   MaybeSpawnBackgroundThread();
980 
981   if (ctx->after_multithreaded_fork) {
982     if (flags()->die_after_fork) {
983       Report("ThreadSanitizer: starting new threads after multi-threaded "
984           "fork is not supported. Dying (set die_after_fork=0 to override)\n");
985       Die();
986     } else {
987       VPrintf(1, "ThreadSanitizer: starting new threads after multi-threaded "
988           "fork is not supported (pid %d). Continuing because of "
989           "die_after_fork=0, but you are on your own\n", internal_getpid());
990     }
991   }
992   __sanitizer_pthread_attr_t myattr;
993   if (attr == 0) {
994     pthread_attr_init(&myattr);
995     attr = &myattr;
996   }
997   int detached = 0;
998   REAL(pthread_attr_getdetachstate)(attr, &detached);
999   AdjustStackSize(attr);
1000 
1001   ThreadParam p;
1002   p.callback = callback;
1003   p.param = param;
1004   atomic_store(&p.tid, 0, memory_order_relaxed);
1005   int res = -1;
1006   {
1007     // Otherwise we see false positives in pthread stack manipulation.
1008     ScopedIgnoreInterceptors ignore;
1009     ThreadIgnoreBegin(thr, pc);
1010     res = REAL(pthread_create)(th, attr, __tsan_thread_start_func, &p);
1011     ThreadIgnoreEnd(thr, pc);
1012   }
1013   if (res == 0) {
1014     int tid = ThreadCreate(thr, pc, *(uptr*)th, IsStateDetached(detached));
1015     CHECK_NE(tid, 0);
1016     // Synchronization on p.tid serves two purposes:
1017     // 1. ThreadCreate must finish before the new thread starts.
1018     //    Otherwise the new thread can call pthread_detach, but the pthread_t
1019     //    identifier is not yet registered in ThreadRegistry by ThreadCreate.
1020     // 2. ThreadStart must finish before this thread continues.
1021     //    Otherwise, this thread can call pthread_detach and reset thr->sync
1022     //    before the new thread got a chance to acquire from it in ThreadStart.
1023     atomic_store(&p.tid, tid, memory_order_release);
1024     while (atomic_load(&p.tid, memory_order_acquire) != 0)
1025       internal_sched_yield();
1026   }
1027   if (attr == &myattr)
1028     pthread_attr_destroy(&myattr);
1029   return res;
1030 }
1031 
TSAN_INTERCEPTOR(int,pthread_join,void * th,void ** ret)1032 TSAN_INTERCEPTOR(int, pthread_join, void *th, void **ret) {
1033   SCOPED_INTERCEPTOR_RAW(pthread_join, th, ret);
1034   int tid = ThreadConsumeTid(thr, pc, (uptr)th);
1035   ThreadIgnoreBegin(thr, pc);
1036   int res = BLOCK_REAL(pthread_join)(th, ret);
1037   ThreadIgnoreEnd(thr, pc);
1038   if (res == 0) {
1039     ThreadJoin(thr, pc, tid);
1040   }
1041   return res;
1042 }
1043 
1044 DEFINE_REAL_PTHREAD_FUNCTIONS
1045 
TSAN_INTERCEPTOR(int,pthread_detach,void * th)1046 TSAN_INTERCEPTOR(int, pthread_detach, void *th) {
1047   SCOPED_INTERCEPTOR_RAW(pthread_detach, th);
1048   int tid = ThreadConsumeTid(thr, pc, (uptr)th);
1049   int res = REAL(pthread_detach)(th);
1050   if (res == 0) {
1051     ThreadDetach(thr, pc, tid);
1052   }
1053   return res;
1054 }
1055 
TSAN_INTERCEPTOR(void,pthread_exit,void * retval)1056 TSAN_INTERCEPTOR(void, pthread_exit, void *retval) {
1057   {
1058     SCOPED_INTERCEPTOR_RAW(pthread_exit, retval);
1059 #if !SANITIZER_MAC && !SANITIZER_ANDROID
1060     CHECK_EQ(thr, &cur_thread_placeholder);
1061 #endif
1062   }
1063   REAL(pthread_exit)(retval);
1064 }
1065 
1066 #if SANITIZER_LINUX
TSAN_INTERCEPTOR(int,pthread_tryjoin_np,void * th,void ** ret)1067 TSAN_INTERCEPTOR(int, pthread_tryjoin_np, void *th, void **ret) {
1068   SCOPED_INTERCEPTOR_RAW(pthread_tryjoin_np, th, ret);
1069   int tid = ThreadConsumeTid(thr, pc, (uptr)th);
1070   ThreadIgnoreBegin(thr, pc);
1071   int res = REAL(pthread_tryjoin_np)(th, ret);
1072   ThreadIgnoreEnd(thr, pc);
1073   if (res == 0)
1074     ThreadJoin(thr, pc, tid);
1075   else
1076     ThreadNotJoined(thr, pc, tid, (uptr)th);
1077   return res;
1078 }
1079 
TSAN_INTERCEPTOR(int,pthread_timedjoin_np,void * th,void ** ret,const struct timespec * abstime)1080 TSAN_INTERCEPTOR(int, pthread_timedjoin_np, void *th, void **ret,
1081                  const struct timespec *abstime) {
1082   SCOPED_INTERCEPTOR_RAW(pthread_timedjoin_np, th, ret, abstime);
1083   int tid = ThreadConsumeTid(thr, pc, (uptr)th);
1084   ThreadIgnoreBegin(thr, pc);
1085   int res = BLOCK_REAL(pthread_timedjoin_np)(th, ret, abstime);
1086   ThreadIgnoreEnd(thr, pc);
1087   if (res == 0)
1088     ThreadJoin(thr, pc, tid);
1089   else
1090     ThreadNotJoined(thr, pc, tid, (uptr)th);
1091   return res;
1092 }
1093 #endif
1094 
1095 // Problem:
1096 // NPTL implementation of pthread_cond has 2 versions (2.2.5 and 2.3.2).
1097 // pthread_cond_t has different size in the different versions.
1098 // If call new REAL functions for old pthread_cond_t, they will corrupt memory
1099 // after pthread_cond_t (old cond is smaller).
1100 // If we call old REAL functions for new pthread_cond_t, we will lose  some
1101 // functionality (e.g. old functions do not support waiting against
1102 // CLOCK_REALTIME).
1103 // Proper handling would require to have 2 versions of interceptors as well.
1104 // But this is messy, in particular requires linker scripts when sanitizer
1105 // runtime is linked into a shared library.
1106 // Instead we assume we don't have dynamic libraries built against old
1107 // pthread (2.2.5 is dated by 2002). And provide legacy_pthread_cond flag
1108 // that allows to work with old libraries (but this mode does not support
1109 // some features, e.g. pthread_condattr_getpshared).
init_cond(void * c,bool force=false)1110 static void *init_cond(void *c, bool force = false) {
1111   // sizeof(pthread_cond_t) >= sizeof(uptr) in both versions.
1112   // So we allocate additional memory on the side large enough to hold
1113   // any pthread_cond_t object. Always call new REAL functions, but pass
1114   // the aux object to them.
1115   // Note: the code assumes that PTHREAD_COND_INITIALIZER initializes
1116   // first word of pthread_cond_t to zero.
1117   // It's all relevant only for linux.
1118   if (!common_flags()->legacy_pthread_cond)
1119     return c;
1120   atomic_uintptr_t *p = (atomic_uintptr_t*)c;
1121   uptr cond = atomic_load(p, memory_order_acquire);
1122   if (!force && cond != 0)
1123     return (void*)cond;
1124   void *newcond = WRAP(malloc)(pthread_cond_t_sz);
1125   internal_memset(newcond, 0, pthread_cond_t_sz);
1126   if (atomic_compare_exchange_strong(p, &cond, (uptr)newcond,
1127       memory_order_acq_rel))
1128     return newcond;
1129   WRAP(free)(newcond);
1130   return (void*)cond;
1131 }
1132 
1133 namespace {
1134 
1135 template <class Fn>
1136 struct CondMutexUnlockCtx {
1137   ScopedInterceptor *si;
1138   ThreadState *thr;
1139   uptr pc;
1140   void *m;
1141   void *c;
1142   const Fn &fn;
1143 
Cancel__anondff5d7540111::CondMutexUnlockCtx1144   int Cancel() const { return fn(); }
1145   void Unlock() const;
1146 };
1147 
1148 template <class Fn>
Unlock() const1149 void CondMutexUnlockCtx<Fn>::Unlock() const {
1150   // pthread_cond_wait interceptor has enabled async signal delivery
1151   // (see BlockingCall below). Disable async signals since we are running
1152   // tsan code. Also ScopedInterceptor and BlockingCall destructors won't run
1153   // since the thread is cancelled, so we have to manually execute them
1154   // (the thread still can run some user code due to pthread_cleanup_push).
1155   ThreadSignalContext *ctx = SigCtx(thr);
1156   CHECK_EQ(atomic_load(&ctx->in_blocking_func, memory_order_relaxed), 1);
1157   atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
1158   MutexPostLock(thr, pc, (uptr)m, MutexFlagDoPreLockOnPostLock);
1159   // Undo BlockingCall ctor effects.
1160   thr->ignore_interceptors--;
1161   si->~ScopedInterceptor();
1162 }
1163 }  // namespace
1164 
INTERCEPTOR(int,pthread_cond_init,void * c,void * a)1165 INTERCEPTOR(int, pthread_cond_init, void *c, void *a) {
1166   void *cond = init_cond(c, true);
1167   SCOPED_TSAN_INTERCEPTOR(pthread_cond_init, cond, a);
1168   MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true);
1169   return REAL(pthread_cond_init)(cond, a);
1170 }
1171 
1172 template <class Fn>
cond_wait(ThreadState * thr,uptr pc,ScopedInterceptor * si,const Fn & fn,void * c,void * m)1173 int cond_wait(ThreadState *thr, uptr pc, ScopedInterceptor *si, const Fn &fn,
1174               void *c, void *m) {
1175   MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1176   MutexUnlock(thr, pc, (uptr)m);
1177   int res = 0;
1178   // This ensures that we handle mutex lock even in case of pthread_cancel.
1179   // See test/tsan/cond_cancel.cpp.
1180   {
1181     // Enable signal delivery while the thread is blocked.
1182     BlockingCall bc(thr);
1183     CondMutexUnlockCtx<Fn> arg = {si, thr, pc, m, c, fn};
1184     res = call_pthread_cancel_with_cleanup(
1185         [](void *arg) -> int {
1186           return ((const CondMutexUnlockCtx<Fn> *)arg)->Cancel();
1187         },
1188         [](void *arg) { ((const CondMutexUnlockCtx<Fn> *)arg)->Unlock(); },
1189         &arg);
1190   }
1191   if (res == errno_EOWNERDEAD) MutexRepair(thr, pc, (uptr)m);
1192   MutexPostLock(thr, pc, (uptr)m, MutexFlagDoPreLockOnPostLock);
1193   return res;
1194 }
1195 
INTERCEPTOR(int,pthread_cond_wait,void * c,void * m)1196 INTERCEPTOR(int, pthread_cond_wait, void *c, void *m) {
1197   void *cond = init_cond(c);
1198   SCOPED_TSAN_INTERCEPTOR(pthread_cond_wait, cond, m);
1199   return cond_wait(
1200       thr, pc, &si, [=]() { return REAL(pthread_cond_wait)(cond, m); }, cond,
1201       m);
1202 }
1203 
INTERCEPTOR(int,pthread_cond_timedwait,void * c,void * m,void * abstime)1204 INTERCEPTOR(int, pthread_cond_timedwait, void *c, void *m, void *abstime) {
1205   void *cond = init_cond(c);
1206   SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait, cond, m, abstime);
1207   return cond_wait(
1208       thr, pc, &si,
1209       [=]() { return REAL(pthread_cond_timedwait)(cond, m, abstime); }, cond,
1210       m);
1211 }
1212 
1213 #if SANITIZER_LINUX
INTERCEPTOR(int,pthread_cond_clockwait,void * c,void * m,__sanitizer_clockid_t clock,void * abstime)1214 INTERCEPTOR(int, pthread_cond_clockwait, void *c, void *m,
1215             __sanitizer_clockid_t clock, void *abstime) {
1216   void *cond = init_cond(c);
1217   SCOPED_TSAN_INTERCEPTOR(pthread_cond_clockwait, cond, m, clock, abstime);
1218   return cond_wait(
1219       thr, pc, &si,
1220       [=]() { return REAL(pthread_cond_clockwait)(cond, m, clock, abstime); },
1221       cond, m);
1222 }
1223 #define TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT TSAN_INTERCEPT(pthread_cond_clockwait)
1224 #else
1225 #define TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT
1226 #endif
1227 
1228 #if SANITIZER_MAC
INTERCEPTOR(int,pthread_cond_timedwait_relative_np,void * c,void * m,void * reltime)1229 INTERCEPTOR(int, pthread_cond_timedwait_relative_np, void *c, void *m,
1230             void *reltime) {
1231   void *cond = init_cond(c);
1232   SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait_relative_np, cond, m, reltime);
1233   return cond_wait(
1234       thr, pc, &si,
1235       [=]() {
1236         return REAL(pthread_cond_timedwait_relative_np)(cond, m, reltime);
1237       },
1238       cond, m);
1239 }
1240 #endif
1241 
INTERCEPTOR(int,pthread_cond_signal,void * c)1242 INTERCEPTOR(int, pthread_cond_signal, void *c) {
1243   void *cond = init_cond(c);
1244   SCOPED_TSAN_INTERCEPTOR(pthread_cond_signal, cond);
1245   MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1246   return REAL(pthread_cond_signal)(cond);
1247 }
1248 
INTERCEPTOR(int,pthread_cond_broadcast,void * c)1249 INTERCEPTOR(int, pthread_cond_broadcast, void *c) {
1250   void *cond = init_cond(c);
1251   SCOPED_TSAN_INTERCEPTOR(pthread_cond_broadcast, cond);
1252   MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
1253   return REAL(pthread_cond_broadcast)(cond);
1254 }
1255 
INTERCEPTOR(int,pthread_cond_destroy,void * c)1256 INTERCEPTOR(int, pthread_cond_destroy, void *c) {
1257   void *cond = init_cond(c);
1258   SCOPED_TSAN_INTERCEPTOR(pthread_cond_destroy, cond);
1259   MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true);
1260   int res = REAL(pthread_cond_destroy)(cond);
1261   if (common_flags()->legacy_pthread_cond) {
1262     // Free our aux cond and zero the pointer to not leave dangling pointers.
1263     WRAP(free)(cond);
1264     atomic_store((atomic_uintptr_t*)c, 0, memory_order_relaxed);
1265   }
1266   return res;
1267 }
1268 
TSAN_INTERCEPTOR(int,pthread_mutex_init,void * m,void * a)1269 TSAN_INTERCEPTOR(int, pthread_mutex_init, void *m, void *a) {
1270   SCOPED_TSAN_INTERCEPTOR(pthread_mutex_init, m, a);
1271   int res = REAL(pthread_mutex_init)(m, a);
1272   if (res == 0) {
1273     u32 flagz = 0;
1274     if (a) {
1275       int type = 0;
1276       if (REAL(pthread_mutexattr_gettype)(a, &type) == 0)
1277         if (type == PTHREAD_MUTEX_RECURSIVE ||
1278             type == PTHREAD_MUTEX_RECURSIVE_NP)
1279           flagz |= MutexFlagWriteReentrant;
1280     }
1281     MutexCreate(thr, pc, (uptr)m, flagz);
1282   }
1283   return res;
1284 }
1285 
TSAN_INTERCEPTOR(int,pthread_mutex_destroy,void * m)1286 TSAN_INTERCEPTOR(int, pthread_mutex_destroy, void *m) {
1287   SCOPED_TSAN_INTERCEPTOR(pthread_mutex_destroy, m);
1288   int res = REAL(pthread_mutex_destroy)(m);
1289   if (res == 0 || res == errno_EBUSY) {
1290     MutexDestroy(thr, pc, (uptr)m);
1291   }
1292   return res;
1293 }
1294 
TSAN_INTERCEPTOR(int,pthread_mutex_trylock,void * m)1295 TSAN_INTERCEPTOR(int, pthread_mutex_trylock, void *m) {
1296   SCOPED_TSAN_INTERCEPTOR(pthread_mutex_trylock, m);
1297   int res = REAL(pthread_mutex_trylock)(m);
1298   if (res == errno_EOWNERDEAD)
1299     MutexRepair(thr, pc, (uptr)m);
1300   if (res == 0 || res == errno_EOWNERDEAD)
1301     MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1302   return res;
1303 }
1304 
1305 #if !SANITIZER_MAC
TSAN_INTERCEPTOR(int,pthread_mutex_timedlock,void * m,void * abstime)1306 TSAN_INTERCEPTOR(int, pthread_mutex_timedlock, void *m, void *abstime) {
1307   SCOPED_TSAN_INTERCEPTOR(pthread_mutex_timedlock, m, abstime);
1308   int res = REAL(pthread_mutex_timedlock)(m, abstime);
1309   if (res == 0) {
1310     MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1311   }
1312   return res;
1313 }
1314 #endif
1315 
1316 #if !SANITIZER_MAC
TSAN_INTERCEPTOR(int,pthread_spin_init,void * m,int pshared)1317 TSAN_INTERCEPTOR(int, pthread_spin_init, void *m, int pshared) {
1318   SCOPED_TSAN_INTERCEPTOR(pthread_spin_init, m, pshared);
1319   int res = REAL(pthread_spin_init)(m, pshared);
1320   if (res == 0) {
1321     MutexCreate(thr, pc, (uptr)m);
1322   }
1323   return res;
1324 }
1325 
TSAN_INTERCEPTOR(int,pthread_spin_destroy,void * m)1326 TSAN_INTERCEPTOR(int, pthread_spin_destroy, void *m) {
1327   SCOPED_TSAN_INTERCEPTOR(pthread_spin_destroy, m);
1328   int res = REAL(pthread_spin_destroy)(m);
1329   if (res == 0) {
1330     MutexDestroy(thr, pc, (uptr)m);
1331   }
1332   return res;
1333 }
1334 
TSAN_INTERCEPTOR(int,pthread_spin_lock,void * m)1335 TSAN_INTERCEPTOR(int, pthread_spin_lock, void *m) {
1336   SCOPED_TSAN_INTERCEPTOR(pthread_spin_lock, m);
1337   MutexPreLock(thr, pc, (uptr)m);
1338   int res = REAL(pthread_spin_lock)(m);
1339   if (res == 0) {
1340     MutexPostLock(thr, pc, (uptr)m);
1341   }
1342   return res;
1343 }
1344 
TSAN_INTERCEPTOR(int,pthread_spin_trylock,void * m)1345 TSAN_INTERCEPTOR(int, pthread_spin_trylock, void *m) {
1346   SCOPED_TSAN_INTERCEPTOR(pthread_spin_trylock, m);
1347   int res = REAL(pthread_spin_trylock)(m);
1348   if (res == 0) {
1349     MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1350   }
1351   return res;
1352 }
1353 
TSAN_INTERCEPTOR(int,pthread_spin_unlock,void * m)1354 TSAN_INTERCEPTOR(int, pthread_spin_unlock, void *m) {
1355   SCOPED_TSAN_INTERCEPTOR(pthread_spin_unlock, m);
1356   MutexUnlock(thr, pc, (uptr)m);
1357   int res = REAL(pthread_spin_unlock)(m);
1358   return res;
1359 }
1360 #endif
1361 
TSAN_INTERCEPTOR(int,pthread_rwlock_init,void * m,void * a)1362 TSAN_INTERCEPTOR(int, pthread_rwlock_init, void *m, void *a) {
1363   SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_init, m, a);
1364   int res = REAL(pthread_rwlock_init)(m, a);
1365   if (res == 0) {
1366     MutexCreate(thr, pc, (uptr)m);
1367   }
1368   return res;
1369 }
1370 
TSAN_INTERCEPTOR(int,pthread_rwlock_destroy,void * m)1371 TSAN_INTERCEPTOR(int, pthread_rwlock_destroy, void *m) {
1372   SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_destroy, m);
1373   int res = REAL(pthread_rwlock_destroy)(m);
1374   if (res == 0) {
1375     MutexDestroy(thr, pc, (uptr)m);
1376   }
1377   return res;
1378 }
1379 
TSAN_INTERCEPTOR(int,pthread_rwlock_rdlock,void * m)1380 TSAN_INTERCEPTOR(int, pthread_rwlock_rdlock, void *m) {
1381   SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_rdlock, m);
1382   MutexPreReadLock(thr, pc, (uptr)m);
1383   int res = REAL(pthread_rwlock_rdlock)(m);
1384   if (res == 0) {
1385     MutexPostReadLock(thr, pc, (uptr)m);
1386   }
1387   return res;
1388 }
1389 
TSAN_INTERCEPTOR(int,pthread_rwlock_tryrdlock,void * m)1390 TSAN_INTERCEPTOR(int, pthread_rwlock_tryrdlock, void *m) {
1391   SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_tryrdlock, m);
1392   int res = REAL(pthread_rwlock_tryrdlock)(m);
1393   if (res == 0) {
1394     MutexPostReadLock(thr, pc, (uptr)m, MutexFlagTryLock);
1395   }
1396   return res;
1397 }
1398 
1399 #if !SANITIZER_MAC
TSAN_INTERCEPTOR(int,pthread_rwlock_timedrdlock,void * m,void * abstime)1400 TSAN_INTERCEPTOR(int, pthread_rwlock_timedrdlock, void *m, void *abstime) {
1401   SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedrdlock, m, abstime);
1402   int res = REAL(pthread_rwlock_timedrdlock)(m, abstime);
1403   if (res == 0) {
1404     MutexPostReadLock(thr, pc, (uptr)m);
1405   }
1406   return res;
1407 }
1408 #endif
1409 
TSAN_INTERCEPTOR(int,pthread_rwlock_wrlock,void * m)1410 TSAN_INTERCEPTOR(int, pthread_rwlock_wrlock, void *m) {
1411   SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_wrlock, m);
1412   MutexPreLock(thr, pc, (uptr)m);
1413   int res = REAL(pthread_rwlock_wrlock)(m);
1414   if (res == 0) {
1415     MutexPostLock(thr, pc, (uptr)m);
1416   }
1417   return res;
1418 }
1419 
TSAN_INTERCEPTOR(int,pthread_rwlock_trywrlock,void * m)1420 TSAN_INTERCEPTOR(int, pthread_rwlock_trywrlock, void *m) {
1421   SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_trywrlock, m);
1422   int res = REAL(pthread_rwlock_trywrlock)(m);
1423   if (res == 0) {
1424     MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1425   }
1426   return res;
1427 }
1428 
1429 #if !SANITIZER_MAC
TSAN_INTERCEPTOR(int,pthread_rwlock_timedwrlock,void * m,void * abstime)1430 TSAN_INTERCEPTOR(int, pthread_rwlock_timedwrlock, void *m, void *abstime) {
1431   SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedwrlock, m, abstime);
1432   int res = REAL(pthread_rwlock_timedwrlock)(m, abstime);
1433   if (res == 0) {
1434     MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
1435   }
1436   return res;
1437 }
1438 #endif
1439 
TSAN_INTERCEPTOR(int,pthread_rwlock_unlock,void * m)1440 TSAN_INTERCEPTOR(int, pthread_rwlock_unlock, void *m) {
1441   SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_unlock, m);
1442   MutexReadOrWriteUnlock(thr, pc, (uptr)m);
1443   int res = REAL(pthread_rwlock_unlock)(m);
1444   return res;
1445 }
1446 
1447 #if !SANITIZER_MAC
TSAN_INTERCEPTOR(int,pthread_barrier_init,void * b,void * a,unsigned count)1448 TSAN_INTERCEPTOR(int, pthread_barrier_init, void *b, void *a, unsigned count) {
1449   SCOPED_TSAN_INTERCEPTOR(pthread_barrier_init, b, a, count);
1450   MemoryWrite(thr, pc, (uptr)b, kSizeLog1);
1451   int res = REAL(pthread_barrier_init)(b, a, count);
1452   return res;
1453 }
1454 
TSAN_INTERCEPTOR(int,pthread_barrier_destroy,void * b)1455 TSAN_INTERCEPTOR(int, pthread_barrier_destroy, void *b) {
1456   SCOPED_TSAN_INTERCEPTOR(pthread_barrier_destroy, b);
1457   MemoryWrite(thr, pc, (uptr)b, kSizeLog1);
1458   int res = REAL(pthread_barrier_destroy)(b);
1459   return res;
1460 }
1461 
TSAN_INTERCEPTOR(int,pthread_barrier_wait,void * b)1462 TSAN_INTERCEPTOR(int, pthread_barrier_wait, void *b) {
1463   SCOPED_TSAN_INTERCEPTOR(pthread_barrier_wait, b);
1464   Release(thr, pc, (uptr)b);
1465   MemoryRead(thr, pc, (uptr)b, kSizeLog1);
1466   int res = REAL(pthread_barrier_wait)(b);
1467   MemoryRead(thr, pc, (uptr)b, kSizeLog1);
1468   if (res == 0 || res == PTHREAD_BARRIER_SERIAL_THREAD) {
1469     Acquire(thr, pc, (uptr)b);
1470   }
1471   return res;
1472 }
1473 #endif
1474 
TSAN_INTERCEPTOR(int,pthread_once,void * o,void (* f)())1475 TSAN_INTERCEPTOR(int, pthread_once, void *o, void (*f)()) {
1476   SCOPED_INTERCEPTOR_RAW(pthread_once, o, f);
1477   if (o == 0 || f == 0)
1478     return errno_EINVAL;
1479   atomic_uint32_t *a;
1480 
1481   if (SANITIZER_MAC)
1482     a = static_cast<atomic_uint32_t*>((void *)((char *)o + sizeof(long_t)));
1483   else if (SANITIZER_NETBSD)
1484     a = static_cast<atomic_uint32_t*>
1485           ((void *)((char *)o + __sanitizer::pthread_mutex_t_sz));
1486   else
1487     a = static_cast<atomic_uint32_t*>(o);
1488 
1489   u32 v = atomic_load(a, memory_order_acquire);
1490   if (v == 0 && atomic_compare_exchange_strong(a, &v, 1,
1491                                                memory_order_relaxed)) {
1492     (*f)();
1493     if (!thr->in_ignored_lib)
1494       Release(thr, pc, (uptr)o);
1495     atomic_store(a, 2, memory_order_release);
1496   } else {
1497     while (v != 2) {
1498       internal_sched_yield();
1499       v = atomic_load(a, memory_order_acquire);
1500     }
1501     if (!thr->in_ignored_lib)
1502       Acquire(thr, pc, (uptr)o);
1503   }
1504   return 0;
1505 }
1506 
1507 #if SANITIZER_LINUX && !SANITIZER_ANDROID
TSAN_INTERCEPTOR(int,__fxstat,int version,int fd,void * buf)1508 TSAN_INTERCEPTOR(int, __fxstat, int version, int fd, void *buf) {
1509   SCOPED_TSAN_INTERCEPTOR(__fxstat, version, fd, buf);
1510   if (fd > 0)
1511     FdAccess(thr, pc, fd);
1512   return REAL(__fxstat)(version, fd, buf);
1513 }
1514 #define TSAN_MAYBE_INTERCEPT___FXSTAT TSAN_INTERCEPT(__fxstat)
1515 #else
1516 #define TSAN_MAYBE_INTERCEPT___FXSTAT
1517 #endif
1518 
TSAN_INTERCEPTOR(int,fstat,int fd,void * buf)1519 TSAN_INTERCEPTOR(int, fstat, int fd, void *buf) {
1520 #if SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_ANDROID || SANITIZER_NETBSD
1521   SCOPED_TSAN_INTERCEPTOR(fstat, fd, buf);
1522   if (fd > 0)
1523     FdAccess(thr, pc, fd);
1524   return REAL(fstat)(fd, buf);
1525 #else
1526   SCOPED_TSAN_INTERCEPTOR(__fxstat, 0, fd, buf);
1527   if (fd > 0)
1528     FdAccess(thr, pc, fd);
1529   return REAL(__fxstat)(0, fd, buf);
1530 #endif
1531 }
1532 
1533 #if SANITIZER_LINUX && !SANITIZER_ANDROID
TSAN_INTERCEPTOR(int,__fxstat64,int version,int fd,void * buf)1534 TSAN_INTERCEPTOR(int, __fxstat64, int version, int fd, void *buf) {
1535   SCOPED_TSAN_INTERCEPTOR(__fxstat64, version, fd, buf);
1536   if (fd > 0)
1537     FdAccess(thr, pc, fd);
1538   return REAL(__fxstat64)(version, fd, buf);
1539 }
1540 #define TSAN_MAYBE_INTERCEPT___FXSTAT64 TSAN_INTERCEPT(__fxstat64)
1541 #else
1542 #define TSAN_MAYBE_INTERCEPT___FXSTAT64
1543 #endif
1544 
1545 #if SANITIZER_LINUX && !SANITIZER_ANDROID
TSAN_INTERCEPTOR(int,fstat64,int fd,void * buf)1546 TSAN_INTERCEPTOR(int, fstat64, int fd, void *buf) {
1547   SCOPED_TSAN_INTERCEPTOR(__fxstat64, 0, fd, buf);
1548   if (fd > 0)
1549     FdAccess(thr, pc, fd);
1550   return REAL(__fxstat64)(0, fd, buf);
1551 }
1552 #define TSAN_MAYBE_INTERCEPT_FSTAT64 TSAN_INTERCEPT(fstat64)
1553 #else
1554 #define TSAN_MAYBE_INTERCEPT_FSTAT64
1555 #endif
1556 
TSAN_INTERCEPTOR(int,open,const char * name,int oflag,...)1557 TSAN_INTERCEPTOR(int, open, const char *name, int oflag, ...) {
1558   va_list ap;
1559   va_start(ap, oflag);
1560   mode_t mode = va_arg(ap, int);
1561   va_end(ap);
1562   SCOPED_TSAN_INTERCEPTOR(open, name, oflag, mode);
1563   READ_STRING(thr, pc, name, 0);
1564   int fd = REAL(open)(name, oflag, mode);
1565   if (fd >= 0)
1566     FdFileCreate(thr, pc, fd);
1567   return fd;
1568 }
1569 
1570 #if SANITIZER_LINUX
TSAN_INTERCEPTOR(int,open64,const char * name,int oflag,...)1571 TSAN_INTERCEPTOR(int, open64, const char *name, int oflag, ...) {
1572   va_list ap;
1573   va_start(ap, oflag);
1574   mode_t mode = va_arg(ap, int);
1575   va_end(ap);
1576   SCOPED_TSAN_INTERCEPTOR(open64, name, oflag, mode);
1577   READ_STRING(thr, pc, name, 0);
1578   int fd = REAL(open64)(name, oflag, mode);
1579   if (fd >= 0)
1580     FdFileCreate(thr, pc, fd);
1581   return fd;
1582 }
1583 #define TSAN_MAYBE_INTERCEPT_OPEN64 TSAN_INTERCEPT(open64)
1584 #else
1585 #define TSAN_MAYBE_INTERCEPT_OPEN64
1586 #endif
1587 
TSAN_INTERCEPTOR(int,creat,const char * name,int mode)1588 TSAN_INTERCEPTOR(int, creat, const char *name, int mode) {
1589   SCOPED_TSAN_INTERCEPTOR(creat, name, mode);
1590   READ_STRING(thr, pc, name, 0);
1591   int fd = REAL(creat)(name, mode);
1592   if (fd >= 0)
1593     FdFileCreate(thr, pc, fd);
1594   return fd;
1595 }
1596 
1597 #if SANITIZER_LINUX
TSAN_INTERCEPTOR(int,creat64,const char * name,int mode)1598 TSAN_INTERCEPTOR(int, creat64, const char *name, int mode) {
1599   SCOPED_TSAN_INTERCEPTOR(creat64, name, mode);
1600   READ_STRING(thr, pc, name, 0);
1601   int fd = REAL(creat64)(name, mode);
1602   if (fd >= 0)
1603     FdFileCreate(thr, pc, fd);
1604   return fd;
1605 }
1606 #define TSAN_MAYBE_INTERCEPT_CREAT64 TSAN_INTERCEPT(creat64)
1607 #else
1608 #define TSAN_MAYBE_INTERCEPT_CREAT64
1609 #endif
1610 
TSAN_INTERCEPTOR(int,dup,int oldfd)1611 TSAN_INTERCEPTOR(int, dup, int oldfd) {
1612   SCOPED_TSAN_INTERCEPTOR(dup, oldfd);
1613   int newfd = REAL(dup)(oldfd);
1614   if (oldfd >= 0 && newfd >= 0 && newfd != oldfd)
1615     FdDup(thr, pc, oldfd, newfd, true);
1616   return newfd;
1617 }
1618 
TSAN_INTERCEPTOR(int,dup2,int oldfd,int newfd)1619 TSAN_INTERCEPTOR(int, dup2, int oldfd, int newfd) {
1620   SCOPED_TSAN_INTERCEPTOR(dup2, oldfd, newfd);
1621   int newfd2 = REAL(dup2)(oldfd, newfd);
1622   if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd)
1623     FdDup(thr, pc, oldfd, newfd2, false);
1624   return newfd2;
1625 }
1626 
1627 #if !SANITIZER_MAC
TSAN_INTERCEPTOR(int,dup3,int oldfd,int newfd,int flags)1628 TSAN_INTERCEPTOR(int, dup3, int oldfd, int newfd, int flags) {
1629   SCOPED_TSAN_INTERCEPTOR(dup3, oldfd, newfd, flags);
1630   int newfd2 = REAL(dup3)(oldfd, newfd, flags);
1631   if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd)
1632     FdDup(thr, pc, oldfd, newfd2, false);
1633   return newfd2;
1634 }
1635 #endif
1636 
1637 #if SANITIZER_LINUX
TSAN_INTERCEPTOR(int,eventfd,unsigned initval,int flags)1638 TSAN_INTERCEPTOR(int, eventfd, unsigned initval, int flags) {
1639   SCOPED_TSAN_INTERCEPTOR(eventfd, initval, flags);
1640   int fd = REAL(eventfd)(initval, flags);
1641   if (fd >= 0)
1642     FdEventCreate(thr, pc, fd);
1643   return fd;
1644 }
1645 #define TSAN_MAYBE_INTERCEPT_EVENTFD TSAN_INTERCEPT(eventfd)
1646 #else
1647 #define TSAN_MAYBE_INTERCEPT_EVENTFD
1648 #endif
1649 
1650 #if SANITIZER_LINUX
TSAN_INTERCEPTOR(int,signalfd,int fd,void * mask,int flags)1651 TSAN_INTERCEPTOR(int, signalfd, int fd, void *mask, int flags) {
1652   SCOPED_TSAN_INTERCEPTOR(signalfd, fd, mask, flags);
1653   if (fd >= 0)
1654     FdClose(thr, pc, fd);
1655   fd = REAL(signalfd)(fd, mask, flags);
1656   if (fd >= 0)
1657     FdSignalCreate(thr, pc, fd);
1658   return fd;
1659 }
1660 #define TSAN_MAYBE_INTERCEPT_SIGNALFD TSAN_INTERCEPT(signalfd)
1661 #else
1662 #define TSAN_MAYBE_INTERCEPT_SIGNALFD
1663 #endif
1664 
1665 #if SANITIZER_LINUX
TSAN_INTERCEPTOR(int,inotify_init,int fake)1666 TSAN_INTERCEPTOR(int, inotify_init, int fake) {
1667   SCOPED_TSAN_INTERCEPTOR(inotify_init, fake);
1668   int fd = REAL(inotify_init)(fake);
1669   if (fd >= 0)
1670     FdInotifyCreate(thr, pc, fd);
1671   return fd;
1672 }
1673 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT TSAN_INTERCEPT(inotify_init)
1674 #else
1675 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT
1676 #endif
1677 
1678 #if SANITIZER_LINUX
TSAN_INTERCEPTOR(int,inotify_init1,int flags)1679 TSAN_INTERCEPTOR(int, inotify_init1, int flags) {
1680   SCOPED_TSAN_INTERCEPTOR(inotify_init1, flags);
1681   int fd = REAL(inotify_init1)(flags);
1682   if (fd >= 0)
1683     FdInotifyCreate(thr, pc, fd);
1684   return fd;
1685 }
1686 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1 TSAN_INTERCEPT(inotify_init1)
1687 #else
1688 #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1
1689 #endif
1690 
TSAN_INTERCEPTOR(int,socket,int domain,int type,int protocol)1691 TSAN_INTERCEPTOR(int, socket, int domain, int type, int protocol) {
1692   SCOPED_TSAN_INTERCEPTOR(socket, domain, type, protocol);
1693   int fd = REAL(socket)(domain, type, protocol);
1694   if (fd >= 0)
1695     FdSocketCreate(thr, pc, fd);
1696   return fd;
1697 }
1698 
TSAN_INTERCEPTOR(int,socketpair,int domain,int type,int protocol,int * fd)1699 TSAN_INTERCEPTOR(int, socketpair, int domain, int type, int protocol, int *fd) {
1700   SCOPED_TSAN_INTERCEPTOR(socketpair, domain, type, protocol, fd);
1701   int res = REAL(socketpair)(domain, type, protocol, fd);
1702   if (res == 0 && fd[0] >= 0 && fd[1] >= 0)
1703     FdPipeCreate(thr, pc, fd[0], fd[1]);
1704   return res;
1705 }
1706 
TSAN_INTERCEPTOR(int,connect,int fd,void * addr,unsigned addrlen)1707 TSAN_INTERCEPTOR(int, connect, int fd, void *addr, unsigned addrlen) {
1708   SCOPED_TSAN_INTERCEPTOR(connect, fd, addr, addrlen);
1709   FdSocketConnecting(thr, pc, fd);
1710   int res = REAL(connect)(fd, addr, addrlen);
1711   if (res == 0 && fd >= 0)
1712     FdSocketConnect(thr, pc, fd);
1713   return res;
1714 }
1715 
TSAN_INTERCEPTOR(int,bind,int fd,void * addr,unsigned addrlen)1716 TSAN_INTERCEPTOR(int, bind, int fd, void *addr, unsigned addrlen) {
1717   SCOPED_TSAN_INTERCEPTOR(bind, fd, addr, addrlen);
1718   int res = REAL(bind)(fd, addr, addrlen);
1719   if (fd > 0 && res == 0)
1720     FdAccess(thr, pc, fd);
1721   return res;
1722 }
1723 
TSAN_INTERCEPTOR(int,listen,int fd,int backlog)1724 TSAN_INTERCEPTOR(int, listen, int fd, int backlog) {
1725   SCOPED_TSAN_INTERCEPTOR(listen, fd, backlog);
1726   int res = REAL(listen)(fd, backlog);
1727   if (fd > 0 && res == 0)
1728     FdAccess(thr, pc, fd);
1729   return res;
1730 }
1731 
TSAN_INTERCEPTOR(int,close,int fd)1732 TSAN_INTERCEPTOR(int, close, int fd) {
1733   SCOPED_TSAN_INTERCEPTOR(close, fd);
1734   if (fd >= 0)
1735     FdClose(thr, pc, fd);
1736   return REAL(close)(fd);
1737 }
1738 
1739 #if SANITIZER_LINUX
TSAN_INTERCEPTOR(int,__close,int fd)1740 TSAN_INTERCEPTOR(int, __close, int fd) {
1741   SCOPED_TSAN_INTERCEPTOR(__close, fd);
1742   if (fd >= 0)
1743     FdClose(thr, pc, fd);
1744   return REAL(__close)(fd);
1745 }
1746 #define TSAN_MAYBE_INTERCEPT___CLOSE TSAN_INTERCEPT(__close)
1747 #else
1748 #define TSAN_MAYBE_INTERCEPT___CLOSE
1749 #endif
1750 
1751 // glibc guts
1752 #if SANITIZER_LINUX && !SANITIZER_ANDROID
TSAN_INTERCEPTOR(void,__res_iclose,void * state,bool free_addr)1753 TSAN_INTERCEPTOR(void, __res_iclose, void *state, bool free_addr) {
1754   SCOPED_TSAN_INTERCEPTOR(__res_iclose, state, free_addr);
1755   int fds[64];
1756   int cnt = ExtractResolvFDs(state, fds, ARRAY_SIZE(fds));
1757   for (int i = 0; i < cnt; i++) {
1758     if (fds[i] > 0)
1759       FdClose(thr, pc, fds[i]);
1760   }
1761   REAL(__res_iclose)(state, free_addr);
1762 }
1763 #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE TSAN_INTERCEPT(__res_iclose)
1764 #else
1765 #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE
1766 #endif
1767 
TSAN_INTERCEPTOR(int,pipe,int * pipefd)1768 TSAN_INTERCEPTOR(int, pipe, int *pipefd) {
1769   SCOPED_TSAN_INTERCEPTOR(pipe, pipefd);
1770   int res = REAL(pipe)(pipefd);
1771   if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0)
1772     FdPipeCreate(thr, pc, pipefd[0], pipefd[1]);
1773   return res;
1774 }
1775 
1776 #if !SANITIZER_MAC
TSAN_INTERCEPTOR(int,pipe2,int * pipefd,int flags)1777 TSAN_INTERCEPTOR(int, pipe2, int *pipefd, int flags) {
1778   SCOPED_TSAN_INTERCEPTOR(pipe2, pipefd, flags);
1779   int res = REAL(pipe2)(pipefd, flags);
1780   if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0)
1781     FdPipeCreate(thr, pc, pipefd[0], pipefd[1]);
1782   return res;
1783 }
1784 #endif
1785 
TSAN_INTERCEPTOR(int,unlink,char * path)1786 TSAN_INTERCEPTOR(int, unlink, char *path) {
1787   SCOPED_TSAN_INTERCEPTOR(unlink, path);
1788   Release(thr, pc, File2addr(path));
1789   int res = REAL(unlink)(path);
1790   return res;
1791 }
1792 
TSAN_INTERCEPTOR(void *,tmpfile,int fake)1793 TSAN_INTERCEPTOR(void*, tmpfile, int fake) {
1794   SCOPED_TSAN_INTERCEPTOR(tmpfile, fake);
1795   void *res = REAL(tmpfile)(fake);
1796   if (res) {
1797     int fd = fileno_unlocked(res);
1798     if (fd >= 0)
1799       FdFileCreate(thr, pc, fd);
1800   }
1801   return res;
1802 }
1803 
1804 #if SANITIZER_LINUX
TSAN_INTERCEPTOR(void *,tmpfile64,int fake)1805 TSAN_INTERCEPTOR(void*, tmpfile64, int fake) {
1806   SCOPED_TSAN_INTERCEPTOR(tmpfile64, fake);
1807   void *res = REAL(tmpfile64)(fake);
1808   if (res) {
1809     int fd = fileno_unlocked(res);
1810     if (fd >= 0)
1811       FdFileCreate(thr, pc, fd);
1812   }
1813   return res;
1814 }
1815 #define TSAN_MAYBE_INTERCEPT_TMPFILE64 TSAN_INTERCEPT(tmpfile64)
1816 #else
1817 #define TSAN_MAYBE_INTERCEPT_TMPFILE64
1818 #endif
1819 
FlushStreams()1820 static void FlushStreams() {
1821   // Flushing all the streams here may freeze the process if a child thread is
1822   // performing file stream operations at the same time.
1823   REAL(fflush)(stdout);
1824   REAL(fflush)(stderr);
1825 }
1826 
TSAN_INTERCEPTOR(void,abort,int fake)1827 TSAN_INTERCEPTOR(void, abort, int fake) {
1828   SCOPED_TSAN_INTERCEPTOR(abort, fake);
1829   FlushStreams();
1830   REAL(abort)(fake);
1831 }
1832 
TSAN_INTERCEPTOR(int,rmdir,char * path)1833 TSAN_INTERCEPTOR(int, rmdir, char *path) {
1834   SCOPED_TSAN_INTERCEPTOR(rmdir, path);
1835   Release(thr, pc, Dir2addr(path));
1836   int res = REAL(rmdir)(path);
1837   return res;
1838 }
1839 
TSAN_INTERCEPTOR(int,closedir,void * dirp)1840 TSAN_INTERCEPTOR(int, closedir, void *dirp) {
1841   SCOPED_TSAN_INTERCEPTOR(closedir, dirp);
1842   if (dirp) {
1843     int fd = dirfd(dirp);
1844     FdClose(thr, pc, fd);
1845   }
1846   return REAL(closedir)(dirp);
1847 }
1848 
1849 #if SANITIZER_LINUX
TSAN_INTERCEPTOR(int,epoll_create,int size)1850 TSAN_INTERCEPTOR(int, epoll_create, int size) {
1851   SCOPED_TSAN_INTERCEPTOR(epoll_create, size);
1852   int fd = REAL(epoll_create)(size);
1853   if (fd >= 0)
1854     FdPollCreate(thr, pc, fd);
1855   return fd;
1856 }
1857 
TSAN_INTERCEPTOR(int,epoll_create1,int flags)1858 TSAN_INTERCEPTOR(int, epoll_create1, int flags) {
1859   SCOPED_TSAN_INTERCEPTOR(epoll_create1, flags);
1860   int fd = REAL(epoll_create1)(flags);
1861   if (fd >= 0)
1862     FdPollCreate(thr, pc, fd);
1863   return fd;
1864 }
1865 
TSAN_INTERCEPTOR(int,epoll_ctl,int epfd,int op,int fd,void * ev)1866 TSAN_INTERCEPTOR(int, epoll_ctl, int epfd, int op, int fd, void *ev) {
1867   SCOPED_TSAN_INTERCEPTOR(epoll_ctl, epfd, op, fd, ev);
1868   if (epfd >= 0)
1869     FdAccess(thr, pc, epfd);
1870   if (epfd >= 0 && fd >= 0)
1871     FdAccess(thr, pc, fd);
1872   if (op == EPOLL_CTL_ADD && epfd >= 0)
1873     FdRelease(thr, pc, epfd);
1874   int res = REAL(epoll_ctl)(epfd, op, fd, ev);
1875   return res;
1876 }
1877 
TSAN_INTERCEPTOR(int,epoll_wait,int epfd,void * ev,int cnt,int timeout)1878 TSAN_INTERCEPTOR(int, epoll_wait, int epfd, void *ev, int cnt, int timeout) {
1879   SCOPED_TSAN_INTERCEPTOR(epoll_wait, epfd, ev, cnt, timeout);
1880   if (epfd >= 0)
1881     FdAccess(thr, pc, epfd);
1882   int res = BLOCK_REAL(epoll_wait)(epfd, ev, cnt, timeout);
1883   if (res > 0 && epfd >= 0)
1884     FdAcquire(thr, pc, epfd);
1885   return res;
1886 }
1887 
TSAN_INTERCEPTOR(int,epoll_pwait,int epfd,void * ev,int cnt,int timeout,void * sigmask)1888 TSAN_INTERCEPTOR(int, epoll_pwait, int epfd, void *ev, int cnt, int timeout,
1889                  void *sigmask) {
1890   SCOPED_TSAN_INTERCEPTOR(epoll_pwait, epfd, ev, cnt, timeout, sigmask);
1891   if (epfd >= 0)
1892     FdAccess(thr, pc, epfd);
1893   int res = BLOCK_REAL(epoll_pwait)(epfd, ev, cnt, timeout, sigmask);
1894   if (res > 0 && epfd >= 0)
1895     FdAcquire(thr, pc, epfd);
1896   return res;
1897 }
1898 
1899 #define TSAN_MAYBE_INTERCEPT_EPOLL \
1900     TSAN_INTERCEPT(epoll_create); \
1901     TSAN_INTERCEPT(epoll_create1); \
1902     TSAN_INTERCEPT(epoll_ctl); \
1903     TSAN_INTERCEPT(epoll_wait); \
1904     TSAN_INTERCEPT(epoll_pwait)
1905 #else
1906 #define TSAN_MAYBE_INTERCEPT_EPOLL
1907 #endif
1908 
1909 // The following functions are intercepted merely to process pending signals.
1910 // If program blocks signal X, we must deliver the signal before the function
1911 // returns. Similarly, if program unblocks a signal (or returns from sigsuspend)
1912 // it's better to deliver the signal straight away.
TSAN_INTERCEPTOR(int,sigsuspend,const __sanitizer_sigset_t * mask)1913 TSAN_INTERCEPTOR(int, sigsuspend, const __sanitizer_sigset_t *mask) {
1914   SCOPED_TSAN_INTERCEPTOR(sigsuspend, mask);
1915   return REAL(sigsuspend)(mask);
1916 }
1917 
TSAN_INTERCEPTOR(int,sigblock,int mask)1918 TSAN_INTERCEPTOR(int, sigblock, int mask) {
1919   SCOPED_TSAN_INTERCEPTOR(sigblock, mask);
1920   return REAL(sigblock)(mask);
1921 }
1922 
TSAN_INTERCEPTOR(int,sigsetmask,int mask)1923 TSAN_INTERCEPTOR(int, sigsetmask, int mask) {
1924   SCOPED_TSAN_INTERCEPTOR(sigsetmask, mask);
1925   return REAL(sigsetmask)(mask);
1926 }
1927 
TSAN_INTERCEPTOR(int,pthread_sigmask,int how,const __sanitizer_sigset_t * set,__sanitizer_sigset_t * oldset)1928 TSAN_INTERCEPTOR(int, pthread_sigmask, int how, const __sanitizer_sigset_t *set,
1929     __sanitizer_sigset_t *oldset) {
1930   SCOPED_TSAN_INTERCEPTOR(pthread_sigmask, how, set, oldset);
1931   return REAL(pthread_sigmask)(how, set, oldset);
1932 }
1933 
1934 namespace __tsan {
1935 
CallUserSignalHandler(ThreadState * thr,bool sync,bool acquire,bool sigact,int sig,__sanitizer_siginfo * info,void * uctx)1936 static void CallUserSignalHandler(ThreadState *thr, bool sync, bool acquire,
1937                                   bool sigact, int sig,
1938                                   __sanitizer_siginfo *info, void *uctx) {
1939   __sanitizer_sigaction *sigactions = interceptor_ctx()->sigactions;
1940   if (acquire)
1941     Acquire(thr, 0, (uptr)&sigactions[sig]);
1942   // Signals are generally asynchronous, so if we receive a signals when
1943   // ignores are enabled we should disable ignores. This is critical for sync
1944   // and interceptors, because otherwise we can miss syncronization and report
1945   // false races.
1946   int ignore_reads_and_writes = thr->ignore_reads_and_writes;
1947   int ignore_interceptors = thr->ignore_interceptors;
1948   int ignore_sync = thr->ignore_sync;
1949   if (!ctx->after_multithreaded_fork) {
1950     thr->ignore_reads_and_writes = 0;
1951     thr->fast_state.ClearIgnoreBit();
1952     thr->ignore_interceptors = 0;
1953     thr->ignore_sync = 0;
1954   }
1955   // Ensure that the handler does not spoil errno.
1956   const int saved_errno = errno;
1957   errno = 99;
1958   // This code races with sigaction. Be careful to not read sa_sigaction twice.
1959   // Also need to remember pc for reporting before the call,
1960   // because the handler can reset it.
1961   volatile uptr pc =
1962       sigact ? (uptr)sigactions[sig].sigaction : (uptr)sigactions[sig].handler;
1963   if (pc != sig_dfl && pc != sig_ign) {
1964     if (sigact)
1965       ((__sanitizer_sigactionhandler_ptr)pc)(sig, info, uctx);
1966     else
1967       ((__sanitizer_sighandler_ptr)pc)(sig);
1968   }
1969   if (!ctx->after_multithreaded_fork) {
1970     thr->ignore_reads_and_writes = ignore_reads_and_writes;
1971     if (ignore_reads_and_writes)
1972       thr->fast_state.SetIgnoreBit();
1973     thr->ignore_interceptors = ignore_interceptors;
1974     thr->ignore_sync = ignore_sync;
1975   }
1976   // We do not detect errno spoiling for SIGTERM,
1977   // because some SIGTERM handlers do spoil errno but reraise SIGTERM,
1978   // tsan reports false positive in such case.
1979   // It's difficult to properly detect this situation (reraise),
1980   // because in async signal processing case (when handler is called directly
1981   // from rtl_generic_sighandler) we have not yet received the reraised
1982   // signal; and it looks too fragile to intercept all ways to reraise a signal.
1983   if (ShouldReport(thr, ReportTypeErrnoInSignal) && !sync && sig != SIGTERM &&
1984       errno != 99) {
1985     VarSizeStackTrace stack;
1986     // StackTrace::GetNestInstructionPc(pc) is used because return address is
1987     // expected, OutputReport() will undo this.
1988     ObtainCurrentStack(thr, StackTrace::GetNextInstructionPc(pc), &stack);
1989     ThreadRegistryLock l(ctx->thread_registry);
1990     ScopedReport rep(ReportTypeErrnoInSignal);
1991     if (!IsFiredSuppression(ctx, ReportTypeErrnoInSignal, stack)) {
1992       rep.AddStack(stack, true);
1993       OutputReport(thr, rep);
1994     }
1995   }
1996   errno = saved_errno;
1997 }
1998 
ProcessPendingSignals(ThreadState * thr)1999 void ProcessPendingSignals(ThreadState *thr) {
2000   ThreadSignalContext *sctx = SigCtx(thr);
2001   if (sctx == 0 ||
2002       atomic_load(&sctx->have_pending_signals, memory_order_relaxed) == 0)
2003     return;
2004   atomic_store(&sctx->have_pending_signals, 0, memory_order_relaxed);
2005   atomic_fetch_add(&thr->in_signal_handler, 1, memory_order_relaxed);
2006   internal_sigfillset(&sctx->emptyset);
2007   int res = REAL(pthread_sigmask)(SIG_SETMASK, &sctx->emptyset, &sctx->oldset);
2008   CHECK_EQ(res, 0);
2009   for (int sig = 0; sig < kSigCount; sig++) {
2010     SignalDesc *signal = &sctx->pending_signals[sig];
2011     if (signal->armed) {
2012       signal->armed = false;
2013       CallUserSignalHandler(thr, false, true, signal->sigaction, sig,
2014           &signal->siginfo, &signal->ctx);
2015     }
2016   }
2017   res = REAL(pthread_sigmask)(SIG_SETMASK, &sctx->oldset, 0);
2018   CHECK_EQ(res, 0);
2019   atomic_fetch_add(&thr->in_signal_handler, -1, memory_order_relaxed);
2020 }
2021 
2022 }  // namespace __tsan
2023 
is_sync_signal(ThreadSignalContext * sctx,int sig)2024 static bool is_sync_signal(ThreadSignalContext *sctx, int sig) {
2025   return sig == SIGSEGV || sig == SIGBUS || sig == SIGILL || sig == SIGTRAP ||
2026          sig == SIGABRT || sig == SIGFPE || sig == SIGPIPE || sig == SIGSYS ||
2027          // If we are sending signal to ourselves, we must process it now.
2028          (sctx && sig == sctx->int_signal_send);
2029 }
2030 
rtl_generic_sighandler(bool sigact,int sig,__sanitizer_siginfo * info,void * ctx)2031 void ALWAYS_INLINE rtl_generic_sighandler(bool sigact, int sig,
2032                                           __sanitizer_siginfo *info,
2033                                           void *ctx) {
2034   cur_thread_init();
2035   ThreadState *thr = cur_thread();
2036   ThreadSignalContext *sctx = SigCtx(thr);
2037   if (sig < 0 || sig >= kSigCount) {
2038     VPrintf(1, "ThreadSanitizer: ignoring signal %d\n", sig);
2039     return;
2040   }
2041   // Don't mess with synchronous signals.
2042   const bool sync = is_sync_signal(sctx, sig);
2043   if (sync ||
2044       // If we are in blocking function, we can safely process it now
2045       // (but check if we are in a recursive interceptor,
2046       // i.e. pthread_join()->munmap()).
2047       (sctx && atomic_load(&sctx->in_blocking_func, memory_order_relaxed))) {
2048     atomic_fetch_add(&thr->in_signal_handler, 1, memory_order_relaxed);
2049     if (sctx && atomic_load(&sctx->in_blocking_func, memory_order_relaxed)) {
2050       atomic_store(&sctx->in_blocking_func, 0, memory_order_relaxed);
2051       CallUserSignalHandler(thr, sync, true, sigact, sig, info, ctx);
2052       atomic_store(&sctx->in_blocking_func, 1, memory_order_relaxed);
2053     } else {
2054       // Be very conservative with when we do acquire in this case.
2055       // It's unsafe to do acquire in async handlers, because ThreadState
2056       // can be in inconsistent state.
2057       // SIGSYS looks relatively safe -- it's synchronous and can actually
2058       // need some global state.
2059       bool acq = (sig == SIGSYS);
2060       CallUserSignalHandler(thr, sync, acq, sigact, sig, info, ctx);
2061     }
2062     atomic_fetch_add(&thr->in_signal_handler, -1, memory_order_relaxed);
2063     return;
2064   }
2065 
2066   if (sctx == 0)
2067     return;
2068   SignalDesc *signal = &sctx->pending_signals[sig];
2069   if (signal->armed == false) {
2070     signal->armed = true;
2071     signal->sigaction = sigact;
2072     if (info)
2073       internal_memcpy(&signal->siginfo, info, sizeof(*info));
2074     if (ctx)
2075       internal_memcpy(&signal->ctx, ctx, sizeof(signal->ctx));
2076     atomic_store(&sctx->have_pending_signals, 1, memory_order_relaxed);
2077   }
2078 }
2079 
rtl_sighandler(int sig)2080 static void rtl_sighandler(int sig) {
2081   rtl_generic_sighandler(false, sig, 0, 0);
2082 }
2083 
rtl_sigaction(int sig,__sanitizer_siginfo * info,void * ctx)2084 static void rtl_sigaction(int sig, __sanitizer_siginfo *info, void *ctx) {
2085   rtl_generic_sighandler(true, sig, info, ctx);
2086 }
2087 
TSAN_INTERCEPTOR(int,raise,int sig)2088 TSAN_INTERCEPTOR(int, raise, int sig) {
2089   SCOPED_TSAN_INTERCEPTOR(raise, sig);
2090   ThreadSignalContext *sctx = SigCtx(thr);
2091   CHECK_NE(sctx, 0);
2092   int prev = sctx->int_signal_send;
2093   sctx->int_signal_send = sig;
2094   int res = REAL(raise)(sig);
2095   CHECK_EQ(sctx->int_signal_send, sig);
2096   sctx->int_signal_send = prev;
2097   return res;
2098 }
2099 
TSAN_INTERCEPTOR(int,kill,int pid,int sig)2100 TSAN_INTERCEPTOR(int, kill, int pid, int sig) {
2101   SCOPED_TSAN_INTERCEPTOR(kill, pid, sig);
2102   ThreadSignalContext *sctx = SigCtx(thr);
2103   CHECK_NE(sctx, 0);
2104   int prev = sctx->int_signal_send;
2105   if (pid == (int)internal_getpid()) {
2106     sctx->int_signal_send = sig;
2107   }
2108   int res = REAL(kill)(pid, sig);
2109   if (pid == (int)internal_getpid()) {
2110     CHECK_EQ(sctx->int_signal_send, sig);
2111     sctx->int_signal_send = prev;
2112   }
2113   return res;
2114 }
2115 
TSAN_INTERCEPTOR(int,pthread_kill,void * tid,int sig)2116 TSAN_INTERCEPTOR(int, pthread_kill, void *tid, int sig) {
2117   SCOPED_TSAN_INTERCEPTOR(pthread_kill, tid, sig);
2118   ThreadSignalContext *sctx = SigCtx(thr);
2119   CHECK_NE(sctx, 0);
2120   int prev = sctx->int_signal_send;
2121   if (tid == pthread_self()) {
2122     sctx->int_signal_send = sig;
2123   }
2124   int res = REAL(pthread_kill)(tid, sig);
2125   if (tid == pthread_self()) {
2126     CHECK_EQ(sctx->int_signal_send, sig);
2127     sctx->int_signal_send = prev;
2128   }
2129   return res;
2130 }
2131 
TSAN_INTERCEPTOR(int,gettimeofday,void * tv,void * tz)2132 TSAN_INTERCEPTOR(int, gettimeofday, void *tv, void *tz) {
2133   SCOPED_TSAN_INTERCEPTOR(gettimeofday, tv, tz);
2134   // It's intercepted merely to process pending signals.
2135   return REAL(gettimeofday)(tv, tz);
2136 }
2137 
TSAN_INTERCEPTOR(int,getaddrinfo,void * node,void * service,void * hints,void * rv)2138 TSAN_INTERCEPTOR(int, getaddrinfo, void *node, void *service,
2139     void *hints, void *rv) {
2140   SCOPED_TSAN_INTERCEPTOR(getaddrinfo, node, service, hints, rv);
2141   // We miss atomic synchronization in getaddrinfo,
2142   // and can report false race between malloc and free
2143   // inside of getaddrinfo. So ignore memory accesses.
2144   ThreadIgnoreBegin(thr, pc);
2145   int res = REAL(getaddrinfo)(node, service, hints, rv);
2146   ThreadIgnoreEnd(thr, pc);
2147   return res;
2148 }
2149 
TSAN_INTERCEPTOR(int,fork,int fake)2150 TSAN_INTERCEPTOR(int, fork, int fake) {
2151   if (in_symbolizer())
2152     return REAL(fork)(fake);
2153   SCOPED_INTERCEPTOR_RAW(fork, fake);
2154   return REAL(fork)(fake);
2155 }
2156 
atfork_prepare()2157 void atfork_prepare() {
2158   if (in_symbolizer())
2159     return;
2160   ThreadState *thr = cur_thread();
2161   const uptr pc = StackTrace::GetCurrentPc();
2162   ForkBefore(thr, pc);
2163 }
2164 
atfork_parent()2165 void atfork_parent() {
2166   if (in_symbolizer())
2167     return;
2168   ThreadState *thr = cur_thread();
2169   const uptr pc = StackTrace::GetCurrentPc();
2170   ForkParentAfter(thr, pc);
2171 }
2172 
atfork_child()2173 void atfork_child() {
2174   if (in_symbolizer())
2175     return;
2176   ThreadState *thr = cur_thread();
2177   const uptr pc = StackTrace::GetCurrentPc();
2178   ForkChildAfter(thr, pc);
2179   FdOnFork(thr, pc);
2180 }
2181 
TSAN_INTERCEPTOR(int,vfork,int fake)2182 TSAN_INTERCEPTOR(int, vfork, int fake) {
2183   // Some programs (e.g. openjdk) call close for all file descriptors
2184   // in the child process. Under tsan it leads to false positives, because
2185   // address space is shared, so the parent process also thinks that
2186   // the descriptors are closed (while they are actually not).
2187   // This leads to false positives due to missed synchronization.
2188   // Strictly saying this is undefined behavior, because vfork child is not
2189   // allowed to call any functions other than exec/exit. But this is what
2190   // openjdk does, so we want to handle it.
2191   // We could disable interceptors in the child process. But it's not possible
2192   // to simply intercept and wrap vfork, because vfork child is not allowed
2193   // to return from the function that calls vfork, and that's exactly what
2194   // we would do. So this would require some assembly trickery as well.
2195   // Instead we simply turn vfork into fork.
2196   return WRAP(fork)(fake);
2197 }
2198 
2199 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2200 typedef int (*dl_iterate_phdr_cb_t)(__sanitizer_dl_phdr_info *info, SIZE_T size,
2201                                     void *data);
2202 struct dl_iterate_phdr_data {
2203   ThreadState *thr;
2204   uptr pc;
2205   dl_iterate_phdr_cb_t cb;
2206   void *data;
2207 };
2208 
IsAppNotRodata(uptr addr)2209 static bool IsAppNotRodata(uptr addr) {
2210   return IsAppMem(addr) && *(u64*)MemToShadow(addr) != kShadowRodata;
2211 }
2212 
dl_iterate_phdr_cb(__sanitizer_dl_phdr_info * info,SIZE_T size,void * data)2213 static int dl_iterate_phdr_cb(__sanitizer_dl_phdr_info *info, SIZE_T size,
2214                               void *data) {
2215   dl_iterate_phdr_data *cbdata = (dl_iterate_phdr_data *)data;
2216   // dlopen/dlclose allocate/free dynamic-linker-internal memory, which is later
2217   // accessible in dl_iterate_phdr callback. But we don't see synchronization
2218   // inside of dynamic linker, so we "unpoison" it here in order to not
2219   // produce false reports. Ignoring malloc/free in dlopen/dlclose is not enough
2220   // because some libc functions call __libc_dlopen.
2221   if (info && IsAppNotRodata((uptr)info->dlpi_name))
2222     MemoryResetRange(cbdata->thr, cbdata->pc, (uptr)info->dlpi_name,
2223                      internal_strlen(info->dlpi_name));
2224   int res = cbdata->cb(info, size, cbdata->data);
2225   // Perform the check one more time in case info->dlpi_name was overwritten
2226   // by user callback.
2227   if (info && IsAppNotRodata((uptr)info->dlpi_name))
2228     MemoryResetRange(cbdata->thr, cbdata->pc, (uptr)info->dlpi_name,
2229                      internal_strlen(info->dlpi_name));
2230   return res;
2231 }
2232 
TSAN_INTERCEPTOR(int,dl_iterate_phdr,dl_iterate_phdr_cb_t cb,void * data)2233 TSAN_INTERCEPTOR(int, dl_iterate_phdr, dl_iterate_phdr_cb_t cb, void *data) {
2234   SCOPED_TSAN_INTERCEPTOR(dl_iterate_phdr, cb, data);
2235   dl_iterate_phdr_data cbdata;
2236   cbdata.thr = thr;
2237   cbdata.pc = pc;
2238   cbdata.cb = cb;
2239   cbdata.data = data;
2240   int res = REAL(dl_iterate_phdr)(dl_iterate_phdr_cb, &cbdata);
2241   return res;
2242 }
2243 #endif
2244 
OnExit(ThreadState * thr)2245 static int OnExit(ThreadState *thr) {
2246   int status = Finalize(thr);
2247   FlushStreams();
2248   return status;
2249 }
2250 
2251 struct TsanInterceptorContext {
2252   ThreadState *thr;
2253   const uptr caller_pc;
2254   const uptr pc;
2255 };
2256 
2257 #if !SANITIZER_MAC
HandleRecvmsg(ThreadState * thr,uptr pc,__sanitizer_msghdr * msg)2258 static void HandleRecvmsg(ThreadState *thr, uptr pc,
2259     __sanitizer_msghdr *msg) {
2260   int fds[64];
2261   int cnt = ExtractRecvmsgFDs(msg, fds, ARRAY_SIZE(fds));
2262   for (int i = 0; i < cnt; i++)
2263     FdEventCreate(thr, pc, fds[i]);
2264 }
2265 #endif
2266 
2267 #include "sanitizer_common/sanitizer_platform_interceptors.h"
2268 // Causes interceptor recursion (getaddrinfo() and fopen())
2269 #undef SANITIZER_INTERCEPT_GETADDRINFO
2270 // We define our own.
2271 #if SANITIZER_INTERCEPT_TLS_GET_ADDR
2272 #define NEED_TLS_GET_ADDR
2273 #endif
2274 #undef SANITIZER_INTERCEPT_TLS_GET_ADDR
2275 #define SANITIZER_INTERCEPT_TLS_GET_OFFSET 1
2276 #undef SANITIZER_INTERCEPT_PTHREAD_SIGMASK
2277 
2278 #define COMMON_INTERCEPT_FUNCTION(name) INTERCEPT_FUNCTION(name)
2279 #define COMMON_INTERCEPT_FUNCTION_VER(name, ver)                          \
2280   INTERCEPT_FUNCTION_VER(name, ver)
2281 #define COMMON_INTERCEPT_FUNCTION_VER_UNVERSIONED_FALLBACK(name, ver) \
2282   (INTERCEPT_FUNCTION_VER(name, ver) || INTERCEPT_FUNCTION(name))
2283 
2284 #define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size)                    \
2285   MemoryAccessRange(((TsanInterceptorContext *)ctx)->thr,                 \
2286                     ((TsanInterceptorContext *)ctx)->pc, (uptr)ptr, size, \
2287                     true)
2288 
2289 #define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size)                       \
2290   MemoryAccessRange(((TsanInterceptorContext *) ctx)->thr,                  \
2291                     ((TsanInterceptorContext *) ctx)->pc, (uptr) ptr, size, \
2292                     false)
2293 
2294 #define COMMON_INTERCEPTOR_ENTER(ctx, func, ...)      \
2295   SCOPED_TSAN_INTERCEPTOR(func, __VA_ARGS__);         \
2296   TsanInterceptorContext _ctx = {thr, caller_pc, pc}; \
2297   ctx = (void *)&_ctx;                                \
2298   (void) ctx;
2299 
2300 #define COMMON_INTERCEPTOR_ENTER_NOIGNORE(ctx, func, ...) \
2301   SCOPED_INTERCEPTOR_RAW(func, __VA_ARGS__);              \
2302   TsanInterceptorContext _ctx = {thr, caller_pc, pc};     \
2303   ctx = (void *)&_ctx;                                    \
2304   (void) ctx;
2305 
2306 #define COMMON_INTERCEPTOR_FILE_OPEN(ctx, file, path) \
2307   if (path)                                           \
2308     Acquire(thr, pc, File2addr(path));                \
2309   if (file) {                                         \
2310     int fd = fileno_unlocked(file);                   \
2311     if (fd >= 0) FdFileCreate(thr, pc, fd);           \
2312   }
2313 
2314 #define COMMON_INTERCEPTOR_FILE_CLOSE(ctx, file) \
2315   if (file) {                                    \
2316     int fd = fileno_unlocked(file);              \
2317     if (fd >= 0) FdClose(thr, pc, fd);           \
2318   }
2319 
2320 #define COMMON_INTERCEPTOR_LIBRARY_LOADED(filename, handle) \
2321   libignore()->OnLibraryLoaded(filename)
2322 
2323 #define COMMON_INTERCEPTOR_LIBRARY_UNLOADED() \
2324   libignore()->OnLibraryUnloaded()
2325 
2326 #define COMMON_INTERCEPTOR_ACQUIRE(ctx, u) \
2327   Acquire(((TsanInterceptorContext *) ctx)->thr, pc, u)
2328 
2329 #define COMMON_INTERCEPTOR_RELEASE(ctx, u) \
2330   Release(((TsanInterceptorContext *) ctx)->thr, pc, u)
2331 
2332 #define COMMON_INTERCEPTOR_DIR_ACQUIRE(ctx, path) \
2333   Acquire(((TsanInterceptorContext *) ctx)->thr, pc, Dir2addr(path))
2334 
2335 #define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \
2336   FdAcquire(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2337 
2338 #define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \
2339   FdRelease(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2340 
2341 #define COMMON_INTERCEPTOR_FD_ACCESS(ctx, fd) \
2342   FdAccess(((TsanInterceptorContext *) ctx)->thr, pc, fd)
2343 
2344 #define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \
2345   FdSocketAccept(((TsanInterceptorContext *) ctx)->thr, pc, fd, newfd)
2346 
2347 #define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) \
2348   ThreadSetName(((TsanInterceptorContext *) ctx)->thr, name)
2349 
2350 #define COMMON_INTERCEPTOR_SET_PTHREAD_NAME(ctx, thread, name) \
2351   __tsan::ctx->thread_registry->SetThreadNameByUserId(thread, name)
2352 
2353 #define COMMON_INTERCEPTOR_BLOCK_REAL(name) BLOCK_REAL(name)
2354 
2355 #define COMMON_INTERCEPTOR_ON_EXIT(ctx) \
2356   OnExit(((TsanInterceptorContext *) ctx)->thr)
2357 
2358 #define COMMON_INTERCEPTOR_MUTEX_PRE_LOCK(ctx, m) \
2359   MutexPreLock(((TsanInterceptorContext *)ctx)->thr, \
2360             ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2361 
2362 #define COMMON_INTERCEPTOR_MUTEX_POST_LOCK(ctx, m) \
2363   MutexPostLock(((TsanInterceptorContext *)ctx)->thr, \
2364             ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2365 
2366 #define COMMON_INTERCEPTOR_MUTEX_UNLOCK(ctx, m) \
2367   MutexUnlock(((TsanInterceptorContext *)ctx)->thr, \
2368             ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2369 
2370 #define COMMON_INTERCEPTOR_MUTEX_REPAIR(ctx, m) \
2371   MutexRepair(((TsanInterceptorContext *)ctx)->thr, \
2372             ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2373 
2374 #define COMMON_INTERCEPTOR_MUTEX_INVALID(ctx, m) \
2375   MutexInvalidAccess(((TsanInterceptorContext *)ctx)->thr, \
2376                      ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
2377 
2378 #define COMMON_INTERCEPTOR_MMAP_IMPL(ctx, mmap, addr, sz, prot, flags, fd,  \
2379                                      off)                                   \
2380   do {                                                                      \
2381     return mmap_interceptor(thr, pc, REAL(mmap), addr, sz, prot, flags, fd, \
2382                             off);                                           \
2383   } while (false)
2384 
2385 #if !SANITIZER_MAC
2386 #define COMMON_INTERCEPTOR_HANDLE_RECVMSG(ctx, msg) \
2387   HandleRecvmsg(((TsanInterceptorContext *)ctx)->thr, \
2388       ((TsanInterceptorContext *)ctx)->pc, msg)
2389 #endif
2390 
2391 #define COMMON_INTERCEPTOR_GET_TLS_RANGE(begin, end)                           \
2392   if (TsanThread *t = GetCurrentThread()) {                                    \
2393     *begin = t->tls_begin();                                                   \
2394     *end = t->tls_end();                                                       \
2395   } else {                                                                     \
2396     *begin = *end = 0;                                                         \
2397   }
2398 
2399 #define COMMON_INTERCEPTOR_USER_CALLBACK_START() \
2400   SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_START()
2401 
2402 #define COMMON_INTERCEPTOR_USER_CALLBACK_END() \
2403   SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_END()
2404 
2405 #include "sanitizer_common/sanitizer_common_interceptors.inc"
2406 
2407 static int sigaction_impl(int sig, const __sanitizer_sigaction *act,
2408                           __sanitizer_sigaction *old);
2409 static __sanitizer_sighandler_ptr signal_impl(int sig,
2410                                               __sanitizer_sighandler_ptr h);
2411 
2412 #define SIGNAL_INTERCEPTOR_SIGACTION_IMPL(signo, act, oldact) \
2413   { return sigaction_impl(signo, act, oldact); }
2414 
2415 #define SIGNAL_INTERCEPTOR_SIGNAL_IMPL(func, signo, handler) \
2416   { return (uptr)signal_impl(signo, (__sanitizer_sighandler_ptr)handler); }
2417 
2418 #include "sanitizer_common/sanitizer_signal_interceptors.inc"
2419 
sigaction_impl(int sig,const __sanitizer_sigaction * act,__sanitizer_sigaction * old)2420 int sigaction_impl(int sig, const __sanitizer_sigaction *act,
2421                    __sanitizer_sigaction *old) {
2422   // Note: if we call REAL(sigaction) directly for any reason without proxying
2423   // the signal handler through rtl_sigaction, very bad things will happen.
2424   // The handler will run synchronously and corrupt tsan per-thread state.
2425   SCOPED_INTERCEPTOR_RAW(sigaction, sig, act, old);
2426   if (sig <= 0 || sig >= kSigCount) {
2427     errno = errno_EINVAL;
2428     return -1;
2429   }
2430   __sanitizer_sigaction *sigactions = interceptor_ctx()->sigactions;
2431   __sanitizer_sigaction old_stored;
2432   if (old) internal_memcpy(&old_stored, &sigactions[sig], sizeof(old_stored));
2433   __sanitizer_sigaction newact;
2434   if (act) {
2435     // Copy act into sigactions[sig].
2436     // Can't use struct copy, because compiler can emit call to memcpy.
2437     // Can't use internal_memcpy, because it copies byte-by-byte,
2438     // and signal handler reads the handler concurrently. It it can read
2439     // some bytes from old value and some bytes from new value.
2440     // Use volatile to prevent insertion of memcpy.
2441     sigactions[sig].handler =
2442         *(volatile __sanitizer_sighandler_ptr const *)&act->handler;
2443     sigactions[sig].sa_flags = *(volatile int const *)&act->sa_flags;
2444     internal_memcpy(&sigactions[sig].sa_mask, &act->sa_mask,
2445                     sizeof(sigactions[sig].sa_mask));
2446 #if !SANITIZER_FREEBSD && !SANITIZER_MAC && !SANITIZER_NETBSD
2447     sigactions[sig].sa_restorer = act->sa_restorer;
2448 #endif
2449     internal_memcpy(&newact, act, sizeof(newact));
2450     internal_sigfillset(&newact.sa_mask);
2451     if ((uptr)act->handler != sig_ign && (uptr)act->handler != sig_dfl) {
2452       if (newact.sa_flags & SA_SIGINFO)
2453         newact.sigaction = rtl_sigaction;
2454       else
2455         newact.handler = rtl_sighandler;
2456     }
2457     ReleaseStore(thr, pc, (uptr)&sigactions[sig]);
2458     act = &newact;
2459   }
2460   int res = REAL(sigaction)(sig, act, old);
2461   if (res == 0 && old) {
2462     uptr cb = (uptr)old->sigaction;
2463     if (cb == (uptr)rtl_sigaction || cb == (uptr)rtl_sighandler) {
2464       internal_memcpy(old, &old_stored, sizeof(*old));
2465     }
2466   }
2467   return res;
2468 }
2469 
signal_impl(int sig,__sanitizer_sighandler_ptr h)2470 static __sanitizer_sighandler_ptr signal_impl(int sig,
2471                                               __sanitizer_sighandler_ptr h) {
2472   __sanitizer_sigaction act;
2473   act.handler = h;
2474   internal_memset(&act.sa_mask, -1, sizeof(act.sa_mask));
2475   act.sa_flags = 0;
2476   __sanitizer_sigaction old;
2477   int res = sigaction_symname(sig, &act, &old);
2478   if (res) return (__sanitizer_sighandler_ptr)sig_err;
2479   return old.handler;
2480 }
2481 
2482 #define TSAN_SYSCALL() \
2483   ThreadState *thr = cur_thread(); \
2484   if (thr->ignore_interceptors) \
2485     return; \
2486   ScopedSyscall scoped_syscall(thr) \
2487 /**/
2488 
2489 struct ScopedSyscall {
2490   ThreadState *thr;
2491 
ScopedSyscallScopedSyscall2492   explicit ScopedSyscall(ThreadState *thr)
2493       : thr(thr) {
2494     Initialize(thr);
2495   }
2496 
~ScopedSyscallScopedSyscall2497   ~ScopedSyscall() {
2498     ProcessPendingSignals(thr);
2499   }
2500 };
2501 
2502 #if !SANITIZER_FREEBSD && !SANITIZER_MAC
syscall_access_range(uptr pc,uptr p,uptr s,bool write)2503 static void syscall_access_range(uptr pc, uptr p, uptr s, bool write) {
2504   TSAN_SYSCALL();
2505   MemoryAccessRange(thr, pc, p, s, write);
2506 }
2507 
syscall_acquire(uptr pc,uptr addr)2508 static USED void syscall_acquire(uptr pc, uptr addr) {
2509   TSAN_SYSCALL();
2510   Acquire(thr, pc, addr);
2511   DPrintf("syscall_acquire(%p)\n", addr);
2512 }
2513 
syscall_release(uptr pc,uptr addr)2514 static USED void syscall_release(uptr pc, uptr addr) {
2515   TSAN_SYSCALL();
2516   DPrintf("syscall_release(%p)\n", addr);
2517   Release(thr, pc, addr);
2518 }
2519 
syscall_fd_close(uptr pc,int fd)2520 static void syscall_fd_close(uptr pc, int fd) {
2521   TSAN_SYSCALL();
2522   FdClose(thr, pc, fd);
2523 }
2524 
syscall_fd_acquire(uptr pc,int fd)2525 static USED void syscall_fd_acquire(uptr pc, int fd) {
2526   TSAN_SYSCALL();
2527   FdAcquire(thr, pc, fd);
2528   DPrintf("syscall_fd_acquire(%p)\n", fd);
2529 }
2530 
syscall_fd_release(uptr pc,int fd)2531 static USED void syscall_fd_release(uptr pc, int fd) {
2532   TSAN_SYSCALL();
2533   DPrintf("syscall_fd_release(%p)\n", fd);
2534   FdRelease(thr, pc, fd);
2535 }
2536 
syscall_pre_fork(uptr pc)2537 static void syscall_pre_fork(uptr pc) { ForkBefore(cur_thread(), pc); }
2538 
syscall_post_fork(uptr pc,int pid)2539 static void syscall_post_fork(uptr pc, int pid) {
2540   ThreadState *thr = cur_thread();
2541   if (pid == 0) {
2542     // child
2543     ForkChildAfter(thr, pc);
2544     FdOnFork(thr, pc);
2545   } else if (pid > 0) {
2546     // parent
2547     ForkParentAfter(thr, pc);
2548   } else {
2549     // error
2550     ForkParentAfter(thr, pc);
2551   }
2552 }
2553 #endif
2554 
2555 #define COMMON_SYSCALL_PRE_READ_RANGE(p, s) \
2556   syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), false)
2557 
2558 #define COMMON_SYSCALL_PRE_WRITE_RANGE(p, s) \
2559   syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), true)
2560 
2561 #define COMMON_SYSCALL_POST_READ_RANGE(p, s) \
2562   do {                                       \
2563     (void)(p);                               \
2564     (void)(s);                               \
2565   } while (false)
2566 
2567 #define COMMON_SYSCALL_POST_WRITE_RANGE(p, s) \
2568   do {                                        \
2569     (void)(p);                                \
2570     (void)(s);                                \
2571   } while (false)
2572 
2573 #define COMMON_SYSCALL_ACQUIRE(addr) \
2574     syscall_acquire(GET_CALLER_PC(), (uptr)(addr))
2575 
2576 #define COMMON_SYSCALL_RELEASE(addr) \
2577     syscall_release(GET_CALLER_PC(), (uptr)(addr))
2578 
2579 #define COMMON_SYSCALL_FD_CLOSE(fd) syscall_fd_close(GET_CALLER_PC(), fd)
2580 
2581 #define COMMON_SYSCALL_FD_ACQUIRE(fd) syscall_fd_acquire(GET_CALLER_PC(), fd)
2582 
2583 #define COMMON_SYSCALL_FD_RELEASE(fd) syscall_fd_release(GET_CALLER_PC(), fd)
2584 
2585 #define COMMON_SYSCALL_PRE_FORK() \
2586   syscall_pre_fork(GET_CALLER_PC())
2587 
2588 #define COMMON_SYSCALL_POST_FORK(res) \
2589   syscall_post_fork(GET_CALLER_PC(), res)
2590 
2591 #include "sanitizer_common/sanitizer_common_syscalls.inc"
2592 #include "sanitizer_common/sanitizer_syscalls_netbsd.inc"
2593 
2594 #ifdef NEED_TLS_GET_ADDR
2595 
handle_tls_addr(void * arg,void * res)2596 static void handle_tls_addr(void *arg, void *res) {
2597   ThreadState *thr = cur_thread();
2598   if (!thr)
2599     return;
2600   DTLS::DTV *dtv = DTLS_on_tls_get_addr(arg, res, thr->tls_addr,
2601                                         thr->tls_addr + thr->tls_size);
2602   if (!dtv)
2603     return;
2604   // New DTLS block has been allocated.
2605   MemoryResetRange(thr, 0, dtv->beg, dtv->size);
2606 }
2607 
2608 #if !SANITIZER_S390
2609 // Define own interceptor instead of sanitizer_common's for three reasons:
2610 // 1. It must not process pending signals.
2611 //    Signal handlers may contain MOVDQA instruction (see below).
2612 // 2. It must be as simple as possible to not contain MOVDQA.
2613 // 3. Sanitizer_common version uses COMMON_INTERCEPTOR_INITIALIZE_RANGE which
2614 //    is empty for tsan (meant only for msan).
2615 // Note: __tls_get_addr can be called with mis-aligned stack due to:
2616 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58066
2617 // So the interceptor must work with mis-aligned stack, in particular, does not
2618 // execute MOVDQA with stack addresses.
TSAN_INTERCEPTOR(void *,__tls_get_addr,void * arg)2619 TSAN_INTERCEPTOR(void *, __tls_get_addr, void *arg) {
2620   void *res = REAL(__tls_get_addr)(arg);
2621   handle_tls_addr(arg, res);
2622   return res;
2623 }
2624 #else // SANITIZER_S390
TSAN_INTERCEPTOR(uptr,__tls_get_addr_internal,void * arg)2625 TSAN_INTERCEPTOR(uptr, __tls_get_addr_internal, void *arg) {
2626   uptr res = __tls_get_offset_wrapper(arg, REAL(__tls_get_offset));
2627   char *tp = static_cast<char *>(__builtin_thread_pointer());
2628   handle_tls_addr(arg, res + tp);
2629   return res;
2630 }
2631 #endif
2632 #endif
2633 
2634 #if SANITIZER_NETBSD
TSAN_INTERCEPTOR(void,_lwp_exit)2635 TSAN_INTERCEPTOR(void, _lwp_exit) {
2636   SCOPED_TSAN_INTERCEPTOR(_lwp_exit);
2637   DestroyThreadState();
2638   REAL(_lwp_exit)();
2639 }
2640 #define TSAN_MAYBE_INTERCEPT__LWP_EXIT TSAN_INTERCEPT(_lwp_exit)
2641 #else
2642 #define TSAN_MAYBE_INTERCEPT__LWP_EXIT
2643 #endif
2644 
2645 #if SANITIZER_FREEBSD
TSAN_INTERCEPTOR(void,thr_exit,tid_t * state)2646 TSAN_INTERCEPTOR(void, thr_exit, tid_t *state) {
2647   SCOPED_TSAN_INTERCEPTOR(thr_exit, state);
2648   DestroyThreadState();
2649   REAL(thr_exit(state));
2650 }
2651 #define TSAN_MAYBE_INTERCEPT_THR_EXIT TSAN_INTERCEPT(thr_exit)
2652 #else
2653 #define TSAN_MAYBE_INTERCEPT_THR_EXIT
2654 #endif
2655 
2656 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_init, void *c, void *a)
2657 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_signal, void *c)
2658 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_broadcast, void *c)
2659 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_wait, void *c, void *m)
2660 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_destroy, void *c)
2661 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_init, void *m, void *a)
2662 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_destroy, void *m)
2663 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_trylock, void *m)
2664 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_init, void *m, void *a)
2665 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_destroy, void *m)
2666 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_rdlock, void *m)
2667 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_tryrdlock, void *m)
2668 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_wrlock, void *m)
2669 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_trywrlock, void *m)
2670 TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_unlock, void *m)
2671 TSAN_INTERCEPTOR_NETBSD_ALIAS_THR(int, once, void *o, void (*f)())
2672 TSAN_INTERCEPTOR_NETBSD_ALIAS_THR2(int, sigsetmask, sigmask, int a, void *b,
2673   void *c)
2674 
2675 namespace __tsan {
2676 
finalize(void * arg)2677 static void finalize(void *arg) {
2678   ThreadState *thr = cur_thread();
2679   int status = Finalize(thr);
2680   // Make sure the output is not lost.
2681   FlushStreams();
2682   if (status)
2683     Die();
2684 }
2685 
2686 #if !SANITIZER_MAC && !SANITIZER_ANDROID
unreachable()2687 static void unreachable() {
2688   Report("FATAL: ThreadSanitizer: unreachable called\n");
2689   Die();
2690 }
2691 #endif
2692 
2693 // Define default implementation since interception of libdispatch  is optional.
InitializeLibdispatchInterceptors()2694 SANITIZER_WEAK_ATTRIBUTE void InitializeLibdispatchInterceptors() {}
2695 
InitializeInterceptors()2696 void InitializeInterceptors() {
2697 #if !SANITIZER_MAC
2698   // We need to setup it early, because functions like dlsym() can call it.
2699   REAL(memset) = internal_memset;
2700   REAL(memcpy) = internal_memcpy;
2701 #endif
2702 
2703   // Instruct libc malloc to consume less memory.
2704 #if SANITIZER_GLIBC
2705   mallopt(1, 0);  // M_MXFAST
2706   mallopt(-3, 32*1024);  // M_MMAP_THRESHOLD
2707 #endif
2708 
2709   new(interceptor_ctx()) InterceptorContext();
2710 
2711   InitializeCommonInterceptors();
2712   InitializeSignalInterceptors();
2713   InitializeLibdispatchInterceptors();
2714 
2715 #if !SANITIZER_MAC
2716   // We can not use TSAN_INTERCEPT to get setjmp addr,
2717   // because it does &setjmp and setjmp is not present in some versions of libc.
2718   using __interception::InterceptFunction;
2719   InterceptFunction(TSAN_STRING_SETJMP, (uptr*)&REAL(setjmp_symname), 0, 0);
2720   InterceptFunction("_setjmp", (uptr*)&REAL(_setjmp), 0, 0);
2721   InterceptFunction(TSAN_STRING_SIGSETJMP, (uptr*)&REAL(sigsetjmp_symname), 0,
2722                     0);
2723 #if !SANITIZER_NETBSD
2724   InterceptFunction("__sigsetjmp", (uptr*)&REAL(__sigsetjmp), 0, 0);
2725 #endif
2726 #endif
2727 
2728   TSAN_INTERCEPT(longjmp_symname);
2729   TSAN_INTERCEPT(siglongjmp_symname);
2730 #if SANITIZER_NETBSD
2731   TSAN_INTERCEPT(_longjmp);
2732 #endif
2733 
2734   TSAN_INTERCEPT(malloc);
2735   TSAN_INTERCEPT(__libc_memalign);
2736   TSAN_INTERCEPT(calloc);
2737   TSAN_INTERCEPT(realloc);
2738   TSAN_INTERCEPT(reallocarray);
2739   TSAN_INTERCEPT(free);
2740   TSAN_INTERCEPT(cfree);
2741   TSAN_INTERCEPT(munmap);
2742   TSAN_MAYBE_INTERCEPT_MEMALIGN;
2743   TSAN_INTERCEPT(valloc);
2744   TSAN_MAYBE_INTERCEPT_PVALLOC;
2745   TSAN_INTERCEPT(posix_memalign);
2746 
2747   TSAN_INTERCEPT(strcpy);
2748   TSAN_INTERCEPT(strncpy);
2749   TSAN_INTERCEPT(strdup);
2750 
2751   TSAN_INTERCEPT(pthread_create);
2752   TSAN_INTERCEPT(pthread_join);
2753   TSAN_INTERCEPT(pthread_detach);
2754   TSAN_INTERCEPT(pthread_exit);
2755   #if SANITIZER_LINUX
2756   TSAN_INTERCEPT(pthread_tryjoin_np);
2757   TSAN_INTERCEPT(pthread_timedjoin_np);
2758   #endif
2759 
2760   TSAN_INTERCEPT_VER(pthread_cond_init, PTHREAD_ABI_BASE);
2761   TSAN_INTERCEPT_VER(pthread_cond_signal, PTHREAD_ABI_BASE);
2762   TSAN_INTERCEPT_VER(pthread_cond_broadcast, PTHREAD_ABI_BASE);
2763   TSAN_INTERCEPT_VER(pthread_cond_wait, PTHREAD_ABI_BASE);
2764   TSAN_INTERCEPT_VER(pthread_cond_timedwait, PTHREAD_ABI_BASE);
2765   TSAN_INTERCEPT_VER(pthread_cond_destroy, PTHREAD_ABI_BASE);
2766 
2767   TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT;
2768 
2769   TSAN_INTERCEPT(pthread_mutex_init);
2770   TSAN_INTERCEPT(pthread_mutex_destroy);
2771   TSAN_INTERCEPT(pthread_mutex_trylock);
2772   TSAN_INTERCEPT(pthread_mutex_timedlock);
2773 
2774   TSAN_INTERCEPT(pthread_spin_init);
2775   TSAN_INTERCEPT(pthread_spin_destroy);
2776   TSAN_INTERCEPT(pthread_spin_lock);
2777   TSAN_INTERCEPT(pthread_spin_trylock);
2778   TSAN_INTERCEPT(pthread_spin_unlock);
2779 
2780   TSAN_INTERCEPT(pthread_rwlock_init);
2781   TSAN_INTERCEPT(pthread_rwlock_destroy);
2782   TSAN_INTERCEPT(pthread_rwlock_rdlock);
2783   TSAN_INTERCEPT(pthread_rwlock_tryrdlock);
2784   TSAN_INTERCEPT(pthread_rwlock_timedrdlock);
2785   TSAN_INTERCEPT(pthread_rwlock_wrlock);
2786   TSAN_INTERCEPT(pthread_rwlock_trywrlock);
2787   TSAN_INTERCEPT(pthread_rwlock_timedwrlock);
2788   TSAN_INTERCEPT(pthread_rwlock_unlock);
2789 
2790   TSAN_INTERCEPT(pthread_barrier_init);
2791   TSAN_INTERCEPT(pthread_barrier_destroy);
2792   TSAN_INTERCEPT(pthread_barrier_wait);
2793 
2794   TSAN_INTERCEPT(pthread_once);
2795 
2796   TSAN_INTERCEPT(fstat);
2797   TSAN_MAYBE_INTERCEPT___FXSTAT;
2798   TSAN_MAYBE_INTERCEPT_FSTAT64;
2799   TSAN_MAYBE_INTERCEPT___FXSTAT64;
2800   TSAN_INTERCEPT(open);
2801   TSAN_MAYBE_INTERCEPT_OPEN64;
2802   TSAN_INTERCEPT(creat);
2803   TSAN_MAYBE_INTERCEPT_CREAT64;
2804   TSAN_INTERCEPT(dup);
2805   TSAN_INTERCEPT(dup2);
2806   TSAN_INTERCEPT(dup3);
2807   TSAN_MAYBE_INTERCEPT_EVENTFD;
2808   TSAN_MAYBE_INTERCEPT_SIGNALFD;
2809   TSAN_MAYBE_INTERCEPT_INOTIFY_INIT;
2810   TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1;
2811   TSAN_INTERCEPT(socket);
2812   TSAN_INTERCEPT(socketpair);
2813   TSAN_INTERCEPT(connect);
2814   TSAN_INTERCEPT(bind);
2815   TSAN_INTERCEPT(listen);
2816   TSAN_MAYBE_INTERCEPT_EPOLL;
2817   TSAN_INTERCEPT(close);
2818   TSAN_MAYBE_INTERCEPT___CLOSE;
2819   TSAN_MAYBE_INTERCEPT___RES_ICLOSE;
2820   TSAN_INTERCEPT(pipe);
2821   TSAN_INTERCEPT(pipe2);
2822 
2823   TSAN_INTERCEPT(unlink);
2824   TSAN_INTERCEPT(tmpfile);
2825   TSAN_MAYBE_INTERCEPT_TMPFILE64;
2826   TSAN_INTERCEPT(abort);
2827   TSAN_INTERCEPT(rmdir);
2828   TSAN_INTERCEPT(closedir);
2829 
2830   TSAN_INTERCEPT(sigsuspend);
2831   TSAN_INTERCEPT(sigblock);
2832   TSAN_INTERCEPT(sigsetmask);
2833   TSAN_INTERCEPT(pthread_sigmask);
2834   TSAN_INTERCEPT(raise);
2835   TSAN_INTERCEPT(kill);
2836   TSAN_INTERCEPT(pthread_kill);
2837   TSAN_INTERCEPT(sleep);
2838   TSAN_INTERCEPT(usleep);
2839   TSAN_INTERCEPT(nanosleep);
2840   TSAN_INTERCEPT(pause);
2841   TSAN_INTERCEPT(gettimeofday);
2842   TSAN_INTERCEPT(getaddrinfo);
2843 
2844   TSAN_INTERCEPT(fork);
2845   TSAN_INTERCEPT(vfork);
2846 #if !SANITIZER_ANDROID
2847   TSAN_INTERCEPT(dl_iterate_phdr);
2848 #endif
2849   TSAN_MAYBE_INTERCEPT_ON_EXIT;
2850   TSAN_INTERCEPT(__cxa_atexit);
2851   TSAN_INTERCEPT(_exit);
2852 
2853 #ifdef NEED_TLS_GET_ADDR
2854 #if !SANITIZER_S390
2855   TSAN_INTERCEPT(__tls_get_addr);
2856 #else
2857   TSAN_INTERCEPT(__tls_get_addr_internal);
2858   TSAN_INTERCEPT(__tls_get_offset);
2859 #endif
2860 #endif
2861 
2862   TSAN_MAYBE_INTERCEPT__LWP_EXIT;
2863   TSAN_MAYBE_INTERCEPT_THR_EXIT;
2864 
2865 #if !SANITIZER_MAC && !SANITIZER_ANDROID
2866   // Need to setup it, because interceptors check that the function is resolved.
2867   // But atexit is emitted directly into the module, so can't be resolved.
2868   REAL(atexit) = (int(*)(void(*)()))unreachable;
2869 #endif
2870 
2871   if (REAL(__cxa_atexit)(&finalize, 0, 0)) {
2872     Printf("ThreadSanitizer: failed to setup atexit callback\n");
2873     Die();
2874   }
2875   if (pthread_atfork(atfork_prepare, atfork_parent, atfork_child)) {
2876     Printf("ThreadSanitizer: failed to setup atfork callbacks\n");
2877     Die();
2878   }
2879 
2880 #if !SANITIZER_MAC && !SANITIZER_NETBSD && !SANITIZER_FREEBSD
2881   if (pthread_key_create(&interceptor_ctx()->finalize_key, &thread_finalize)) {
2882     Printf("ThreadSanitizer: failed to create thread key\n");
2883     Die();
2884   }
2885 #endif
2886 
2887   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_init);
2888   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_signal);
2889   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_broadcast);
2890   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_wait);
2891   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_destroy);
2892   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_init);
2893   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_destroy);
2894   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_trylock);
2895   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_init);
2896   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_destroy);
2897   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_rdlock);
2898   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_tryrdlock);
2899   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_wrlock);
2900   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_trywrlock);
2901   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_unlock);
2902   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(once);
2903   TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(sigsetmask);
2904 
2905   FdInit();
2906 }
2907 
2908 }  // namespace __tsan
2909 
2910 // Invisible barrier for tests.
2911 // There were several unsuccessful iterations for this functionality:
2912 // 1. Initially it was implemented in user code using
2913 //    REAL(pthread_barrier_wait). But pthread_barrier_wait is not supported on
2914 //    MacOS. Futexes are linux-specific for this matter.
2915 // 2. Then we switched to atomics+usleep(10). But usleep produced parasitic
2916 //    "as-if synchronized via sleep" messages in reports which failed some
2917 //    output tests.
2918 // 3. Then we switched to atomics+sched_yield. But this produced tons of tsan-
2919 //    visible events, which lead to "failed to restore stack trace" failures.
2920 // Note that no_sanitize_thread attribute does not turn off atomic interception
2921 // so attaching it to the function defined in user code does not help.
2922 // That's why we now have what we have.
2923 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
__tsan_testonly_barrier_init(u64 * barrier,u32 count)2924 void __tsan_testonly_barrier_init(u64 *barrier, u32 count) {
2925   if (count >= (1 << 8)) {
2926       Printf("barrier_init: count is too large (%d)\n", count);
2927       Die();
2928   }
2929   // 8 lsb is thread count, the remaining are count of entered threads.
2930   *barrier = count;
2931 }
2932 
2933 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
__tsan_testonly_barrier_wait(u64 * barrier)2934 void __tsan_testonly_barrier_wait(u64 *barrier) {
2935   unsigned old = __atomic_fetch_add(barrier, 1 << 8, __ATOMIC_RELAXED);
2936   unsigned old_epoch = (old >> 8) / (old & 0xff);
2937   for (;;) {
2938     unsigned cur = __atomic_load_n(barrier, __ATOMIC_RELAXED);
2939     unsigned cur_epoch = (cur >> 8) / (cur & 0xff);
2940     if (cur_epoch != old_epoch)
2941       return;
2942     internal_sched_yield();
2943   }
2944 }
2945