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