Re: Fix overflow in pg_size_pretty

From: David Rowley <dgrowleyml(at)gmail(dot)com>
To: Joseph Koshakow <koshy44(at)gmail(dot)com>
Cc: PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Re: Fix overflow in pg_size_pretty
Date: 2024-07-28 03:42:36
Message-ID: CAApHDvq6B7rhyf8WBshgVnWpDrhnTK0jNfmY5wPDsp_RKAmT+A@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Sun, 28 Jul 2024 at 13:10, Joseph Koshakow <koshy44(at)gmail(dot)com> wrote:
>
> On Sat, Jul 27, 2024 at 8:00 PM David Rowley <dgrowleyml(at)gmail(dot)com> wrote:
> > What if we spelt it out the same way as pg_lltoa() does?
> >
> > i.e: uint64 usize = size < 0 ? 0 - (uint64) size : (uint64) size;
>
> My understanding of pg_lltoa() is that it produces an underflow and
> relies wrapping around from 0 to PG_UINT64_MAX. In fact the following
> SQL, which relies on pg_lltoa() under the hood, panics with `-ftrapv`
> enabled (which panics on underflows and overflows):
>
> SELECT int8out(-9223372036854775808);

I didn't test to see where that's coming from, but I did test the two
attached .c files. int.c uses the 0 - (unsigned int) var method and
int2.c uses (unsigned int) (-var). Using clang and -ftrapv, I get:

$ clang int.c -o int -O2 -ftrapv
$ ./int
2147483648
$ clang int2.c -o int2 -O2 -ftrapv
$ ./int2
Illegal instruction

Similar with gcc:
$ gcc int.c -o int -O2 -ftrapv
$ ./int
2147483648
$ gcc int2.c -o int2 -O2 -ftrapv
$ ./int2
Aborted

I suspect your trap must be coming from somewhere else. It looks to me
like the "uint64 usize = size < 0 ? 0 - (uint64) size : (uint64)
size;" will be fine.

David

Attachment Content-Type Size
int.c text/plain 201 bytes
int2.c text/plain 198 bytes

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Joseph Koshakow 2024-07-28 04:30:10 Re: Fix overflow in pg_size_pretty
Previous Message John Naylor 2024-07-28 03:20:02 Re: Vacuum ERRORs out considering freezing dead tuples from before OldestXmin