Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
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 @@ -5,6 +5,7 @@
using System.Collections.Immutable;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;

namespace System.Reflection.Emit
{
Expand Down Expand Up @@ -223,12 +224,67 @@ private static void WriteSignatureForType(SignatureTypeEncoder signature, Type t
{
signature.GenericTypeParameter(type.GenericParameterPosition);
}
else if (type.IsFunctionPointer)
{
WriteSignatureForFunctionPointerType(signature, type, module);
}
else
{
WriteSimpleSignature(signature, type, module);
}
}

private static void WriteSignatureForFunctionPointerType(SignatureTypeEncoder signature, Type type, ModuleBuilderImpl module)
{
SignatureCallingConvention callConv = SignatureCallingConvention.Default;
FunctionPointerAttributes attribs = FunctionPointerAttributes.None;
List<Type> retModOpts = [.. type.GetFunctionPointerReturnType().GetOptionalCustomModifiers()];

if (type.GetFunctionPointerCallingConventions() is Type[] conventions && conventions.Length > 0)
{
foreach (Type conv in conventions)
{
if (conv == typeof(CallConvCdecl))
callConv = SignatureCallingConvention.CDecl;
else if (conv == typeof(CallConvStdcall))
callConv = SignatureCallingConvention.StdCall;
else if (conv == typeof(CallConvThiscall))
callConv = SignatureCallingConvention.ThisCall;
else if (conv == typeof(CallConvFastcall))
callConv = SignatureCallingConvention.FastCall;
else
retModOpts.Add(conv);
}
}

MethodSignatureEncoder sigEncoder = signature.FunctionPointer(callConv, attribs);
sigEncoder.Parameters(type.GetFunctionPointerParameterTypes().Length, out ReturnTypeEncoder retTypeEncoder, out ParametersEncoder paramsEncoder);

CustomModifiersEncoder retModifiersEncoder = retTypeEncoder.CustomModifiers();

if (retModOpts.Count > 0)
WriteCustomModifiers(retModifiersEncoder, [.. retModOpts], isOptional: true, module);

if (type.GetFunctionPointerReturnType().GetRequiredCustomModifiers() is Type[] retModReqs)
WriteCustomModifiers(retModifiersEncoder, retModReqs, isOptional: false, module);

WriteSignatureForType(retTypeEncoder.Type(), type.GetFunctionPointerReturnType(), module);

foreach (Type paramType in type.GetFunctionPointerParameterTypes())
{
ParameterTypeEncoder paramEncoder = paramsEncoder.AddParameter();
CustomModifiersEncoder paramModifiersEncoder = paramEncoder.CustomModifiers();

if (paramType.GetOptionalCustomModifiers() is Type[] paramModOpts)
WriteCustomModifiers(paramModifiersEncoder, paramModOpts, isOptional: true, module);

if (paramType.GetRequiredCustomModifiers() is Type[] paramModReqs)
WriteCustomModifiers(paramModifiersEncoder, paramModReqs, isOptional: false, module);

WriteSignatureForType(paramEncoder.Type(), paramType, module);
}
}

private static void WriteSimpleSignature(SignatureTypeEncoder signature, Type type, ModuleBuilderImpl module)
{
CoreTypeId? typeId = module.GetTypeIdFromCoreTypes(type);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Xunit;

namespace System.Reflection.Emit.Tests
Expand Down Expand Up @@ -789,6 +791,76 @@ public void CreateGenericTypeFromMetadataLoadContextSignatureTypes()
Assert.Equal("ValueTypeChildren", fields[1].Name);
Assert.True(fields[1].FieldType.GetGenericArguments()[0].IsValueType);
}

[Fact]
public void SaveFunctionPointerFields()
{
using TempFile file = TempFile.Create();
using MetadataLoadContext mlc = new MetadataLoadContext(new CoreMetadataAssemblyResolver());

PersistedAssemblyBuilder ab = AssemblySaveTools.PopulateAssemblyAndModule(out ModuleBuilder mb);
TypeBuilder tb = mb.DefineType("TestType", TypeAttributes.Public | TypeAttributes.Class);

// delegate*<int, int>
Type funcPtr1 = typeof(delegate*<int, int>);
tb.DefineField("FuncPtr1", funcPtr1, FieldAttributes.Public | FieldAttributes.Static);

// delegate* unmanaged[Cdecl]<int, float, double>
Type funcPtr4 = new ModifiedTypeHelpers.FunctionPointer(
typeof(delegate* unmanaged[Cdecl]<int, float, double>),
[typeof(CallConvCdecl)]);
tb.DefineField("FuncPtr2", funcPtr4, FieldAttributes.Public | FieldAttributes.Static);

// delegate* unmanaged[Stdcall]<string, in int, void>
Type funcPtr5 = new ModifiedTypeHelpers.FunctionPointer(
typeof(delegate* unmanaged[Stdcall]<string, in int, void>),
[typeof(CallConvStdcall)],
customParameterTypes: [typeof(string), new ModifiedTypeHelpers.ModifiedType(typeof(int).MakeByRefType(), [typeof(InAttribute)], [])]);
tb.DefineField("FuncPtr3", funcPtr5, FieldAttributes.Public | FieldAttributes.Static);

tb.CreateType();
ab.Save(file.Path);

Assembly assemblyFromDisk = mlc.LoadFromAssemblyPath(file.Path);
Type testType = assemblyFromDisk.Modules.First().GetType("TestType");
Assert.NotNull(testType);

FieldInfo field1 = testType.GetField("FuncPtr1");
Assert.NotNull(field1);
Assert.True(field1.FieldType.IsFunctionPointer);
Assert.False(field1.FieldType.IsUnmanagedFunctionPointer);
Type[] paramTypes1 = field1.FieldType.GetFunctionPointerParameterTypes();
Assert.Equal(1, paramTypes1.Length);
Assert.Equal(typeof(int).FullName, paramTypes1[0].FullName);
Assert.Equal(typeof(int).FullName, field1.FieldType.GetFunctionPointerReturnType().FullName);

FieldInfo field2 = testType.GetField("FuncPtr2");
Type field2Type = field2.GetModifiedFieldType();
Assert.NotNull(field2);
Assert.True(field2Type.IsFunctionPointer);
Assert.True(field2Type.IsUnmanagedFunctionPointer);
Type[] paramTypes2 = field2Type.GetFunctionPointerParameterTypes();
Assert.Equal(2, paramTypes2.Length);
Assert.Equal(typeof(int).FullName, paramTypes2[0].FullName);
Assert.Equal(typeof(float).FullName, paramTypes2[1].FullName);
Assert.Equal(typeof(double).FullName, field2Type.GetFunctionPointerReturnType().FullName);
Type[] callingConventions2 = field2Type.GetFunctionPointerCallingConventions();
Assert.Contains(callingConventions2, t => t.FullName == typeof(CallConvCdecl).FullName);

FieldInfo field3 = testType.GetField("FuncPtr3");
Type field3Type = field3.GetModifiedFieldType();
Assert.NotNull(field3);
Assert.True(field3Type.IsFunctionPointer);
Assert.True(field3Type.IsUnmanagedFunctionPointer);
Type[] paramTypes3 = field3Type.GetFunctionPointerParameterTypes();
Assert.Equal(2, paramTypes3.Length);
Assert.Equal(typeof(string).FullName, paramTypes3[0].FullName);
Assert.Equal(typeof(int).MakeByRefType().FullName, paramTypes3[1].FullName);
Assert.Contains(paramTypes3[1].GetRequiredCustomModifiers(), t => t.FullName == typeof(InAttribute).FullName);
Assert.Equal(typeof(void).FullName, field3Type.GetFunctionPointerReturnType().FullName);
Type[] callingConventions3 = field3Type.GetFunctionPointerCallingConventions();
Assert.Contains(callingConventions3, t => t.FullName == typeof(CallConvStdcall).FullName);
}
}

