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

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

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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 is powered by AI, so mistakes are possible. Review output carefully before use.

Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options
{
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()
Copy link
Member

Choose a reason for hiding this comment

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

Is there any benefit to adding an ExplicitThis test? I'm still not entirely clear on what it is used for.

Copy link
Member

Choose a reason for hiding this comment

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

ExplicitThis means that the this type is explicitly encoded in the signature.

For example, MyClassWithGuidProperty.MyGuid property from the existing test would be called like this: il.EmitCalli(OpCodes.Calli, CallingConventions.HasThis | CallingConventions.ExplicitThis, typeof(Guid), [typeof(MyClassWithGuidProperty)], null); with ExplicitThis.

It makes sense on function pointers and calli signatures only. From ECMA spec: "The EXPLICITTHIS (0x40) bit can be set only in signatures for function pointers"

Copy link
Member Author

Choose a reason for hiding this comment

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

I could add a test, but other than to verify the signature actually has the extra "this" parameter there isn't much to test since the IL stays the same: the caller still needs to push the "this" pointer before the calli, and the target instance method still needs to do a ldarg.0 as the first statement.

I did at least find one test that would verify the runtime doesn't choke on it:

IL.Emit.Calli(new StandAloneMethodSig(CallingConventions.Standard | CallingConventions.HasThis | CallingConventions.ExplicitThis,
.

If C# adds support for instance-based function pointers, I think it would want to use ExplicitThis since it would get the "this" parameter in the signature instead of some passing it some other way. We may also want to use it for intrinstic\UnsafeAccessor for #112994.

Copy link
Member

Choose a reason for hiding this comment

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

I could add a test, but other than to verify the signature actually has the extra "this" parameter

Right, the test would verify that the extra "this" is not dropped on the floor somewhere along the way in the System.Reflection.Emit or System.Reflection.Metadata.

Copy link
Member

Choose a reason for hiding this comment

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

Yep. I would like to see a test in this particular test suite even if only for completeness.

Copy link
Member Author

Choose a reason for hiding this comment

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

I added a test for both the AssemblyBuilder and for the DynamicMethod case, and it is failing on the ExplicitThis tests.

I did verify that the signature is being created correctly with calli explicit instance, but the "this" pointer in the test's Guid-based property getter is not valid.

Copy link
Member

Choose a reason for hiding this comment

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

How is it failing?

Copy link
Member Author

Choose a reason for hiding this comment

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

I just pushed a change to the jitter - it needs to know that the first arg is "this" for ExplicitThis.

Copy link
Member

@jakobbotsch jakobbotsch Mar 21, 2025

Choose a reason for hiding this comment

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

Yeah, looks like a pretty old bug. Without this we insert the retbuffer in the wrong place for callis with explicitthis that use return buffers.

{
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