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