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

来源:互联网 发布:人民币入篮 知乎 编辑:程序博客网 时间:2024/06/10 21:07

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函数并检查返回值。

下面编译执行以下

$ lsprog.c  test.txt$ gcc prog.c -o prog$ lsprog  prog.c  test.txt$ ./progCalling 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.cNow we can simply modify LD_PRELOAD:$ LD_PRELOAD=./myfopen.so ./progCalling the fopen() function...Always failing fopenfopen() returned NULL


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

总结

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

 

原创粉丝点击