Re: Undefined behavior detected by new clang's ubsan

From: John Naylor <johncnaylorls(at)gmail(dot)com>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: Alexander Lakhin <exclusion(at)gmail(dot)com>, pgsql-hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: Undefined behavior detected by new clang's ubsan
Date: 2026-02-02 11:30:13
Message-ID: CANWCAZb9YDMS-7uQ=_s-9DVXzm-rSn5-W4RJA9_g_jaUo-Ns1w@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Wed, Jan 21, 2026 at 5:05 PM John Naylor <johncnaylorls(at)gmail(dot)com> wrote:
> heaptoast.c
> memcpy(VARDATA(result) +
> - (curchunk * TOAST_MAX_CHUNK_SIZE - sliceoffset) + chcpystrt,
> + (int)(curchunk * TOAST_MAX_CHUNK_SIZE - sliceoffset) + chcpystrt,

Recall, the error was "runtime error: addition of unsigned offset to
0x7395fbd3d204 overflowed to 0x7395fbd3d142"

It looks like "- 194" got turned into "+ (SIZE_MAX - 193)".

Curiously, just removing the parentheses is enough to pass make check for me.:

- (curchunk * TOAST_MAX_CHUNK_SIZE - sliceoffset) + chcpystrt,
+ curchunk * TOAST_MAX_CHUNK_SIZE - sliceoffset + chcpystrt,

That's obviously equivalent in math, and IIUC in C precedence, so I'm
not sure what to think of this. For v2 I've just done the above, but
I'm curious if this raises anyone else's eyebrow.

0001 is backpatchable to v14, and doesn't change the sort template,
and just guards NULL at the call site.

The sort template change 0002 is a master-only patch. I don't think it
would make any difference for performance, but to remove any doubt we
could bump the insertion sort threshold, which is a good idea anyway.

--
John Naylor
Amazon Web Services

Attachment Content-Type Size
v2-0001-Fix-various-instances-of-undefined-behavior.patch text/x-patch 3.4 KB
v2-0002-Future-proof-sort-template-against-undefined-beha.patch text/x-patch 2.7 KB

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Shlok Kyal 2026-02-02 11:48:45 Re: Skipping schema changes in publication
Previous Message Ahmed Et-tanany 2026-02-02 11:18:29 Re: [PATCH] Add max_logical_replication_slots GUC