Skip to content

Research injecting a constructor to avoid reflection in NSObject.AllocateNSObject in the managed static registrar #18357

Closed

Description

@rolfbjarne

Problem: we need to set the handle and flags fields before reaching the NSObject ctor.

Solution:

// Handle32 is an enum - its only purpose is to be unique
// Alternatively, we could use IntPtr and put a custom modifier on the parameter
// The custom modifier also guarantees a unique signature that cannot possibly conflict with user constructors
.method public hidebysig specialname rtspecialname 
        instance void  .ctor(valuetype Handle32 handle) cil managed
{
  // Store the handle first
  // This should be legal. It's a violation of CLS rules but not a problem for correctness or even verifiability
  ldarg.1
  ldarg.0
  stfld NSObject.Handle
  // Chain to the constructor we wanted to call
  // Load any parameter if there's any
  ldarg.0
  call       instance void Blah::.ctor()
  ret
}

This could potentially make it much faster to create NSObjects in the MSR trampolines.

Ref: dotnet/runtime#86649 (comment)

Activity

  1. added
    enhancement
    performance
    on May 26, 2023
  2. added this to the .NET 8 milestone on May 26, 2023
  3. simonrozsival commented on Jun 28, 2023

    @simonrozsival
    Member

    Based on the discussion in dotnet/runtime#81741 (comment) I think we should be to implement this without this IL hack using the new UnsafeAccessor attribute. I'm not sure if it would work for private-nested classes but we're already changing visibility of classes in the custom linker steps anyway.

    @rolfbjarne I inspected the code we generate and I can't locate where we invoke the constructor via reflection. I believe the call to the .ctor doesn't involve reflection:
    image

    Are there cases where we would generate different code to call the constructor? I thought that it could be in the case when we create an instance of classes with generic arguments, but those can't be instantiated this way and the UCO throws an exception.

  4. rolfbjarne commented on Jun 28, 2023

    @rolfbjarne
    MemberAuthor

    I inspected the code we generate and I can't locate where we invoke the constructor via reflection.

    NSObject.AllocateNSObject calls RuntimeHelpers.GetUninitializedObject (which uses reflection as far as I know):

    https://github.com/xamarin/xamarin-macios/blob/3f6d43c75649a85e47fd23d6d48c8d5a87257d7b/src/Foundation/NSObject2.cs#L236

  5. added a commit that references this issue on Aug 7, 2023
    14f75f0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancementperformance

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions