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
How to Parse Very Huge Xml Files in C#
C#: Convert Byte Array into a Float
Adding Images into Excel Using Epplus
Return/Consume Dynamic Anonymous Type Across Assembly Boundaries
C# How to Loop While Mouse Button Is Held Down
Executenonquery for Select SQL Statement Returning No Rows
Why Does Timespan.Parseexact Not Work
Uncompressing Gzip Response from Webclient
How to Connect to ASP.NET Development Server Issue
Add Two Lists of Different Length in C#
Implicit Conversion Issue in a Ternary Condition
How to Ignore the Utf-8 Byte Order Marker in String Comparisons
Using Dataannotations with Entity Framework
When Is Optimization Premature
Badimageformatexception When Loading 32 Bit Dll, Target Is X86