Skip to content

Fix race condition in SharedMemoryHelpers.CreateOrOpenFile for named mutexes on Unix#129923

Draft
Copilot wants to merge 2 commits into
mainfrom
copilot/fix-nuget-migrations-issue
Draft

Fix race condition in SharedMemoryHelpers.CreateOrOpenFile for named mutexes on Unix#129923
Copilot wants to merge 2 commits into
mainfrom
copilot/fix-nuget-migrations-issue

Conversation

Copilot AI commented Jun 27, 2026

Copy link
Copy Markdown
Contributor

Two processes racing to create the same named mutex could hit a TOCTOU window where O_RDWR sees ENOENT but O_CREAT|O_EXCL then fails with EEXIST (another process won the race), producing an unhandled IOException.

Fix: Wrap CreateOrOpenFile in a retry loop — when O_CREAT|O_EXCL fails with EEXIST, loop back and open the now-existing file instead of throwing.

// Before: threw IOException on EEXIST
fd = Interop.Sys.Open(path, O_RDWR | O_CLOEXEC | O_CREAT | O_EXCL, perms);
if (fd.IsInvalid)
{
    error = Interop.Sys.GetLastErrorInfo();
    throw Interop.GetExceptionForIoErrno(error, path); // throws on EEXIST
}

// After: retry when another process beat us to creation
if (fd.IsInvalid)
{
    error = Interop.Sys.GetLastErrorInfo();
    if (error.Error == Interop.Error.EEXIST)
        continue; // loop back to open the existing file
    throw Interop.GetExceptionForIoErrno(error, path);
}

This mirrors the existing retry pattern already used in EnsureDirectoryExists for the same class of race.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-infrastructure-libraries
See info in area-owners.md if you want to be subscribed.

When O_CREAT|O_EXCL fails with EEXIST, another process created the file
between our ENOENT check and our creation attempt. Instead of throwing an
IOException, retry opening the existing file from the top of the loop.

This fixes the race condition that caused:
  System.IO.IOException: The file '...NuGet-Migrations' already exists.
when two processes try to create the same named mutex simultaneously.

Closes #91987

Co-authored-by: jkotas <6668460+jkotas@users.noreply.github.com>
Copilot AI requested review from Copilot and removed request for Copilot June 27, 2026 06:29
Copilot AI changed the title [WIP] Fix issue with opening device or file specified 'NuGet-Migrations' Fix race condition in SharedMemoryHelpers.CreateOrOpenFile for named mutexes on Unix Jun 27, 2026
Copilot AI requested a review from jkotas June 27, 2026 06:30
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.

2 participants