Definition
A sanitizer is a bug detector built into a compiler. When a program is compiled with a sanitizer, the compiler inserts checks next to selected operations, and a runtime library linked into the program keeps the information those checks need. When the running program performs an erroneous operation of the class a check watches, such as an access outside an object’s memory or a signed integer overflow §4.15, the sanitizer reports it at that moment, with its location. Common C and C++ compilers provide sanitizers through the flag -fsanitize=.
The idea
A C program writes one byte past the end of an array §14.5. Usually nothing visible happens: the byte lands in memory the program owns, perhaps in a neighboring variable, and the test passes. The damage shows up later, somewhere else, or never during testing. The C language calls such an operation undefined behavior §4.12: the language standard places no requirement at all on what the program then does. Memory errors, overflow of signed integers, reads of memory that was never written, and unsynchronized access to shared memory by two threads are all errors that can stay silent in this way.
A sanitizer turns such silent errors into immediate, loud failures. Each check sits next to the operation it guards and knows the rule that operation must obey, so the report names the exact operation, the values involved and the chain of function calls that led there. Fuzzing §10.9 depends on this: a fuzzer recognizes a bug mainly by a crash, and a sanitizer makes a silent bug crash. A smoke detector is a fair picture, including its limits: it sounds the moment smoke appears, but only in its own room, only for some kinds of fire, and only to someone who hears it.
How it works
Build. The program is compiled with a flag such as
-fsanitize=address. The compiler inserts a check before each operation of the watched kind, and the linker §12.4 adds the sanitizer’s runtime library.Track. The runtime keeps metadata, meaning data about the program’s data, often in shadow memory: a reserved area that holds a few bits or bytes of state for each piece of the program’s memory. It also replaces or wraps standard functions such as
malloc,freeandmemcpy, so that it sees allocations and copies made by library code it did not compile.Check. While the program runs, each inserted check compares its operation with the metadata.
Report. A failed check prints the kind of error, the code location and the chain of calls. AddressSanitizer §10.22 stops the program at the first error by default. UndefinedBehaviorSanitizer §10.23, for most of its checks, prints a report and lets the program continue by default; the flag
-fno-sanitize-recover=undefinedmakes it stop instead.
The main sanitizers of Clang §12.17 and of GCC (the GNU Compiler Collection, from the free-software project GNU, whose name stands for GNU’s Not Unix) follow, with the typical slowdowns that Clang’s documentation gives.
AddressSanitizer (
-fsanitize=address): reads and writes outside heap, stack and global objects; use-after-free §4.6, a use of heap memory after it was freed; freeing memory twice. Slowdown about 2 times. On some platforms it includes LeakSanitizer, which reports memory never freed.UndefinedBehaviorSanitizer (
-fsanitize=undefined): a list of individual kinds of undefined behavior, among them signed integer overflow, shifts by too many bits, misaligned or null pointer §4.26 use, integer division by zero, and out-of-range array indexes where the array size is known at compile time. Small run-time cost.MemorySanitizer §10.24 (
-fsanitize=memory, Clang only): use of uninitialized memory, memory read before anything was written to it, when the value decides a branch, forms an address or is passed to the operating system. Slowdown about 3 times. All code, including the standard libraries, must be compiled with it, or it can report errors that do not exist.ThreadSanitizer §10.25 (
-fsanitize=thread): data races §9.3, in which two threads access the same memory location, at least one access is a write, and no synchronization orders the two accesses. Slowdown 5 to 15 times, with 5 to 10 times the memory.
AddressSanitizer, MemorySanitizer and ThreadSanitizer each need their own layout of shadow memory, so no two of them can share one build. UndefinedBehaviorSanitizer is commonly combined with AddressSanitizer.
AddressSanitizer, MemorySanitizer and ThreadSanitizer need their runtime library and a large reserved range of address space, which mainstream 64-bit desktop and server operating systems provide; firmware for small microcontrollers §6.1 is therefore commonly sanitized in a build for a desktop computer or for a simulator. With Clang, adding -fsanitize-trap=undefined turns each UndefinedBehaviorSanitizer check into a trap instruction, which the processor handles as a fault and which needs no runtime library, so those checks can run on the device itself.
Worked example
Five defects, and the sanitizer built to detect each one:
The variable
xholds 2147483647, which is , the largest 32-bit signedint, and the program computesx + 1. The true sum, , does not fit, so the addition is undefined behavior. UndefinedBehaviorSanitizer reports a signed integer overflow.The program reads
p[0]afterfree(p). AddressSanitizer reports a heap use-after-free.The program declares
int v;, never assigns it, and testsif (v > 0). MemorySanitizer reports a use of an uninitialized value.Two threads each run
count++on a shared counter without a lock. ThreadSanitizer reports a data race when both threads perform their increments during the run; the increments need not happen at the same instant, because it looks for accesses that no synchronization orders.A request handler performs an action without checking that the sender may request it. It uses only valid, initialized memory from one thread, so no sanitizer reports anything: the defect breaks a rule of the application, which no sanitizer knows.
Cost: a test suite that runs in 40 seconds without sanitizers takes about seconds under AddressSanitizer, and between and seconds under ThreadSanitizer. Because three of the sanitizers cannot share a build, covering all four classes takes at least three builds and three runs: AddressSanitizer with UndefinedBehaviorSanitizer, MemorySanitizer, and ThreadSanitizer. Reach: if the use-after-free above sits in a function that no test calls, AddressSanitizer reports nothing, however good its checks are.
Stated precisely
A sanitizer reports a defect during a run only if all four of the following conditions hold.
Executed: the faulty operation runs during that run, with inputs that make it faulty; for a data race, both conflicting accesses run.
Instrumented: the operation lies in code compiled with , or in a library function that the runtime of wraps.
In class and in reach: the defect belongs to a class that checks, that check is enabled, and this instance falls within the mechanism of . For example, an out-of-bounds access that lands inside another valid object is out of AddressSanitizer’s reach.
Observed: the report reaches the verdict of the test, for example because the program stops with a failure status or the test reads the sanitizer’s output.
A clean run therefore shows only that no defect met all four conditions in that run, not that the program is free of the class. In the other direction, a report can be trusted when the assumptions of hold: for MemorySanitizer, that all code was compiled with it; for ThreadSanitizer, that all synchronization goes through operations it can see. Otherwise false positives §1.22, reports of errors that do not exist, can occur.
Limits and common mistakes
A sanitizer is a dynamic check: it sees only operations that execute. Static analysis §3.1, which reasons about all executions without running the program, complements it, and a coverage metric §10.18 measured on the same sanitized runs shows which code the sanitizer could have watched.
A sanitized build is a different program. Checks, guard areas and shadow memory change timing, memory layout and memory use, so a timing or stack-size figure from a sanitized build does not describe the release build, and a bug that depends on layout or timing can appear or vanish. The instrumentation overhead §11.32 entry treats such effects.
A report locates the faulty operation, not necessarily the cause: a length computed wrongly early in the program shows up later, at the copy that uses it.
Sanitizers are testing tools, not protection in production. Their checks have gaps that an attacker can aim at, such as an out-of-bounds offset large enough to jump past the guard area around an object.
With default settings, UndefinedBehaviorSanitizer prints most of its reports and continues, so a test that checks only the program’s exit status §13.24 misses them unless recovery is turned off.
Questions answered
Which bug classes and execution paths does a particular sanitizer cover?
A sanitizer covers only the bug classes its checks were built for, and only on the execution paths that the tests actually ran through instrumented code. The classes differ per sanitizer:
AddressSanitizer: out-of-bounds reads §4.5 and writes on heap, stack and global objects, use of heap memory after it was freed, and freeing memory twice;
UndefinedBehaviorSanitizer: the enabled kinds of undefined behavior from its list, such as signed integer overflow, oversized shifts, and misaligned or null pointer use;
MemorySanitizer: uses of uninitialized memory that decide a branch, form an address or reach the operating system;
ThreadSanitizer: data races, unsynchronized accesses by two threads to the same memory, at least one a write, when both accesses run during the test.
The paths covered are narrower than the program. A defect is reported only when its operation actually executes in a test, lies in code compiled with the sanitizer or in a library function its runtime wraps, and produces a report that reaches the test’s verdict. To state the coverage of a particular sanitizer, name the sanitizer with its enabled checks and options, list the components compiled with it and those that were not, and measure which code the sanitized test runs executed. Errors outside these classes, such as a wrong result or a missing authorization §1.7 check, need test oracles §10.5 of their own.
Related entries: AddressSanitizer (§10.22), UndefinedBehaviorSanitizer (§10.23), MemorySanitizer (§10.24), ThreadSanitizer (§10.25), Test oracle (§10.5), Undefined behavior (UB) (§4.12), Data race (§9.3), Coverage metric (§10.18). Further reading: [25, 26, 105, 106].