Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[release/8.0] Fix calling existing ctor with MethodInvoker; share tests with invokers #90968

Merged
merged 2 commits into from
Aug 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ public object Invoke(object? arg1, object? arg2, object? arg3, object? arg4)

private object InvokeImpl(object? arg1, object? arg2, object? arg3, object? arg4)
{
if ((_invocationFlags & (InvocationFlags.NoInvoke | InvocationFlags.ContainsStackPointers)) != 0)
if ((_invocationFlags & (InvocationFlags.NoInvoke | InvocationFlags.ContainsStackPointers | InvocationFlags.NoConstructorInvoke)) != 0)
{
_method.ThrowNoInvokeException();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,12 @@ public static MethodInvoker Create(MethodBase method)
{
// This is useful for calling a constructor on an already-initialized object
// such as created from RuntimeHelpers.GetUninitializedObject(Type).
return new MethodInvoker(rci);
MethodInvoker invoker = new MethodInvoker(rci);

// Use the interpreted version to avoid having to generate a new method that doesn't allocate.
invoker._strategy = GetStrategyForUsingInterpreted();

return invoker;
}

throw new ArgumentException(SR.Argument_MustBeRuntimeMethod, nameof(method));
Expand Down Expand Up @@ -181,7 +186,7 @@ private MethodInvoker(MethodBase method, RuntimeType[] argumentTypes)

private object? InvokeImpl(object? obj, object? arg1, object? arg2, object? arg3, object? arg4)
{
if ((_invocationFlags & (InvocationFlags.NoInvoke | InvocationFlags.ContainsStackPointers)) != 0)
if ((_invocationFlags & (InvocationFlags.NoInvoke | InvocationFlags.ContainsStackPointers | InvocationFlags.NoConstructorInvoke)) != 0)
{
ThrowForBadInvocationFlags();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@ internal static void Initialize(
{
if (LocalAppContextSwitches.ForceInterpretedInvoke && !LocalAppContextSwitches.ForceEmitInvoke)
{
// Always use the native invoke; useful for testing.
strategy = InvokerStrategy.StrategyDetermined_Obj4Args | InvokerStrategy.StrategyDetermined_ObjSpanArgs | InvokerStrategy.StrategyDetermined_RefArgs;
// Always use the native interpreted invoke.
// Useful for testing, to avoid startup overhead of emit, or for calling a ctor on already initialized object.
strategy = GetStrategyForUsingInterpreted();
}
else if (LocalAppContextSwitches.ForceEmitInvoke && !LocalAppContextSwitches.ForceInterpretedInvoke)
{
// Always use emit invoke (if IsDynamicCodeSupported == true); useful for testing.
strategy = InvokerStrategy.HasBeenInvoked_Obj4Args | InvokerStrategy.HasBeenInvoked_ObjSpanArgs | InvokerStrategy.HasBeenInvoked_RefArgs;
strategy = GetStrategyForUsingEmit();
}
else
{
Expand Down Expand Up @@ -69,6 +70,18 @@ internal static void Initialize(
}
}

internal static InvokerStrategy GetStrategyForUsingInterpreted()
{
// This causes the default strategy, which is interpreted, to always be used.
return InvokerStrategy.StrategyDetermined_Obj4Args | InvokerStrategy.StrategyDetermined_ObjSpanArgs | InvokerStrategy.StrategyDetermined_RefArgs;
}

private static InvokerStrategy GetStrategyForUsingEmit()
{
// This causes the emit strategy, if supported, to be used on the first call as well as subsequent calls.
return InvokerStrategy.HasBeenInvoked_Obj4Args | InvokerStrategy.HasBeenInvoked_ObjSpanArgs | InvokerStrategy.HasBeenInvoked_RefArgs;
}

/// <summary>
/// Confirm member invocation has an instance and is of the correct type
/// </summary>
Expand Down
167 changes: 167 additions & 0 deletions src/libraries/System.Reflection/tests/ConstructorCommonTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Linq;
using Xunit;

namespace System.Reflection.Tests
{
/// <summary>
/// These tests are shared with ConstructorInfo.Invoke and ConstructorInvoker.Invoke by using
/// the abstract Invoke(...) methods below.
/// </summary>
public abstract class ConstructorCommonTests
{
public abstract object Invoke(ConstructorInfo constructorInfo, object?[]? parameters);

protected abstract bool IsExceptionWrapped { get; }

/// <summary>
/// Invoke constructor on an existing instance. Should return null.
/// </summary>
public abstract object? Invoke(ConstructorInfo constructorInfo, object obj, object?[]? parameters);

public static ConstructorInfo[] GetConstructors(Type type)
{
return type.GetTypeInfo().DeclaredConstructors.ToArray();
}

[Fact]
public void SimpleInvoke()
{
ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors));
Assert.Equal(3, constructors.Length);
ClassWith3Constructors obj = (ClassWith3Constructors)Invoke(constructors[0], null);
Assert.NotNull(obj);
}

[Fact]
[ActiveIssue("https://github.com/mono/mono/issues/15024", TestRuntimes.Mono)]
public void Invoke_StaticConstructor_ThrowsMemberAccessException()
{
ConstructorInfo[] constructors = GetConstructors(typeof(ClassWithStaticConstructor));
Assert.Equal(1, constructors.Length);
Assert.Throws<MemberAccessException>(() => Invoke(constructors[0], new object[0]));
}

[Fact]
public void Invoke_OneDimensionalArray()
{
ConstructorInfo[] constructors = GetConstructors(typeof(object[]));
int[] arraylength = { 1, 2, 99, 65535 };

// Try to invoke Array ctors with different lengths
foreach (int length in arraylength)
{
// Create big Array with elements
object[] arr = (object[])Invoke(constructors[0], new object[] { length });
Assert.Equal(arr.Length, length);
}
}

[Fact]
public void Invoke_OneDimensionalArray_NegativeLengths_ThrowsOverflowException()
{
ConstructorInfo[] constructors = GetConstructors(typeof(object[]));
int[] arraylength = new int[] { -1, -2, -99 };
// Try to invoke Array ctors with different lengths
foreach (int length in arraylength)
{
// Create big Array with elements
if (IsExceptionWrapped)
{
Exception ex = Assert.Throws<TargetInvocationException>(() => Invoke(constructors[0], new object[] { length }));
Assert.IsType<OverflowException>(ex.InnerException);
}
else
{
Assert.Throws<OverflowException>(() => Invoke(constructors[0], new object[] { length }));
}
}
}

[Fact]
public void Invoke_OneParameter()
{
ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors));
ClassWith3Constructors obj = (ClassWith3Constructors)Invoke(constructors[1], new object[] { 100 });
Assert.Equal(100, obj.intValue);
}

[Fact]
public void Invoke_TwoParameters()
{
ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors));
ClassWith3Constructors obj = (ClassWith3Constructors)Invoke(constructors[2], new object[] { 101, "hello" });
Assert.Equal(101, obj.intValue);
Assert.Equal("hello", obj.stringValue);
}

[Fact]
public void Invoke_NoParameters_ThowsTargetParameterCountException()
{
ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors));
Assert.Throws<TargetParameterCountException>(() => Invoke(constructors[2], new object[0]));
}

