anduin revised this gist . Go to revision
No changes
anduin revised this gist . Go to revision
1 file changed, 2 deletions
main.c
@@ -4,8 +4,6 @@ | |||
4 | 4 | #include <sys/mman.h> | |
5 | 5 | #include <unistd.h> | |
6 | 6 | ||
7 | - | // 这是 add 函数的机器码,假设它的二进制数据已经嵌入到这里 | |
8 | - | // 注意:这个数据需要根据具体架构和编译器生成的机器码来填充 | |
9 | 7 | unsigned char add_bin[] = { | |
10 | 8 | // 这里是针对 x86_64 架构的 add 函数的二进制机器码 | |
11 | 9 | 0x55, // push %rbp |
anduin revised this gist . Go to revision
1 file changed, 0 insertions, 0 deletions
gistfile1.txt renamed to main.c
File renamed without changes
anduin revised this gist . Go to revision
1 file changed, 54 insertions
gistfile1.txt(file created)
@@ -0,0 +1,54 @@ | |||
1 | + | #include <stdio.h> | |
2 | + | #include <stdlib.h> | |
3 | + | #include <string.h> | |
4 | + | #include <sys/mman.h> | |
5 | + | #include <unistd.h> | |
6 | + | ||
7 | + | // 这是 add 函数的机器码,假设它的二进制数据已经嵌入到这里 | |
8 | + | // 注意:这个数据需要根据具体架构和编译器生成的机器码来填充 | |
9 | + | unsigned char add_bin[] = { | |
10 | + | // 这里是针对 x86_64 架构的 add 函数的二进制机器码 | |
11 | + | 0x55, // push %rbp | |
12 | + | 0x48, 0x89, 0xe5, // mov %rsp,%rbp | |
13 | + | 0x89, 0x7d, 0xfc, // mov %edi,-0x4(%rbp) | |
14 | + | 0x89, 0x75, 0xf8, // mov %esi,-0x8(%rbp) | |
15 | + | 0x8b, 0x55, 0xfc, // mov -0x4(%rbp),%edx | |
16 | + | 0x8b, 0x45, 0xf8, // mov -0x8(%rbp),%eax | |
17 | + | 0x01, 0xd0, // add %edx,%eax | |
18 | + | 0x5d, // pop %rbp | |
19 | + | 0xc3 // retq | |
20 | + | }; | |
21 | + | ||
22 | + | void load_and_execute() { | |
23 | + | // 获取页面大小 | |
24 | + | size_t pagesize = sysconf(_SC_PAGESIZE); | |
25 | + | ||
26 | + | // 分配可读、可写、可执行的内存页 | |
27 | + | void *exec_mem = mmap(NULL, pagesize, PROT_READ | PROT_WRITE | PROT_EXEC, | |
28 | + | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); | |
29 | + | if (exec_mem == MAP_FAILED) { | |
30 | + | perror("mmap"); | |
31 | + | exit(EXIT_FAILURE); | |
32 | + | } | |
33 | + | ||
34 | + | // 将函数的机器码复制到可执行内存中 | |
35 | + | memcpy(exec_mem, add_bin, sizeof(add_bin)); | |
36 | + | ||
37 | + | // 定义一个函数指针并指向加载到内存中的代码段 | |
38 | + | int (*add_func)(int, int) = (int (*)(int, int))exec_mem; | |
39 | + | ||
40 | + | // 调用加载的函数 | |
41 | + | int result = add_func(2, 3); | |
42 | + | printf("Result of add(2, 3): %d\n", result); | |
43 | + | ||
44 | + | // 释放内存 | |
45 | + | if (munmap(exec_mem, pagesize) == -1) { | |
46 | + | perror("munmap"); | |
47 | + | exit(EXIT_FAILURE); | |
48 | + | } | |
49 | + | } | |
50 | + | ||
51 | + | int main() { | |
52 | + | load_and_execute(); | |
53 | + | return 0; | |
54 | + | } |