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

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

  1. Future-proof sort template against undefined behavior

  2. Fix various instances of undefined behavior