[llvm] [Support] Fix thread safety issue in raw_null_ostream (PR #162787)
Scott Pillow via llvm-commits
llvm-commits at lists.llvm.org
Fri Oct 10 16:01:13 PDT 2025
https://github.com/scottp101 updated https://github.com/llvm/llvm-project/pull/162787
>From 96454bdb682bda2755dab78bf71a483fa0b7488b Mon Sep 17 00:00:00 2001
From: "Pillow, Scott" <scott.pillow at intel.com>
Date: Thu, 9 Oct 2025 20:35:59 -0700
Subject: [PATCH] [Support] Fix thread safety issue in raw_null_ostream
The global raw_null_ostream singleton returned by llvm::nulls() is
marked as InternalBuffer rather than Unbuffered, causing it to
allocate a buffer when first written to. In multithreaded environments,
multiple threads can simultaneously trigger buffer allocation via
SetBuffered(), leading to race conditions on the buffer pointer
fields (OutBufCur, OutBufEnd).
For example:
raw_ostream::write(const char *Ptr, size_t Size)
->
raw_ostream::SetBuffered()
->
raw_ostream::SetBufferSize(size_t Size)
->
raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
BufferKind Mode)
This can manifest as a heap corruption when multiple threads write to the
null stream concurrently, as the buffer pointers will become corrupted
during the race.
The fix is to explicitly pass Unbuffered=true to the raw_pwrite_stream
constructor, ensuring the null stream never allocates a buffer and
all writes go directly to the no-op write_impl().
For example, this can fix multithreaded applications using MCELFStreamer
where getCommentOS() returns the shared nulls() singleton.
---
llvm/include/llvm/Support/raw_ostream.h | 2 +-
llvm/unittests/Support/raw_ostream_test.cpp | 5 +++++
2 files changed, 6 insertions(+), 1 deletion(-)
diff --git a/llvm/include/llvm/Support/raw_ostream.h b/llvm/include/llvm/Support/raw_ostream.h
index f87344e860518..70916d8e4adb0 100644
--- a/llvm/include/llvm/Support/raw_ostream.h
+++ b/llvm/include/llvm/Support/raw_ostream.h
@@ -739,7 +739,7 @@ class LLVM_ABI raw_null_ostream : public raw_pwrite_stream {
uint64_t current_pos() const override;
public:
- explicit raw_null_ostream() = default;
+ explicit raw_null_ostream() : raw_pwrite_stream(/*Unbuffered=*/true) {}
~raw_null_ostream() override;
};
diff --git a/llvm/unittests/Support/raw_ostream_test.cpp b/llvm/unittests/Support/raw_ostream_test.cpp
index fbeff37d26a35..8f9ed4143a873 100644
--- a/llvm/unittests/Support/raw_ostream_test.cpp
+++ b/llvm/unittests/Support/raw_ostream_test.cpp
@@ -626,6 +626,11 @@ TEST(raw_ostreamTest, writeToDevNull) {
EXPECT_TRUE(DevNullIsUsed);
}
+TEST(raw_ostreamTest, nullStreamZeroBufferSize) {
+ raw_ostream &NullStream = nulls();
+ EXPECT_EQ(NullStream.GetBufferSize(), 0u);
+}
+
TEST(raw_ostreamTest, writeToStdOut) {
outs().flush();
testing::internal::CaptureStdout();
More information about the llvm-commits
mailing list