When it comes to native development, it’s important to have a proper toolset to debug. In 2012 Google introduces a class of tools called code sanitizer to detect program bugs. The first tool was the address sanitizer enabled memory corruption detection by using shadow memory. Though some sanitizers are available out of the Android scope, our focus will be on Android sanitizer. In continuation, I will try to cover the available sanitizers in Android and give you a big picture of what they do.
Address Sanitizer (ASan)
ASan is a compile-based tool introduced with Android O (API level 27) running on both ARM and X86 architecture (32-bit & 64-bit) to detect memory bugs such as:
- Stack and heap buffer overflow/underflow
- Heap use after free
- Stack use outside scope
- Double free/wild free
Just notice that it does not support Java/Kotlin applications but can be enabled in the JNI libraries. But then it will have an overhead that does not work on devices with only 2GB memory.
Enabling ASan leads to having an overhead on code size, memory usage and performance. The code size can be increased between 50% to 2X, the CPU overhead will be about 2X and memory usage is at least 2X based on your memory allocation pattern.
Android.bp
cc_binary{
...
sanitize: ["address"],
...
}
Android.mk
...
LOCAL_SANITIZE := address
...
There some parameters can be sent to Android Adress Sanitizer through sanitize_extra_flags :
- detect_leaks
- halt_on_error
- alloc_dealloc_mismatch
- check_initialization_order
- coverage
- fast_unwind_on_fatal
example
cc_binary {
...
sanitize: ["address"],
sanitize_extra_flags: [
"detect_leaks=1",
"fast_unwind_on_fatal=1",
],
...
}
HWAddress Sanitizer (HWASan)
HWAsan is introduced in Android 10 (API 29) and NDKr21 which only supports ARM 64-bit. In favour of that ASan os is deprecated for ARM 64-bit in Android 11. HWAsan supports similar detection tools/features with some exceptions:
- Much smaller memory overhead (10% – 35%) compared to ASan.
- Stack use after return. (The extra detection)
Android.bp
cc_binary {
...
sanitize: ["hwaddress"],
...
}
or
cc_binary {
...
sanitize: {
hwaddress: true,
},
...
}
Android.mk
...
LOCAL_SANITIZE := hwaddress
...
There are some flags that can be used with HWAsan:
- detect_container_overflow
- detect_stack_use_after_return
- fast_unwind_on_fatal
- log_path
- max_history_size
- report_globals
- verbosity
example
...
sanitize: {
hwaddress: true,
extra_flags: [
"detect_container_overflow=0",
"detect_stack_use_after_return=1",
],
},
...
Good article , giving a good introduction to the sanitizers in Android.
Tried enabling the HWaddress sanitizer with extra flags as mentioned above.
But the compilation fails with the error:
Undefined property “sanitize.extra_flags” .
Do you have any suggestions ? I am using Android.bp for my compilation.
Which Android version are you trying to build?
Could you provide what you added to enable it?