Skip to content

Conversation

scottp101
Copy link
Contributor

@scottp101 scottp101 commented Oct 10, 2025

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.

Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@scottp101 scottp101 marked this pull request as ready for review October 10, 2025 05:52
@llvmbot
Copy link
Member

llvmbot commented Oct 10, 2025

@llvm/pr-subscribers-llvm-support

Author: Scott Pillow (scottp101)

Changes

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 --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();

@michalpaszkowski michalpaszkowski requested review from dwblaikie, jurahul, kuhar, michalpaszkowski and topperc and removed request for jurahul October 10, 2025 16:47
Copy link
Member

@michalpaszkowski michalpaszkowski left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Let's wait for the builds and checks to finish. Tagging @dwblaikie and @kuhar (maintainers for this part of the project) for visibility/review.

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.
@scottp101
Copy link
Contributor Author

Okay, build succeeded. I don't have merge privileges. Can someone push this through?

@kuhar kuhar merged commit cb4fdc0 into llvm:main Oct 11, 2025
10 checks passed
Copy link

@scottp101 Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

@llvm-ci
Copy link
Collaborator

llvm-ci commented Oct 11, 2025

LLVM Buildbot has detected a new failure on builder clang-armv8-quick running on linaro-clang-armv8-quick while building llvm at step 5 "ninja check 1".

Full details are available at: https://lab.llvm.org/buildbot/#/builders/154/builds/22604

Here is the relevant piece of the build log for the reference
Step 5 (ninja check 1) failure: stage 1 checked (failure)
******************** TEST 'Clangd Unit Tests :: ./ClangdTests/289/335' FAILED ********************
Script(shard):
--
GTEST_OUTPUT=json:/home/tcwg-buildbot/worker/clang-armv8-quick/stage1/tools/clang/tools/extra/clangd/unittests/./ClangdTests-Clangd Unit Tests-1096693-289-335.json GTEST_SHUFFLE=0 GTEST_TOTAL_SHARDS=335 GTEST_SHARD_INDEX=289 /home/tcwg-buildbot/worker/clang-armv8-quick/stage1/tools/clang/tools/extra/clangd/unittests/./ClangdTests
--

Note: This is test shard 290 of 335.
[==========] Running 4 tests from 4 test suites.
[----------] Global test environment set-up.
[----------] 1 test from BuildCompilerInvocation
[ RUN      ] BuildCompilerInvocation.EmptyArgs
[       OK ] BuildCompilerInvocation.EmptyArgs (0 ms)
[----------] 1 test from BuildCompilerInvocation (0 ms total)

[----------] 1 test from HeaderSourceSwitchTest
[ RUN      ] HeaderSourceSwitchTest.ClangdServerIntegration
ASTWorker building file /clangd-test/src/lib/test.cpp version null with command 
[/clangd-test/src/lib]
clang -I/clangd-test/src/include /clangd-test/src/lib/test.cpp
Driver produced command: cc1 -cc1 -triple armv8a-unknown-linux-gnueabihf -fsyntax-only -disable-free -clear-ast-before-backend -main-file-name test.cpp -mrelocation-model pic -pic-level 2 -pic-is-pie -mframe-pointer=all -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -target-cpu generic -target-feature +read-tp-tpidruro -target-feature +vfp2 -target-feature +vfp2sp -target-feature +vfp3 -target-feature +vfp3d16 -target-feature +vfp3d16sp -target-feature +vfp3sp -target-feature +fp16 -target-feature +vfp4 -target-feature +vfp4d16 -target-feature +vfp4d16sp -target-feature +vfp4sp -target-feature +fp-armv8 -target-feature +fp-armv8d16 -target-feature +fp-armv8d16sp -target-feature +fp-armv8sp -target-feature -fullfp16 -target-feature +fp64 -target-feature +d32 -target-feature +sha2 -target-feature +aes -target-feature -fp16fml -target-feature +neon -target-abi aapcs-linux -mfloat-abi hard -debugger-tuning=gdb -fdebug-compilation-dir=/clangd-test/src/lib -fcoverage-compilation-dir=/clangd-test/src/lib -resource-dir lib/clang/22 -I /clangd-test/src/include -internal-isystem lib/clang/22/include -internal-isystem /usr/local/include -internal-externc-isystem /include -internal-externc-isystem /usr/include -fdeprecated-macro -ferror-limit 19 -fno-signed-char -fgnuc-version=4.2.1 -fskip-odr-check-in-gmf -fcxx-exceptions -fexceptions -no-round-trip-args -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -x c++ /clangd-test/src/lib/test.cpp
Building first preamble for /clangd-test/src/lib/test.cpp version null
not idle after addDocument
UNREACHABLE executed at ../llvm/clang-tools-extra/clangd/unittests/SyncAPI.cpp:22!
Built preamble of size 417788 for file /clangd-test/src/lib/test.cpp version null in 13.78 seconds
indexed preamble AST for /clangd-test/src/lib/test.cpp version null:
  symbol slab: 1 symbols, 4304 bytes
  ref slab: 0 symbols, 0 refs, 72 bytes
  relations slab: 0 relations, 12 bytes
Build dynamic index for header symbols with estimated memory usage of 6112 bytes
#0 0x02720540 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/home/tcwg-buildbot/worker/clang-armv8-quick/stage1/tools/clang/tools/extra/clangd/unittests/./ClangdTests+0xb40540)
#1 0x0271da00 llvm::sys::RunSignalHandlers() (/home/tcwg-buildbot/worker/clang-armv8-quick/stage1/tools/clang/tools/extra/clangd/unittests/./ClangdTests+0xb3da00)
#2 0x02721544 SignalHandler(int, siginfo_t*, void*) Signals.cpp:0:0
#3 0xeb21d6f0 __default_rt_sa_restorer ./signal/../sysdeps/unix/sysv/linux/arm/sigrestorer.S:80:0
#4 0xeb20db06 ./csu/../sysdeps/unix/sysv/linux/arm/libc-do-syscall.S:47:0
#5 0xeb24d292 __pthread_kill_implementation ./nptl/pthread_kill.c:44:76
#6 0xeb21c840 gsignal ./signal/../sysdeps/posix/raise.c:27:6

--
exit: -6
--
shard JSON output does not exist: /home/tcwg-buildbot/worker/clang-armv8-quick/stage1/tools/clang/tools/extra/clangd/unittests/./ClangdTests-Clangd Unit Tests-1096693-289-335.json
********************


DharuniRAcharya pushed a commit to DharuniRAcharya/llvm-project that referenced this pull request Oct 13, 2025
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants