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