Reputation: 1349
I'm trying to hook some functions of glibc, like fopen, fread etc. But in the hook function, i have to use the same function as in glibc. Like this:
// this is my fopen
FILE *fopen(.....)
{
fopen(....);// this is glibc fopen
}
I have found one way to do this using dlsym, but in this way i have to replace all the glibc function calls with wrappers inside which call glibc function using dlsym. I'm curious whether where is another way to do the same job without coding wrapper functions. I ever tryed this :
fopen.c
....fopen(..)
{
myfopen(..);
}
myfopen.c
myfopen(..)
{
fopen(...);// glibc version
}
main.c
int main()
{
fopen(...);
}
$ gcc -c *.c
$ gcc -shared -o libmyopen.so myopen.o
$ gcc -o test main.o fopen.o libmyopen.so
In my understanding, gcc will link from left to right as specified in the command line, so main.o will use fopen in fopen.o, fopen.o will use myfopen in libmyfopen.so, libmyfopen.so will use fopen in glibc. But when running, i got a segment fault, gdb shows there is a recusive call of fopen and myfopen. I'm a little confused. Can anyone explain why ?
Upvotes: 2
Views: 1556
Reputation: 213799
my understanding, gcc will link from left to right as specified in the command line, so main.o will use fopen in fopen.o, fopen.o will use myfopen in libmyfopen.so, libmyfopen.so will use fopen in glibc
Your understanding is incorrect. The myfopen
from libmyfopen.so
will use the first definition of fopen
available to it. In your setup, that definition will come from fopen.o
linked into the test
program, and you'll end up with infinite recursion, and a crash due to stack exhaustion.
You can observe this by running gdb ./test
, running until crash, and using backtrace
. You will see an unending sequence of fopen
and myfopen
calls.
the symbol fopen is not bond to that in libc when compiling
That is correct: in ELF
format, the library records that it needs the symbol (fopen
in this case) to be defined, but it doesn't "remember" or care which other module defines that symbol.
You can see this by running readelf -Wr libmyfopen.so | grep fopen
.
That's different from windows DLL.
Yes.
Upvotes: 3