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

Add ldvirtftn #141

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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 @@ -257,7 +257,7 @@ private static CilDispatchResult Invoke(CilExecutionContext context, IMethodDesc
}
}

protected static MethodDefinition? FindMethodImplementationInType(TypeDefinition? type, MethodDefinition? baseMethod)
internal static MethodDefinition? FindMethodImplementationInType(TypeDefinition? type, MethodDefinition? baseMethod)
{
if (type is null || baseMethod is null || !baseMethod.IsVirtual)
return baseMethod;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System.Linq;
using AsmResolver.DotNet;
using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Cil;

namespace Echo.Platforms.AsmResolver.Emulation.Dispatch.ObjectModel;

/// <summary>
/// Implements a CIL instruction handler for <c>ldvirtftn</c> instruction.
/// </summary>
[DispatcherTableEntry(CilCode.Ldvirtftn)]
public class LdvirtftnHandler : FallThroughOpCodeHandler
{
/// <inheritdoc/>
protected override CilDispatchResult DispatchInternal(CilExecutionContext context, CilInstruction instruction)
{
var stack = context.CurrentFrame.EvaluationStack;
var factory = context.Machine.ValueFactory;
var methods = context.Machine.ValueFactory.ClrMockMemory.MethodEntryPoints;
var type = context.Machine.ContextModule.CorLibTypeFactory.IntPtr;

var thisObject = stack.Pop().Contents;
if (!thisObject.IsFullyKnown)
throw new CilEmulatorException("Unable to resolve an unknown object.");

var thisObjectType = thisObject.AsObjectHandle(context.Machine).GetObjectType().Resolve();
if (thisObjectType == null)
throw new CilEmulatorException("Unable to resolve the type of object");

var virtualFunction = (IMethodDescriptor)instruction.Operand!;

IMethodDescriptor? implementation = CallHandlerBase.FindMethodImplementationInType(thisObjectType, virtualFunction.Resolve());

if (implementation == null)
{
return CilDispatchResult.Exception(
context.Machine.Heap.AllocateObject(
context.Machine.ValueFactory.MissingMethodExceptionType,
true)
.AsObjectHandle(context.Machine)
);
}

// Instantiate any generics.
var genericContext = GenericContext.FromMethod(virtualFunction);
if (!genericContext.IsEmpty)
{
var instantiated = thisObjectType
.CreateMemberReference(implementation.Name!, implementation.Signature!);

implementation = genericContext.Method != null
? instantiated.MakeGenericInstanceMethod(genericContext.Method.TypeArguments.ToArray())
: instantiated;
}

var functionPointer = methods.GetAddress(implementation);
stack.Push(factory.CreateNativeInteger(functionPointer), type);
return CilDispatchResult.Success();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Reflection;
using System.Text;
using System.Threading;
using AsmResolver;
using AsmResolver.DotNet;
using AsmResolver.DotNet.Code.Cil;
using AsmResolver.DotNet.Signatures;
Expand Down Expand Up @@ -603,7 +604,7 @@

// Verify.
Assert.NotNull(result);
Assert.Equal(1337, result.AsSpan().I32);

Check warning on line 607 in test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/CilVirtualMachineTest.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 607 in test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/CilVirtualMachineTest.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 607 in test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/CilVirtualMachineTest.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
}

[Fact]
Expand Down Expand Up @@ -710,5 +711,41 @@
Assert.Single(_mainThread.CallStack.Peek().EvaluationStack);
Assert.Equal(5, _mainThread.CallStack.Peek().EvaluationStack.Peek().Contents.AsSpan().I32);
}

[Fact]
public void CallDelegateWithVirtualFunction()
{
var method = _fixture.MockModule
.LookupMember<TypeDefinition>(typeof(TestClass).MetadataToken)
.Methods.First(m => m.Name == nameof(TestClass.TestVirtualDelegateCall));

_vm.Invoker = DefaultInvokers.CreateDefaultShims().WithFallback(DefaultInvokers.StepIn).WithFallback(DefaultInvokers.ReflectionInvoke);
_mainThread.CallStack.Push(method);

var instructions = method.CilMethodBody!.Instructions;

var invokeDelegateOffset = instructions
.First(instruction => instruction.Operand is IMethodDescriptor descriptor
&& descriptor.Name == "Invoke")
.Offset;

var expectedResults = new string[] { "Mr.String", "Mocks.TestClass" };

for (int i = 0; i < expectedResults.Length; i++)
{
_mainThread.StepWhile(CancellationToken.None, context => context.CurrentFrame.ProgramCounter != invokeDelegateOffset);
_mainThread.Step(); // invoke: string Func<object>::Invoke()
// Expected stack:
// (0) root -> (1) TestVirtualDelegateCall -> (2) Func<object>::Invoke -> (3) *::ToString
Assert.Equal(4, _mainThread.CallStack.Count);

// exit from *::ToString
while (_mainThread.CallStack.Count != 2)
_mainThread.StepOut();

var returnedString = _mainThread.CallStack.Peek().EvaluationStack.Peek();
Assert.Equal(expectedResults[i], _vm.ObjectMarshaller.ToObject<string>(returnedString.Contents.AsSpan()));
}
}
}
}
16 changes: 16 additions & 0 deletions test/Platforms/Mocks/TestClass.cs
Original file line number Diff line number Diff line change
Expand Up @@ -295,5 +295,21 @@ public static int TestDelegateCall()
ReturnAnyIntDelegate del = ReturnAnyInt;
return del();
}

public static void TestVirtualDelegateCall()
{
var objects = new object[] { "Mr.String", new TestClass() };
for(int i = 0; i < objects.Length; i++)
{
var @object = objects[i];
var function = new Func<string>(@object.ToString);
_ = function();
}
}

public override string ToString()
{
return "Mocks.TestClass";
}
}
}
Loading