My objective is to hook the open function that dlopen on linux uses. For some reason, this code is not hooking dlopen->open, but it does hook my version of open main.c->open. Is dlopen not using my symbols somehow?
Compilation process is as follows:
gcc main.c -ldl -ggdb
gcc fake-open.c -o libexample.so -fPIC -shared
export LD_PRELOAD="$PWD/libexample.so"
When I run the program, everything works. Ensuring the LD_PRELOAD variable is set.. etc.
Here is the problem, when I try to hook the open function directly or indirectly called by dlopen, somehow this "version" of open is not being resolved/redirected/hooked by my version.
[main.c]
#include <dlfcn.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
puts("calling open");
int fd = open("/tmp/test.so", O_RDONLY|O_CLOEXEC);
puts("calling dlopen");
int *handle = dlopen("/tmp/test.so", RTLD_LAZY);
}
[fake-open.c]
#define _GNU_SOURCE
#include <stdio.h>
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/stat.h>
//#include <fcntl.h>
int open(const char *pathname, int flags)
{
puts("from hooked..");
return 1;
}
Console Output:
calling open
from hooked..
calling dlopen
I know for a fact dlopen is somehow calling open due to strace.
write(1, "calling open\n", 13calling open
) = 13
write(1, "from hooked..\n", 14from hooked..
) = 14
write(1, "calling dlopen\n", 15calling dlopen
) = 15
brk(0) = 0x804b000
brk(0x806c000) = 0x806c000
open("/tmp/test.so", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\2\0\3\0\1\0\0\0`\205\4\0104\0\0\0"..., 512) = 512
But, for some reason, when dlopen calls open, it is not using my version of open. This has to be some kind of linking of run time symbol resolution problem, or perhaps dlopen is using a static version of open and doesnt need to resolve any symbols at run or load time?