我想执行以下操作:.c
文件中有一个函数。我想对其进行编译,然后在我的主要功能中,将该对象放到某个虚拟地址。
这是我在sharedfunction.c
中的共享功能
#include <stdio.h>
int dummy;
void sharedfunction(int x){
if(x){
dummy &= x;
}
}
我使用以下命令对其进行了编译:gcc -c -fPIC sharedfunction.c -o sharedfunction.o
现在,我想将此对象放到我的主要功能中的某个虚拟地址。
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define pagesize 4096UL
#define handle_error(msg) \
do { perror(msg); exit(EXIT_FAILURE); } while (0)
int main() {
void *p = main;
printf("main:%p\n", p);
int fd;
struct stat sb;
off_t offset, pa_offset;
fd = open("sharedfunction.o", O_RDONLY);
if(fd == -1)
handle_error("open");
if (fstat(fd, &sb) == -1) /* To obtain file size */
handle_error("fstat");
offset = 0;
pa_offset = offset & ~(sysconf(_SC_PAGE_SIZE) - 1);
/* offset for mmap() must be page aligned */
if (offset >= sb.st_size) {
fprintf(stderr, "offset is past end of file\n");
exit(EXIT_FAILURE);
}
// want to put main + 0x10_000 virtual address
void* func = mmap(
(void*) (p + 0x10000),
pagesize,
PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_PRIVATE,
fd, pa_offset);
if (func == MAP_FAILED)
handle_error("mmap");
// how can I call this?
func(10);
return 0;
}
我正在使用:gcc -O0 main.c -o main.o
func
? func
完成后如何清除内存?