[Fact]
public void Invoke_ParameterMismatch_ThrowsTargetParameterCountException()
{
ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors));
Assert.Throws<TargetParameterCountException>(() => (ClassWith3Constructors)Invoke(constructors[2], new object[] { 121 }));
}

[Fact]
public void Invoke_ParameterWrongType_ThrowsArgumentException()
{
ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors));
AssertExtensions.Throws<ArgumentException>(null, () => (ClassWith3Constructors)Invoke(constructors[1], new object[] { "hello" }));
}

[Fact]
public void Invoke_ExistingInstance()
{
// Should not produce a second object.
ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors));
ClassWith3Constructors obj1 = new ClassWith3Constructors(100, "hello");
ClassWith3Constructors obj2 = (ClassWith3Constructors)Invoke(constructors[2], obj1, new object[] { 999, "initialized" });
Assert.Null(obj2);
Assert.Equal(999, obj1.intValue);
Assert.Equal("initialized", obj1.stringValue);
}

[Fact]
public void Invoke_NullForObj()
{
ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors));
Assert.Throws<TargetException>(() => Invoke(constructors[2], obj: null, new object[] { 999, "initialized" }));
}

[Fact]
[ActiveIssue("https://github.com/mono/mono/issues/15026", TestRuntimes.Mono)]
public void Invoke_AbstractClass_ThrowsMemberAccessException()
{
ConstructorInfo[] constructors = GetConstructors(typeof(ConstructorInfoAbstractBase));
Assert.Throws<MemberAccessException>(() => (ConstructorInfoAbstractBase)Invoke(constructors[0], new object[0]));
}

[Fact]
public void Invoke_SubClass()
{
ConstructorInfo[] constructors = GetConstructors(typeof(ConstructorInfoDerived));
ConstructorInfoDerived obj = null;
obj = (ConstructorInfoDerived)Invoke(constructors[0], new object[] { });
Assert.NotNull(obj);
}

[Fact]
public void Invoke_Struct()
{
ConstructorInfo[] constructors = GetConstructors(typeof(StructWith1Constructor));
StructWith1Constructor obj;
obj = (StructWith1Constructor)Invoke(constructors[0], new object[] { 1, 2 });
Assert.Equal(1, obj.x);
Assert.Equal(2, obj.y);
}
}
}
Loading