Skip to content

[clr-ios] Strip IL method body in R2R composite for Apple mobile #124860

Closed

Description

@kotlarmilos

Description

On Apple mobile platforms, non-user assemblies are compiled into an R2R composite image, while their IL bodies are not stripped. In general, R2R is used for optimization, and when tiered compilation is enabled, the original IL method bodies must be preserved.

On Apple mobile, R2R is the default compilation engine for non-user assemblies. This means the IL bodies are not required for execution. If they were stripped, this would yield an estimated ~40% size reduction per dll in a MAUI template app bundle.

To validate this, I implemented a simple IL stripping mechanism in crossgen2 by emitting a minimal method body (tiny header + ret):

public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
        {
            if (relocsOnly)
            {
                return new ObjectData(
                    data: Array.Empty<byte>(),
                    relocs: Array.Empty<Relocation>(),
                    alignment: 1,
                    definedSymbols: new ISymbolDefinitionNode[] { this });
            }

            // Emit a minimal stub method body instead of the original IL.
            if (factory.OptimizationFlags.StripILBodies && !ShouldPreserveILBody())
            {
                return new ObjectData(new byte[] { 0x06, 0x2A }, Array.Empty<Relocation>(), 4, new ISymbolDefinitionNode[] { this });
            }

            var rva = _method.MetadataReader.GetMethodDefinition(_method.Handle).RelativeVirtualAddress;
            var reader = _method.Module.PEReader.GetSectionData(rva).GetReader();
            int size = MethodBodyBlock.Create(reader).Size;

            return new ObjectData(reader.ReadBytes(size), Array.Empty<Relocation>(), 4, new ISymbolDefinitionNode[] { this });
        }

However, it appears that MAUI initialization code relies on IL bodies. This leads to several failures, including:

  • Failure in xamarin_bridge_call_runtime_initialize
  • Failure in xamarin_find_assembly (the managed function find_assembly could not be loaded)
  • Failures in xamarin_print_all_exceptions_wrapper

A workaround was to strip IL only for void methods from third-party NuGet packages (excluding SDK assemblies). With this approach, the size reduction reached only ~20% of the maximum.

To fully enable IL stripping safely, we need a reliable set of rules to identify all methods that are used during MAUI startup.

ips-1.txt
ips-2.txt
ips-3.txt

