Definition
UndefinedBehaviorSanitizer (UBSan) is a sanitizer §10.21 for C and C++: checks that the compiler inserts into a program and that run while it runs. Each check watches one kind of operation that the C or C++ standard leaves undefined, meaning the standard sets no requirement on what then happens, such as a signed integer overflow §4.15 or a shift by too many bits. When an enabled check fails, UBSan reports the operation and its source line, then lets the program continue or stops it. The Clang §12.17 compiler’s documentation defines the checks.
The idea
Undefined behavior §4.12 rarely announces itself. On a common 32-bit processor, adding 1 to the largest int just produces a wrong number, and the test that follows may still pass. Worse, the optimizer may assume that undefined behavior never happens. A programmer writes if (len + 16 < len) to catch an overflow of the signed variable len. Because a signed sum cannot overflow in a correct program, the compiler may treat the condition as always false and delete the check.
UBSan moves detection to the operation itself. Before each checked operation it tests the operands, and if the operation is undefined for them, it reports the source line, whether or not anything visibly goes wrong later. A referee who whistles at the foul, not at the goal it leads to, is a fair picture, with one limit: this referee watches only the fouls on its list, and only in the plays that actually happen during the run.
How it works
Choose the checks. Each check has a name, passed to the compiler as a compiler flag §12.3:
-fsanitize=shift,alignmentenables two checks. A group name enables several:-fsanitize=undefinedenables most checks for real undefined behavior.-fno-sanitize=removes checks, and for each check the last option wins.Instrument. While compiling each source file, the compiler places a test before every operation of a checked kind. For
a + bonint, it tests whether the exact sum fits in anint; forx << n, whether is at least 0 and less than the bit width ofx; for a load through a pointer, whether the address is a multiple of the alignment §4.22 that the type requires. A failed test calls a handler.Report. The handler in the UBSan run-time library prints the file, line and column and a description, such as
runtime error: signed integer overflow:
2147483647 + 1 cannot be represented in type 'int'
What happens after the report is set for each check.
Recover, the default for most checks: keep running. A signed overflow continues with the wrapped value that the processor produced.
Exit, selected with
-fno-sanitize-recover=: end the program with an error status.Trap, selected with
-fsanitize-trap=: execute a trap instruction, one that deliberately raises a processor exception, with no message and no run-time library. On Linux the program usually dies with the signalSIGILLorSIGTRAP; on an Arm Cortex-M microcontroller §6.1 the fault handler §6.15 receives the exception.
A few checks never continue, such as the check for reaching code marked as unreachable. The run-time setting UBSAN_OPTIONS=halt_on_error=1 stops at the first report without recompiling. Recovery and trap options enable nothing: they are silently ignored for a check that -fsanitize= did not enable.
Code escapes the checks in four ways: through the attribute no_sanitize("undefined") on a function; through an ignore list of files and functions given with -fsanitize-ignorelist=; through a run-time suppression file, which works only for recoverable checks; and by being compiled without the options, as a prebuilt library or hand-written assembly usually is. GCC (GNU Compiler Collection; GNU stands for GNU’s Not Unix) offers its own UBSan with many of the same check names.
Worked example
A 32-bit int holds values from to . With x holding 2,147,483,647, the exact value of x + 1 is 2,147,483,648, one more than the largest int. The addition is undefined, and signed-integer-overflow prints the report shown above. In recover mode the program continues with the wrapped value .
A 32-bit unsigned int holding behaves differently when 1 is added. C defines unsigned arithmetic modulo , so the result is , nothing is undefined, and -fsanitize=undefined stays silent. The separate check unsigned-integer-overflow, in the group -fsanitize=integer, reports this unsigned wraparound §4.16 anyway, because such a wrap is often unintended. Code that wraps on purpose, such as a hash function, then needs that check switched off.
Finally, shift the 32-bit unsigned value 1 left by a variable n that holds 32. A shift by 32 or more bits of a 32-bit operand is undefined, and the check shift reports it. Without UBSan the outcome depends on the processor. An x86 processor uses only the low 5 bits of the shift amount: , so it shifts by 0 and returns 1. A 32-bit Arm processor uses the low 8 bits, shifts by the full 32 and returns 0. Leaving the result undefined lets each compiler use the processor’s own shift instruction, and it means that a test on one machine cannot reveal the defect.
Stated precisely
For each enabled check , let be its failure condition. Three examples:
signed-integer-overflow: for an operation whose result has a signed type with range , the exact result of , , , or lies outside that range; for division the only such case is .shift-exponent: the shift amount satisfies or , where is the bit width of the shifted operand after integer promotion §4.18, the rule that converts integer types narrower thaninttointbefore arithmetic.alignment: an access to an object of type uses an address with , where is the alignment that requires.
The guarantee: if an operation of a checked kind executes in code that was compiled with check and not excluded, and holds for its operands, then the handler runs at that operation, before its result is used. The Clang documentation states that UBSan is not expected to produce false positives §1.22, so a report names a real instance of the condition. The guarantee rests on three assumptions: the operation executed in this run; the code containing it was instrumented; and the report was collected, from the error output or because the program stopped. In recover mode the exit status §13.24 is unchanged, so a test runner that looks only at the exit status counts a run with reports as a pass.
Limits and common mistakes
UBSan checks a list, not the whole language. It misses most out-of-bounds accesses to memory obtained at run time and uses of freed memory (AddressSanitizer §10.22 finds those), reads of uninitialized memory (MemorySanitizer §10.24), data races §9.3 (ThreadSanitizer), violations of the strict aliasing rule §4.23, which forbids reading an object through a pointer to an unrelated type, and two unsequenced changes to one variable, as in i = i++ + 1. Its bounds check covers only arrays §14.5 whose size the compiler knows.
A clean run covers only the operations that ran, which is why UBSan is often combined with fuzzing §10.9.
The checked build is a different program. The checks change code layout, timing and what the optimizer may do, so a symptom of the normal optimized build may vanish. The report still appears, because the check sits at the operation.
Recover mode keeps running after undefined behavior, so later reports can be consequences of the first. Investigate the first report first.
The full run-time library is a debugging aid. For security-sensitive builds, the Clang documentation recommends trap mode or the minimal run-time library, selected with -fsanitize-minimal-runtime.
Check names and the contents of groups change between compiler releases, so record the compiler version with the options.
Questions answered
Which checks are enabled, recoverable, or excluded in this build?
The enabled, recoverable and excluded checks of a UBSan (UndefinedBehaviorSanitizer) build are fixed by its compiler options, its source annotations and its run-time settings, so they must be read from those three places; the tool name says none of it.
Enabled: for every source file, the checks named by
-fsanitize=minus those removed by-fno-sanitize=, the last option winning for each check. Groups must be expanded: in the current Clang documentation,-fsanitize=undefinedleaves outfloat-divide-by-zero,unsigned-integer-overflow,implicit-conversion,local-bounds,vptrand thenullabilitychecks. A file compiled without these options has no checks.Recoverable: by default, most checks report and continue. Checks named in the option
-fno-sanitize-recover=exit after the report instead, and checks named in-fsanitize-trap=trap without a message. A few checks, such asunreachable, never continue, and the run-time settinghalt_on_error=1, given in the environment variableUBSAN_OPTIONS, stops at the first report. Neither option does anything for a check that is not enabled.Excluded: functions marked
no_sanitize, files and functions in the ignore list, reports matched by a run-time suppression file, and code built without the options, such as prebuilt libraries and assembly.
Record this list with the compiler version, and make the test runner fail on any report: in recover mode a program can print a report and still exit with status 0.
Related entries: Sanitizer (§10.21), Undefined behavior (UB) (§4.12), Signed integer overflow (§4.15), Unsigned modular arithmetic (§4.16), Integer promotion and conversion (§4.18), Shift semantics (§4.20), Alignment (§4.22), AddressSanitizer (§10.22). Further reading: [26, 78].