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