在执行内存的机器code [英] Executing machine code in memory
问题描述
我试图找出如何执行存储在内存的机器code。
I'm trying to figure out how to execute machine code stored in memory.
我有以下的code:
#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]);
}
上面的code编译海合会很好,但是当我尝试从这样的命令行执行程序:
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
程序段错误。我已经想通了,问题是最后一行,因为注释掉它停止了段错误。
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头? <一href=\"http://en.wikipedia.org/wiki/Executable_and_Linkable_Format\">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?
这篇关于在执行内存的机器code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!