我想在x64 Linux上编写自己的二进制代码加载程序。将来我希望能够自己执行链接步骤,从而能够从.o
对象文件调用代码。但现在,我想从已经链接的可执行二进制文件中调用一个函数。
为了创建一些应该从“outside”调用的函数,我从以下源代码开始:
void foo(void)
{
int a = 2;
int b = 3;
a + b;
}
int main(void)
{
foo();
return 0;
}
这是我想使用加载程序调用的
foo()
-函数。使用以下命令链gcc -o /tmp/main main.c
strip -s /tmp/main
objdump -D /tmp/main
我获得了
foo()
函数的汇编代码,如下所示:...
0000000000001125 <foo>:
1125: 55 push %rbp
1126: 48 89 e5 mov %rsp,%rbp
1129: c7 45 fc 02 00 00 00 movl $0x2,-0x4(%rbp)
1130: c7 45 f8 03 00 00 00 movl $0x3,-0x8(%rbp)
1137: 90 nop
1138: 5d pop %rbp
1139: c3 retq
...
这意味着,
foo()
函数从main
中的偏移量0x1125开始。我用hexeditor验证了这一点。下面是我的装载机。目前还没有错误处理,代码非常难看。但是,它应该表明,我想要实现的目标:
#include <stdio.h>
#include <stdlib.h>
typedef void(*voidFunc)(void);
int main(int argc, char* argv[])
{
FILE *fileptr;
char *buffer;
long filelen;
voidFunc mainFunc;
fileptr = fopen(argv[1], "rb"); // Open the file in binary mode
fseek(fileptr, 0, SEEK_END); // Jump to the end of the file
filelen = ftell(fileptr); // Get the current byte offset in the file
rewind(fileptr); // Jump back to the beginning of the file
buffer = (char *)malloc((filelen+1)*sizeof(char)); // Enough memory for file + \0
fread(buffer, filelen, 1, fileptr); // Read in the entire file
fclose(fileptr); // Close the file
mainFunc = ((voidFunc)(buffer + 0x1125));
mainFunc();
free(buffer);
return 0;
}
当执行这个程序时,它会导致SEGFAULT。
变量指向正确的位置。我用
objloader /tmp/main
验证了这一点。操作码存在堆上是个问题吗?实际上,我决定使我要调用的函数尽可能简单(副作用、函数参数所需的堆栈或寄存器…)。不过,我还是不明白。
有人能给我指一下这里的正确方向吗?任何有关这方面的有用文献的提示也非常感谢!
最佳答案
要使buffer
内存区域可执行,必须使用mmap
。尝试
#include <sys/mman.h>
...
buffer = (char *)mmap(NULL, filelen /* + 1? Not sure why. */, PROT_EXEC | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
这应该为内存区域提供所需的权限,并使其能够处理周围的代码。事实上,如果你想使用
mmap
的方式,就去int fd = open(argv[1], O_RDONLY);
struct stat myfilestats;
fstat(fd, &myfilestats);
buffer = (char*)mmap(NULL, myfilestats.st_size, PROT_EXEC, MAP_PRIVATE, fd, 0);
fclose(fd);
...
munmap(buffer, myfilestats.st_size);
使用
MAP_ANONYMOUS
将使内存区域与文件描述符无关,但其思想是,如果它表示一个文件,则应将文件描述符与其关联。当你这样做的时候,Linux会做各种很酷的技巧,比如只加载你最终访问的部分文件(当文件很大的时候,延迟加载也会使程序非常平滑),如果多个程序都在访问同一个文件,那么它们将共享相同的物理内存位置。