Chinaunix首页 | 论坛 | 博客
  • 博客访问: 228545
  • 博文数量: 31
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 296
  • 用 户 组: 普通用户
  • 注册时间: 2016-06-22 11:52
文章分类

全部博文(31)

文章存档

2018年(3)

2017年(11)

2016年(12)

2015年(5)

我的朋友

分类: C/C++

2018-02-09 18:39:54

LD_PRELOAD是unix下的一个环境变量,用来加载动态库的,动态库的加载顺序为LD_PRELOAD>LD_LIBRARY_PATH>/etc/ld.so.cache>/lib>/usr/lib。一般情况下,我们的程序都会用到很多库函数,只要是动态库的函数,都可以通过LD_PRELOAD 来让程序优先调用自定义的库函数,从而达到修改标准库函数的目的。下面的例子转载的:https://www.cnblogs.com/davad/p/4563478.html

测试代码test.c

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <string.h>

  3. int main(int argc, char *argv[])
  4. {
  5.     if( strcmp(argv[1], "test") )
  6.     {
  7.         printf("Incorrect password\n");
  8.     }
  9.     else
  10.     {
  11.         printf("Correct password\n");
  12.     }
  13.     return 0;
  14. }

自定义的库ldpreload.c

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <dlfcn.h>

  4. typedef int(*STRCMP)(const char*, const char*);

  5. int strcmp(const char *s1, const char *s2)
  6. {
  7.     static void *handle = NULL;
  8.     static STRCMP old_strcmp = NULL;

  9.     if( !handle )
  10.     {
  11.         handle = dlopen("libc.so.6", RTLD_LAZY);
  12.         old_strcmp = (STRCMP)dlsym(handle, "strcmp");
  13.     }
  14.     printf("hack function invoked. s1=<%s> s2=<%s>\n", s1, s2);
  15.     return old_strcmp(s1, s2);
  16. }


编译测试代码:gcc -o test test.c
编译自定义动态库:gcc -fPIC -shared -o ldpreload.so ldpreload.c

运行结果如下图,可以看出输出结果多了自定义的strcmp中的打印信息,如果想保留库函数原来的功能,只是想添加一些特殊的处理,可以像这个例子这么做,如果想完全改写库函数,就直接自定义一个同名同参数的库函数,然后用LD_PRELOAD 环境变量来控制调用就好了



阅读(2581) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~