There are times when you want to wrap a library function in order to provide some additional functionality. A common example of this is wrapping the standard library’s malloc() and free() so that you can easily track memory allocations in your program. While there are several techniques for wrapping library functions, one well-known method is using dlsym() with RTLD_NEXT to locate the wrapped function’s address so that you can correctly forward calls to it.


Problem

So what can go wrong? Let’s look at an example:

LibWrap.h

void* memAlloc(size_t s);
// Allocate a memory block of size 's' bytes.
void memDel(void* p);
// Free the block of memory pointed to by 'p'.

LibWrap.c

#define _GNU_SOURCE
#include <dlfcn.h>
#include "LibWrap.h" static void* malloc(size_t s) {
// Wrapper for standard library's 'malloc'.
// The 'static' keyword forces all calls to malloc() in this file to resolve
// to this functions.
void* (*origMalloc)(size_t) = dlsym(RTLD_NEXT,"malloc");
return origMalloc(s);
} static void free(void* p) {
// Wrapper for standard library's 'free'.
// The 'static' keyword forces all calls to free() in this file to resolve
// to this functions.
void (*origFree)(void*) = dlsym(RTLD_NEXT,"free");
origFree(p);
} void* memAlloc(size_t s) {
return malloc(s);
// Call the malloc() wrapper.
} void memDel(void* p) {
free(p);
// Call the free() wrapper.
}

Main.c

#include <malloc.h>
#include "LibWrap.h" int main() {
struct mallinfo beforeMalloc = mallinfo();
printf("Bytes allocated before malloc: %d\n",beforeMalloc.uordblks); void* p = memAlloc(57);
struct mallinfo afterMalloc = mallinfo();
printf("Bytes allocated after malloc: %d\n",afterMalloc.uordblks); memDel(p);
struct mallinfo afterFree = mallinfo();
printf("Bytes allocated after free: %d\n",afterFree.uordblks); return 0;
}

First compile LibWrap.c into a shared library:

$ gcc -Wall -Werror -fPIC -shared -o libWrap.so LibWrap.c

Next compile Main.c and link it against the libWrap.so that we just created:

$ gcc -Wall -Werror -o Main Main.c ./libWrap.so -ldl

Time to run the program!

$ ./Main
Bytes allocated before malloc: 0
Bytes allocated after malloc: 80
Bytes allocated after free: 0

So far, so good. No surprises. We allocated a bunch of memory and then freed it. The statistics returned by mallinfo() confirm this.

Out of curiosity, let’s look at ldd output for the application binary we created.

$ ldd Main
linux-vdso.so.1 => (0x00007fff1b1fe000)
./libWrap.so (0x00007fe7d2755000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fe7d2542000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fe7d217c000)
/lib64/ld-linux-x86-64.so.2 (0x00007fe7d2959000)

Take note of the relative placement of libWrap.so with respect to libc.so.6libWrap.socomes before libc.so.6. Remember this. It will be important later.

Now for fun, let’s re-compile Main.c with libc.so.6 explicitly specified on the command-line and coming before libWrap.so:

$ gcc -Wall -Werror -o Main Main.c /lib/x86_64-linux-gnu/libc.so.6 ./libWrap.so -ldl

Re-run:

$ ./Main
Bytes allocated before malloc: 0
Bytes allocated after malloc: 80
Bytes allocated after free: 80

Uh oh, why are we leaking memory all of a sudden? We de-allocate everything we allocate, so why the memory leak?

It turns out that the leak is occurring because we are not actually forwarding malloc() and free() calls to libc.so.6‘s implementations. Instead, we are forwarding them to malloc() and free() inside ld-linux-x86-64.so.2!

“What are you talking about?!” you might be asking.

Well, it just so happens that ld-linux-x86-64.so.2, which is the dynamic linker/loader, has its own copy of malloc() and free(). Why? Because ld-linux has to allocate memory from the heap before it loads libc.so.6. But the version of malloc/free that ld-linuxhas does not actually free memory!

[RTLD_NEXT] will find the next occurrence of a function in the search order after the current library. This allows one to provide a wrapper around a function in another shared library.But why does libWrap.so forward calls to ld-linux instead of libc? The answer comes down to how dlsym() searches for symbols when RTLD_NEXT is specified. Here’s the relevant excerpt from the dlsym(3) man page:— dlsym(3)

