[llvm] [Support] Fix thread safety issue in raw_null_ostream (PR #162787)
via llvm-commits
llvm-commits at lists.llvm.org
Thu Oct 9 22:53:31 PDT 2025
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-llvm-support
Author: Scott Pillow (scottp101)
<details>
<summary>Changes</summary>
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.
---
Full diff: https://github.com/llvm/llvm-project/pull/162787.diff
2 Files Affected:
- (modified) llvm/include/llvm/Support/raw_ostream.h (+1-1)
- (modified) llvm/unittests/Support/raw_ostream_test.cpp (+5)
``````````diff
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..a007baa8527b9 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(), 0);
+}
+
TEST(raw_ostreamTest, writeToStdOut) {
outs().flush();
testing::internal::CaptureStdout();
``````````
</details>
https://github.com/llvm/llvm-project/pull/162787
More information about the llvm-commits
mailing list