Skip to content

Support HasThis and ExplicitThis calling conventions in AssemblyBuilder and DynamicMethod #113666

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

Merged
merged 7 commits into from
Mar 24, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -28,6 +28,7 @@
<Compile Include="System\Reflection\Emit\PersistedAssemblyBuilder.cs" />
<Compile Include="System\Reflection\Emit\PropertyBuilderImpl.cs" />
<Compile Include="System\Reflection\Emit\PseudoCustomAttributesData.cs" />
<Compile Include="System\Reflection\Emit\SignatureCallingConventionEx.cs" />
<Compile Include="System\Reflection\Emit\SignatureHelper.cs" />
<Compile Include="System\Reflection\Emit\TypeBuilderImpl.cs" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -802,14 +802,19 @@ private static bool IsInstance(CallingConventions callingConvention) =>

internal static SignatureCallingConvention GetSignatureConvention(CallingConventions callingConvention)
{
SignatureCallingConvention convention = SignatureCallingConvention.Default;
SignatureCallingConventionEx convention = (SignatureCallingConventionEx)SignatureCallingConvention.Default;

if ((callingConvention & CallingConventions.VarArgs) != 0)
{
convention = SignatureCallingConvention.VarArgs;
convention = (SignatureCallingConventionEx)SignatureCallingConvention.VarArgs;
}

return convention;
if ((callingConvention & CallingConventions.HasThis) != 0)
Copy link
Preview

Copilot AI Mar 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure that the conversion from SignatureCallingConvention to SignatureCallingConventionEx preserves all intended flags without conflicts. Adding a short comment to document why the cast to the extended enum is safe would improve maintainability.

Copilot uses AI. Check for mistakes.

{
convention |= SignatureCallingConventionEx.HasThis;
}

return (SignatureCallingConvention)convention;
}

private MemberInfo GetOriginalMemberIfConstructedType(MemberInfo memberInfo)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Reflection.Metadata;

namespace System.Reflection.Emit
{
/// <summary>
/// Extensions to the public <cref>System.Reflection.Metadata.SignatureCallingConvention</cref> enum.
/// </summary>
[Flags]
internal enum SignatureCallingConventionEx : byte
{
/// <summary>
/// Indicates the presence of a "this" parameter.
/// </summary>
HasThis = 0x20,

// Other values based on ECMA-335:
// 0x0A: GenericInst (generic method instantiation)
// 0x0B: NativeVarArg
// 0x0C: Max (first invalid calling convention)
// 0x0F: Mask for SignatureCallingConvention values
// 0x10: Generic (generic method signature with explicit number of type arguments)
// 0x40: ExplicitThis ("this" parameter is explicitly in the signature)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,74 @@ public void AssemblyWithDifferentTypes()
}
}

[Fact]
public unsafe void AssemblyWithInstanceBasedFunctionPointer()
{
byte[] assemblyData = GenerateMethodInPersistedAssembly();
using MemoryStream stream = new MemoryStream(assemblyData);
TestAssemblyLoadContext testAssemblyLoadContext = new();

// Verify the assembly is properly generated and the runtime supports the IL.
try
{
Assembly assembly = testAssemblyLoadContext.LoadFromStream(stream);
Type generatedType = assembly.GetType("MyGeneratedType")!;
Assert.NotNull(generatedType);
MethodInfo generatedMethod = generatedType.GetMethod("GetGuid")!;
Assert.NotNull(generatedMethod);
Func<object, IntPtr, Guid> generatedMethodToCall = generatedMethod.CreateDelegate<Func<object, IntPtr, Guid>>();

// Call the property getter through the generated method.
IntPtr fn = typeof(MyClassWithGuidProperty).GetProperty(nameof(MyClassWithGuidProperty.MyGuid))!.GetGetMethod().MethodHandle.GetFunctionPointer();
Guid guid = Guid.NewGuid();
MyClassWithGuidProperty obj = new (guid);
Assert.Equal(guid, generatedMethodToCall(obj, fn));
}
finally
{
testAssemblyLoadContext.Unload();
}

static unsafe byte[] GenerateMethodInPersistedAssembly()
{
AssemblyName assemblyName = new("MyAssembly");
PersistedAssemblyBuilder ab = new(assemblyName, typeof(object).Assembly);
ModuleBuilder moduleBuilder = ab.DefineDynamicModule("MyModule");

// Define a type with a method that calls the instance-based function pointer through calli.
TypeBuilder typeBuilder = moduleBuilder.DefineType("MyGeneratedType", TypeAttributes.Public | TypeAttributes.Class);
MethodBuilder methodBuilder = typeBuilder.DefineMethod(
"GetGuid",
MethodAttributes.Public | MethodAttributes.Static,
typeof(Guid),
new Type[] { typeof(object), typeof(IntPtr) });

ILGenerator il = methodBuilder.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // this
il.Emit(OpCodes.Ldarg_1); // fn
il.EmitCalli(OpCodes.Calli, CallingConventions.HasThis, typeof(Guid), null, null);
il.Emit(OpCodes.Ret);

typeBuilder.CreateType();

MetadataBuilder metadataBuilder = ab.GenerateMetadata(out BlobBuilder ilStream, out BlobBuilder _);
ManagedPEBuilder peBuilder = new ManagedPEBuilder(PEHeaderBuilder.CreateLibraryHeader(), new MetadataRootBuilder(metadataBuilder), ilStream);
BlobBuilder blob = new BlobBuilder();
peBuilder.Serialize(blob);
return blob.ToArray();
}
}

private class MyClassWithGuidProperty
{
public MyClassWithGuidProperty(Guid guid)
{
MyGuid = guid;
}

public Guid MyGuid { get; init; }
}

void CheckCattr(IList<CustomAttributeData> attributes)
{
CustomAttributeData cattr = attributes.First(a => a.AttributeType.Name == nameof(AttributeUsageAttribute));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<TargetFramework>$(NetCoreAppCurrent)</TargetFramework>
<TestRuntime>true</TestRuntime>
<IncludeRemoteExecutor>true</IncludeRemoteExecutor>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

<ItemGroup>
Expand Down
Loading