Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom memory manager with thread local storage

Tags:

c++

c

There is a custom memory manager in our program, all of our malloc/free calls are managed by the memory manager, but in the initial of the program getpwuid() will be call and in some customers' machine with nss_ldap activated it will call the malloc from libc not from our memory manager which leads to an error in our memory manager, the stack report from gdb is:

Breakpoint 2, 0x0000003df8cc6eb0 in brk () from /lib64/libc.so.6
0  0x0000003df8cc6eb0 in brk () from /lib64/libc.so.6
1  0x0000003df8cc6f72 in sbrk () from /lib64/libc.so.6
2  0x0000003df8c73d29 in __default_morecore () from /lib64/libc.so.6
3  0x0000003df8c70090 in _int_malloc () from /lib64/libc.so.6
4  0x0000003df8c70c9d in malloc () from /lib64/libc.so.6
5  0x0000003df880fc65 in __tls_get_addr () from /lib64/ld-linux-x86-64.so.2
6  0x00002aaaae302a7c in _nss_ldap_inc_depth () from /lib64/libnss_ldap.so.2
7  0x00002aaaae2f91a4 in _nss_ldap_enter () from /lib64/libnss_ldap.so.2
8  0x00002aaaae2f942c in _nss_ldap_getbyname () from /lib64/libnss_ldap.so.2
9  0x00002aaaae2f9aa9 in _nss_ldap_getpwuid_r () from /lib64/libnss_ldap.so.2
10 0x0000003df8c947c5 in getpwuid_r@@GLIBC_2.2.5 () from /lib64/libc.so.6
11 0x0000003df8c9412f in getpwuid () from /lib64/libc.so.6
12 0x0000000001414be3 in lc_username ()

I've traced the code of _nss_ldap_inc_depth(), it seems the __tls_get_addr() got call because the thread local storage is used, I've try to change the memory manager to shared library but the __tls_get_addr() still call the malloc from libc, how can I made it call our memory manager instead of libc's ??

like image 225
DreamLinuxer Avatar asked Nov 21 '12 07:11

DreamLinuxer


1 Answers

You can use LD_PRELOAD to load your library before any other library (including glibc) and it will be linked instead, something like:

$ LD_PRELOAD=/path/to/library/libmymalloc.so /bin/myprog

There's a tutorial here that shows how it works, it even has an example interposed malloc

like image 187
iabdalkader Avatar answered Nov 19 '22 20:11

iabdalkader