whitenoise

technology notes… mobile and embedded.

Posts Tagged ‘libc

Android HOWTOs : Memory leak debugging with libc

with one comment

Android’s  libc module provides a way to run in ‘debug’ mode.

In this mode it keeps track of allocated memory and also adds extra data to detect memory corruption /overflow. This tools is useful to debug issues related to memory corruptions and memory leaks too.

Before looking at using this tool it would be good to know the symptoms of a memory corruption/leak.

Symptoms:

Memory corruptions usually manifest as native crashes in dlfree or *alloc methods with invalid pointers like 0xdeadbaad . Here is sample call stack where you could suspect a heap memory corruption.

heap_corruption

 

In the above scenario the module calling calloc crashed as the heap is already corrupted. The next steps would be to enable libc memory debugging options to identify source of corruption.

Memory leaks usually trigger Out of Memory Java exceptions or will result in OOM killer invoked. The procrank and librank output will show high memory used by the application  (Assumption: The data was collected before the app/process was killed)

procrank_highmem

In the above scenario, com.android.foo.bar app has a lot of memory allocated. It is likely this app is leaking memory . We could use libc’s memory debug options to identify the source of leak.

Enabling the option:

The next step is to enable the debug options of libc.
On a rooted device , we could enable libc malloc debugging with following steps:

enable_libc

The libc would now run in debug mode and will track memory allocations and corruptions.

Debug level 10 is a good option to setup. It would detect both leaks and corruptions. See here for a complete list of debug levels. 

Now run the original use case that caused the crash/corruption. There would be extra logs from the libc module if there is corruption/leak.  Memory leaks will usually show the call stack of the allocation and the number of bytes leaked.

leak_signature

Memory corruptions will have a slightly different signature. Here is the log when the library detects corrupt heap.

corruption_signature

False Positives:

When using this mode we have to be aware of false positives too.

For e.g.: If an application was terminated abruptly (via ‘adb shell kill –9 <pid>’)  then memory that was not properly de allocated would be reported as ‘leaks’ by libc.

Likewise there could be false memory corruption logs if we use  memory optimization modules that manipulate the heap nodes.

However such false positives are very rare. Even if they occur ,they usually show up in generic modules (like Android shell) which could not be suspected to have leaks.

Advertisements

Written by sujai

October 14, 2013 at 6:53 pm

%d bloggers like this: