Skip to content

ilc: Add the ability to specify whether UnmanagedCallersOnly methods with entry points should be treated as roots or not #127575

Closed

Description

@rolfbjarne

Currently, ILC will root [UnmanagedCallersOnly] methods that have an entry point if building a library.

This generally makes sense if you're shipping a library, but for mobile scenarios (ios/android), even if we ask ILC to build a library, we really end up building an executable, so that reasoning doesn't quite apply to us.

Additionally, we generate managed code that will be called from native code, and we need that managed code to be trimmable. As such, we have workarounds for ILC rooting such [UnmanagedCallersOnly] methods by generating UCO methods without an entry point, and then we have a separate managed function pointer lookup method which is trimmable (and thus also the UCO method is trimmable).

This is rather wasteful, we'd like to call the UCO method directly from native code.

Ideas:

  • Add an option to ILC to never root UCO methods. If we find out that this trims away too much, we can use other means to manually root them if needed (xml files, DynamicDependency attributes, etc.)
  • Add an option to ILC that specifies a file with a list of native entry points whose UCO methods should not be treated as roots.
  • This is probably overkill, but combine the two, and possibly make them complimentary: an option to never/always root UCO methods + an option to specify a list of native entry points that should/should not be rooted. That way it's possible to say both "root everything, except X, Y and Z", and the opposite "root nothing, except A, B and C."

CC @simonrozsival

