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