LD_PRELOAD

下面的helloworld会在屏幕上打印出什么内容?

1
2
3
4
5
6
#include <stdio.h>
int main(int argc, char* argv[], char* env[])
{
    printf("Hello World! ");
    return 0;
}

肯定是“Hello World!”,不是吗?下面我们来个托梁换柱:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
preload.c
#include <stdio.h>
#include <ctype.h>
 
int puts(const char *s)
{
    const char* p = s;
    while(*p != '')
    {
        putc(toupper(*p), stdout);
        p++;
    }
    return 0;
}

编译:

gcc -g -shared preload.c -o libpreload.so

按下列方式运行helloworld:

LD_PRELOAD=./libpreload.so ./helloworld

屏幕打印:

HELLO WORLD!

设置环境变量LD_PRELOAD之后,打印的内容变成大写了!原来,LD_PRELOAD指定的

共享库被预先加载,如果出现重名的函数,预先加载的函数将会被调用。通过这种方法,我

们可以在不需要修改源代码(有时候可能没有源代码)的情况下,来改变一个程序的行为。

原文地址:https://www.cnblogs.com/solohac/p/4154199.html