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