小编典典

是否可以从C#中执行x86汇编序列?

c#

继续进行逆向工程教育,我经常希望能够复制x86汇编代码的一部分,并从我选择的高级语言中对其进行调用以进行测试。

有谁知道从C#方法中调用x86指令序列的方法吗?我知道可以使用C ++完成此操作,但我很好奇是否可以使用C#完成吗?

注意:我不是在谈论执行MSIL指令。我说的是执行一系列原始的x86汇编指令。


阅读 289

收藏
2020-05-19

共1个答案

小编典典

为了反驳Brian的主张,从leppie的答案链接中重写了代码:

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