Skip to content

Commit 5f10b7a

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 c5ec406 commit 5f10b7a

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
@@ -6266,8 +6266,14 @@ div_var_fast(NumericVar *var1, NumericVar *var2, NumericVar *result,
62666266
/*
62676267
* maxdiv tracks the maximum possible absolute value of any div[] entry;
62686268
* when this threatens to exceed INT_MAX, we take the time to propagate
6269-
* carries. To avoid overflow in maxdiv itself, it actually represents
6270-
* the max possible abs. value divided by NBASE-1.
6269+
* carries. Furthermore, we need to ensure that overflow doesn't occur
6270+
* during the carry propagation passes either. The carry values may have
6271+
* an absolute value as high as INT_MAX/NBASE + 1, so really we must
6272+
* normalize when digits threaten to exceed INT_MAX - INT_MAX/NBASE - 1.
6273+
*
6274+
* To avoid overflow in maxdiv itself, it represents the max absolute
6275+
* value divided by NBASE-1, ie, at the top of the loop it is known that
6276+
* no div[] entry has an absolute value exceeding maxdiv * (NBASE-1).
62716277
*/
62726278
maxdiv = 1;
62736279

@@ -6293,7 +6299,7 @@ div_var_fast(NumericVar *var1, NumericVar *var2, NumericVar *result,
62936299
{
62946300
/* Do we need to normalize now? */
62956301
maxdiv += Abs(qdigit);
6296-
if (maxdiv > INT_MAX / (NBASE - 1))
6302+
if (maxdiv > (INT_MAX - INT_MAX / NBASE - 1) / (NBASE - 1))
62976303
{
62986304
/* Yes, do it */
62996305
carry = 0;

0 commit comments

Comments
 (0)