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