从内存运行可执行文件 [英] Running executable from memory
问题描述
我试图直接从该可执行文件的byte []表示形式作为C#中的资源运行可执行文件.
I'm trying to run an executable directly from a byte[] representation of this executable as a resource in C#.
所以基本上,我想直接运行PE的byte []而不接触硬盘.
So basically i want to run a byte[] of an PE directly without touching the harddisk.
我为此使用的代码可以正常工作,但现在不再可用.
The code I'm using for this used to work but it doesn't anymore.
代码使用冻结的主线程创建一个进程,更改整个进程数据,最后将其恢复,从而运行PE的byte [].但是,如果继续执行该线程,进程似乎就死了,我真的不知道怎么了.
The code creates a process with a frozen main thread, changes the whole process data and finally resumes it so it runs the byte[] of the PE. But it seems like the process dies if the thread is resumed, i don't really know whats wrong.
所以这是pastebin中的代码,因为我猜这里太长了...
So here is the code in a pastebin because its too long for here i guess...
我要运行非托管代码! 任何PE文件...
I want to run non-managed code ! Any PE File ...
推荐答案
以下是一些执行本机代码的代码(在字节数组中).请注意,这并不是您要的(不是PE文件字节,而是本地过程字节,即汇编语言)
Here is some code to execute native code (inside a byte array). Note that it is not exactly what you are asking for (it's not a PE file bytes, but a native procedure bytes ie. in assembly language)
using System;
using System.Runtime.InteropServices;
namespace Native
{
class Program
{
private const UInt32 MEM_COMMIT = 0x1000;
private const UInt32 PAGE_EXECUTE_READWRITE = 0x40;
private const UInt32 MEM_RELEASE = 0x8000;
[DllImport("kernel32")] private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, UInt32 size, UInt32 flAllocationType, UInt32 flProtect);
[DllImport("kernel32")] private static extern bool VirtualFree(IntPtr lpAddress, UInt32 dwSize, UInt32 dwFreeType);
[DllImport("kernel32")]
private static extern IntPtr CreateThread(
UInt32 lpThreadAttributes,
UInt32 dwStackSize,
UInt32 lpStartAddress,
IntPtr param,
UInt32 dwCreationFlags,
ref UInt32 lpThreadId
);
[DllImport("kernel32")] private static extern bool CloseHandle(IntPtr handle);
[DllImport("kernel32")] private static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
static void Main(string[] args)
{
byte[] nativecode = new byte[] { /* here your native bytes */ };
UInt32 funcAddr = VirtualAlloc(0, (UInt32)nativecode.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
Marshal.Copy(nativecode, 0, (IntPtr)(funcAddr), nativecode.Length);
IntPtr hThread = IntPtr.Zero;
UInt32 threadId = 0;
hThread = CreateThread(0, 0, funcAddr, IntPtr.Zero, 0, ref threadId);
WaitForSingleObject(hThread, 0xFFFFFFFF);
CloseHandle(hThread);
VirtualFree((IntPtr)funcAddr, 0, MEM_RELEASE);
}
}
}
这篇关于从内存运行可执行文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!