How to Use AddressSanitizer (ASan)

Memory bugs in C and C++ often do not crash at the point of the error. A use-after-free can corrupt data and crash much later in unrelated code. AddressSanitizer (ASan) is a compiler-based tool that detects these bugs at the faulting memory access. GCC and Clang both support it. This post shows how to enable ASan, read its report, and use it with GDB.

Advantages of ASan

AdvantageDescription
Early detectionASan reports the first invalid memory access when it occurs.
Detailed reportThe report shows the error type, the address, and the stack traces of the access, allocation, and free.
Low overheadA typical slowdown is about 2x. This is much faster than tools such as Valgrind, so you can run full test suites with it.

Memory errors that ASan detects

How ASan works

  1. Instrumentation: At compile time, the compiler instruments each memory access with a check.
  2. Shadow memory: ASan maps application memory to shadow memory. Each shadow byte records whether 8 bytes of application memory are addressable.
  3. Runtime check: On each load or store, the instrumented code checks the shadow memory. If the address is poisoned, ASan reports the error and terminates the program.
  4. Error report: ASan prints the error type, the memory address, and the stack traces.

How to use ASan

To enable ASan, compile and link with the -fsanitize=address flag.

$ gcc -o my_program -fsanitize=address my_program.c

Then run the program. If ASan finds a memory error, it prints a report and exits.

Use-after-free example

This program reads from a heap buffer after it frees the buffer.

#include <stdlib.h>
int main() {
  char *x = (char*)malloc(10 * sizeof(char*));
  free(x);
  return x[5];
}

Compile it with -fsanitize=address. Add -fno-omit-frame-pointer to get better stack traces.

$ gcc use-after-free.c -fsanitize=address -fno-omit-frame-pointer

Result

The report shows a heap-use-after-free error, the faulting address, and the stack traces where the memory was allocated and freed.

AddressSanitizer heap-use-after-free report

Using ASan with GDB

You can debug an ASan-instrumented binary with GDB as usual. When ASan finds a bug, it calls one of the __asan_report_{load,store}{1,2,4,8,16} functions. These functions then call __asan::ReportGenericError.

When to stopMethod
Before ASan prints the reportSet a breakpoint on __asan::ReportGenericError.
After ASan prints the reportSet a breakpoint on __sanitizer::Die, or run the binary with ASAN_OPTIONS=abort_on_error=1.

In GDB, you can ask ASan to describe a memory address.

(gdb) set overload-resolution off
(gdb) p __asan_describe_address(0x7ffff73c3f80)
0x7ffff73c3f80 is located 0 bytes inside of 10-byte region [0x7ffff73c3f80,0x7ffff73c3f8a)
freed by thread T0 here: 
...

References

Leave a Reply