Skip to content

Commit b17a02b

Browse files
committed
Fix corner-case 64-bit integer subtraction bug on some platforms.
When computing "0 - INT64_MIN", most platforms would report an overflow error, which is correct. However, platforms without integer overflow builtins or 128-bit integers would fail to spot the overflow, and incorrectly return INT64_MIN. Back-patch to all supported branches. Patch be me. Thanks to Jian He for initial investigation, and Laurenz Albe and Tom Lane for review. Discussion: https://postgr.es/m/CAEZATCUNK-AZSD0jVdgkk0N%3DNcAXBWeAEX-QU9AnJPensikmdQ%40mail.gmail.com
1 parent 2fe2d1a commit b17a02b

File tree

3 files changed

+8
-1
lines changed

3 files changed

+8
-1
lines changed

src/include/common/int.h

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,8 +211,12 @@ pg_sub_s64_overflow(int64 a, int64 b, int64 *result)
211211
*result = (int64) res;
212212
return false;
213213
#else
214+
/*
215+
* Note: overflow is also possible when a == 0 and b < 0 (specifically,
216+
* when b == PG_INT64_MIN).
217+
*/
214218
if ((a < 0 && b > 0 && a < PG_INT64_MIN + b) ||
215-
(a > 0 && b < 0 && a > PG_INT64_MAX + b))
219+
(a >= 0 && b < 0 && a > PG_INT64_MAX + b))
216220
{
217221
*result = 0x5EED; /* to avoid spurious warnings */
218222
return true;

src/test/regress/expected/int8.out

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -659,6 +659,8 @@ select -('-9223372036854775807'::int8);
659659

660660
select -('-9223372036854775808'::int8);
661661
ERROR: bigint out of range
662+
select 0::int8 - '-9223372036854775808'::int8;
663+
ERROR: bigint out of range
662664
select '9223372036854775800'::int8 + '9223372036854775800'::int8;
663665
ERROR: bigint out of range
664666
select '-9223372036854775800'::int8 + '-9223372036854775800'::int8;

src/test/regress/sql/int8.sql

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@ select '9223372036854775808'::int8;
131131

132132
select -('-9223372036854775807'::int8);
133133
select -('-9223372036854775808'::int8);
134+
select 0::int8 - '-9223372036854775808'::int8;
134135

135136
select '9223372036854775800'::int8 + '9223372036854775800'::int8;
136137
select '-9223372036854775800'::int8 + '-9223372036854775800'::int8;

0 commit comments

Comments
 (0)