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

source code of compiler-rt/lib/tsan/rtl/tsan_interceptors_posix.cpp