Skip to content

Commit

Permalink
[NativeAOT] Fix Activator.CreateInstance for shared generic structs (d…
Browse files Browse the repository at this point in the history
…otnet#101021)

The default constructor has to be invoked using fat pointer in shared generic structs.
  • Loading branch information
jkotas authored and matouskozak committed Apr 30, 2024
1 parent a095f12 commit 37fa590
Show file tree
Hide file tree
Showing 10 changed files with 87 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public static partial class Activator
else
{
t = default!;
RawCalliHelper.Call(defaultConstructor, ref Unsafe.As<T, byte>(ref t));
RawCalliHelper.CallDefaultStructConstructor(defaultConstructor, ref Unsafe.As<T, byte>(ref t));

// Debugger goo so that stepping in works. Only affects debug info generation.
// The call gets optimized away.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,14 +143,14 @@ public unsafe void Initialize()
if (constructorEntryPoint == IntPtr.Zero)
return;

var constructorFtn = (delegate*<ref byte, void>)RuntimeAugments.TypeLoaderCallbacks.ConvertUnboxingFunctionPointerToUnderlyingNonUnboxingPointer(constructorEntryPoint, new RuntimeTypeHandle(pElementEEType));
IntPtr constructorFtn = RuntimeAugments.TypeLoaderCallbacks.ConvertUnboxingFunctionPointerToUnderlyingNonUnboxingPointer(constructorEntryPoint, new RuntimeTypeHandle(pElementEEType));

ref byte arrayRef = ref MemoryMarshal.GetArrayDataReference(this);
nuint elementSize = ElementSize;

for (int i = 0; i < Length; i++)
{
constructorFtn(ref arrayRef);
RawCalliHelper.CallDefaultStructConstructor(constructorFtn, ref arrayRef);
arrayRef = ref Unsafe.Add(ref arrayRef, elementSize);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

using Internal.Runtime;
using Internal.Runtime.Augments;
using Internal.Runtime.CompilerServices;

namespace System.Runtime
{
Expand Down Expand Up @@ -162,8 +163,20 @@ private static unsafe Value CacheMiss(IntPtr context, IntPtr signature, RuntimeO
internal static unsafe class RawCalliHelper
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Call(System.IntPtr pfn, ref byte data)
=> ((delegate*<ref byte, void>)pfn)(ref data);
public static void CallDefaultStructConstructor(System.IntPtr pfn, ref byte data)
{
// Manually expand call of the instance method fat pointer. We cannot use a regular static C# function
// pointer call since it would not work for shared generic instance method.
if (FunctionPointerOps.IsGenericMethodPointer(pfn))
{
GenericMethodDescriptor* gmd = FunctionPointerOps.ConvertToGenericDescriptor(pfn);
((delegate*<ref byte, IntPtr, void>)gmd->MethodFunctionPointer)(ref data, gmd->InstantiationArgument);
}
else
{
((delegate*<ref byte, void>)pfn)(ref data);
}
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T Call<T>(System.IntPtr pfn, IntPtr arg)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -337,9 +337,19 @@ internal override IntPtr Create(TypeBuilder builder)
{
IntPtr result = TypeLoaderEnvironment.TryGetDefaultConstructorForType(Type);


if (result == IntPtr.Zero)
if (result != IntPtr.Zero)
{
if (Type.IsValueType)
{
result = TypeLoaderEnvironment.ConvertUnboxingFunctionPointerToUnderlyingNonUnboxingPointer(result,
builder.GetRuntimeTypeHandle(Type));
}
}
else
{
result = RuntimeAugments.GetFallbackDefaultConstructor();
}

return result;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ public ISymbolNode ComputeConstantLookup(ReadyToRunHelperId lookupKind, object t
{
var type = (TypeDesc)targetOfLookup;
MethodDesc ctor = GetConstructorForCreateInstanceIntrinsic(type);
return NodeFactory.CanonicalEntrypoint(ctor);
return type.IsValueType ? NodeFactory.ExactCallableAddress(ctor) : NodeFactory.CanonicalEntrypoint(ctor);
}
case ReadyToRunHelperId.ObjectAllocator:
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -781,7 +781,7 @@ public override ISymbolNode GetTarget(NodeFactory factory, GenericLookupResultCo
{
TypeDesc instantiatedType = _type.GetNonRuntimeDeterminedTypeFromRuntimeDeterminedSubtypeViaSubstitution(dictionary.TypeInstantiation, dictionary.MethodInstantiation);
MethodDesc defaultCtor = Compilation.GetConstructorForCreateInstanceIntrinsic(instantiatedType);
return factory.CanonicalEntrypoint(defaultCtor);
return instantiatedType.IsValueType ? factory.ExactCallableAddress(defaultCtor) : factory.CanonicalEntrypoint(defaultCtor);
}

public override void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -360,8 +360,9 @@ private void ImportCall(ILOpcode opcode, int token)
}
else
{
MethodDesc ctor = Compilation.GetConstructorForCreateInstanceIntrinsic(method.Instantiation[0]);
_dependencies.Add(_factory.CanonicalEntrypoint(ctor), reason);
TypeDesc type = method.Instantiation[0];
MethodDesc ctor = Compilation.GetConstructorForCreateInstanceIntrinsic(type);
_dependencies.Add(type.IsValueType ? _factory.ExactCallableAddress(ctor) : _factory.CanonicalEntrypoint(ctor), reason);
}

return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,22 @@ public void CreateInstanceT_StructWithoutDefaultConstructor_InvokesConstructor()
public void CreateInstanceT_StructWithDefaultConstructorThatThrows_ThrowsTargetInvocationException() =>
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance<StructWithDefaultConstructorThatThrows>());

[Fact]
public void CreateInstanceT_GenericTypes()
{
TestGenericClassWithDefaultConstructor<string>();
TestGenericClassWithDefaultConstructor<int>();

TestGenericStructWithDefaultConstructor<string>();
TestGenericStructWithDefaultConstructor<int>();

void TestGenericClassWithDefaultConstructor<T>()
=> Assert.Equal(typeof(T), Activator.CreateInstance<GenericClassWithDefaultConstructor<T>>().TypeOfT);

void TestGenericStructWithDefaultConstructor<T>()
=> Assert.Equal(typeof(T), Activator.CreateInstance<GenericStructWithDefaultConstructor<T>>().TypeOfT);
}

private interface IInterface
{
}
Expand Down Expand Up @@ -96,5 +112,27 @@ private class ClassWithDefaultConstructorThatThrows
public ClassWithDefaultConstructorThatThrows() =>
throw new Exception();
}

public class GenericClassWithDefaultConstructor<T>
{
public GenericClassWithDefaultConstructor() =>
TypeOfT = typeof(T);

public Type TypeOfT { get; }
}

public struct StructWithDefaultConstructorThatThrows
{
public StructWithDefaultConstructorThatThrows() =>
throw new Exception();
}

public struct GenericStructWithDefaultConstructor<T>
{
public GenericStructWithDefaultConstructor() =>
TypeOfT = typeof(T);

public Type TypeOfT { get; }
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,18 +57,6 @@
ret
}
}

.class public sequential sealed StructWithDefaultConstructorThatThrows
extends [System.Runtime]System.ValueType
{
.size 1

.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
newobj instance void [System.Runtime]System.Exception::.ctor()
throw
}
}
}

.class public sequential sealed '.GlobalStructStartingWithDot'
Expand Down
14 changes: 14 additions & 0 deletions src/tests/nativeaot/SmokeTests/DynamicGenerics/activation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,18 @@ public override string ToString()
return memberVar;
}
}
struct StructToString<T>
{
string memberVar;
public StructToString()
{
memberVar = typeof(T).Name;
}
public override string ToString()
{
return memberVar;
}
}
class SomeUnrealtedType<T>
{
string memberVar;
Expand Down Expand Up @@ -195,5 +207,7 @@ public static void TestDefaultCtorInLazyGenerics()
AllocViaGVMBase typeWithGVM = AllocViaGVMDerived.Alloc();
Assert.AreEqual("ToStringIsInteresting1", typeWithGVM.Alloc<ToStringIsInteresting1>().ToString());
Assert.AreEqual("ToStringIsInteresting2", typeWithGVM.Alloc<ToStringIsInteresting2>().ToString());
Assert.AreEqual("ToStringIsInteresting1", typeWithGVM.Alloc<StructToString<ToStringIsInteresting1>>().ToString());
Assert.AreEqual("ToStringIsInteresting2", typeWithGVM.Alloc<StructToString<ToStringIsInteresting2>>().ToString());
}
}

0 comments on commit 37fa590

Please sign in to comment.