使用dlsym()的RTLD_NEXT来实现库函数拦截
int __thread (*_open)(const char * pathname, int flags, ...) = NULL;
int open(const char * pathname, int flags, mode_t mode)
{
if (NULL == _open) {
_open = (int (*)(const char * pathname, int flags, ...)) dlsym(RTLD_NEXT, "open");
}
printf("intercepted open: %s\n",pathname);
if(flags & O_CREAT)
return _open(pathname, flags | O_NOATIME, mode);
else
return _open(pathname, flags | O_NOATIME, 0);
}
编译 gcc -fPIC -c -o library_calls_hook.o library_calls_hook.c
evn LD_PRELOAD=./library_calls_hook.so ./test
这样 你的test 中的open 函数就被 library_calls_hook.so 中的替换了
那这个原理是什么呢?
这里主要是 linux 在动态库查询时遵循如下规则:
LD_PRELOAD > LD_LIBRARY_PATH > /etc/ld.so.cache > /lib > /usr/lib
所以你env 带库运行时 库函数总会被替换.
dlsym(RTLD_NEXT, "open") 这句话时动态 查找下一个出现的函数.
通过这两部我们就实现了 库函数拦截