这恰好起作用,因为 function1 和 function2 在内存中的大小完全相同。我们的 memcopy 需要 function2 的长度,所以应该做的是: int diff = (&main - &function2);
您会注意到您可以根据自己的喜好编辑功能 2,并且它可以正常工作!
顺便说一句,巧妙的把戏。Unfurtunate g++ 编译器确实吐出了从 void* 到 int 的无效转换......但实际上使用 gcc 它可以完美编译;)
修改来源:
//Hacky solution and simple proof of concept that works for me (and compiles without warning on Mac OS X/GCC 4.2.1):
//fixed the diff address to also work when function2 is variable size
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include <sys/mman.h>
int function1(int x){
return x-5;
}
int function2(int x){
//printf("hello world");
int k=32;
int l=40;
return x+5+k+l;
}
int main(){
int diff = (&main - &function2);
printf("pagesize: %d, diff: %d\n",getpagesize(),diff);
int (*fptr)(int);
void *memfun = malloc(4096);
if (mprotect(memfun, 4096, PROT_READ|PROT_EXEC|PROT_WRITE) == -1) {
perror ("mprotect");
}
memcpy(memfun, (const void*)&function2, diff);
fptr = &function1;
printf("native: %d\n",(*fptr)(6));
fptr = memfun;
printf("memory: %d\n",(*fptr)(6) );
fptr = &function1;
printf("native: %d\n",(*fptr)(6));
free(memfun);
return 0;
}
输出:
Walter-Schrepperss-MacBook-Pro:cppWork wschrep$ gcc memoryFun.c
Walter-Schrepperss-MacBook-Pro:cppWork wschrep$ ./a.out
pagesize: 4096, diff: 35
native: 1
memory: 83
native: 1
另一个需要注意的是调用 printf 将出现段错误,因为 printf 很可能由于相对地址出错而找不到......