Skip to content

Work around documented Linux mmap bug. #152595

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 13, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions llvm/lib/Support/MemoryBuffer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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__
Copy link
Collaborator

Choose a reason for hiding this comment

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

How sure are we that Linux is the only OS which has this issue? Would it make sense to just remove the ifdef?

There's also a race condition here: if another processes modifies the file while it's mapped, you get undefined behavior. But we can't really do much about that.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I expect that on any OS, if another process concurrently mmaps the file with MAP_SHARED and writes into the slack bytes, or truncates the file, we will probably crash, but Linux is the only OS that I've found that documents that this can happen even if the file is not concurrently modified. I wouldn't say I'm sure that other OSes don't have similar behavior; maybe they just don't document it?

I'm happy to generalize the check if you think it's worthwhile; as far as I can see, the only real consequence is that this would fault in the final page earlier, which is probably not an especially interesting difference given that we're presumably going to reach it pretty soon anyway.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Done.

// 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__
Expand Down