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