【发布时间】:2020-05-31 08:47:31
【问题描述】:
我正在尝试在 C 代码中执行二进制可执行文件而不使用 system,因为它存在安全和资源管理问题。
这里使用的系统是 Debian Buster,内核 5.4.0-2-amd64 和 gcc 9.2.1。
我在这个问题中使用了方法: execute binary machine code from C
即用xxd -i将可执行文件转换为十六进制代码,但不断得到Segmentation fault。
我使用的程序是:
第一次尝试
可执行文件.c:
#include <stdio.h>
int main(void)
{
printf("Hello, World!\n");
return 0;
}
用gcc -o executable executable.c编译后
xxd -i executable 将二进制文件显示为十六进制
然后将输出复制粘贴到embedded.c
embedded.c:
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
const unsigned char[] executable = {
0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01,
...
};
int main(void)
{
void *buf = mmap(
NULL, sizeof(executable), PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANON, -1, 0);
memcpy(buf, sizeof(executable);
__builtin___clear_cache(buf, buf + sizeof(executable) - 1);
int i = ((int (*) (void)buf)();
return 0;
}
编译运行后,终端显示Segmentation fault。
第二次尝试
我尝试的另一种方法是使用ld,它也显示Segmentation fault:
embedded.c:
extern const char _binary_executable_start[];
extern const char _binary_executable_end[];
// And same as the previous code.
代码编译使用:
gcc -c -o embedded.o embedded.c
ld -r -b binary -o executable.o executable
gcc -o embedded embedded.o executable.o
失败了。
有什么我遗漏的或者无法将二进制文件嵌入到 C 代码中并运行它吗?
【问题讨论】:
-
实际上,内核支持执行二进制程序:它是
execfunction-family。通常与fork一起使用。
标签: c linux gcc binary segmentation-fault