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