Skip to content

Boxing ref struct using MethodInfo.Invoke #38769

Closed

Description

@MaximGurschi

Hi team,

Accidentally i've discovered the ability to box a ref struct by using reflection.

The scenario is the invocation via reflection of a method that has, say, an in ref struct parameter. Upon the exit of the call the parameter array passed to MethodInfo.Invoke will contain a boxed ref struct.

Small reproduction (call Repro.Test()):

     static class Repro
    {
        ref struct RefStruct
            {
                private long L;
                private int I;
            }

        private static void MethodStr(in RefStruct rs) { }

        private static void ReflectionInvoke(string method)
        {
            var parameters = new object[1];

            var message = parameters[0] == null ? "null" : parameters[0].GetType().Name;
            Console.WriteLine(message); // Displays null.
            typeof(Repro)
                .GetMethod(method, BindingFlags.Static | BindingFlags.NonPublic)
                .Invoke(null, parameters);
            message = parameters[0] == null ? "null" : parameters[0].GetType().Name;
            Console.WriteLine(message); //Displays RefStruct.
        }

       public static void Test() => ReflectionInvoke(nameof(MethodStr));
    }

Can someone please confirm if the outcome of the second Console.WriteLine is by design?

Activity

  1. Dotnet-GitSync-Bot commented on Jul 3, 2020

    @Dotnet-GitSync-Bot
    Collaborator

    I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

  2. added
    untriaged
    on Jul 3, 2020
  3. added this to the 5.0.0 milestone on Jul 3, 2020
  4. GrabYourPitchforks commented on Jul 3, 2020

    @GrabYourPitchforks
    Member

    Probably something we should address, as boxing ref structs could destabilize the runtime. It's possible that the only reason this worked rather than resulting in an internal VM error is that the ref struct defined in the repro doesn't contain any reference-type fields.

  5. MaximGurschi commented on Jul 3, 2020

    @MaximGurschi
    Author

    Thanks, I've edited the post to include some fields in the struct. Even with fields it works. Yes i was thinking that this should not be allowed by the runtime as it can lead to passed stack frame reads.

  6. removed
    untriaged
    on Jul 7, 2020
  7. ghost locked as resolved and limited conversation to collaborators on Dec 8, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions