linux c 如何拦截库函数 来做统计

文章介绍了如何在Linux中利用dlsym函数的RTLD_NEXT标志来拦截并替换动态库中的open函数。通过创建一个共享对象(library_calls_hook.so),并在环境变量LD_PRELOAD中指定,可以使得在执行程序(test)时,其open函数调用被hook函数替代,从而实现对文件创建时添加额外属性的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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") 这句话时动态 查找下一个出现的函数.

通过这两部我们就实现了 库函数拦截

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值