Why passing tests settle nothing#
UndefinedBehaviorSanitizer (UBSan) inserts checks before operations whose result the language leaves undefined, such as signed overflow, oversized shifts, misaligned loads and null dereferences. The program a test exercised was compiled under the assumption that none of those operations happen. When one does, the test measured the behavior of one compiler at one optimization level, and a different level can produce different behavior with no error.
This constructed quota check is a common shape. It tries to detect overflow after doing the addition:
/* Returns -1 if used + request would overflow, else stores the sum. */
__attribute__((noinline))
int reserve(int used, int request, int *total) {
if (request > 0 && used + request < used) /* line 8 */
return -1;
*total = used + request;
return 0;
}
Built with Ubuntu clang 18.1.3 and run with used near INT_MAX, the result depends on the flag:
$ for o in -O0 -O1 -O2; do clang $o quota.c -o q$o; ./q$o 2147483000 1000; done
rc=-1 total=0
rc=0 total=-2147483296
rc=0 total=-2147483296
At -O0 the addition wraps, the comparison sees a negative sum, and the check rejects the request. At -O1 and -O2 the check no longer fires: the compiler may assume signed overflow never happens, and under that assumption used + request < used with request > 0 is always false. The release build accepts the request and stores a negative total. GCC 13.3.0 removed the check at -O0 as well. A unit test run against the debug build passes, and the bug ships.
Read the report#
With clang -O0 -g -fsanitize=undefined quota.c, the same input produces:
quota.c:8:27: runtime error: signed integer overflow: 2147483000 + 1000 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior quota.c:8:27
rc=-1 total=0
The report gives the file, line and column of the operation, the check that failed, and the operand values. Those values are the input for a regression test. Two details matter before trusting a CI run that had UBSan enabled.
First, UBSan does not stop the program by default. The clang documentation says that for most checks "the instrumented program prints a verbose error report and continues execution upon a failed check." The run above exited 0. A test that only checks the exit status passes with the report in its log. Building with -fno-sanitize-recover=undefined makes the same input exit 1.
Second, the report is one line with no stack. The documentation's steps for a symbolized stack are to compile with -g and -fno-omit-frame-pointer and to run with UBSAN_OPTIONS=print_stacktrace=1. Add both when the faulting line is in a helper called from many places.
Shift and alignment reports read the same way. This constructed pair builds a flag mask with 1 << bit and reads a length field one byte into a packet:
uint32_t flag_bit(int bit) { return 1 << bit; } /* line 5 */
uint32_t read_len(const unsigned char *packet) {
return *(const uint32_t *)(packet + 1); /* line 8 */
}
other.c:5:39: runtime error: left shift of 1 by 31 places cannot be represented in type 'int'
other.c:8:10: runtime error: load of misaligned address 0x... for type 'const uint32_t' (aka 'const unsigned int'), which requires 4 byte alignment
2147483648 16
Both print the expected values on x86-64, and both are still defects: the literal 1 is an int, so the fix is 1u << bit, and a field at an odd offset is read with memcpy into a local uint32_t. A passing run on x86-64 does not show how the same code behaves on another target or under another optimizer.
On false positives the documentation is direct: "UndefinedBehaviorSanitizer is not expected to produce false positives. If you see one, look again; most likely it is a true positive!" Treat the report as true and spend the time on deciding what the code meant.
Fix the arithmetic instead of silencing the report#
The documentation offers a way to silence a function: "if your function deliberately contains possible signed integer overflow, you can use __attribute__((no_sanitize("signed-integer-overflow")))." That attribute removes the check. It does not make the overflow defined. Applied to reserve, the report disappears and the optimized build still drops the comparison:
$ clang -O0 -g -fsanitize=undefined quota_nosan.c -o qn-O0 && ./qn-O0 2147483000 1000
rc=-1 total=0
$ clang -O2 -g -fsanitize=undefined quota_nosan.c -o qn-O2 && ./qn-O2 2147483000 1000
rc=0 total=-2147483296
The fix tests for overflow without performing it. GCC and clang provide __builtin_add_overflow, which the GCC 13.3.0 manual describes this way: "As the addition is performed in infinite signed precision, these built-in functions have fully defined behavior for all argument values." It returns true when the stored result differs from that exact sum:
int reserve(int used, int request, int *total) {
int sum;
if (__builtin_add_overflow(used, request, &sum))
return -1;
*total = sum;
return 0;
}
The overflowing input and an ordinary one now give the same answers at both levels, with no report:
$ clang -O0 -g -fsanitize=undefined quota_fixed.c -o qf-O0 && ./qf-O0 2147483000 1000 && ./qf-O0 100 5
rc=-1 total=0
rc=0 total=105
$ clang -O2 -g -fsanitize=undefined quota_fixed.c -o qf-O2 && ./qf-O2 2147483000 1000 && ./qf-O2 100 5
rc=-1 total=0
rc=0 total=105
The disconfirming report: wraparound that was intended#
Some reports point at code whose author wanted modular arithmetic. A string hash that multiplies by 31 and lets the value wrap is the usual case:
int bucket(const char *s, int nbuckets) {
int h = 0;
while (*s) h = h * 31 + *s++; /* line 6 */
return (h & 0x7fffffff) % nbuckets;
}
UBSan reports it on a 19-character key, and the output is the same at both levels in this build:
hash.c:6:20: runtime error: signed integer overflow: 109327991 * 31 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior hash.c:6:20
33 55
Here the reviewer's first reading flips. The overflow is not a defect in the algorithm: the code wants h modulo 2^32 and nobody reads the value as a count. Dismissing the report is still wrong, because the wrap happens in int, and the program only produced 33 55 because this compiler did not exploit the overflow in this function. The fix is the type that defines wrapping:
uint32_t h = 0;
while (*s) h = h * 31u + (unsigned char)*s++;
return (int)((h & 0x7fffffffu) % (uint32_t)nbuckets);
Built with -fsanitize=undefined at -O0 and -O2, this version prints 33 55 with no report. The cast to unsigned char also stops a byte above 127 from entering the hash as a negative value on platforms where char is signed; for such keys the bucket changes, so persisted tables need a rebuild.
Expect one more report if the build enables the optional unsigned check:
$ clang -O0 -g -fsanitize=undefined,unsigned-integer-overflow hash_fixed.c -o hfu && ./hfu
hash_fixed.c:7:20: runtime error: unsigned integer overflow: 3389167832 * 31 cannot be represented in type 'unsigned int'
33 55
That check is not part of -fsanitize=undefined. The documentation describes it as "Unsigned integer overflow, where the result of an unsigned integer computation cannot be represented in its type. Unlike signed integer overflow, this is not undefined behavior, but it is often unintentional." A report from this check on a deliberate hash is the one place a suppression fits, scoped to that function in the sanitizer's ignorelist or with no_sanitize("unsigned-integer-overflow").
Decide from the operand values and the intent#
| What the report says | Evidence to collect | Decision |
|---|---|---|
| Signed overflow in a bounds or overflow check | Output of the same input at -O0 and -O2 | Fix with __builtin_add_overflow or a check that compares before adding |
| Signed overflow in a hash, checksum or PRNG meant to wrap | Whether any caller treats the value as a count | Change the type to unsigned; do not add no_sanitize |
Unsigned overflow, only with unsigned-integer-overflow enabled | Whether wrapping is the intended result | Dismiss or scope a suppression to that function; fix if the value is a size or count |
| Report in the log of a passing CI run | The build's recover flags | Build with -fno-sanitize-recover=undefined so the next one fails the run |
| Shift into the sign bit, or misaligned load | The operand type and the field's offset | Fix with an unsigned operand, or memcpy for the load |
| Report without a usable location | A rebuild with -g, -fno-omit-frame-pointer and print_stacktrace=1 | Collect the stack before deciding |
When the finding came from a reviewer comment rather than a sanitizer run, the guide to integer overflow comments covers what to check. The operand values in the report make a ready regression test, as the guide to turning a comment into a test describes.