Skip to content

Commit 7df6dc4

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 faf18a9 commit 7df6dc4

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
@@ -4875,8 +4875,14 @@ div_var_fast(NumericVar *var1, NumericVar *var2, NumericVar *result,
48754875
/*
48764876
* maxdiv tracks the maximum possible absolute value of any div[] entry;
48774877
* when this threatens to exceed INT_MAX, we take the time to propagate
4878-
* carries. To avoid overflow in maxdiv itself, it actually represents
4879-
* the max possible abs. value divided by NBASE-1.
4878+
* carries. Furthermore, we need to ensure that overflow doesn't occur
4879+
* during the carry propagation passes either. The carry values may have
4880+
* an absolute value as high as INT_MAX/NBASE + 1, so really we must
4881+
* normalize when digits threaten to exceed INT_MAX - INT_MAX/NBASE - 1.
4882+
*
4883+
* To avoid overflow in maxdiv itself, it represents the max absolute
4884+
* value divided by NBASE-1, ie, at the top of the loop it is known that
4885+
* no div[] entry has an absolute value exceeding maxdiv * (NBASE-1).
48804886
*/
48814887
maxdiv = 1;
48824888

@@ -4902,7 +4908,7 @@ div_var_fast(NumericVar *var1, NumericVar *var2, NumericVar *result,
49024908
{
49034909
/* Do we need to normalize now? */
49044910
maxdiv += Abs(qdigit);
4905-
if (maxdiv > INT_MAX / (NBASE - 1))
4911+
if (maxdiv > (INT_MAX - INT_MAX / NBASE - 1) / (NBASE - 1))
49064912
{
49074913
/* Yes, do it */
49084914
carry = 0;

0 commit comments

Comments
 (0)