Skip to content

Reflection is able to set initonly static fields in some situation #37796

Closed

Description

@aromaa

Description

It appears that you can set initonly static fields by using reflection when the type load is invoked by the reflection itself. This requires that the value assigned to it is non zero or is being set by a method.

This also has interesting side effect that it allows the JIT to inline the value! Normally this only happens on values set to zero which is a shame. This seems to be bug as per comment on #4287 (comment) explains that JIT is already capable on performing suck inline. It seems like changes to JIT has made it unable to inline static fields but abusing reflection magically restores it.

The following code prints out 0x123456789. However when InlineMagicNumber is set to zero FieldAccessException is thrown as expected.

internal class Program
{
    private static void Main(string[] args)
    {
        typeof(InlineReadOnly).GetField(nameof(InlineReadOnly.InlineMagicNumber)).SetValue(null, 0x123456789);

        InlineReadOnly.Test();
    }
}

public static class InlineReadOnly
{
    public static readonly long InlineMagicNumber = InlineReadOnly.GetInlineMagicNumber();

    [MethodImpl(MethodImplOptions.NoInlining)]
    public static void Test() => Console.WriteLine(InlineReadOnly.InlineMagicNumber);

    public static long GetInlineMagicNumber() => 0;
}

Configuration

Tested on 5.0.0-preview.6.20305.6 using Window 10 1909 x64

Regression?

This bug seems to go as far as .NET Core 1. However there are some behavior differences. On .NET Core 1 you can freely set static readonly fields whenever you want. So I'm assuming there was no guard against it.

On .NET Core 2 the behavior has changed and the reflection fails silently on values set to zero and you are unable to change the value.

On .NET Core 3 the method starts to throw FieldAccessException.

Other information

When abusing reflection to set the value the JIT is able to produce inlined code. Magic!

IN0001: 00000A mov      rcx, 0x123456789
IN0002: 000014 call     Console:WriteLine(long)
IN0003: 000019 nop   

When the value is left to zero the JIT is able to inline it too!

IN0001: 00000A xor      rcx, rcx
IN0002: 00000C call     Console:WriteLine(long)
IN0003: 000011 nop      

However when assigning the value to any other value the JIT is unable to inline it. Boo :(

IN0001: 00000A mov      rcx, 0x7FF7AEBBE8C0
IN0002: 000014 mov      edx, 2
IN0003: 000019 call     CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE
IN0004: 00001E mov      rcx, qword ptr [reloc classVar[0xaebe97f8]]
IN0005: 000025 call     Console:WriteLine(long)
IN0006: 00002A nop      

Activity

  1. added
    area-CodeGen-coreclr
    untriaged
    on Jun 12, 2020
  2. aromaa commented on Jun 12, 2020

    @aromaa
    ContributorAuthor

    Forgot to test on .NET Framework also! But I can confirm that assigning any value to static readonly inlines it correctly. Starting from .NET Framework 4

  3. AndyAyersMS commented on Jun 13, 2020

    @AndyAyersMS
    Member

    Yeah, there's a loophole here. Thanks for finding this.

    Reflection field setting eventually invokes the runtime helper method RuntimeFieldHandle::SetValue. This checks the class init state early on , before it calls InvokeUtil::SetValidField to actually modify the field's value. That callee may trigger class initialization. So if you call RuntimeFieldHandle::SetValue on a readonly static field of a class before the class is initialized, it will over-write the value provided during class initialization, as the early check will pass, then the class will get initialized and the static gets set to the cctor value, and then then the reflection provided value gets written to the static, overwriting the cctor value.

    I suspect we can move the class init bailout check down until after the point SetValidField triggers class initialization to close the loophole.

    The jit side of things looks ok to me; it sees that the class is initialized and so picks up the value for the static, which in your test above, happens to be the value provided by reflection.

    The values provided via the cctor and reflection shouldn't influence behavior any, so I'm not sure I follow that part of your report.

    Going to re-tag this as a VM issue. cc @jkotas

  4. added and removed
    area-CodeGen-coreclr
    untriaged
    on Jun 13, 2020
  5. aromaa commented on Jun 13, 2020

    @aromaa
    ContributorAuthor

    The values provided via the cctor and reflection shouldn't influence behavior any, so I'm not sure I follow that part of your report.

    For some reason doing the following will NOT inline the InlineMagicNumber but in case of using the reflection hack it does inline it for some reason. Its a bit odd behavior.

    internal class Program
    {
        private static void Main(string[] args)
        {
            InlineReadOnly.Test();
        }
    }
    
    public static class InlineReadOnly
    {
        public static readonly long InlineMagicNumber = 0x123456789;
    
        [MethodImpl(MethodImplOptions.NoInlining)]
        public static void Test() => Console.WriteLine(InlineReadOnly.InlineMagicNumber);
    }
  6. AndyAyersMS commented on Jun 13, 2020

    @AndyAyersMS
    Member

    It all depends on the relative ordering of class initialization and jitting.

    In your first examples class initialization happens first, so the jitted code for Test incorporates the static's value.

    In the example just above Test is jitted before class initialization, so the jitted code cannot incorporate the static's value.

  7. aromaa commented on Jun 13, 2020

    @aromaa
    ContributorAuthor

    Ah, interesting... For some reason .NET Framework does not suffer from this and is able to inline it? Any insight on this?

  8. AndyAyersMS commented on Jun 15, 2020

    @AndyAyersMS
    Member

    Timing of static constructors in beforefieldinit classes can vary in .NET Framework, see #13036 (comment).

  9. aromaa commented on Jun 15, 2020

    @aromaa
    ContributorAuthor

    Wasn't aware of that! Thank you for the link

  10. added a commit that references this issue on Jun 15, 2020
    d629976
  11. 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

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions