Skip to content

System.Linq.Expressions factories throw NullReferenceException with global fields and global methods #19068

Closed
dotnet/corefx
#15318

Description

@hughbe

Consider the following test class I put together of all instances. I will submit a PR fixing these bugs if it you guys approve, so please let me know. Here I've used RefEmit to produce the global fields/methods, as C# doesn't support them

public class GlobalMethodGlobalField
{
    [Fact]
    public void AndAlso_GlobalMethod_ThrowsNullReferenceException()
    {
        MethodInfo method = GlobalMethod(typeof(int), new Type[] { typeof(int), typeof(int) });
        Assert.Throws<NullReferenceException>(() => Expression.AndAlso(Expression.Constant(1), Expression.Constant(2), method));
    }

    [Fact]
    public void Bind_GlobalMethod_ThrowsNullReferenceException()
    {
        Assert.Throws<NullReferenceException>(() => Expression.Bind(GlobalMethod(typeof(int), new Type[0]), Expression.Constant("abc")));
    }

    [Fact]
    public void Default_TypeBuilder_CreateLambda_ThrowsNotSupportedException()
    {
        AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.Run);
        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module");
        TypeBuilder typeBuilder = moduleBuilder.DefineType("Type");

        DefaultExpression defaultExpression = Expression.Default(typeBuilder.AsType());
        Assert.Throws<NotSupportedException>(() => Expression.Lambda(defaultExpression));

        LambdaExpression genericLambda = Expression.Lambda<Func<object>>(defaultExpression);
        Assert.Null(genericLambda.Compile());
    }

    [Fact]
    public void ListBind_GlobalMethod_ThrowsNullReferenceException()
    {
        Assert.Throws<NullReferenceException>(() => Expression.ListBind(GlobalMethod(typeof(int), new Type[0]), new ElementInit[0]));
        Assert.Throws<NullReferenceException>(() => Expression.ListBind(GlobalMethod(typeof(int), new Type[0]), (IEnumerable<ElementInit>)new ElementInit[0]));
    }

    [Fact]
    public void MemberBind_GlobalMethod_ThrowsNullReferenceException()
    {
        Assert.Throws<NullReferenceException>(() => Expression.MemberBind(GlobalMethod(typeof(int), new Type[0]), new MemberBinding[0]));
        Assert.Throws<NullReferenceException>(() => Expression.MemberBind(GlobalMethod(typeof(int), new Type[0]), (IEnumerable<MemberBinding>)new MemberBinding[0]));
    }

    [Fact]
    public void MemberBind_GlobalFieldInBindings_ThrowsNullReferenceException()
    {
        MemberBinding[] bindings = new MemberBinding[] { Expression.MemberBind(GlobalField()) };
        Assert.Throws<NullReferenceException>(() => Expression.MemberBind(GlobalField(), bindings));
        Assert.Throws<NullReferenceException>(() => Expression.MemberBind(GlobalField(), (IEnumerable<MemberBinding>)bindings));

    }

    [Fact]
    public void New_GlobalMethodInMembers_ThrowsNullReferenceException()
    {
        ConstructorInfo constructor = typeof(ClassWithConstructor).GetConstructor(new Type[] { typeof(int) });
        Expression[] arguments = new Expression[] { Expression.Constant(5) };
        MemberInfo[] members = new MemberInfo[] { GlobalMethod(typeof(int), new Type[0]) };
        Assert.Throws<NullReferenceException>(() => Expression.New(constructor, arguments, members));
    }

    [Fact]
    public void New_GlobalFieldInMembers_ThrowsNullReferenceException()
    {
        ConstructorInfo constructor = typeof(ClassWithConstructor).GetConstructor(new Type[] { typeof(int) });
        Expression[] arguments = new Expression[] { Expression.Constant(5) };
        MemberInfo[] members = new MemberInfo[] { GlobalField() };
        Assert.Throws<NullReferenceException>(() => Expression.New(constructor, arguments, members));
    }

    [Fact]
    public void OrElse_GlobalMethod_ThrowsNullReferenceException()
    {
        MethodInfo method = GlobalMethod(typeof(int), new Type[] { typeof(int), typeof(int) });
        Assert.Throws<NullReferenceException>(() => Expression.OrElse(Expression.Constant(1), Expression.Constant(2), method));
    }

    private class ClassWithConstructor
    {
        public ClassWithConstructor(int i) { }
    }

    private static MethodInfo GlobalMethod(Type returnType, Type[] parameterTypes)
    {
        AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("ABC"), AssemblyBuilderAccess.Run);
        ModuleBuilder module = assembly.DefineDynamicModule("Module");

        MethodBuilder globalMethod = module.DefineGlobalMethod("GlobalMethod", MethodAttributes.Public | MethodAttributes.Static, returnType, parameterTypes);
        globalMethod.GetILGenerator().Emit(OpCodes.Ret);

        module.CreateGlobalFunctions();
        return module.GetMethod(globalMethod.Name);
    }

    private static FieldInfo GlobalField()
    {
        AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("ABC"), AssemblyBuilderAccess.Run);
        ModuleBuilder module = assembly.DefineDynamicModule("Module");

        FieldBuilder fieldBuilder = module.DefineInitializedData("Name", new byte[1], FieldAttributes.Public);

        module.CreateGlobalFunctions();
        return module.GetField(fieldBuilder.Name);
    }
}

