简体   繁体   English

使用LD_PRELOAD修复对malloc的递归调用

[英]fixing the recursive call to malloc with LD_PRELOAD

I am using LD_PRELOAD to log malloc calls from an application and map out the virtual address space however malloc is used internally by fopen/printf. 我正在使用LD_PRELOAD记录来自应用程序的malloc调用并映射出虚拟地址空间,但是fopen / printf内部使用了malloc。 Is there a way I can fix this issue? 有什么办法可以解决此问题?

I know about glibc's hooks but I want to avoid changing the source code of the application. 我知道glibc的钩子,但我想避免更改应用程序的源代码。

My issue was caused by the fact that malloc is used internally by glibc so when I use LD_PRELOAD to override malloc any attempt to log caused malloc to be called resulting in a recursive call to malloc itself 我的问题是由glibc在内部使用malloc引起的,因此当我使用LD_PRELOAD覆盖malloc时,任何尝试记录的尝试都会导致malloc被调用,从而导致对malloc本身的递归调用

Solution: call original malloc whenever the TLS needs memory allocation providing code: 解决方案:每当TLS需要内存分配时,调用原始malloc并提供以下代码:

 static __thread int no_hook; static void *(*real_malloc)(size_t) = NULL; static void __attribute__((constructor))init(void) { real_malloc = (void * (*)(size_t))dlsym(RTLD_NEXT, "malloc"); } void * malloc(size_t len) { void* ret; void* caller; if (no_hook) { return (*real_malloc)(len); } no_hook = 1; caller = (void*)(long) __builtin_return_address(0); printf("malloc call %zu from %lu\\n", len, (long)caller); ret = (*real_malloc)(len); // fprintf(logfp, ") -> %pn", ret); no_hook = 0; return ret; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM