Re: BUG #16790: Integer overflow not detected with <<

From: Alexander Lakhin <exclusion(at)gmail(dot)com>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: pgsql-bugs(at)lists(dot)postgresql(dot)org
Subject: Re: BUG #16790: Integer overflow not detected with <<
Date: 2020-12-23 17:50:00
Message-ID: 17340682-ad3e-9145-543a-27a62518357e@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

23.12.2020 18:29, Tom Lane wrote:
> PG Bug reporting form <noreply(at)postgresql(dot)org> writes:
>> It seems that the bitwise shift left operator ignores overflow:
>> Is this an expected behavior (a kind of UB)? It's not like an arithmetic
>> shift. (The semantic of '1::int4<<-1' is questionable too.)
> It's defined to do whatever the C << operator does. That will certainly
> not involve throwing an error.
Unfortunately, the behavior of the C << operator varies from defined to
implementation-defined and undefined. In fact I found this issue when
executing that query in an instance built with "-fsanitize=undefined".
Also I found an interesting reading about the shift operator:
https://devblogs.microsoft.com/cppblog/hello-arm-exploring-undefined-unspecified-and-implementation-defined-behavior-in-c/
So it's not that simple to describe the expected result of the operator
for all cases/platforms/architectures. It seems that a user is left with
"just try and see" or "avoid illegal values" approach.
On the other hand, there are pg_{mul,add,sub}_s{16,32,64}_overflow()
functions. Aren't they purposed to provide a well-defined behaviour for
related arithmetic operators?
Maybe the bitwise shift can be thought as something different from
arithmetic shift, and i<<1 is not the same as i*2, but in my opinion
it's not that could be expected at the database level.

Best regards,
Alexander

In response to

Browse pgsql-bugs by date

  From Date Subject
Next Message Konstantin Knizhnik 2020-12-24 14:06:34 Re: Large objects and out-of-memory
Previous Message Tom Lane 2020-12-23 15:29:56 Re: BUG #16790: Integer overflow not detected with <<