Activity

  1. added
    untriaged
    on Apr 29, 2026
  2. dotnet-policy-service commented on Apr 29, 2026

    @dotnet-policy-service
    Contributor

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

  3. MihuBot commented on Apr 29, 2026

    @MihuBot

    I'm a bot. Here is a possible related and/or duplicate issue (I may be wrong):

  4. MichalStrehovsky commented on Apr 29, 2026

    @MichalStrehovsky
    Member

    The list of assemblies the compiler looks at for UCO with entrypoints is controlled with UnmanagedEntryPointsAssembly ItemGroup.

    Who computes the list of UCO methods that are needed and based on what?

  5. rolfbjarne commented on Apr 30, 2026

    @rolfbjarne
    MemberAuthor

    The list of assemblies the compiler looks at for UCO with entrypoints is controlled with UnmanagedEntryPointsAssembly ItemGroup.

    Right now we add every assembly to the UnmanagedEntryPointsAssembly item group: https://github.com/dotnet/macios/blob/685053919f37d5d07604bdb4a3071ecbffa0244d/dotnet/targets/Xamarin.Shared.Sdk.targets#L1544-L1547

    We have an issue to see if we can shrink this list: dotnet/macios#18484

    Who computes the list of UCO methods that are needed and based on what?

    We (the iOS workload) compute/generate a number of UCO methods. Application/user code is unlikely to have any, but it's not technically impossible.

    Given this C# class:

    public class MyObject : NSObject {
        [Export ("myMethod")]
    	void MyMethod () {}
    }

    The managed MyMethod is exported to Objective-C using the myMethod selector.

    Meaning that it's possible to do this in Objective-C:

    MyObject* obj = [[MyObject alloc] init];
    [obj myMethod]

    and it should call the managed MyMethod method.

    We solve this by generating a proxy class with an [UnmanagedCallersOnly] method (lots of details omitted here, but this is the gist of it):

    class MyObjectProxy {
        [UnmanagedCallersOnly (EntryPoint = "MyObjectProxy_MyMethod"]
        static void MyMethod (IntPtr handle)
        {
            var obj = (MyObject) Runtime.GetNSObject (handle);
            obj.MyMethod ();
        }
    }

    Then we generate an Objective-C version of the MyObject class, where the myMethod selector calls the MyObjectProxy_MyMethod UCO method.

    Now this solution isn't trimmable, so our workaround is to do something like this:

    class MyObjectProxy {
        unsafe static IntPtr GetMyMethod ()
        {
           return (IntPtr) (delegate* unmanaged<IntPtr, void>) (&MyMethod);
        }
    
        [UnmanagedCallersOnly]
        static void MyMethod (IntPtr handle)
        {
            var obj = (MyObject) Runtime.GetNSObject (handle);
            obj.MyMethod ();
        }
    }

    and then, in Objective-C, we lookup the MyMethod function pointer instead of calling the UCO method directly.

  6. MichalStrehovsky commented on Apr 30, 2026

    @MichalStrehovsky
    Member

    Ah, I see. Looks like this is one of the aspects we discussed in the past over at #80912.

    The thing that concerns me with the proposed additional UCO controls is that these just support the existing architecture where there is a whole program analysis step before ILC runs that figures out things that should/should not be generated and then dictates what ILC should do.

    ILC can typically do a better job at trimming by the nature of its output (output of IL trimming needs to be valid IL, output of ILC is machine code, GC/EH metadata, and reflection metadata - all of which can be pretty disconnected; one can have a method body without knowing its name or signature; one can even have instructions from a method body without having the method body (method that was inlined everywhere)).

    I wonder if we could introduce a more declarative mechanism for this - something like what we did with TypeMap. Just throwing a suggestion:

    class MyObjectProxy
    {
        // TrimTarget tells analysis to only generate force the UCO entrypoint if a MyObjectProxy instance could exist in the program.
        [UnmanagedCallersOnly (EntryPoint = "MyObjectProxy_MyMethod", TrimTarget = typeof(MyObjectProxy)]
        static void MyMethod (IntPtr handle) { }
    }
  7. rolfbjarne commented on Apr 30, 2026

    @rolfbjarne
    MemberAuthor

    I wonder if we could introduce a more declarative mechanism for this - something like what we did with TypeMap. Just throwing a suggestion:

    class MyObjectProxy
    {
        // TrimTarget tells analysis to only generate force the UCO entrypoint if a MyObjectProxy instance could exist in the program.
        [UnmanagedCallersOnly (EntryPoint = "MyObjectProxy_MyMethod", TrimTarget = typeof(MyObjectProxy)]
        static void MyMethod (IntPtr handle) { }
    }

    I like this approach a lot!

    I believe this would work for the Apple workloads, but I'm not sure about Android (@simonrozsival ?)

    That said, it seems slightly inflexible (what if we'd want TrimTarget to be a method?)

    Maybe something like this:

    [DynamicDependency (DynamicallyAccessedMemberTypes.UCOEntryPoint, "MyMethod()")]
    class MyObjectProxy
    {
        [UnmanagedCallersOnly (EntryPoint = "MyObjectProxy_MyMethod"]
        static void MyMethod (IntPtr handle) { }
    }

    which is more flexible, but runs into other problems (currently [DynamicDependency] can't be put on a type)

  8. simonrozsival commented on Apr 30, 2026

    @simonrozsival
    Member

    but I'm not sure about Android

    We won't be using UCOs with EntryPoint in Android, we need to set up the Java native callbacks via function pointers anyway.

    The TrimTarget attribute property looks like exactly what iOS would need. In the iOS case, I don't think the value will ever be anything other than the declaring type, so a simple boolean would be enough and it might be simpler to implement. OTOH TrimTarget gives more flexibility to other users of this API and I believe neither will have any size impact on the final binary because ILC will throw this metadata out anyway.

  9. MichalStrehovsky commented on Apr 30, 2026

    @MichalStrehovsky
    Member

    The TrimTarget shouldn't add much extra complexity to the implementation so I'm not too worried.

    I'll Cc a couple more folks for feedback but if this would work for the necessary scenarios I don't see any blockers. Architecturally it fits the long term goals (be able to write interop layers without deep integration with the compilation pipeline or the runtime).

    We'll want to define what the TrimTarget means (same rules as for TypeMap or more restricted to "one can have an actual instance of this at runtime" - feels like we can do the latter first and if really needed, extend). We can decide if this should be a property on UnmanagedCallersOnly or an extra attribute (I prefer the extra property).

    Cc @dotnet/interop-contrib @Sergio0694 @manodasanW

  10. MichalStrehovsky commented on Apr 30, 2026

    @MichalStrehovsky
    Member

    That said, it seems slightly inflexible (what if we'd want TrimTarget to be a method?)

    Would it currently be a blocker if we didn't have this?

  11. rolfbjarne commented on Apr 30, 2026

    @rolfbjarne
    MemberAuthor

    That said, it seems slightly inflexible (what if we'd want TrimTarget to be a method?)

    Would it currently be a blocker if we didn't have this?

    No, it wouldn't.

  12. manodasanW commented on Apr 30, 2026

    @manodasanW
    Contributor

    In WinRT, for the scenario talked about here, we use UnmanagedCallersOnly without an entry point as we use those functions to setup a virtual function table for the interface and then class which is then able to be called by native code. The scenarios where we do use entry point is where we export the activation factory for the DLL exposing those function tables which we wouldn't want trimmed and probably won't use TrimTarget there as it is called by native code and we don't know whether they will call it or not.

  13. MichalStrehovsky commented on May 1, 2026

    @MichalStrehovsky
    Member

    Filed #127634 with the public API proposal. Please let me know what you think. If you don't have any comments, a thumbs up is also feedback!

  14. MichalStrehovsky commented on May 1, 2026

    @MichalStrehovsky
    Member

    In WinRT, for the scenario talked about here, we use UnmanagedCallersOnly without an entry point as we use those functions to setup a virtual function table for the interface and then class which is then able to be called by native code. The scenarios where we do use entry point is where we export the activation factory for the DLL exposing those function tables which we wouldn't want trimmed and probably won't use TrimTarget there as it is called by native code and we don't know whether they will call it or not.

    Yeah, I didn't really expect WinRT would have immediate use for this - mostly cc'd you FYI. This is mostly for interops that need to generate subsequent native glue. WinRT has fully laid out vtables readily available in the image and doesn't require further metadata that would be difficult to emit.

  15. MichalStrehovsky commented on May 1, 2026

    @MichalStrehovsky
    Member

    Also cc @dotnet/illink since this affects trimming (even though IL trimming is currently unaware of UnmanagedCallersOnly(EntryPoint) right now).

  16. MichalStrehovsky commented on Jun 11, 2026

    @MichalStrehovsky
    Member

    #127634 should address the scenario.

  17. locked and limited conversation to collaborators on Jul 11, 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-NativeAOT-coreclruntriaged

    Type

    No type

    Projects

    • Status
      No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions