dotnet / corert

This repo contains CoreRT, an experimental .NET Core runtime optimized for AOT (ahead of time compilation) scenarios, with the accompanying compiler toolchain.
http://dot.net
MIT License
2.91k stars 510 forks source link

[Interpreter] Static constructors and field access #8370

Closed tonerdo closed 3 years ago

tonerdo commented 3 years ago

Opening this here, since I don't yet have a branch in the runtimelabs repo.

This PR adds support for instance and static fields on a reference type. It interprets the following opcodes:

As a consequence of adding static field support, I also added support for interpreting static constructors on dynamically loaded types. The following scenario is now supported:

class DynamicClass1
{
    public string Field1;
    public int Field2;
    public float Field3;
    public Random Field4 = new Random();

    public static string StaticField1;
    public static int StaticField2;
    public static float StaticField3;

    static DynamicClass1()
    {
        StaticField1 = "statically nice!";
        StaticField2 = 10;
        StaticField3 = 3.56f;
    }
}

.....

public static void DoFields()
{
    DynamicClass1 class1 = new DynamicClass1();
    class1.Field1 = "nice";
    class1.Field2 = 23;
    class1.Field3 = 2.5f;

    Console.WriteLine(class1.Field1);
    Console.WriteLine(class1.Field2);
    Console.WriteLine(class1.Field3);
    Console.WriteLine(class1.Field4);
}

public static void DoStaticFields()
{
    Console.WriteLine(DynamicClass1.StaticField1);
    Console.WriteLine(string.Empty);
    Console.WriteLine(DynamicClass1.StaticField2);
    Console.WriteLine(DynamicClass1.StaticField3);
}

The interpreter will happily load instance and static fields on both dynamically loaded types and types compiled into the native executable, while ensuring that static constructors have been run in both cases.

Note: Thread statics on dynamically loaded types are currently unsupported

cc @jkotas @MichalStrehovsky

tonerdo commented 3 years ago

I'm guessing this won't be able to make the cut before the archive?