Your Toolkit: Sanitizers, gdb and checksec
A memory bug rarely announces itself. The program writes one byte too many, the byte lands in padding, and everything keeps working until a different input moves the layout. To study these bugs you need tools that turn silent corruption into a loud, precise report. This lesson introduces the four the course uses everywhere and teaches you to read a sanitizer report from the top, line by line.
The tools
| Tool | Build or run | Finds | Cost |
|---|---|---|---|
| AddressSanitizer (ASan) | -fsanitize=address (gcc, clang, MSVC /fsanitize=address) |
out-of-bounds on heap, stack and globals; use-after-free; double free; use after return/scope | ~2x time, ~3x memory |
| LeakSanitizer (LSan) | on with ASan on Linux; alone with -fsanitize=leak |
memory never freed at exit | small |
| UndefinedBehaviorSanitizer (UBSan) | -fsanitize=undefined |
signed overflow, bad shifts, out-of-bounds index of an array of known size, misaligned or null pointers, invalid enum and bool values, bad casts (vptr) |
small |
| MemorySanitizer (MSan) | clang only, -fsanitize=memory |
reads of uninitialised memory | ~3x; every library must be instrumented |
| ThreadSanitizer (TSan) | -fsanitize=thread |
data races | 5-15x time |
| gdb | -g for symbols; gdb -q -batch -ex … |
where things are in memory; registers and frames at a breakpoint | none at build |
| checksec | checksec --file=prog |
which build-time mitigations a binary has | none |
ASan, MSan and TSan can't be combined in one build: each owns a different "shadow memory" layout. The usual CI matrix has one ASan+UBSan build, one TSan build and, with clang, one MSan build.
How ASan works, in one paragraph. For every 8 bytes of application memory, ASan keeps one shadow byte: 00 means all 8 bytes may be used, 01–07 means only the first k bytes may, and negative values (fa, fd, f1…) mean "poisoned" with a reason. Around every heap block, stack array and global, the compiler adds red zones that are poisoned, and before every load and store it inserts a check of the shadow byte. free poisons the block (fd) and keeps it in a quarantine for a while, so a later use of it is caught. The first bad access prints a report and stops the program.
Reading an ASan report
The toy program sums an array of four scores but loops with <=. The session runs in your sandbox. Addresses change on every run, so they are masked when the session is verified; offsets, sizes, line numbers and the shadow bytes are stable. The long legend at the end is cut with sed:
cat > scores.c <<'SRC'
#include <stdio.h>
#include <stdlib.h>
int total(const int *v, int n) {
int sum = 0;
for (int i = 0; i <= n; i++) /* BUG: <= reads one past the end */
sum += v[i];
return sum;
}
int main(void) {
int *scores = malloc(4 * sizeof(int));
for (int i = 0; i < 4; i++) scores[i] = 10 * (i + 1);
printf("total = %d\n", total(scores, 4));
free(scores);
return 0;
}
SRC
gcc -g -O0 -fsanitize=address,undefined scores.c -o scores
./scores 2>&1 | sed '/Shadow byte legend/,$d'
echo "exit code: ${PIPESTATUS[0]}"=================================================================
==15==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x502000000020 at pc 0x5d2868098394 bp 0x7fff36710780 sp 0x7fff36710770
READ of size 4 at 0x502000000020 thread T0
#0 0x5d2868098393 in total /home/learner/scores.c:7
#1 0x5d286809855b in main /home/learner/scores.c:14
#2 0x7f5a01bbb1c9 in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58
#3 0x7f5a01bbb28a in __libc_start_main_impl ../csu/libc-start.c:360
#4 0x5d2868098204 in _start (/home/learner/scores+0x1204) (BuildId: 82ee491e7a129be9bab2e7a4ad7fb3cf381bdc6a)
0x502000000020 is located 0 bytes after 16-byte region [0x502000000010,0x502000000020)
allocated by thread T0 here:
#0 0x7f5a024b79c7 in malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:69
#1 0x5d2868098414 in main /home/learner/scores.c:12
#2 0x7f5a01bbb1c9 in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58
#3 0x7f5a01bbb28a in __libc_start_main_impl ../csu/libc-start.c:360
#4 0x5d2868098204 in _start (/home/learner/scores+0x1204) (BuildId: 82ee491e7a129be9bab2e7a4ad7fb3cf381bdc6a)
SUMMARY: AddressSanitizer: heap-buffer-overflow /home/learner/scores.c:7 in total
Shadow bytes around the buggy address:
0x501ffffffd80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x501ffffffe00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x501ffffffe80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x501fffffff00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x501fffffff80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x502000000000: fa fa 00 00[fa]fa fa fa fa fa fa fa fa fa fa fa
0x502000000080: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x502000000100: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x502000000180: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x502000000200: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x502000000280: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
exit code: 1
Read it in this order:
- The headline:
heap-buffer-overflowis the kind (others:stack-buffer-overflow,global-buffer-overflow,heap-use-after-free,double-free,stack-use-after-return).pc,bpandspare the instruction, frame and stack pointers at the fault; you rarely need them. - The access:
READ of size 4, oneint. AWRITEis usually more serious than aREAD, but both are bugs. - The access stack: frame
#0is where the bad access happened,totalatscores.c:7, the linesum += v[i]. Frame#1is its caller. Frames inlibcand_startare the program's start-up and can be ignored. - The location:
0 bytes after 16-byte region: the address is the first byte after a 16-byte block. Fourints are 16 bytes, so index 4 is one past the end: an off-by-one. - The allocation stack: where that block came from,
mainatscores.c:12. For a use-after-free there is also a "freed by" stack. - The summary repeats kind, file, line and function in one line, which is what you paste into a bug tracker.
- The shadow map:
00 00are the two 8-byte granules of the 16-byte block,fathe heap red zones on both sides, and[fa]in brackets is the granule that was touched.
UBSan: one line per problem
UBSan reports have one line each: file:line:column: runtime error: what happened. By default it prints and continues, which shows every problem in one run:
cat > ub.c <<'SRC'
#include <stdio.h>
int main(int argc, char **argv) {
int shift = 31 + argc; /* 32 when run with no arguments */
int big = 0x7fffffff;
int arr[4] = {1, 2, 3, 4};
int idx = 3 + argc; /* 4 */
printf("1 << %d = %d\n", shift, 1 << shift);
printf("big + 1 = %d\n", big + argc);
printf("arr[%d] = %d\n", idx, arr[idx]);
return 0;
}
SRC
gcc -g -O0 -fsanitize=undefined ub.c -o ub
./ub 2>&1 | grep 'runtime error'
echo "exit code (recovering): ${PIPESTATUS[0]}"
gcc -g -O0 -fsanitize=undefined -fno-sanitize-recover=undefined ub.c -o ub-strict
./ub-strict 2>&1 | grep 'runtime error'
echo "exit code (strict): ${PIPESTATUS[0]}"ub.c:7:39: runtime error: shift exponent 32 is too large for 32-bit type 'int'
ub.c:8:5: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
ub.c:9:38: runtime error: index 4 out of bounds for type 'int [4]'
ub.c:9:5: runtime error: load of address 0x7ffc21a6e2e0 with insufficient space for an object of type 'int'
exit code (recovering): 0
ub.c:7:39: runtime error: shift exponent 32 is too large for 32-bit type 'int'
exit code (strict): 1
The values depend on argc so that the compiler can't see the bugs at build time. Three undefined operations, three lines: an over-wide shift, a signed overflow, and an index out of bounds for int [4] (the fourth line is the load that follows from it). The default build exits 0 after reporting: fine for exploring, wrong for CI. With -fno-sanitize-recover the first problem stops the program with exit code 1, so a test fails.
gdb and checksec in one breath
The Stack Frames lesson uses gdb in batch mode (gdb -q -batch -ex 'break 6' -ex run -ex 'info frame' ./prog), which runs a fixed list of commands and exits, so a session's output is reproducible. The Mitigations section uses checksec --file=prog, which reads a binary's headers and prints its build-time protections. Both appear in many lessons; their flags are explained where they are first used.
Flags worth remembering
-ggives file and line numbers;-O0or-O1keeps reports close to the source (at-O2some code is merged or removed).-fno-omit-frame-pointergives better stack traces in optimised builds.ASAN_OPTIONS=detect_leaks=0turns LSan off;halt_on_error=0lets ASan continue after an error if the build used-fsanitize-recover=address;detect_stack_use_after_return=1catches pointers to dead stack frames.UBSAN_OPTIONS=print_stacktrace=1adds a stack trace to UBSan lines.- Sanitizer reports go to stderr:
./prog 2>&1 | …to pipe them.
Pitfalls
- Sanitizers find only what runs. A bug on a code path no test reaches stays invisible; that is what fuzzing is for.
- A clean run is not a proof. ASan can miss an access that jumps over the red zone into another valid object.
- Don't ship sanitizer builds. They add attack surface (environment-controlled options, huge shadow mappings) and cost speed. Use them in tests, CI and fuzzing.
- Optimised builds can hide UB. The compiler may delete code that relies on undefined behaviour before UBSan's check runs; test at
-O0/-O1as well.
Practice
1. A report says "0 bytes after 16-byte region" for a WRITE of size 1. What is the likely bug?
A one-byte write right after a 16-byte block: classically a NUL terminator written at buf[16] into malloc(16), an off-by-one in the allocation (should be len + 1).
2. Why did the UBSan build print "1 << 32 = …" (filtered out above) and keep running?
UBSan's default is to report and recover. The result of the shift is still undefined; the program printed whatever the hardware produced. Use -fno-sanitize-recover=undefined in CI.
3. Which shadow byte would you expect for the last granule of a 13-byte heap block?
13 = 8 + 5, so the first granule is 00 and the second is 05 (only the first 5 bytes addressable), followed by fa red zone.
Test yourself
In an ASan report, what does frame #0 of the first stack trace show?
- Where the memory was allocated
- Where the invalid access happened
- Where the program started
- The last function to return
What does a shadow byte of 00 mean?
- Freed memory
- All 8 application bytes it covers are addressable
- A stack red zone
- Uninitialised memory
Why add -fno-sanitize-recover=undefined to a CI build?
- It makes UBSan faster
- So the first undefined behaviour stops the program with a non-zero exit code and fails the test
- It turns ASan on
- It removes the report
Which sanitizer can't run with ASan in the same build?
- UBSan
- LeakSanitizer
- ThreadSanitizer
- None: all combine