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