Undefined behavior detected by new clang's ubsan - Mailing list pgsql-hackers

From Alexander Lakhin
Subject Undefined behavior detected by new clang's ubsan
Date
Msg-id 777bd201-6e3a-4da0-a922-4ea9de46a3ee@gmail.com
Whole thread Raw
Responses Re: Undefined behavior detected by new clang's ubsan
List 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

pgsql-hackers by date:

Previous
From: shveta malik
Date:
Subject: Re: Simplify code building the LR conflict messages
Next
From: Michael Paquier
Date:
Subject: Re: A minor grammar error was found in a comment in the smgrtruncate function