// Test Types
Expand Down
50 changes: 50 additions & 0 deletions src/libraries/System.Reflection.Emit/tests/Utilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,4 +164,54 @@ public static string GetFullName(string name)
return name;
}
}

public static class ModifiedTypeHelpers
{
public class FunctionPointer : TypeDelegator
{
private readonly Type[] callingConventions;
private readonly Type returnType;
private readonly Type[] parameterTypes;
private readonly Type[] requiredModifiers;
private readonly Type[] optionalModifiers;

public FunctionPointer(
Type baseFunctionPointerType,
Type[] conventions = null,
Type customReturnType = null,
Type[] customParameterTypes = null,
Type[] fnPtrRequiredMods = null,
Type[] fnPtrOptionalMods = null)
: base(baseFunctionPointerType)
{
callingConventions = conventions ?? [];
returnType = customReturnType ?? baseFunctionPointerType.GetFunctionPointerReturnType();
parameterTypes = customParameterTypes ?? baseFunctionPointerType.GetFunctionPointerParameterTypes();
requiredModifiers = fnPtrRequiredMods ?? [];
optionalModifiers = fnPtrOptionalMods ?? [];
}

public override Type[] GetFunctionPointerCallingConventions() => callingConventions;
public override Type GetFunctionPointerReturnType() => returnType;
public override Type[] GetFunctionPointerParameterTypes() => parameterTypes;
public override Type[] GetRequiredCustomModifiers() => requiredModifiers;
public override Type[] GetOptionalCustomModifiers() => optionalModifiers;
}

public class ModifiedType : TypeDelegator
{
private readonly Type[] requiredModifiers;
private readonly Type[] optionalModifiers;

public ModifiedType(Type delegatingType, Type[] requiredMods = null, Type[] optionalMods = null)
: base(delegatingType)
{
requiredModifiers = requiredMods ?? [];
optionalModifiers = optionalMods ?? [];
}

public override Type[] GetRequiredCustomModifiers() => requiredModifiers;
public override Type[] GetOptionalCustomModifiers() => optionalModifiers;
}
}
}
Loading