覆盖使用LD_ preLOAD机制'的malloc“ [英] Overriding 'malloc' using the LD_PRELOAD mechanism
问题描述
我想写日志会调用malloc的到stderr(一种'命令mtrace如果你愿意的)一个简单的共享库。
I'm trying to write a simple shared library that would log malloc calls to stderr (a sort of 'mtrace' if you will).
但是,这是行不通的。
这是我做的:
However, this is not working. Here's what I do:
/* mtrace.c */
#include <dlfcn.h>
#include <stdio.h>
static void* (*real_malloc)(size_t);
void *malloc(size_t size)
{
void *p = NULL;
fprintf(stderr, "malloc(%d) = ", size);
p = real_malloc(size);
fprintf(stderr, "%p\n", p);
return p;
}
static void __mtrace_init(void) __attribute__((constructor));
static void __mtrace_init(void)
{
void *handle = NULL;
handle = dlopen("libc.so.6", RTLD_LAZY);
if (NULL == handle) {
fprintf(stderr, "Error in `dlopen`: %s\n", dlerror());
return;
}
real_malloc = dlsym(handle, "malloc");
if (NULL == real_malloc) {
fprintf(stderr, "Error in `dlsym`: %s\n", dlerror());
return;
}
}
我编译这个用:
gcc -shared -fPIC -o mtrace.so mtrace.c
,然后当我尝试执行 LS
:
$ LD_PRELOAD=./mtrace.so ls
malloc(352) = Segmentation fault
现在,我怀疑的dlopen需求的malloc,和我共享库中重新定义它,它使用该版本的还是未分配 real_malloc
。
Now, I suspect that dlopen needs malloc, and as I am redefining it within the shared library, it uses that version with the still unassigned real_malloc
.
现在的问题是...我怎么做工作?
The question is...how do I make it work?
P.S。对不起,在标签的缺乏,我找不到合适的标签,我仍然没有足够的信誉来塑造新的。
P.S. sorry for the paucity in tags, I couldn't find appropriate tags, and I still don't have enough reputation to create new ones.
推荐答案
我总是这样说:
#define _GNU_SOURCE
#include <stdio.h>
#include <dlfcn.h>
static void* (*real_malloc)(size_t)=NULL;
static void mtrace_init(void)
{
real_malloc = dlsym(RTLD_NEXT, "malloc");
if (NULL == real_malloc) {
fprintf(stderr, "Error in `dlsym`: %s\n", dlerror());
}
}
void *malloc(size_t size)
{
if(real_malloc==NULL) {
mtrace_init();
}
void *p = NULL;
fprintf(stderr, "malloc(%d) = ", size);
p = real_malloc(size);
fprintf(stderr, "%p\n", p);
return p;
}
不要使用构造,就在第一次调用初始化的malloc
。使用 RTLD_NEXT
来避免的dlopen
。您也可以尝试的malloc挂钩。请注意,所有这些都是GNU扩展,并可能不会在其他地方工作。
Don't use constructors, just initialize at first call to malloc
. Use RTLD_NEXT
to avoid dlopen
. You can also try malloc hooks. Be aware that all those are GNU extensions, and probably wont work elsewhere.
这篇关于覆盖使用LD_ preLOAD机制'的malloc“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!