是否有可能从C#中执行一个x86汇编程序

是否有可能从C#中执行一个x86汇编程序

本文介绍了是否有可能从C#中执行一个x86汇编程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

继续我的逆向工程教育我常常希望能够复制x86汇编code的部分,并从我选择测试的高级语言调用它。

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.

有谁知道从C#方法中调用的x86指令序列的方法?我知道,这可以用C来完成++,但我很好奇,如果它可以在C#做什么?

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#?

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

Note: I'm not talking about executing MSIL instructions. I'm talking about executing a series of raw x86 assembly instructions.

推荐答案

只是为了对抗Brian的说法,改写code从leppie的答案link:

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

这篇关于是否有可能从C#中执行一个x86汇编程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 08:53