task 3.3-3.4: x86 cdecl stub encoding + CallingConvention enum

Add CallingConvention enum (Cdecl, Stdcall, Thiscall, Fastcall).
Implement BuildCallStub on StubAssembler with x86 cdecl support:
reverse arg push, call rel32, add esp (caller cleanup), ret.
x64 stub is a placeholder (task 3.7-3.8).

3 new tests: 0-arg (call+ret), 1-arg (push+call+cleanup+ret),
2-args (reverse push+call+cleanup+ret). Known byte expectations.
All passing (total: 67).
This commit is contained in:
kbe
2026-07-21 19:37:20 +02:00
parent 855595837f
commit f7236eea9b
3 changed files with 163 additions and 11 deletions
+66 -2
View File
@@ -4,8 +4,8 @@ namespace WhiteMagicTest;
/// <summary>
/// Tests for <see cref="StubAssembler"/> emit primitives (<see cref="StubAssembler.EmitU8"/>,
/// <see cref="StubAssembler.EmitU32"/>, <see cref="StubAssembler.EmitU64"/>) and the
/// <see cref="IAssembler"/> interface contract.
/// <see cref="StubAssembler.EmitU32"/>, <see cref="StubAssembler.EmitU64"/>) and
/// calling-convention stub encoding.
/// </summary>
public class StubAssemblerTests
{
@@ -75,4 +75,68 @@ public class StubAssemblerTests
var sut = Create();
Assert.Throws<NotSupportedException>(() => sut.Assemble("nop", 0));
}
// ── Calling convention: x86 cdecl ──────────────────────────────────────
[Fact]
public void Cdecl_stub_with_zero_args_is_call_then_ret()
{
var sut = Create();
IntPtr stubAddr = (IntPtr)0x10000000;
IntPtr target = (IntPtr)0x12345678;
uint[] args = [];
uint rel32 = (uint)target - ((uint)stubAddr + 5);
byte[] stub = sut.BuildCallStub(stubAddr, target, args, 4, CallingConvention.Cdecl);
Assert.Equal(6, stub.Length);
Assert.Equal(0xE8, stub[0]); // call
Assert.Equal(rel32, BitConverter.ToUInt32(stub, 1)); // rel32
Assert.Equal(0xC3, stub[5]); // ret
}
[Fact]
public void Cdecl_stub_one_arg_reverse_push_then_call_then_cleanup()
{
var sut = Create();
IntPtr stubAddr = (IntPtr)0x10000000;
IntPtr target = (IntPtr)0x12345678;
uint[] args = [0xAABBCCDD];
uint callAddr = (uint)stubAddr + 5;
uint rel32 = (uint)target - (callAddr + 5);
byte[] stub = sut.BuildCallStub(stubAddr, target, args, 4, CallingConvention.Cdecl);
byte[] expected = [
0x68, 0xDD, 0xCC, 0xBB, 0xAA, // push 0xAABBCCDD
0xE8,
(byte)rel32, (byte)(rel32 >> 8), (byte)(rel32 >> 16), (byte)(rel32 >> 24),
0x83, 0xC4, 0x04, // add esp, 4
0xC3 // ret
];
Assert.Equal(expected, stub);
}
[Fact]
public void Cdecl_stub_two_args_reverse_order()
{
var sut = Create();
IntPtr stubAddr = (IntPtr)0x10000000;
IntPtr target = (IntPtr)0x12345678;
uint[] args = [0x11111111, 0x22222222];
uint callAddr = (uint)stubAddr + 10;
uint rel32 = (uint)target - (callAddr + 5);
byte[] stub = sut.BuildCallStub(stubAddr, target, args, 4, CallingConvention.Cdecl);
byte[] expected = [
0x68, 0x22, 0x22, 0x22, 0x22, // push arg1 (reverse order)
0x68, 0x11, 0x11, 0x11, 0x11, // push arg0
0xE8,
(byte)rel32, (byte)(rel32 >> 8), (byte)(rel32 >> 16), (byte)(rel32 >> 24),
0x83, 0xC4, 0x08, // add esp, 8
0xC3
];
Assert.Equal(expected, stub);
}
}