Skip to content

[Trimming] ipconstprop deletes cleanup (SemaphoreSlim.Release / Dispose / Monitor.Exit) inside an async finally in a preserved method #131088

Closed

Description

@hydraxman

Description

With trimming enabled, ILLink's inter-procedural constant propagation optimization (ipconstprop) can physically delete cleanup code that lives inside a finally of a preserved async method. The method itself is kept (it is reachable and marked) — only the body of a finally nested inside the async state machine is removed.

In the minimal repro below a SemaphoreSlim(1, 1) is acquired with WaitAsync(TimeSpan.Zero) and released in a nested finally. After trimming, the WaitAsync (acquire) is still present but SemaphoreSlim.Release() is gone, so the gate is acquired once and never released and every subsequent call is rejected. The same happens to the compiler-generated cleanup for using (Dispose), lock (Monitor.Exit) and foreach (enumerator Dispose) when they sit inside an outer async finally.

This looks closely related to the already-fixed dotnet/linker#1507, and to the "constant propagation and branch removal" corruption that was explicitly called out as not having a candidate fix in dotnet/linker#2181.

The bug in pseudo-code

// What the developer writes -- valid, idiomatic C#:
if (gate.Wait(0))               // acquire a re-entrancy gate (SemaphoreSlim, lock, ...)
{
    try
    {
        await DoWorkAsync();    // an 'await' => the compiler builds an async state machine
    }
    finally
    {
        Cleanup();              // e.g. gate.Release() / Dispose() / Monitor.Exit()
    }
}
else
{
    Reject();                   // "already running / busy"
}

// What ILLink emits after 'ipconstprop' (bug): the acquire is KEPT, the cleanup is DELETED.
if (gate.Wait(0))               // acquire            <-- KEPT
{
    try
    {
        await DoWorkAsync();
    }
    finally
    {
        /* Cleanup() REMOVED */ // gate.Release()/Dispose()/Monitor.Exit() gone
    }
}
else
{
    Reject();
}
// => the gate is acquired once and never released; every entry after the first hits Reject().

The C# compiler emits correct IL for this (the pre-link assembly contains every finally); it is ipconstprop that mis-classifies a branch as unreachable and strips the nested cleanup handler out of the preserved MoveNext.

Minimal repro

Program.cs:

using System.Runtime.CompilerServices;

var service = new TransferService(new Connection());

await service.ReceiveAsync();
await service.ReceiveAsync();
await service.SendAsync();
await service.SendAsync();

internal sealed class TransferService
{
    private readonly IConnection connection;
    private readonly SemaphoreSlim semaphore = new(1, 1);
    private TransferState state = TransferState.Idle;

    public TransferService(IConnection connection) => this.connection = connection;

    public async Task ReceiveAsync()
    {
        if (await this.semaphore.WaitAsync(TimeSpan.Zero))
        {
            try
            {
                this.state = TransferState.Receiving;
                await Task.Yield();                 // force the async state machine
            }
            catch (Exception exception)
            {
                Console.WriteLine($"Receive failed: {exception.Message}");
            }
            finally
            {
                try
                {
                    this.connection.CloseConnection();
                }
                finally
                {
                    this.state = TransferState.Idle;
                    this.semaphore.Release();         // <-- DELETED by ipconstprop
                    Console.WriteLine("Receive gate released");
                }
            }
        }
        else
        {
            Console.WriteLine($"Receive gate rejected: {this.state}");
        }
    }

    public async Task SendAsync()
    {
        if (await this.semaphore.WaitAsync(TimeSpan.Zero))
        {
            CancellationTokenSource? cancellationTokenSource = new();
            try
            {
                this.state = TransferState.Sending;
                await Task.Yield();
            }
            catch (Exception exception)
            {
                Console.WriteLine($"Send failed: {exception.Message}");
            }
            finally
            {
                try
                {
                    Console.WriteLine("CloseConnection begin");
                    this.connection.CloseConnection();
                    Console.WriteLine("CloseConnection returned");
                }
                catch (Exception exception)
                {
                    Console.WriteLine($"CloseConnection failed: {exception.Message}");
                }
                finally
                {
                    this.state = TransferState.Idle;
                    this.semaphore.Release();         // <-- DELETED by ipconstprop
                    cancellationTokenSource?.Dispose();
                    Console.WriteLine("Send gate released");
                }
            }
        }
        else
        {
            Console.WriteLine($"Send gate rejected: {this.state}");
        }
    }
}

internal interface IConnection
{
    void CloseConnection();
}

internal sealed class Connection : IConnection
{
    [MethodImpl(MethodImplOptions.NoInlining)]
    public void CloseConnection()
    {
        if (Environment.TickCount == int.MinValue)
        {
            throw new InvalidOperationException();
        }
    }
}

internal enum TransferState
{
    Idle,
    Receiving,
    Sending,
}

