[llvm] Work around documented Linux mmap bug. (PR #152595)
via llvm-commits
llvm-commits at lists.llvm.org
Thu Aug 7 13:45:38 PDT 2025
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-llvm-support
Author: Richard Smith (zygoloid)
<details>
<summary>Changes</summary>
On Linux, mmap doesn't always zero-fill slack bytes, despite being required to do so by POSIX. If the final page of a file is in the page cache and the bytes past the end of the file get overwritten by some process, those bytes then remain non-zero until the page falls out of the cache or another process overwrites them.
Stop trusting that mmap behaves properly on Linux and instead check whether the buffer was indeed properly terminated. If not, fall back to using `read` to read the file contents.
This fixes an obscure clang crash bug that can occur if another program (such as an editor) mmap's a source file and writes past the end of the mmap'd region shortly before clang or clangd attempts to parse the file.
---
Full diff: https://github.com/llvm/llvm-project/pull/152595.diff
1 Files Affected:
- (modified) llvm/lib/Support/MemoryBuffer.cpp (+9-2)
``````````diff
diff --git a/llvm/lib/Support/MemoryBuffer.cpp b/llvm/lib/Support/MemoryBuffer.cpp
index 601f11f6d23c8..ac686b5fb9099 100644
--- a/llvm/lib/Support/MemoryBuffer.cpp
+++ b/llvm/lib/Support/MemoryBuffer.cpp
@@ -501,8 +501,15 @@ getOpenFileImpl(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize,
std::unique_ptr<MB> Result(
new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile<MB>(
RequiresNullTerminator, FD, MapSize, Offset, EC));
- if (!EC)
- return std::move(Result);
+ if (!EC) {
+#ifdef __linux__
+ // On Linux, mmap may return pages from the page cache that are not
+ // properly filled with trailing zeroes, if some prior user of the page
+ // wrote non-zero bytes. Detect this and don't use mmap in that case.
+ if (!RequiresNullTerminator || *Result->getBufferEnd() == '\0')
+#endif
+ return std::move(Result);
+ }
}
#ifdef __MVS__
``````````
</details>
https://github.com/llvm/llvm-project/pull/152595
More information about the llvm-commits
mailing list