Skip to content

Commit 014796a

Browse files
committed
pgbench: Install guard against overflow when dividing by -1.
Commit 64f5edc fixed the same hazard on master; this is a backport, but the modulo operator does not exist in older releases. Michael Paquier
1 parent 1f2b195 commit 014796a

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

contrib/pgbench/pgbench.c

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,10 @@
5757
#ifndef INT64_MAX
5858
#define INT64_MAX INT64CONST(0x7FFFFFFFFFFFFFFF)
5959
#endif
60+
#ifndef INT64_MIN
61+
#define INT64_MIN (-INT64CONST(0x7FFFFFFFFFFFFFFF) - 1)
62+
#endif
63+
6064

6165
/*
6266
* Multi-platform pthread implementations
@@ -1331,13 +1335,37 @@ doCustom(TState *thread, CState *st, instr_time *conn_time, FILE *logfile, AggVa
13311335
snprintf(res, sizeof(res), INT64_FORMAT, ope1 * ope2);
13321336
else if (strcmp(argv[3], "/") == 0)
13331337
{
1338+
int64 operes;
1339+
13341340
if (ope2 == 0)
13351341
{
13361342
fprintf(stderr, "%s: division by zero\n", argv[0]);
13371343
st->ecnt++;
13381344
return true;
13391345
}
1340-
snprintf(res, sizeof(res), INT64_FORMAT, ope1 / ope2);
1346+
/*
1347+
* INT64_MIN / -1 is problematic, since the result can't
1348+
* be represented on a two's-complement machine. Some
1349+
* machines produce INT64_MIN, some produce zero, some
1350+
* throw an exception. We can dodge the problem by
1351+
* recognizing that division by -1 is the same as
1352+
* negation.
1353+
*/
1354+
if (ope2 == -1)
1355+
{
1356+
operes = -ope1;
1357+
1358+
/* overflow check (needed for INT64_MIN) */
1359+
if (ope1 == INT64_MIN)
1360+
{
1361+
fprintf(stderr, "bigint out of range\n");
1362+
st->ecnt++;
1363+
return true;
1364+
}
1365+
}
1366+
else
1367+
operes = ope1 / ope2;
1368+
snprintf(res, sizeof(res), INT64_FORMAT, operes);
13411369
}
13421370
else
13431371
{

0 commit comments

Comments
 (0)