linux中环境变量LD_PRELOAD是怎样工作的?

A Simple LD_PRELOAD Tutorial

有的时候为了研究需要,我们需要重载C的标准库函数,比如printf,fopen等等,这篇文章介绍如何利用LD_PRELOAD这个环境变量实现这个目标。

首先由一个简单的C程序开始。(prog.c)

 

#include <stdio.h>

int main(void) {
    printf("Calling the fopen() function...\n");

    FILE *fd = fopen("test.txt","r");
    if (!fd) {
        printf("fopen() returned NULL\n");
        return 1;
    }

    printf("fopen() succeeded\n");

    return 0;
}


这段程序简单地调用了fopen函数并检查返回值。

下面编译执行以下

$ ls
prog.c  test.txt

$ gcc prog.c -o prog

$ ls
prog  prog.c  test.txt

$ ./prog
Calling the fopen() function...
fopen() succeeded

可以看到调用标准库函数成功。

然后我们编写自己的fopen替代libc库函数中的fopen

#include <stdio.h>

FILE *fopen(const char *path, const char *mode) {
    printf("Always failing fopen\n");
    return NULL;
}


并且编译成共享库。

gcc -Wall -fPIC -shared -o myfopen.so myfopen.c
Now we can simply modify LD_PRELOAD:

$ LD_PRELOAD=./myfopen.so ./prog
Calling the fopen() function...
Always failing fopen
fopen() returned NULL


可以看到,调用失败,因为我们的共享库返回null。

总结

我们如果需要调试或者使用我们自己的函数来代替libc库或者其他库的函数时,这个方法是可行的。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值