Skip to content

Commit 80be419

Browse files
committed
Fix possible internal overflow in numeric division.
div_var_fast() postpones propagating carries in the same way as mul_var(), so it has the same corner-case overflow risk we fixed in 246693e, namely that the size of the carries has to be accounted for when setting the threshold for executing a carry propagation step. We've not devised a test case illustrating the brokenness, but the required fix seems clear enough. Like the previous fix, back-patch to all active branches. Dean Rasheed
1 parent 331828b commit 80be419

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

src/backend/utils/adt/numeric.c

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6260,8 +6260,14 @@ div_var_fast(NumericVar *var1, NumericVar *var2, NumericVar *result,
62606260
/*
62616261
* maxdiv tracks the maximum possible absolute value of any div[] entry;
62626262
* when this threatens to exceed INT_MAX, we take the time to propagate
6263-
* carries. To avoid overflow in maxdiv itself, it actually represents
6264-
* the max possible abs. value divided by NBASE-1.
6263+
* carries. Furthermore, we need to ensure that overflow doesn't occur
6264+
* during the carry propagation passes either. The carry values may have
6265+
* an absolute value as high as INT_MAX/NBASE + 1, so really we must
6266+
* normalize when digits threaten to exceed INT_MAX - INT_MAX/NBASE - 1.
6267+
*
6268+
* To avoid overflow in maxdiv itself, it represents the max absolute
6269+
* value divided by NBASE-1, ie, at the top of the loop it is known that
6270+
* no div[] entry has an absolute value exceeding maxdiv * (NBASE-1).
62656271
*/
62666272
maxdiv = 1;
62676273

@@ -6287,7 +6293,7 @@ div_var_fast(NumericVar *var1, NumericVar *var2, NumericVar *result,
62876293
{
62886294
/* Do we need to normalize now? */
62896295
maxdiv += Abs(qdigit);
6290-
if (maxdiv > INT_MAX / (NBASE - 1))
6296+
if (maxdiv > (INT_MAX - INT_MAX / NBASE - 1) / (NBASE - 1))
62916297
{
62926298
/* Yes, do it */
62936299
carry = 0;

0 commit comments

Comments
 (0)