Skip to content

Sigsegv when calling a virtual method via UnsafeAccessor #101643

@andriivitiv

Description

@andriivitiv

Description

Calling a virtual method via UnsafeAccessor many times crashes the runtime with exit code 139. This is likely caused by a JIT optimization.

Reproduction Steps

dotnet run -c Release
using System.Runtime.CompilerServices;

Console.WriteLine("Program started");

var obj = new Foo();

for (var i = 0; i < 1_000_000; i++)
{
    FooAccessor.Func(obj);

    // There must be another call after the call to UnsafeAccessor otherwise no crash.
    // Any of the below will cause the crash but methods like
    // GC.KeepAlive(obj), Console.Write("") or await Task.Delay(0) won't.
    // Don't know why.
    await Task.Delay(1);
    //GC.Collect();
    //Console.WriteLine(0);
}

Console.WriteLine("Success - no crash");

internal class Foo
{
    // Only crashes on virtual methods
    public virtual void Func()
    {
    }
}

internal class FooAccessor
{
    [UnsafeAccessor(UnsafeAccessorKind.Method, Name = nameof(Foo.Func))]
    public static extern void Func(Foo b);
}

Expected behavior

Prints:

Program started
Success - no crash

Exit code: 0

Actual behavior

Prints:

Program started

Exit code: 139

Regression?

No. Crashes on both .NET 8 and 9.

Known Workarounds

Apply [MethodImpl(MethodImplOptions.NoOptimization)] to the UnsafeAccessor method.

Configuration

Happens on both linux-x64 and osx-x64.

.NET SDK:
 Version:           9.0.100-preview.3.24204.13
 Commit:            81f61d8290
 Workload version:  9.0.100-manifests.77bb7ba9
 MSBuild version:   17.11.0-preview-24178-16+7ca3c98fa

Runtime Environment:
 OS Name:     ubuntu
 OS Version:  22.04
 OS Platform: Linux
 RID:         linux-x64
 Base Path:   /home/andrii/dev/dotnet/runtime/.dotnet/sdk/9.0.100-preview.3.24204.13/

.NET workloads installed:
There are no installed workloads to display.

Host:
  Version:      9.0.0-preview.3.24172.9
  Architecture: x64
  Commit:       9e6ba1f68c

.NET SDKs installed:
  9.0.100-preview.3.24204.13 [/home/andrii/dev/dotnet/runtime/.dotnet/sdk]

.NET runtimes installed:
  Microsoft.AspNetCore.App 9.0.0-preview.3.24172.13 [/home/andrii/dev/dotnet/runtime/.dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 9.0.0-preview.3.24172.9 [/home/andrii/dev/dotnet/runtime/.dotnet/shared/Microsoft.NETCore.App]

Other information

No response

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions