Repository navigation
Description
Description
Win32ThreadPoolNativeOverlapped.AllocateNew can hand out the same instance twice.
I have been using usbipd to expose USB devices to programs running inside WSL and have observed crashes due to double-freeing of a Win32ThreadPoolNativeOverlapped while accessing multiple devices simultaneously.
The exception is:
Unhandled exception. System.InvalidOperationException: 'overlapped' has already been freed.
at System.Threading.ThreadPoolBoundHandle.OnNativeIOCompleted(IntPtr instance, IntPtr context, IntPtr overlappedPtr, UInt32 ioResult, UIntPtr numberOfBytesTransferred, IntPtr ioPtr)
The allocation code in question is:
overlapped = (Win32ThreadPoolNativeOverlapped*)freePtr;
if (Interlocked.CompareExchange(ref s_freeList, overlapped->_nextFree, freePtr) != freePtr)
continue;Start with s_freeList as A->B->C
- Thread 1 enters, assigns overlapped = A and evaluates overlapped->_nextFree as B. It is then interrupted before calling Interlocked.CompareExchange.
- Thread 2 enters and takes A from the list, leaving behind B->C.
- Thread 3 enters and takes B from the list, leaving behind C.
- Thread 2 finishes, returning A to the list, leaving behind A->C.
- Thread 1 resumes, does its comparison successfully, since A is still at the head. It then leaves the list as B->(null)
- Another thread then enters and takes B, which is still in use by thread 3.
This means that we have two requests sharing the same overlapped structure and also have leaked C and any instances linked to it.
Reproduction Steps
Running this project in release reproduces the failure almost immediately.
OverlappedRepro.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<Optimize>true</Optimize>
<!-- Override on the command line: dotnet run -c Release -p:UseWindowsThreadPool=false -->
<UseWindowsThreadPool Condition="'$(UseWindowsThreadPool)' == ''">true</UseWindowsThreadPool>
</PropertyGroup>
</Project>Program.cs:
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Runtime.InteropServices;
// Hammers ThreadPoolBoundHandle.AllocateNativeOverlapped / FreeNativeOverlapped from many threads.
// No I/O is issued; only the overlapped allocator is exercised.
// With the Windows thread pool, AllocateNew() can hand out a NativeOverlapped* that is still allocated.
var seconds = args.Length > 0 ? int.Parse(args[0]) : 30;
var threadCount = args.Length > 1 ? int.Parse(args[1]) : Environment.ProcessorCount * 2;
const int BatchSize = 8;
var useWindowsThreadPool = AppContext.TryGetSwitch("System.Threading.ThreadPool.UseWindowsThreadPool", out var s) && s;
Console.WriteLine($"Runtime {Environment.Version}, UseWindowsThreadPool={useWindowsThreadPool}, threads={threadCount}, duration={seconds}s");
var path = Path.Combine(Path.GetTempPath(), $"overlapped-repro-{Guid.NewGuid():N}.tmp");
// File.OpenHandle(..., FileOptions.Asynchronous) binds the handle itself; we need an unbound overlapped handle, like usbipd's DeviceFile.
const uint GENERIC_READ_WRITE = 0xC0000000;
const uint CREATE_NEW = 1;
const uint FILE_FLAG_OVERLAPPED_AND_DELETE_ON_CLOSE = 0x40000000 | 0x04000000;
using var handle = Native.CreateFileW(path, GENERIC_READ_WRITE, 0, IntPtr.Zero, CREATE_NEW, FILE_FLAG_OVERLAPPED_AND_DELETE_ON_CLOSE, IntPtr.Zero);
if (handle.IsInvalid)
{
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
}
using var boundHandle = ThreadPoolBoundHandle.BindHandle(handle);
var stop = new ManualResetEventSlim();
long iterations = 0;
var failure = 0;
void Fail(string message)
{
if (Interlocked.Exchange(ref failure, 1) == 0)
{
Console.WriteLine($"REPRODUCED after {Interlocked.Read(ref iterations):N0} allocations: {message}");
stop.Set();
}
}
unsafe void Worker()
{
var ptrs = new NativeOverlapped*[BatchSize];
var owners = new object[BatchSize];
var rng = new Random(Environment.CurrentManagedThreadId);
IOCompletionCallback callback = static (_, _, _) => { };
while (!stop.IsSet)
{
for (var i = 0; i < BatchSize; i++)
{
owners[i] = new object();
ptrs[i] = boundHandle.AllocateNativeOverlapped(callback, owners[i], null);
}
// Each pointer must still carry the state this thread gave it. If another thread was handed the same
// pointer, its SetData has overwritten the state.
for (var i = 0; i < BatchSize; i++)
{
if (!ReferenceEquals(ThreadPoolBoundHandle.GetNativeOverlappedState(ptrs[i]), owners[i]))
{
Fail($"overlapped 0x{(nint)ptrs[i]:X} was allocated to more than one owner at the same time");
return;
}
}
// Free in random order to churn the free list.
for (var i = BatchSize - 1; i > 0; i--)
{
var j = rng.Next(i + 1);
var tmp = ptrs[i];
ptrs[i] = ptrs[j];
ptrs[j] = tmp;
}
for (var i = 0; i < BatchSize; i++)
{
try
{
boundHandle.FreeNativeOverlapped(ptrs[i]);
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
{
Fail($"{ex.GetType().Name}: {ex.Message}");
return;
}
}
_ = Interlocked.Add(ref iterations, BatchSize);
}
}
var threads = Enumerable.Range(0, threadCount).Select(_ => new Thread(Worker) { IsBackground = true }).ToArray();
var sw = Stopwatch.StartNew();
foreach (var t in threads) { t.Start(); }
_ = stop.Wait(TimeSpan.FromSeconds(seconds));
stop.Set();
foreach (var t in threads) { _ = t.Join(5000); }
if (failure == 0)
{
Console.WriteLine($"No failure in {sw.Elapsed.TotalSeconds:F0}s, {Interlocked.Read(ref iterations):N0} allocations.");
return 0;
}
return 1;
static class Native
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeFileHandle CreateFileW(string fileName, uint access, uint share, IntPtr security, uint disposition, uint flags, IntPtr template);
}Expected behavior
A Win32ThreadPoolNativeOverlapped is never re-used until it has been finished with.
Actual behavior
A race makes it possible for a Win32ThreadPoolNativeOverlapped instance to be issued by two requests simultaneously.
Regression?
No response
Known Workarounds
If you don't use the windows thread pool, then the problem does not occur.
Configuration
.NET 10.0.15 and .NET 11.0.0
Windows 11 25H2 x64
Other information
No response
Activity
dotnet-policy-service commentedon Nov 17, 2026
Tagging subscribers to this area: @JulieLeeMSFT, @VSadov
See info in area-owners.md if you want to be subscribed.
Delete NativeOverlapped pool for Win32ThreadPool (dotnet#137800)
johnhallxjtag commentedon Nov 19, 2026
Is this fix just targeted for .NET 12, or is there a way to advocate for inclusion in a point release?
Use portable thread pool to prevent race allocating overlapped structs
jkotas commentedon Nov 19, 2026
We can consider it for .NET 11 backport. Is that good enough for you?