Continuing my reverse engineering education I've often wanted to be able to copy portions of x86 assembly code and call it from a high level language of my choice for testing.
Does anyone know of a method of calling a sequence of x86 instructions from within a C# method? I know that this can be done using C++ but I'm curious if it can be done in C#?
Note: I'm not talking about executing MSIL instructions. I'm talking about executing a series of raw x86 assembly instructions.
It is used to produce object code for the x86 class of processors. Regarded as a programming language, assembly is machine-specific and low-level. Like all assembly languages, x86 assembly uses mnemonics to represent fundamental CPU instructions, or machine code.
An x86 instruction can have zero to three operands. Operands are separated by commas (,) (ASCII 0x2C). For instructions with two operands, the first (lefthand) operand is the source operand, and the second (righthand) operand is the destination operand (that is, source->destination).
CX is known as the count register, as the ECX, CX registers store the loop count in iterative operations. DX is known as the data register. It is also used in input/output operations. It is also used with AX register along with DX for multiply and divide operations involving large values.
MOVB and MOVW are data movement instructions which more closely resemble the MOVE instructions of CPU32-based microcontrollers more so than the load-store architecture of the 8- and 16-bit machines. The PSHM and PULM instructions move data to and from the registers and the built-in hardware stack.
Just to counter Brian's claim, rewritten code from leppie's answer link:
using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace DynamicX86 { class Program { const uint PAGE_EXECUTE_READWRITE = 0x40; const uint MEM_COMMIT = 0x1000; [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); private delegate int IntReturner(); static void Main(string[] args) { List<byte> bodyBuilder = new List<byte>(); bodyBuilder.Add(0xb8); bodyBuilder.AddRange(BitConverter.GetBytes(42)); bodyBuilder.Add(0xc3); byte[] body = bodyBuilder.ToArray(); IntPtr buf = VirtualAlloc(IntPtr.Zero, (uint)body.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE); Marshal.Copy(body, 0, buf, body.Length); IntReturner ptr = (IntReturner)Marshal.GetDelegateForFunctionPointer(buf, typeof(IntReturner)); Console.WriteLine(ptr()); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With