runtime: Mono linker failed with function pointer delegates

Description

Mono linker failed with function pointer delegates. Code:

#define UNICODE
#define WIN32
#include <cstring>

extern "C" __declspec(dllexport) char* __cdecl InvokeFun(char* (*foo)(int)) {
    return foo(5);
}
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace Test
{
    unsafe class Program
    {
        [DllImport("./Test.dll")]
        static extern string InvokeFun(delegate* cdecl<int, IntPtr> fun);

        [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
        public static IntPtr Foo(int x)
        {
            var str = Enumerable.Repeat("x", x).Aggregate((a, b) => $"{a}{b}");
            return Marshal.StringToHGlobalAnsi(str);
        }
        static void Main(string[] args)
        {
            var callback = (delegate* cdecl<int, nint>)(delegate*<int, nint>)&Foo;
            Console.WriteLine(InvokeFun(callback));
        }
    }
}

Now run dotnet publish with PublishTrimmed:

dotnet publish -c Release -r win-x64 /p:PublishTrimmed=true

Got exception from mono lnker:

  Mono.Linker.LinkerFatalErrorException: ILLink: error IL1005: Test.Program.InvokeFun(method): Error processing method 'Test.Program.InvokeFun(method)' in assembly 'Test.dll'
   ---> System.NullReferenceException: Object reference not set to an instance of an object.
     at Mono.Linker.Steps.MarkStep.ProcessInteropMethod(MethodDefinition method)
     at Mono.Linker.Steps.MarkStep.ProcessMethod(MethodDefinition method, DependencyInfo& reason)
     at Mono.Linker.Steps.MarkStep.ProcessQueue()
     --- End of inner exception stack trace ---
     at Mono.Linker.Steps.MarkStep.ProcessQueue()
     at Mono.Linker.Steps.MarkStep.ProcessPrimaryQueue()
     at Mono.Linker.Steps.MarkStep.Process()
     at Mono.Linker.Steps.MarkStep.Process(LinkContext context)
     at Mono.Linker.Pipeline.ProcessStep(LinkContext context, IStep step)
     at Mono.Linker.Pipeline.Process(LinkContext context)
     at Mono.Linker.Driver.Run(ILogger customLogger)

Configuration

.NET 5 preview 8

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 18 (17 by maintainers)

Commits related to this issue

Most upvoted comments

@akoeplinger isn’t the rollout scheduled for Monday?

@EgorBo we can’t do that, it needs to happen as part of the monthly infrastructure rollout (https://github.com/dotnet/runtime/issues/41684)