Activity

  1. added
    untriaged
    on Feb 25, 2026
  2. changed the title [-]Strip IL bodies for methods that are R2R, estimated ~40% size reduction per dll in the app bundle[/-] [+][clr-ios] Strip IL method body in R2R composite for Apple mobile[/+] on Feb 25, 2026
  3. jkotas commented on Feb 25, 2026

    @jkotas
    Member

    it appears that MAUI initialization code relies on IL bodies via reflection

    Can this dependency be deleted? Why is MAUI initialization parsing IL? If nothing else, it is bad for perf.

  4. added
    os-ios
    and removed
    untriaged
    on Feb 25, 2026
  5. dotnet-policy-service commented on Feb 25, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to 'os-ios': @vitek-karas, @kotlarmilos, @steveisok, @akoeplinger
    See info in area-owners.md if you want to be subscribed.

  6. akoeplinger commented on Feb 25, 2026

    @akoeplinger
    Member
  7. akoeplinger commented on Feb 25, 2026

    @akoeplinger
    Member

    but maybe the mono runtime handled reflection specially in that case since the assembly would have been AOTd.

  8. kotlarmilos commented on Feb 25, 2026

    @kotlarmilos
    MemberAuthor

    Corrected myself - not necessarily via reflection, but it requires the IL body. Note that this was a simple PoC; ILStrip is likely more advanced.

  9. rolfbjarne commented on Feb 25, 2026

    @rolfbjarne
    Member

    From the second ips:

    Thread 0 name:   Dispatch queue: com.apple.main-thread
    Thread 0 Crashed:
    0   libcoreclr                    	       0x1032e046c 0x1030a4000 + 2344044
    1   libcoreclr                    	       0x103362df4 0x1030a4000 + 2878964
    2   libcoreclr                    	       0x103484ea8 0x1030a4000 + 4066984
    3   libcoreclr                    	       0x103354d80 0x1030a4000 + 2821504
    4   libcoreclr                    	       0x1033575c4 0x1030a4000 + 2831812
    5   libcoreclr                    	       0x1032b7ad4 0x1030a4000 + 2177748
    6   libcoreclr                    	       0x103483ddc 0x1030a4000 + 4062684
    7   SampleMAUI                    	       0x10215cbe4 xamarin_bridge_call_runtime_initialize + 152
    8   SampleMAUI                    	       0x10214e2cc xamarin_initialize + 232
    9   SampleMAUI                    	       0x102161568 xamarin_main + 1604
    10  SampleMAUI                    	       0x102162ee8 main + 64
    11  dyld                          	       0x19fedae28 start + 7115
    

    something goes wrong here:

    https://github.com/dotnet/macios/blob/6eaeeee9122570ea4f81a08bce7a30a2f5d1dc92/runtime/coreclr-bridge.m#L549-L555

    I'm guessing an exception is thrown when we try to call the managed method "Runtime.SafeInitialize", because from another crash report it's trying to print exception details:

    Thread 0 name:   Dispatch queue: com.apple.main-thread
    Thread 0 Crashed:
    0   libsystem_kernel.dylib        	       0x25069d0cc __pthread_kill + 8
    1   libsystem_pthread.dylib       	       0x1ffa57810 pthread_kill + 267
    2   libsystem_c.dylib             	       0x1ae884ff4 __abort + 131
    3   libsystem_c.dylib             	       0x1ae884f70 abort + 135
    4   SampleMAUI                    	       0x104ab3d10 xamarin_assertion_message + 112
    5   SampleMAUI                    	       0x104ab4254 xamarin_print_all_exceptions_wrapper + 80
    6   SampleMAUI                    	       0x104ab9ad4 xamarin_print_all_exceptions + 48
    7   SampleMAUI                    	       0x104ab9c34 xamarin_process_fatal_exception_gchandle + 72
    8   SampleMAUI                    	       0x104aba2dc xamarin_initialize + 248
    9   SampleMAUI                    	       0x104acd568 xamarin_main + 1604
    10  SampleMAUI                    	       0x104aceee8 main + 64
    11  dyld                          	       0x19fedae28 start + 7115
    

    which goes sideways because we can't call into managed code to get information about the exception (because of the first problem).

    It would be interesting to get the frame names for libcoreclr frames in the second ips.

  10. MichalStrehovsky commented on Feb 25, 2026

    @MichalStrehovsky
    Member

    This could be tied into PublishTrimmed being set. We'd already generate a build time warning if an app accesses MethodBase.GetMethodBody, so eliminating the body is a fair game (doesn't matter it's a different tool that does the removing).

    If we were to do this without trimming being enabled, it would silently break things like Ben.Demystifier.

  11. jkotas commented on Feb 26, 2026

    @jkotas
    Member

    ShouldPreserveILBody

    What did your implementation of this method looked like? My guess is that it has some subtle bug.

  12. rolfbjarne commented on Feb 26, 2026

    @rolfbjarne
    Member

    A workaround was to strip IL only for void methods from third-party NuGet packages (excluding SDK assemblies).

    This is strange, could it be some kind of IL validation kicking in?

  13. kotlarmilos commented on Feb 27, 2026

    @kotlarmilos
    MemberAuthor

    Here is the stack trace:

    Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
    Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000000
    Exception Codes: 0x0000000000000001, 0x0000000000000000
    VM Region Info: 0 is not in any region.  Bytes before following region: 4332290048
          REGION TYPE                 START - END      [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
          UNUSED SPACE AT START
    --->  
          __TEXT                   102398000-1025e8000 [ 2368K] r-x/r-x SM=COW  /var/containers/Bundle/Application/C0ECA690-8C15-4BB1-BF53-363D6C27BCA2/SampleMAUI.app/SampleMAUI
    Termination Reason: SIGNAL 11 Segmentation fault: 11
    Terminating Process: exc handler [65516]
    
    Triggered by Thread:  0
    
    Thread 0 name:   Dispatch queue: com.apple.main-thread
    Thread 0 Crashed:
    0   libcoreclr                    	       0x10926846c TypeHandle::IsBlittable() const + 36
    1   libcoreclr                    	       0x1092eadf4 MarshalNative_SizeOfHelper + 100
    2   libcoreclr                    	       0x10940cea8 CallJittedMethodRetI8 + 32
    3   libcoreclr                    	       0x1092dcd80 InvokeUnmanagedMethodWithTransition(UnmanagedMethodWithTransitionParam*) + 284
    4   libcoreclr                    	       0x1092df5c4 InterpExecMethod(InterpreterFrame*, InterpMethodContextFrame*, InterpThreadContext*, ExceptionClauseArgs*) + 5068
    5   libcoreclr                    	       0x10923fad4 ExecuteInterpretedMethod + 392
    6   libcoreclr                    	       0x10940bddc InterpreterStubRetVoid + 20
    7   SampleMAUI                    	       0x1023d0be4 xamarin_bridge_call_runtime_initialize + 152
    8   SampleMAUI                    	       0x1023c22cc xamarin_initialize + 232
    9   SampleMAUI                    	       0x1023d5568 xamarin_main + 1604
    10  SampleMAUI                    	       0x1023d6ee8 main + 64
    11  dyld                          	       0x19fedae28 start + 7115
    

    The null TypeHandle suggests the type couldn't be loaded. Execution goes through the interpreter, which might be a fallback from R2R. I will investigate further.

  14. jkotas commented on Feb 27, 2026

    @jkotas
    Member

    You may also want to look at whether Marshal.SizeOf needs to be used in iOS startup. Marshal.SizeOf is relatively expensive since it returns size of the marshalled view. If you are dealing with blittable types. there are much cheaper equivalents - sizeof(T) if the type is known statically and RuntimeHelpers.SizeOf if the type is not known statically.

  15. added this to the 11.0.0 milestone on Mar 11, 2026
  16. kotlarmilos commented on Mar 17, 2026

    @kotlarmilos
    MemberAuthor

    It seems the crash is caused by stripping IL bodies of generic methods that require instantiation at runtime. I've opened a draft PR #125647 with a --strip-il-bodies implementation that guards against this by only stripping methods that were successfully compiled by crossgen2 and preserving generic methods.

    I will evaluate size savings once the startup path is optimized and we reduce the number of interpreted methods further. As more methods get compiled by crossgen2, we may be able to strip more aggressively.

  17. locked and limited conversation to collaborators on May 9, 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

    Type

    No type

    Projects

    • Status
      No status

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions