Reputation: 7510
I'm trying to use address sanitizer using (-fsanitize=address
) and I'm not sure if it belongs into CFLAGS or LDFLAGS. It actually seems to work fine when added just to LDFLAGS, but I do not know if that is a coincidence or if it is supposed to be like that.
Is -fsanitize=address
needed for the compilation itself, or does it suffice to provide the flag for the linking step?
Upvotes: 3
Views: 2145
Reputation: 213754
Is -fsanitize=address needed for the compilation itself, or does it suffice to provide the flag for the linking step?
Address Sanitizer instruments source code to insert additional checks, and so must be present at compilation time.
Providing the argument only on the link line results in asan runtime being linked into the process, but no checks being actually done, except for a small subset -- namely the checks achievable by interposing new
delete
, malloc
, free
, and other standard functions.
Example:
1 #include <malloc.h>
2 #include <stdio.h>
3
4 void fn(int *ip)
5 {
6 ip[0] = 1; // BUG: heap buffer overflow
7 }
8
9 int main()
10 {
11 int *ip = malloc(1); // Allocation too small.
12 printf("%d\n", ip[0]); // BUG: heap buffer overflow
13 free(ip);
14 free(ip); // BUG: double free
15 }
With no instrumentation, only the double-free is detected:
gcc -g -c t.c && gcc -fsanitize=address t.o && ./a.out
190
=================================================================
==55787==ERROR: AddressSanitizer: attempting double-free on 0x602000000010 in thread T0:
With instrumentation: both the bug in printf
and the bug in fn
are also detected.
gcc -g -c -fsanitize=address t.c && gcc -fsanitize=address t.o && ./a.out
=================================================================
==58202==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000010 at pc 0x564565639252 bp 0x7ffe36b0a560 sp 0x7ffe36b0a558
READ of size 4 at 0x602000000010 thread T0
#0 0x564565639251 in main /tmp/t.c:12
Upvotes: 4