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