To understand this better, take a look at ldd output for the new Main binary:

$ ldd Main
linux-vdso.so.1 => (0x00007fffe1da0000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f32c2e91000)
./libWrap.so (0x00007f32c2c8f000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f32c2a8a000)
/lib64/ld-linux-x86-64.so.2 (0x00007f32c3267000)

Unlike earlierlibWrap.so comes after libc.so.6. So when dlsym() is called inside libWrap.so to search for functions, it skips libc.so.6 since it precedes libWrap.so in the search order list. That means the searches continue through to ld-linux-x86-64.so.2where they find linker/loader’s malloc/free and return pointers to those functions. And so, libWrap.so ends up forwading calls to ld-linux instead of libc!

The answer is unfortunately no. At OptumSoft, we recently encountered this very same memory leak with a binary compiled using the standard ./configure && make on x86-64 Ubuntu 14.04.1 LTS. For reasons we don’t understand, the linking order for the binary was such that using dlsym() with RTLD_NEXT to lookup malloc/free resulted in pointers to implementations inside ld-linux. It took a ton of effort and invaluable help from Mozilla’s rr tool to root-cause the issue. After the whole ordeal, we decided to write a blog post about this strange behavior in case someone else encounters it in the future.At this point you might be wondering: We ran a somewhat funky command to build our application and then encountered a memory leak due to weird library linking order caused by said command. Isn’t this whole thing a silly contrived scenario?


Solution

If you find dlsym() with RTLD_NEXT returning pointers to malloc/free inside ld-linux, what can you do?

For starters, you need to detect that a function address indeed does belong to ld-linuxusing dladdr():

void* func = dlsym(RTLD_NEXT,"malloc");
Dl_info dlInfo;
if(!dladdr(func,&dlInfo)) {
// dladdr() failed.
}
if(strstr(dlInfo.dli_fname,"ld-linux")) {
// 'malloc' is inside linker/loader.
}

Once you have figured out that a function is inside ld-linux, you need to decide what to do next. Unfortunately, there is no straightforward way to continue searching for the same function name in all other libraries. But if you know the name of a specific library in which the function exists (e.g. libc), you can use dlopen() and dlsym() to fetch the desired pointer:

void* handle = dlopen("libc.so.6",RTLD_LAZY);
// NOTE: libc.so.6 may *not* exist on Alpha and IA-64 architectures.
if(!handle) {
// dlopen() failed.
}
void* func = dlsym(handle,"free");
if(!func) {
// Bad! 'free' was not found inside libc.
}

Summary

  • One can use dlsym() with RTLD_NEXT to implement wrappers around malloc() and free().
  • Due to unexpected linking behavior, dlsym() when using RTLD_NEXT can return pointers to malloc/free implementations inside ld-linux (dynamic linker/loader). Using ld-linux‘s malloc/free for general heap allocations leads to memory leaks because that particular version of free() doesn’t actually release memory.
  • You can check if an address returned by dlsym() belongs to ld-linux via dladdr(). You can also lookup a function in a specific library using dlopen() and dlsym().

From: http://optumsoft.com/dangers-of-using-dlsym-with-rtld_next/

