Undefined behavior detected by new clang's ubsan

From: Alexander Lakhin <exclusion(at)gmail(dot)com>
To: pgsql-hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Undefined behavior detected by new clang's ubsan
Date: 2026-01-20 05:00:00
Message-ID: 777bd201-6e3a-4da0-a922-4ea9de46a3ee@gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

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

Attachment Content-Type Size
fixes-for-new-clang-sanitizers.patch text/x-patch 2.1 KB

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Michael Paquier 2026-01-20 05:03:55 Re: A minor grammar error was found in a comment in the smgrtruncate function
Previous Message shveta malik 2026-01-20 04:43:28 Re: Simplify code building the LR conflict messages