Skip to content

Resolve interface calls in x86 funclets with a helper - #138485

Open
am11 wants to merge 7 commits into
dotnet:mainfrom
am11:fix/x86-dispatch-slow-unwind
Open

am11 wants to merge 7 commits into
dotnet:mainfrom
am11:fix/x86-dispatch-slow-unwind

Conversation

@am11

@am11 am11 commented Nov 29, 2026

Copy link
Copy Markdown
Member

The interface dispatch slow path cannot unwind into funclets on x86
since it does not know the size of the callee-popped arguments.

Fixes #138481

am11 added 2 commits November 30, 2026 00:01
The interface dispatch slow path cannot unwind into funclets on x86
since it does not know the size of the callee-popped arguments.

Fixes dotnet#138481
@am11
am11 requested a review from jkotas November 29, 2026 22:03
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 29, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 5 pipeline(s).
10 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

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

@jkotas

jkotas commented Nov 30, 2026

Copy link
Copy Markdown
Member

I do not think this is a complete fix. The same problem exists outside funclets as well. This is Copilot generated repro that is still crashing with the fix in the PR:

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Xunit;

// On x86 NativeAOT, the interface dispatch slow path unwinds to the caller with an SP that does not
// account for the callee-popped stack arguments of the interface method. In partially interruptible
// code, pending pushed GC ref arguments of an outer call are reported relative to ESP, so a GC during
// the nested interface dispatch reports the wrong slots.
public class PendingArgRepro
{
    private interface IManyArgs
    {
        int Sum(int a, int b, int c, int d, int e, int f);
    }

    [DynamicInterfaceCastableImplementation]
    private interface IManyArgsImpl : IManyArgs
    {
        int IManyArgs.Sum(int a, int b, int c, int d, int e, int f) => a + b + c + d + e + f;
    }

    private sealed class Castable : IDynamicInterfaceCastable
    {
        public RuntimeTypeHandle GetInterfaceImplementation(RuntimeTypeHandle interfaceType)
        {
            GC.Collect(2, GCCollectionMode.Forced, blocking: true, compacting: true);

            // Reuse the memory of anything that was not reported so that a stale reference is visible.
            for (int i = 0; i < 1000; i++)
                s_junk[i % s_junk.Length] = new long[] { -1, -1, -1, -1 };

            return typeof(IManyArgsImpl).TypeHandle;
        }

        public bool IsInterfaceImplemented(RuntimeTypeHandle interfaceType, bool throwIfNotImplemented) => true;
    }

    private static object[] s_junk = new object[64];

    private sealed class Payload
    {
        public int Magic;
        public Payload(int magic) => Magic = magic;
    }

    private const int ExpectedMagic = 0x12345678;

    [MethodImpl(MethodImplOptions.NoInlining)]
    private static IManyArgs Get() => (IManyArgs)(object)new Castable();

    [MethodImpl(MethodImplOptions.NoInlining)]
    private static Payload MakePayload() => new Payload(ExpectedMagic);

    [MethodImpl(MethodImplOptions.NoInlining)]
    private static int Outer(int a, int b, Payload obj, int sum)
    {
        if (obj.GetType() != typeof(Payload) || obj.Magic != ExpectedMagic)
        {
            Console.WriteLine($"Bad payload: magic=0x{obj.Magic:X}");
            return -1;
        }
        return a + b + sum;
    }

    // Partially interruptible, no EH, no loops. `obj` is pushed on the stack for Outer
    // before the nested interface call is made.
    [MethodImpl(MethodImplOptions.NoInlining)]
    private static int Caller()
    {
        return Outer(1, 2, MakePayload(), Get().Sum(1, 2, 3, 4, 5, 6));
    }

    [Fact]
    public static void InterfaceCallWithPendingGcArg()
    {
        for (int i = 0; i < 8; i++)
        {
            Assert.Equal(3 + 21, Caller());
        }
    }
}

@jkotas

jkotas commented Nov 30, 2026

Copy link
Copy Markdown
Member

We may want to switch NAOT x86 to the ldftn plan unconditionally. It may be a bit slower, but I do not think we care.

am11 and others added 2 commits November 30, 2026 10:54
Co-authored-by: Cursor <cursoragent@cursor.com>
The interface dispatch slow path does not know the size of the
callee-popped arguments, so it cannot unwind to the caller correctly
outside funclets either: pending pushed GC refs of an outer call in
partially interruptible code were misreported.

Co-authored-by: Cursor <cursoragent@cursor.com>
@am11

am11 commented Nov 30, 2026

Copy link
Copy Markdown
Member Author

Thanks, confirmed: the repro crashed 5/5 on win-x86 with the previous fix. Switched NAOT x86 to the ldftn plan unconditionally (same path as wasm) in cb0a85d and added the repro to the test in 838d138. Both tests and the x86 smoke tests pass.

@jkotas
jkotas requested a balanced review from Copilot November 30, 2026 09:56
@jkotas jkotas added the blocked Issue/PR is blocked on something - see comments label Nov 30, 2026
@jkotas

jkotas commented Nov 30, 2026

Copy link
Copy Markdown
Member

Let's wait for #137436 to be merged first. We should be able to delete a bit of x86 asm code for the non-ldftn resolution helper.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Standalone interface ldvirtftn on NativeAOT x86 still supplies a thunk where the importer expects a dispatch cell, risking a crash when the function pointer is invoked via calli.

1 open issue
What changed in this PR

This PR addresses NativeAOT x86 stack-unwinding corruption reported in #138481 by resolving interface calls through a helper before invoking the target.

Changes:

  • Enables helper-based interface resolution for NativeAOT x86 in the compiler and JIT importer.
  • Maps fast interface resolution to RhpDispatchResolve.
  • Adds regression tests for interface calls inside catch handlers and calls with pending GC-reference arguments.
File Description
src/​tests/​Regressions/​coreclr/​GitHub_138481/​test138481.csproj Registers the regression test source and test-library reference.
src/​tests/​Regressions/​coreclr/​GitHub_138481/​test138481.cs Exercises interface resolution during GC in both affected scenarios.
src/​coreclr/​tools/​aot/​ILCompiler.RyuJit/​JitInterface/​CorInfoImpl.RyuJit.cs Selects helper-based interface dispatch on x86.
src/​coreclr/​tools/​aot/​ILCompiler.Compiler/​Compiler/​DependencyAnalysis/​KnownExternFunctions.cs Supplies the resolver mapping and helper signature.
src/​coreclr/​jit/​importer.cpp Extends NativeAOT interface lookup handling to x86.

Review effort: Balanced

@@ -1612,8 +1612,10 @@ private void getCallInfo(ref CORINFO_RESOLVED_TOKEN pResolvedToken, CORINFO_RESO
&& ((flags & CORINFO_CALLINFO_FLAGS.CORINFO_CALLINFO_LDFTN) == 0
|| _compilation.TypeSystemContext.Target.Architecture == TargetArchitecture.Wasm32))

This branch has not been deployed

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

Labels

area-NativeAOT-coreclr blocked Issue/PR is blocked on something - see comments community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[NativeAOT] [Windows/x86] Stack unwinding from interface dispatch inside funclets corrupts stack pointer

3 participants