DreamLinuxer
DreamLinuxer

Reputation: 371

Custom memory manager with thread local storage

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 ??

Upvotes: 6

Views: 403

Answers (2)

ugoren
ugoren

Reputation: 16441

You can change your memory manager to use mmap instread of brk.

There can be only one user of brk in a process. So if you haven't replaced all calls to malloc and related functions (calloc, strdup and more), you must not use brk.

mmap, however, has no such problems. Your memory manager can use mmap, and malloc can still work in parallel.

Upvotes: 0

iabdalkader
iabdalkader

Reputation: 17312

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

Upvotes: 2

Related Questions