tsan: fix a race when assigning ThreadSignalContext
authorPeter Ammon <corydoras@ridiculousfish.com>
Tue, 10 Jan 2023 18:21:41 +0000 (19:21 +0100)
committerMarco Elver <elver@google.com>
Tue, 10 Jan 2023 18:32:28 +0000 (19:32 +0100)
commit35acc32b3e6535213d3ec651c9b7870cf74fe0ec
tree58f2b7e7e851f60930cca4129e5da456d5d90c2b
parentdcf23e13615f88bdd4975058595ee60cf1d5811c
tsan: fix a race when assigning ThreadSignalContext

The SigCtx function lazily allocates a ThreadSignalContext, and stores it
in the ThreadState. This function may be called by various interceptors and
the signal handler itself.

If SigCtx itself is interrupted by a signal, then (prior to this fix) there
was a possibility of allocating two ThreadSignalContexts. This not only
leaks, it fails to deliver the signal to the program's signal handler, as
the recorded signal is overwritten by the new ThreadSignalContext.

Fix this by using a CAS to swap in the ThreadSignalContext, preventing the
race. Add a test for this case.

Reviewed By: dvyukov, melver

Differential Revision: https://reviews.llvm.org/D140582
compiler-rt/lib/tsan/rtl/tsan_interceptors_posix.cpp
compiler-rt/lib/tsan/rtl/tsan_rtl.h
compiler-rt/test/tsan/signal_thread_sigctx_race.cpp [new file with mode: 0644]