Android memory leak detection

转自 http://letsgoustc.spaces.live.com/Blog/cns!89AD27DFB5E249BA!1687.entry

 

学习了,以备后查

 

Android provides memory leak detection capability in its bionic implementation. The topic is about how to use this feature in our native application or library.

 

When you compiled Android source code, you will get two bionic libc dynamic libraries. One is libc.so, another is libc_debug.so. For enabling detecting memory leak, we should first replace libc.so with libc_debug.so in the Android rootfs.

In libc_debug.so, Android provides two hidden APIs for memory leak detection. Here are these two APIs and its description:

/*
 * Retrieve native heap information.
 *
 * "*info" is set to a buffer we allocate
 * "*overallSize" is set to the size of the "info" buffer
 * "*infoSize" is set to the size of a single entry
 * "*totalMemory" is set to the sum of all allocations we're tracking; does
 *   not include heap overhead
 * "*backtraceSize" is set to the maximum number of entries in the back trace
 */

void get_malloc_leak_info(uint8_t** info, size_t* overallSize, size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
void free_malloc_leak_info(uint8_t* info);

 

So we can call get_malloc_leak_info twice, one is at the beginning of the program(eg, main entry) and another is at the end of program. Then we can compare these two outputs to get the difference. If any difference is met, it means some memory leak.

 

This method can also detect C++ new/delete memory leak because in bionic new/delete is based on malloc/free.

 

If you want to know how bionic implement this feature, you can refer to bionic/libc/bionic/memory_leak.c

If you want to know how to use this feature, you can refer to frameworks/base/media/libmediaplayerservice/MediaPlayerService.cpp.

You can also get memory usage information for media player service like this:

#dumpsys media.player -m

你可能感兴趣的:(android,service,application,buffer,include,leak)