[TSan] Zero-initialize Trace.local_head
Trace.local_head is currently uninitialized when Trace is created. It is
first initialized when the first event is added to the trace, via the
first call to TraceSwitchPartImpl.
However, ThreadContext::OnFinished uses local_head, assuming that it is
initialized. If it has not been initialized, we have undefined behavior,
likely crashing if the contents are garbage. The allocator (Alloc)
reuses previously allocations, so the contents of the uninitialized
memory are arbitrary.
In a C/C++ TSAN binary it is likely very difficult for a thread to start
and exit without a single event inbetween. For Go programs, code running
in the Go runtime itself is not TSan-instrumented, so goroutines that
exclusively run runtime code (such as GC workers) can quite reasonably
have no TSan events.
The addition of such a goroutine to the Go test.c is sufficient to
trigger this case, though for reliable failure (segfault) I've found it
necessary to poison the ThreadContext allocation like so:
```
diff --git a/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp b/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp index feee566f44..352db9aa7c 100644
--- a/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp
+++ b/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp
@@ -392,7 +392,9 @@
report_mtx(MutexTypeReport),
nreported(),
thread_registry([](Tid tid) -> ThreadContextBase* {
- return new (Alloc(sizeof(ThreadContext))) ThreadContext(tid);
+ void* ptr = Alloc(sizeof(ThreadContext));
+ internal_memset(ptr, 0xde, sizeof(ThreadContext));
+ return new (ptr) ThreadContext(tid);
}),
racy_mtx(MutexTypeRacy),
racy_stacks(),
```
The fix is trivial: local_head should be zero-initialized.
NOKEYCHECK=True
GitOrigin-RevId: cdfdb06c9155080ec97d6e4f4dd90b6e7cefb0ca
2 files changed