在内存中执行机器代码 [英] Executing machine code in memory
问题描述
我想知道如何执行存储在内存中的机器码。
I'm trying to figure out how to execute machine code stored in memory.
我有以下代码:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
FILE* f = fopen(argv[1], "rb");
fseek(f, 0, SEEK_END);
unsigned int len = ftell(f);
fseek(f, 0, SEEK_SET);
char* bin = (char*)malloc(len);
fread(bin, 1, len, f);
fclose(f);
return ((int (*)(int, char *)) bin)(argc-1, argv[1]);
}
上面的代码在GCC中编译正常,但是当我尝试并执行程序从命令行如下:
The code above compiles fine in GCC, but when I try and execute the program from the command line like this:
./my_prog /bin/echo hello
程序segfaults。我发现问题是在最后一行,因为注释它停止了segfault。
The program segfaults. I've figured out the problem is on the last line, as commenting it out stops the segfault.
我不认为我做的很对,
I don't think I'm doing it quite right, as I'm still getting my head around function pointers.
这个问题是错误的转换还是别的什么?
Is the problem a faulty cast, or something else?
推荐答案
在我看来你正在加载一个ELF图像,然后试图直接跳进ELF标题? http://en.wikipedia.org/wiki/Executable_and_Linkable_Format
It seems to me you're loading an ELF image and then trying to jump straight into the ELF header? http://en.wikipedia.org/wiki/Executable_and_Linkable_Format
如果你试图执行另一个二进制文件,你为什么不使用你使用的平台的进程创建函数?
If you're trying to execute another binary, why don't you use the process creation functions for whichever platform you're using?
这篇关于在内存中执行机器代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!