Search code examples
gccfuzzingsanitizeraddress-sanitizer

Enable AddressSanitizer by default in gcc


To be able to debug and fuzz a whole Linux distribution, I would like to set ASAN (AddressSanitizer, https://en.wikipedia.org/wiki/AddressSanitizer) as default option to gcc. So normally to achieve what I want, generally, I set the following variables before to compile a linux package:

CFLAGS="-fsanitize=address,undefined -Wformat -Werror=format-security -Werror=array-bounds -g" 
CXXFLAGS="-fsanitize=address,undefined -Wformat -Werror=format-security -Werror=array-bounds -g" 
LDFLAGS="-fsanitize=address,undefined"

and try to compile and run my code. I would like to have it default to gcc.

One option to do it is using spec files: https://gcc.gnu.org/onlinedocs/gcc/Spec-Files.html. However I didn't find a way to set a "catch all rules" to compile and link all my c/c++ code with AddressSanitizer.

My questions are:

  • Any example how to do it using spec files?
  • Is that the best approach to do it?
  • Any other alternative approach?

Solution

  • First of all, be sure to take a look at existing whole-distro Asan enablings in Tizen (also here) and Gentoo.

    In general there are two main approaches:

    • customize your build system to enable Asan by default, usually using CFLAGS and CXXFLAGS; this won't always work because many packages ignore them (I think that's what Hanno Boeck did in Gentoo)
    • replace /usr/bin/gcc, /usr/bin/g++ and /usr/bin/cc (and may x86_64-linux-gnu-gcc, x86_64-linux-gnu-g++) with wrappers which would add Asan flags and redirect calls to original executables (this is the approach we eventually took in Tizen and found it very successful)

    As a side note, I'd suggest to add the following options

    CFLAGS += -fsanitize-recover=address,undefined
    

    otherwise boot will fail at too early stages. Also look at suggested settings ASAN_OPTIONS in above links, it took people long time to figure them out.