I have a simple c program, my_bin.c:
#include <stdio.h> int main() { printf("Success!\n"); return 0; }
I compile it with gcc and get the executable: my_bin.
Now I want to call main (or run this my_bin) using another C program. I did this with mmap and the function pointer as follows:
#include <stdio.h> #include <fcntl.h> #include <sys/mman.h> int main() { void (*fun)(); int fd; int *map; fd = open("./my_bin", O_RDONLY); map = mmap(0, 8378, PROT_READ, MAP_SHARED, fd, 0); fun = map; fun(); return 0; }
EDIT 1: PROT_EXEC added Due to a clearer answer from the answers ... I want to call an external binary program in a second program.
I do not know how to initialize a function pointer with the address main (other programs). any idea?
EDIT 2:
Why seg fault, after googling, understood, due to my size and mmap offset argument. It should be a multiple of the number of pages. [Link: Segfault when using mmap in C to read binary files
Now the code looks like this:
#include <stdio.h> #include <fcntl.h> #include <sys/mman.h> int main() { void (*fun)(); int fd; int *map; int offset = 8378; int pageoffset = offset % getpagesize(); fd = open("./my_bin", O_RDONLY); if(fd == -1) { printf("Err opening file\n"); return -1; } map = mmap(0, 8378 + pageoffset, PROT_READ|PROT_EXEC, MAP_SHARED, fd, offset - pageoffset); perror("Err\n"); //This is printing err and Success! //fun = map; // If I uncomment this and //fun(); // this line then, still it // print err and Success! from perror // but later it says Illegal instruction. return 0; }
Still with fun () or without it does not print ... not sure how to specify the address of main ().
Edit 2 [SOLVED]:
First: I didnโt read the definition correctly, I already gave the address from which I should read the binary. Secondly: mmap: size and offset should be a multiple of the page size.