Enable mtrace (MALLOC_TRACE) for binary program

安稳与你 提交于 2019-11-30 07:39:47

问题


How can I enable mtrace() (and MALLOC_TRACE env) for a binary program without sources?

mtrace is feature of glibc: http://www.gnu.org/s/hello/manual/libc/Allocation-Debugging.html

Thanks


回答1:


mtrace.c

#include <mcheck.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>


void __mtracer_on () __attribute__((constructor));
void __mtracer_off () __attribute__((destructor));
void __mtracer_on ()
{
    char *p=getenv("MALLOC_TRACE");
    char tracebuf[1023];
    if(!p)
        p="malloc_trace";
    sprintf(tracebuf, "%s.%d", p, getpid());
    setenv("MALLOC_TRACE",tracebuf, 1);
    atexit(&__mtracer_off);
    mtrace();
}

void __mtracer_off ()
{
    muntrace();
}

Compile with gcc mtrace.c -fPIC -shared -o libmmtrace.so

Run with

MALLOC_TRACE=echo LD_PRELOAD=./libmmtrace.so /bin/echo 42

or

LD_PRELOAD=./libmmtrace.so /bin/echo 42

Is it ok for you?



来源:https://stackoverflow.com/questions/2593284/enable-mtrace-malloc-trace-for-binary-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!