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