[转] Dangers of using dlsym() with RTLD_NEXT的更多相关文章

  1. Android so 文件进阶<二> 从dlsym()源码看android 动态链接过程

    0x00  前言 这篇文章其实是我之前学习elf文件关于符号表的学习笔记,网上也有很多关于符号表的文章,怎么说呢,感觉像是在翻译elf文件格式的文档一样,千篇一律,因此把自己的学习笔记分享出来.dls ...

  2. 加载动态链接库——dlopen dlsym dlclose

    DLOPEN DLMOPEN DLCLOSE NAME     dlclose, dlopen, dlmopen - 打开/关闭共享对象 SYNOPSIS #include <dlfcn.h&g ...

  3. 采用dlopen、dlsym、dlclose加载动态链接库【总结】(转)

    1.前言 为了使程序方便扩展,具备通用性,可以采用插件形式.采用异步事件驱动模型,保证主程序逻辑不变,将各个业务已动态链接库的形式加载进来,这就是所谓的插件.linux提供了加载和处理动态链接库的系统 ...

  4. dlopen、dlsym和dlclose的使用

    在dlopen()函数以指定模式打开指定的动态链接库文件,并返回一个句柄给dlsym()的调用进程.使用dlclose()来卸载打开的库. dlopen: dlopen() The function ...

  5. 采用dlopen、dlsym、dlclose加载动态链接库【总结】

    摘自http://www.cnblogs.com/Anker/p/3746802.html 采用dlopen.dlsym.dlclose加载动态链接库[总结]   1.前言 为了使程序方便扩展,具备通 ...

  6. gcc编译出现dlopen、dlerror、dlsym、dlcolse的解决方法

      ➜  test_sqlite3 gcc *.c -I . -o xixi -pthread      /tmp/cckGKTrr.o: In function `unixDlOpen': sqli ...

  7. 【转】采用dlopen、dlsym、dlclose加载动态链接库

    1.前言 为了使程序方便扩展,具备通用性,可以采用插件形式.采用异步事件驱动模型,保证主控制逻辑不变,将各个业务以动态链接库的形式加载进来,这就是所谓的插件.linux提供了加载和处理动态链接库的系统 ...

  8. 用dlopen,dlsym加载动态链接库.so中函数

    代码如下 static void *findSymbol(const char *path, const char *symbol) { void *handle = dlopen(path, RTL ...

  9. the example of dlsym

    void *handle; int i, (*fptr)(int); /* open the needed object */ handle = dlopen("/usr/home/me/l ...

随机推荐

  1. Springbatch headerCallback 居然是在processor之前执行的

    今天遇到一个奇怪的问题,在一个step里有一个chunk,还有一个step的listener,这个listener实际上是一个headerCallback,这个headerCallback里面有一个@ ...

  2. 【Java】 剑指offer(25) 合并两个排序的链表

    本文参考自<剑指offer>一书,代码采用Java语言. 更多:<剑指Offer>Java实现合集   题目 输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照 ...

  3. fmod()函数 (对浮点数取模)

    头文件:#include <math.h> fmod() 用来对浮点数进行取模(求余),其原型为:    double fmod (double x); 设返回值为 ret,那么 x = ...

  4. python的random模块(生成验证码)

    python的random模块(生成验证码) random模块常用方法 random.random() #生成0到1之间的随机数,没有参数,float类型 random.randint(1, 3) # ...

  5. xadmin2.0(for Django2.0) 基本设置

    一.下载xadmin 1.使用安装工具安装: pip install git+git://github.com/sshwsfc/xadmin.git@django2 2.下载源码: git clone ...

  6. 玩转SpringCloud(F版本) 三.断路器(Hystrix)RestTemplate+Ribbon和Feign两种方式

    此文章基于: 玩转SpringCloud 一.服务的注册与发现(Eureka) 玩转SpringCloud 二.服务消费者(1)ribbon+restTemplate 转SpringCloud 二.服 ...

  7. 【Java】同步阻塞式(BIO)TCP通信

    TCP BIO 背景 网络编程的基本模型是Clien/Server模型,也就是两个进程之间进行相互通信,其中服务端提供位置信息(绑定的IP地址和监听端口),客户端通过连接操作向服务端监听的地址发起连接 ...

  8. python——设计模式

    设计模式是什么? 设计模式是经过总结.优化的,对我们经常会碰到的一些编程问题的可重用解决方案.一个设计模式并不像一个类或一个库那样能够直接作用于我们的代码.反之,设计模式更为高级,它是一种必须在特定情 ...

  9. 潭州课堂25班:Ph201805201 redis第四课 (课堂笔记)

    redis支持丰富的数据类型, 是个非关系型数据库.以键值对存储,存在内存里, : string. 字符 list.   列表 set. 集合 zset(sorted set). 有序集合 hash ...

  10. [BZOJ4987]Tree

    题目大意: 给定一棵\(n(n\le3000)\)个点的带边权的树,找出\(k\)个点\(A_{1\sim k}\)使得\(\sum_{1\le i<k} dis(A_i,A_i+1)\)最小. ...