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