Skip to content

Commit cc95595

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 8bc496c commit cc95595

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

src/backend/utils/adt/numeric.c

+9-3
Original file line numberDiff line numberDiff line change
@@ -5311,8 +5311,14 @@ div_var_fast(NumericVar *var1, NumericVar *var2, NumericVar *result,
53115311
/*
53125312
* maxdiv tracks the maximum possible absolute value of any div[] entry;
53135313
* when this threatens to exceed INT_MAX, we take the time to propagate
5314-
* carries. To avoid overflow in maxdiv itself, it actually represents
5315-
* the max possible abs. value divided by NBASE-1.
5314+
* carries. Furthermore, we need to ensure that overflow doesn't occur
5315+
* during the carry propagation passes either. The carry values may have
5316+
* an absolute value as high as INT_MAX/NBASE + 1, so really we must
5317+
* normalize when digits threaten to exceed INT_MAX - INT_MAX/NBASE - 1.
5318+
*
5319+
* To avoid overflow in maxdiv itself, it represents the max absolute
5320+
* value divided by NBASE-1, ie, at the top of the loop it is known that
5321+
* no div[] entry has an absolute value exceeding maxdiv * (NBASE-1).
53165322
*/
53175323
maxdiv = 1;
53185324

@@ -5338,7 +5344,7 @@ div_var_fast(NumericVar *var1, NumericVar *var2, NumericVar *result,
53385344
{
53395345
/* Do we need to normalize now? */
53405346
maxdiv += Abs(qdigit);
5341-
if (maxdiv > INT_MAX / (NBASE - 1))
5347+
if (maxdiv > (INT_MAX - INT_MAX / NBASE - 1) / (NBASE - 1))
53425348
{
53435349
/* Yes, do it */
53445350
carry = 0;

0 commit comments

Comments
 (0)