Skip to content

ILVerify false positive: StackUnderflow at the start of an exception filter nested inside a finally handler #134711

Closed

Description

@DavidObando

Description

ILVerify reports StackUnderflow at the first instruction of an exception filter when the filter's protected region is nested inside a finally handler. The IL is valid: csc emits it for an ordinary catch (...) when (...) inside a finally block, and the program runs correctly.

The same try/catch ... when verifies cleanly when it is nested inside a try body, a catch handler, or a filtered handler. It fails only inside a finally handler, and by the root cause below a fault handler should fail the same way.

Reproduction

Tool: dotnet-ilverify 10.0.8. The same code is in main; line links below are to 754db27.
Compiler: Roslyn in the .NET SDK 10.0.401.
Target: net10.0.

Program.cs:

using System;
using System.IO;

public static class Program
{
    public static void InFinally()
    {
        try { Console.WriteLine("body"); }
        finally
        {
            try { Console.WriteLine("cleanup"); }
            catch (Exception ex) when (ex is IOException) { }
        }
    }

    // Controls: the same try/filter nested elsewhere verifies cleanly.
    public static void InCatch()
    {
        try { Console.WriteLine("body"); }
        catch (InvalidOperationException)
        {
            try { Console.WriteLine("handler"); }
            catch (Exception ex) when (ex is IOException) { }
        }
    }

    public static void InTry()
    {
        try
        {
            try { Console.WriteLine("inner"); }
            catch (Exception ex) when (ex is IOException) { }
        }
        finally { Console.WriteLine("cleanup"); }
    }

    public static void Main() { InFinally(); InCatch(); InTry(); }
}

Test.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
  </PropertyGroup>
</Project>

Build, run, and verify. The Debug build fails the same way, at offset 0x20.

$ dotnet build -c Release -nologo -clp:NoSummary
$ dotnet bin/Release/net10.0/Test.dll
body
cleanup
body
inner
cleanup

$ ilverify bin/Release/net10.0/Test.dll -s System.Private.CoreLib \
    -r /usr/local/share/dotnet/shared/Microsoft.NETCore.App/10.0.12/*.dll
[IL]: Error [StackUnderflow]: [Test.dll : Program::InFinally()][offset 0x00000019] Stack underflow.
1 Error(s) Verifying bin/Release/net10.0/Test.dll

The exception regions and IL of InFinally:

Filter   try [0x0D, 0x19)  filter [0x19, 0x32)  handler [0x32, 0x35)
Finally  try [0x00, 0x0C)  handler [0x0C, 0x36)

IL_0000: ldstr      "body"
IL_0005: call       void [System.Console]System.Console::WriteLine(string)
IL_000a: leave.s    IL_0036
IL_000c: nop                       // finally handler starts
IL_000d: ldstr      "cleanup"      // nested try starts
IL_0012: call       void [System.Console]System.Console::WriteLine(string)
IL_0017: leave.s    IL_0035
IL_0019: isinst     System.Exception   // filter starts: the exception object is on the stack
IL_001e: dup                           // ILVerify: StackUnderflow at IL_0019
IL_001f: brtrue.s   IL_0025
IL_0021: pop
IL_0022: ldc.i4.0
IL_0023: br.s       IL_0030
IL_0025: isinst     System.IO.IOException
IL_002a: ldnull
IL_002b: cgt.un
IL_002d: ldc.i4.0
IL_002e: cgt.un
IL_0030: endfilter
IL_0032: pop                       // filtered handler
IL_0033: leave.s    IL_0035
IL_0035: endfinally
IL_0036: ret

The filter block [0x19, 0x32) lies inside the finally handler [0x0C, 0x36). The runtime enters it with the exception object on the stack (ECMA-335 II.19). ILVerify enters it with an empty stack.

Root cause analysis

FindEnclosingExceptionRegions sets both indices on the filter's first block:

  • HandlerIndex points at the enclosing finally region, because offset 0x19 lies in that handler's range;
  • FilterIndex points at the filter region, because 0x19 lies in [FilterOffset, HandlerOffset).

StartImportingBasicBlock then chooses the region that decides the entry stack by checking HandlerIndex first:

if (basicBlock.FilterStart || basicBlock.HandlerStart)
{
    ExceptionRegion r;
    if (basicBlock.HandlerIndex.HasValue)
    {
        r = _exceptionRegions[basicBlock.HandlerIndex.Value];   // the enclosing finally
    }
    else if (basicBlock.FilterIndex.HasValue)
    {
        r = _exceptionRegions[basicBlock.FilterIndex.Value];    // never reached here
    }
    ...
    if (r.ILRegion.Kind == ILExceptionRegionKind.Filter || r.ILRegion.Kind == ILExceptionRegionKind.Catch)
    {
        // pushes the exception object
    }
    else
    {
        // stack must be uninit or empty
        Check(basicBlock.EntryStack == null || basicBlock.EntryStack.Length == 0, VerifierError.FinOrFaultNonEmptyStack);
        if (basicBlock.EntryStack == null)
            basicBlock.EntryStack = s_emptyStack;
    }
}

So the filter start is treated as the start of the enclosing finally, it gets an empty entry stack, and its first instruction underflows.

The same mix-up happens silently when the enclosing handler is a catch. The filter start gets the outer catch's exception type (InvalidOperationException in InCatch) rather than object. That happens to verify here, but it types the filter's exception object wrongly. For example, a filter that uses a member of the outer catch's exception type without casting would be accepted.

Suggested fix

For a filter start, use the block's own filter region:

ExceptionRegion r;
if (basicBlock.FilterStart)
{
    r = _exceptionRegions[basicBlock.FilterIndex.Value];
}
else if (basicBlock.HandlerIndex.HasValue)
{
    r = _exceptionRegions[basicBlock.HandlerIndex.Value];
}
else
{
    Debug.Fail("Block marked as filter / handler start but no filter / handler index set.");
    return;
}

This can't change which region a handler start uses. A filter block cannot also start a handler, because the filter comes after its own try, which is nested inside any handler that contains it.

Related issues

Other compilers

The G# compiler I work on emits the same layout for the equivalent source, and ILVerify fails it the same way:

func A() string {
    try {
        return "a"
    } finally {
        try {
            Console.WriteLine("cleanup")
        } catch (ex Exception) when ex is IOException {
        }
    }
}

For now we carry a narrowly scoped suppression: a StackUnderflow whose offset is the start of a filter nested in a finally/fault handler.

I'm happy to send a PR with the fix above and a test if a maintainer confirms the direction.

Environment

  • OS: macOS (Darwin), arm64
  • .NET SDK: 10.0.401 (runtime 10.0.12)
  • dotnet-ilverify: 10.0.8
  • Target framework: net10.0

Activity

  1. added
    untriaged
    on Sep 26, 2026
  2. added
    area-Tools-ILVerification
    and removed
    area-ExceptionHandling-coreclr
    on Sep 26, 2026
  3. dotnet-policy-service commented on Sep 26, 2026

    @dotnet-policy-service
    Contributor

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

  4. added a commit that references this issue on Oct 13, 2026
    1e0326f
  5. removed
    untriaged
    on Oct 13, 2026
  6. locked and limited conversation to collaborators on Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-Tools-ILVerification

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions