This is the mail archive of the crossgcc@sourceware.org mailing list for the crossgcc project.

See crosstool-NG for lots more information.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: How can I modify the source of new,malloc


On 26.06.2012 22:14, Yann E. MORIN wrote:

> As Mirko suggested, I'd use a loader trick to pre-load a shared lib that
> overrides the malloc() and free() functions. Something like (untested!):
> 
> void* malloc( size_t size )
> {
>     static void* real_malloc;
> 
>     if( ! real_malloc ) {
>         real_malloc = dlsym( RTLD_NEXT, "malloc" );
>         if( ! real_malloc ) {
>             panic_and_exit();
>         }
>     }
>     fprintf( stderr, "Allocating %d bytes\n", size );
>     return real_malloc( size );
> }
> 
> Then, replacing printf with calls to backtrace(3) and backtrace_symbols_fd(3),
> you can know the caller (function, offset), if you have the debug symbols in
> the binaries (libs and executable), in which case you can post-process that
> to find the actual  file, function and line at which the call to malloc is
> made.
> 
> (Note: do not use backtrace_symbols(3), as it calls malloc! So you have
> to use backtrace_symbols_fd(3)).
> 
> Then, you can write such wrappers to free(3) and so on...

Also note that if you wrap calloc() like malloc() above, you will run
into the problem that dlsym calls calloc (at least on all the Linux
systems I have tested on). What I do is to load the pointers to the real
functions in a special initialization function that is marked with the
"constructor" attribute, and call sbrk() instead of the real calloc if
the pointer to the real calloc hasn't been defined yet.

> Note however, that if you can recompile your application, you may want to
> link with a library like DUMA or dmalloc instead of using the above trick.
>   http://duma.sourceforge.net/
>   http://dmalloc.com/

If you really want to go down the wrapper route, I can send you my
wrapper off-list as a starting point. It currently prints out how much
memory was requested (and tracks all allocations, so it can tell you
about possible memory leaks on exit), but since I didn't know about
backtrace(3) and friends it doesn't show you where the call came from (yet).
-- 
Dr. Eric Dönges                            doenges@mvtec.com
MVTec Software GmbH | Neherstr. 1 | 81675 München  | Germany
www.mvtec.com | Tel: +49 89 457695-0 | Fax: +49 89 457695-55
Geschäftsführer: Dr. Wolfgang Eckstein, Dr. Olaf Munkelt
Amtsgericht München HRB 114695



--
For unsubscribe information see http://sourceware.org/lists.html#faq


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]