Invoking a function (main()) from a binary file in C
Posted
by
Dhara Darji
on Stack Overflow
See other posts from Stack Overflow
or by Dhara Darji
Published on 2012-09-13T15:36:20Z
Indexed on
2012/09/13
15:37 UTC
Read the original article
Hit count: 239
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;
}
PS: I went through some tutorial, for how to read binary file and execute.
But this gives Seg fault, any help appreciated! Thanks!
© Stack Overflow or respective owner