@bartdesmet @VSadov @JonHanna

Activity

  1. bartdesmet commented on Oct 24, 2016

    @bartdesmet
    Contributor

    Interesting behavior... Where does the NullReferenceException originate from? Is it assuming that something like DeclaringType is non-null maybe?

  2. hughbe commented on Oct 24, 2016

    @hughbe
    ContributorAuthor

    Correct - we assume DeclaringType is nonnull

  3. bartdesmet commented on Oct 25, 2016

    @bartdesmet
    Contributor

    I don't see any compelling reason why these shouldn't work just fine. MethodInfo instances with DeclaringType set to null are valid, and our API claims to deal with all MethodInfo instances just fine. I'd be curious to see how many places we have this assumption of a non-null DeclaringType though (same for other MemberInfo subtypes); the fix may show up in quite a few places.

  4. hughbe commented on Oct 25, 2016

    @hughbe
    ContributorAuthor

    FieldInfo, MethodInfo and ConstructorInfo are the only MemberInfos that can have a null DeclaringType

    I'll go through the ones I found:

    • AndAlso: should allow (as MethodInfo can come from anywhere)
    • Bind (method): should not allow (as MethodInfo should represent a property accessor)
    • Bind (field): should allow (as MemberInfo represents the field to be set)
    • ListBind (method): should not allow (as MethodInfo should represent a property accessor)
    • ListBind (field): should allow (as MemberInfo represents the field to be set)
    • MemberBind (method): should not allow (as MethodInfo should represent a property accessor)
    • MemberBind (field): should allow (as MemberInfo represents the field to be set)
    • New: should not allow (as MemberInfo must represent a member on the type**
    • OrElse: should allow (as MethodInfo can come from anywhere)

    Let me know if you disagree with any of these - I'll submit a PR for each adding tests etc. just to make sure we're allowing/disallowing the proper scenarios

  5. hughbe commented on Oct 25, 2016

    @hughbe
    ContributorAuthor

    Actually, I'm wrong about AndAlso and OrElse, as apparently op_true and op_false have to be declared on the declaring type of method

  6. JonHanna commented on Jan 11, 2017

    @JonHanna
    Contributor

    I don't think there's any reason a method or field should have to have a DeclaringType unless there's some inherent reason for a restriction on what that DeclaringType can be.

    With the *Bind methods though the objects produced are all MemberBindings rather than complete Expressions and used to produce MemberInitExpressions which have to be validated so that the DeclaringType of the binding is assignable from the type being initialised. Since any use of the object (unless there's another I can't think of) would hence fail (taking a look at the validation method, there's an assumption that the DeclaringType isn't null) throwing early is better than throwing late. It should be an ArgumentException rather than an NRE though.

  7. JonHanna commented on Jan 18, 2017

    @JonHanna
    Contributor

    @hughbe are you still intending to work on this? While I don't think it makes sense to allow such methods on bindings, we shouldn't have NRE thrown.

  8. hughbe commented on Jan 18, 2017

    @hughbe
    ContributorAuthor

    @JonHanna not currently! feel free to grab this if you'd like.

  9. JonHanna commented on Jan 18, 2017

    @JonHanna
    Contributor

    Will do.

  10. transferred this issue fromdotnet/corefxon Jan 31, 2020
  11. added this to the 2.0.0 milestone on Jan 31, 2020
  12. ghost locked as resolved and limited conversation to collaborators on Dec 28, 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

    Labels

    area-System.Linq.Expressionsenhancementhelp wanted

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions