Skip to content

Race allocating Win32ThreadPoolNativeOverlapped #137737

Closed

Description

@johnhallxjtag

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

  1. Thread 1 enters, assigns overlapped = A and evaluates overlapped->_nextFree as B. It is then interrupted before calling Interlocked.CompareExchange.
  2. Thread 2 enters and takes A from the list, leaving behind B->C.
  3. Thread 3 enters and takes B from the list, leaving behind C.
  4. Thread 2 finishes, returning A to the list, leaving behind A->C.
  5. Thread 1 resumes, does its comparison successfully, since A is still at the head. It then leaves the list as B->(null)
  6. 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

  1. added
    untriaged
    on Nov 17, 2026
  2. dotnet-policy-service commented on Nov 17, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @JulieLeeMSFT, @VSadov
    See info in area-owners.md if you want to be subscribed.

  3. removed
    untriaged
    on Nov 19, 2026
  4. added a commit that references this issue on Nov 19, 2026
    d30189e
  5. johnhallxjtag commented on Nov 19, 2026

    @johnhallxjtag
    Author

    Is this fix just targeted for .NET 12, or is there a way to advocate for inclusion in a point release?

  6. jkotas commented on Nov 19, 2026

    @jkotas
    Member

    We can consider it for .NET 11 backport. Is that good enough for you?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions