如何在不创建一个新的进程中运行组装code? [英] How to run assembly code without creating a new process?
问题描述
该文件包含本地组装code,我想在当前进程中运行它。
但我不希望创建一个真正的文件(.com或.exe文件),所以我尝试:
The file contains the native assembly code, and I want to run it in the current process. But I don't want to create a real file (.com or .exe), so I tried:
...
using namespace std;
typedef void bitcode();
void testcode(){
cout<<"test";
};
int main()
{
bitcode *c=&testcode; // bitcode *c stands for the file containing the assembly code.
bitcode *d=reinterpret_cast<bitcode*> (malloc(20));
memcpy(d, c, 20);
d(); // it doesn't work
return 0;
};
然而,这并不当调用研发工作();.我想知道什么是用C来做到这一点的正确方法/ C ++。
However, it doesn't work when I invoke d();. I want to know what's the correct way to do this with C/C++.
(我在Windows,和我最好的AP preciate非常多,如果你能告诉我如何让它在Linux上)
(I'm on Windows, and I’d appreciate it very much if you could tell me how to make it on Linux)
非常感谢!
的 PS:我的不可以问。跑在一个可执行的其他过程中没有创建一个新进程的
PS: I'm NOT asking "Running a executable in another process without creating a new process."
推荐答案
,这是code我之前写的。它的工作原理上的Win7 + VS2010,至少在我的机器。
on windows, this is code I wrote before. It works on Win7+VS2010 at least in my machine.
基本想法是,调用VirtualAlloc的与PAGE_EXECUTE_READWRITE标志分配内存。
并调用它的正确的方式,也就是保持堆栈的平衡。
the base idea is that call VirtualAlloc to allocate memory with PAGE_EXECUTE_READWRITE flag. And call it in right way, that is, keep the stack balance.
#include "stdafx.h"
#include "windows.h"
int emitcode[] =
{0x83ec8b55,0x565340ec,0x0c758b57,0x8b087d8b,
0x348d104d,0xcf3c8dce,0x6f0fd9f7,0x6f0fce04,
0x0f08ce4c,0x10ce546f,0xce5c6f0f,0x646f0f18,
0x6f0f20ce,0x0f28ce6c,0x30ce746f,0xce7c6f0f,
0x04e70f38,0x4ce70fcf,0xe70f08cf,0x0f10cf54,
0x18cf5ce7,0xcf64e70f,0x6ce70f20,0xe70f28cf,
0x0f30cf74,0x38cf7ce7,0x7508c183,0xf8ae0fad,
0x5e5f770f,0x5de58b5b,0xccccccc3};
int _tmain(int argc, _TCHAR* argv[])
{
int *src = new int[64];
int *dst = new int[64];
int *dst2 = new int[64];
for (int i = 0; i < 64; ++i){
src[i] = i;
}
//fastercopy(dst,src, 64/2);
void* address = NULL;
address= VirtualAlloc(NULL,
sizeof(emitcode),
MEM_COMMIT|MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
memcpy(address,emitcode,sizeof(emitcode));
//call emit code from assemble
__asm {
push 20h
mov eax,dword ptr [src]
push eax
mov ecx,dword ptr [dst]
push ecx
mov ecx, dword ptr [address]
call ecx
add esp,0Ch
}
for (int i = 0; i < 64; ++i){
printf("%d ",dst[i]);
}
//call emit code from function pointer
typedef void (*FASTCALL)(void* dst, void* src, int len);
FASTCALL fastcall;
fastcall = (FASTCALL)address;
fastcall(dst2,src,64/2);
printf("\n");
for (int i = 0; i < 64; ++i){
printf("%d ",dst2[i]);
}
return 0;
}
这篇关于如何在不创建一个新的进程中运行组装code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!