Skip to content

Commit 2e06d52

Browse files
committed
Fix the int8 and int2 cases of (minimum possible integer) % (-1).
The correct answer for this (or any other case with arg2 = -1) is zero, but some machines throw a floating-point exception instead of behaving sanely. Commit f9ac414 dealt with this in int4mod, but overlooked the fact that it also happens in int8mod (at least on my Linux x86_64 machine). Protect int2mod as well; it's not clear whether any machines fail there (mine does not) but since the test is so cheap it seems better safe than sorry. While at it, simplify the original guard in int4mod: we need only check for arg2 == -1, we don't need to check arg1 explicitly. Xi Wang, with some editing by me.
1 parent 797ea52 commit 2e06d52

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/backend/utils/adt/int.c

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1094,8 +1094,12 @@ int4mod(PG_FUNCTION_ARGS)
10941094
PG_RETURN_NULL();
10951095
}
10961096

1097-
/* SELECT ((-2147483648)::int4) % (-1); causes a floating point exception */
1098-
if (arg1 == INT_MIN && arg2 == -1)
1097+
/*
1098+
* Some machines throw a floating-point exception for INT_MIN % -1, which
1099+
* is a bit silly since the correct answer is perfectly well-defined,
1100+
* namely zero.
1101+
*/
1102+
if (arg2 == -1)
10991103
PG_RETURN_INT32(0);
11001104

11011105
/* No overflow is possible */
@@ -1118,6 +1122,15 @@ int2mod(PG_FUNCTION_ARGS)
11181122
PG_RETURN_NULL();
11191123
}
11201124

1125+
/*
1126+
* Some machines throw a floating-point exception for INT_MIN % -1, which
1127+
* is a bit silly since the correct answer is perfectly well-defined,
1128+
* namely zero. (It's not clear this ever happens when dealing with
1129+
* int16, but we might as well have the test for safety.)
1130+
*/
1131+
if (arg2 == -1)
1132+
PG_RETURN_INT16(0);
1133+
11211134
/* No overflow is possible */
11221135

11231136
PG_RETURN_INT16(arg1 % arg2);

src/backend/utils/adt/int8.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -651,6 +651,14 @@ int8mod(PG_FUNCTION_ARGS)
651651
PG_RETURN_NULL();
652652
}
653653

654+
/*
655+
* Some machines throw a floating-point exception for INT64_MIN % -1,
656+
* which is a bit silly since the correct answer is perfectly
657+
* well-defined, namely zero.
658+
*/
659+
if (arg2 == -1)
660+
PG_RETURN_INT64(0);
661+
654662
/* No overflow is possible */
655663

656664
PG_RETURN_INT64(arg1 % arg2);

0 commit comments

Comments
 (0)