Skip to content

Commit

Permalink
Fix argument validation in RuntimeType.InvokeMember (#74998)
Browse files Browse the repository at this point in the history
The rollout of `!!` erroneously moved an ArgumentNullException to be thrown earlier in the method, preventing a null name from being used (which is valid with BindingFlags.CreateInstance).

(Separately, we should consider fixing the nullable reference type annotation on `string name`, since null is allowed in some circumstances.)
  • Loading branch information
stephentoub authored Sep 2, 2022
1 parent 9ea5d2d commit e6e4d22
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -459,8 +459,6 @@ public override bool IsAssignableFrom([NotNullWhen(true)] Type? c)
string name, BindingFlags bindingFlags, Binder? binder, object? target,
object?[]? providedArgs, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParams)
{
ArgumentNullException.ThrowIfNull(name);

const BindingFlags MemberBindingMask = (BindingFlags)0x000000FF;
const BindingFlags InvocationMask = (BindingFlags)0x0000FF00;
const BindingFlags BinderGetSetField = BindingFlags.GetField | BindingFlags.SetField;
Expand Down Expand Up @@ -567,10 +565,12 @@ public override bool IsAssignableFrom([NotNullWhen(true)] Type? c)
// PutDispProperty and\or PutRefDispProperty ==> SetProperty.
if ((bindingFlags & (BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) != 0)
bindingFlags |= BindingFlags.SetProperty;

ArgumentNullException.ThrowIfNull(name);
if (name.Length == 0 || name.Equals("[DISPID=0]"))
{
// in InvokeMember we always pretend there is a default member if none is provided and we make it ToString
name = GetDefaultMemberName()! ?? "ToString";
name = GetDefaultMemberName() ?? "ToString";
}

// GetField or SetField
Expand Down
8 changes: 8 additions & 0 deletions src/libraries/System.Reflection/tests/DefaultBinderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,14 @@ public static void InvokeWithNamedParametersOutOfOrder()
Assert.Equal(8, result);
}

[Theory]
[InlineData("")]
[InlineData(null)]
public static void InvokeWithCreateInstance(string name)
{
Assert.IsType<Sample>(typeof(Sample).InvokeMember(name, BindingFlags.CreateInstance, null, null, null));
}

public class Test
{
public void TestMethod(int param1) { }
Expand Down

0 comments on commit e6e4d22

Please sign in to comment.