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