I have simple c program like, my_bin.c:
#include <stdio.h>
int main()
{
printf("Success!\n");
return 0;
}
I compile it with gcc and got executable: my_bin.
Now I want to invoke main (or run this my_bin) using another C program. That I did with mmap and function pointer like this:
#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: added PROT_EXEC Making it more clear from responses ... I want to call an external binary program within second program.
I don't know how to initialize function pointer with the address of main(other program's). any idea?
EDIT 2:
Why seg fault, after googling, figured out, its because of my size and offset argument of mmap. It should be multiple of pagesize. [Reference: Segfault while using mmap in C for reading binary files
Now the code looks like:
#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 that its not printing ... not sure how to give main() address.
Edit 2[Solved]:
First thing: I didn't read definition properly, I have already given address from which I should read binary file. Second: mmap: size and offset should be multiple of pagesize.