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 2 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 @@ -800,15 +800,19 @@ private BlobBuilder GetMethodArrayMethodSignature(ArrayMethod method) => Metadat
private static bool IsInstance(CallingConventions callingConvention) =>
callingConvention.HasFlag(CallingConventions.HasThis) || callingConvention.HasFlag(CallingConventions.ExplicitThis) ? true : false;

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

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

// CallingConventions.HasThis (0x20) and ExplicitThis (0x40) can use a bitwise OR with SignatureCallingConvention.
const byte Mask = (byte)(CallingConventions.HasThis | CallingConventions.ExplicitThis);
convention = (SignatureCallingConvention)((byte)convention | (unchecked((byte)callingConventions) & Mask));

return convention;
}

Expand Down
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