How to Execute an X86 Assembly Sequence from Within C#

Is it possible to execute an x86 assembly sequence from within C#?

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());
}
}
}

Execute Byte array as a new program

You have two way

first way make .exe from that byte array and then start it

second look at this execute byte array

Create method from byte array

Yes, you can do it using Reflection Emit. But you should write logic that will read this byte array byte-by-byte and Emmit OpCodes that you need into ILGenerator.

It's really simple. First you create new DynamicMethod, call GetILGenerator from it, do series of "Emmit" calls from GetILGenerator, call CreateDelegate from DynamicMethod, and finally call the new method itself by calling this delegate.



Related Topics



Leave a reply



Submit