repro.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <RuntimeIdentifier>win-x64</RuntimeIdentifier>
    <SelfContained>true</SelfContained>
    <PublishTrimmed>true</PublishTrimmed>
    <PublishReadyToRun>false</PublishReadyToRun> <!-- proves it is ILLink, not R2R -->
  </PropertyGroup>
</Project>

Steps to reproduce

# 1) default trimming (bug present)
dotnet publish -c Release -o out/on

# 2) identical source, one optimization disabled (fixed)
dotnet publish -c Release -o out/off -p:_TrimmerIPConstProp=false

Run each published exe, and/or disassemble out/*/repro.dll with ildasm.

Expected behavior

Both publishes behave identically: each call acquires the gate, runs, and releases it in the finally. No call is rejected.

Actual behavior

With default trimming, the trimmed IL contains zero SemaphoreSlim::Release() calls even though both WaitAsync() (acquire) calls remain. The single gate is taken on the first call and never returned, so every later call takes the else branch and is rejected. Publishing the identical source with -p:_TrimmerIPConstProp=false restores the Release() calls and the program runs correctly.

IL marker counts (same source, two publishes; measured with ildasm)

Marker in the trimmed assembly default (ipconstprop on) _TrimmerIPConstProp=false
callvirt SemaphoreSlim::Release() 0 2
WaitAsync() (gate acquire) 2 2
ldstr "Send gate released" 0 1
ldstr "Receive gate released" 0 1
.try clauses (whole module) 14 20
endfinally (whole module) 2 4

The deleted region (distilled from ildasm output)

_TrimmerIPConstProp=false — inner finally intact:

.try { ...; call IConnection::CloseConnection(); ... }   // body of the outer async finally
finally
{
    ldfld  ...::semaphore
    callvirt SemaphoreSlim::Release()                     // present
    callvirt CancellationTokenSource::Dispose()
    ldstr  "Send gate released"
    endfinally
}

default trimming — the entire inner finally above is gone:

finally                                                   // body of the outer async finally
{
    ...; call IConnection::CloseConnection(); ...
    leave.s
    endfinally                                            // Release()/Dispose()/"Send gate released" all absent
}

Also affects compiler-generated using / lock / foreach cleanup

The same shape deletes the cleanup the C# compiler emits, not just a hand-written Release():

// Dispose is deleted -> DisposeCount stays 0 after this runs
public async Task UsingAsync()
{
    try { await Task.Yield(); }
    finally
    {
        using var lease = new Lease(() => this.DisposeCount++);
        Console.WriteLine("Using body");
    }
}

// Monitor.Exit is deleted -> the lock is never released (stays held)
public async Task LockAsync()
{
    try { await Task.Yield(); }
    finally
    {
        lock (this.Gate) { Console.WriteLine("Lock body"); }
    }
}

Under default trimming the program observes Dispose count: 0 and Lock available: False (the lock is never released). foreach enumerator Dispose is deleted the same way.

What does NOT work around it

  • Per-assembly disable has no effect — setting <IPConstProp>false</IPConstProp> on the assembly's ResolvedFileToPublish item does not restore the cleanup; the optimization must be disabled globally.
  • [MethodImpl(MethodImplOptions.NoOptimization)] on the method does not help.
  • Rooting (TrimmerRootAssembly / TrimmerRootDescriptor / DynamicDependency) does not help — those preserve members; they do not stop in-body statement removal.

Working workaround

Disable this single optimization globally (trimming otherwise stays fully on):

<_TrimmerIPConstProp>false</_TrimmerIPConstProp>

(equivalent to passing --disable-opt ipconstprop to ILLink.)

Configuration / versions

  • Reproduced on .NET 10 (Microsoft.NET.ILLink.Tasks 10.0.10) and .NET 11 Preview 6 (Microsoft.NET.ILLink.Tasks 11.0.0-preview.6.26359.118).
  • RuntimeIdentifier=win-x64, SelfContained=true, PublishTrimmed=true, PublishReadyToRun=false (so R2R is ruled out — it is the IL linker).
  • OS: Windows 11 x64.

Related issues

Activity

  1. transferred this issue fromdotnet/linkeron Jul 20, 2026
  2. added
    untriaged
    on Jul 20, 2026
  3. dotnet-policy-service commented on Jul 20, 2026

    @dotnet-policy-service
    Contributor

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

  4. added
    area-Tools-ILLink
    and removed on Jul 20, 2026
  5. added this to the 11.0.0 milestone on Jul 20, 2026
  6. removed
    untriaged
    on Jul 20, 2026
  7. dotnet-policy-service commented on Jul 20, 2026

    @dotnet-policy-service
    Contributor

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

  8. self-assigned this
    on Jul 22, 2026
  9. added a commit that references this issue on Jul 23, 2026
    ce07ce4
  10. added a commit that references this issue on Jul 26, 2026
    832bd2e
  11. locked and limited conversation to collaborators on Aug 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-Tools-ILLink

Type

No type

Projects

  • Status
    No status

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions