Undefined behavior detected by new clang's ubsan
Alexander Law <exclusion@gmail.com>
From: Alexander Lakhin <exclusion@gmail.com>
To: pgsql-hackers <pgsql-hackers@postgresql.org>
Date: 2026-01-20T05:00:00Z
Lists: pgsql-hackers
Attachments
- fixes-for-new-clang-sanitizers.patch (text/x-patch) patch
Hello hackers. When trying to run `make check` for a build made by clang-21 with sanitizers enabled: CFLAGS="-Og -fsanitize=address -fsanitize=undefined -fno-sanitize-recover -fno-sanitize=function" LDFLAGS="-static-libsan" ... I hit into: ../../src/include/lib/sort_template.h:314:15: runtime error: applying non-zero offset 8 to null pointer SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior ../../src/include/lib/sort_template.h:314:15 I could workaround that with: --- a/src/include/lib/sort_template.h +++ b/src/include/lib/sort_template.h @@ -307,6 +307,9 @@ ST_SORT(ST_ELEMENT_TYPE * data, size_t n int r, presorted; +if (!data && n == 0) + return; + loop: But then there was: heaptoast.c:770:26: runtime error: addition of unsigned offset to 0x7395fbd3d204 overflowed to 0x7395fbd3d142 SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior heaptoast.c:770:26 sharedtuplestore.c:326:30: runtime error: applying non-zero offset 24 to null pointer SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior sharedtuplestore.c:326:30 and trgm_gist.c:702:40: runtime error: applying non-zero offset 16 to null pointer SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior trgm_gist.c:702:40 With the attached patch applied, `make check-world` passes for me. Reproduced with clang 20.1, but not reproduced with clang 20.0, so maybe this note is relevant here: https://releases.llvm.org/20.1.0/tools/clang/docs/ReleaseNotes.html#sanitizers Changed -fsanitize=pointer-overflow to no longer report NULL + 0 as undefined behavior in C, in line with N3322, and matching the previous behavior for C++. NULL + non_zero continues to be reported as undefined behavior. Best regards, Alexander
Commits
-
Future-proof sort template against undefined behavior
- 7467041cde9e 19 (unreleased) landed
-
Fix various instances of undefined behavior
- 176dffdf7d2a 19 (unreleased) landed
- fc56793c9ae5 14.21 landed
- b5e1cd2fdca1 18.2 landed
- 73ac2b37401d 16.12 landed
- 6b81a1c7c905 15.16 landed
- 1662cd0cb7ae 17.8 landed