Section 10.23

UndefinedBehaviorSanitizer

Full name: UndefinedBehaviorSanitizer, usually shortened to UBSan. The name joins the words undefined behavior and sanitizer; it is not an abbreviation.

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

  1. Choose the checks. Each check has a name, passed to the compiler as a compiler flag §12.3: -fsanitize=shift,alignment enables two checks. A group name enables several: -fsanitize=undefined enables most checks for real undefined behavior. -fno-sanitize= removes checks, and for each check the last option wins.

  2. Instrument. While compiling each source file, the compiler places a test before every operation of a checked kind. For a + b on int, it tests whether the exact sum fits in an int; for x << n, whether nn is at least 0 and less than the bit width of x; 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.

  3. 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.

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 −231=−2,147,483,648-2^{31} = -2{,}147{,}483{,}648 to 231−1=2,147,483,6472^{31} - 1 = 2{,}147{,}483{,}647. 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 2,147,483,648−232=−2,147,483,6482{,}147{,}483{,}648 - 2^{32} = -2{,}147{,}483{,}648.

A 32-bit unsigned int holding 232−1=4,294,967,2952^{32} - 1 = 4{,}294{,}967{,}295 behaves differently when 1 is added. C defines unsigned arithmetic modulo 2322^{32}, so the result is 232mod232=02^{32} \bmod 2^{32} = 0, 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: 32mod32=032 \bmod 32 = 0, 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 cc, let condc\mathrm{cond}_c be its failure condition. Three examples:

The guarantee: if an operation of a checked kind executes in code that was compiled with check cc and not excluded, and condc\mathrm{cond}_c 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.

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].