Skip to content

Commit 09c5988

Browse files
committed
Avoid integer overflow while sifting-up a heap in tuplesort.c.
If the number of tuples in the heap exceeds approximately INT_MAX/2, this loop's calculation "2*i+1" could overflow, resulting in a crash. Fix it by using unsigned int rather than int for the relevant local variables; that shouldn't cost anything extra on any popular hardware. Per bug #14722 from Sergey Koposov. Original patch by Sergey Koposov, modified by me per a suggestion from Heikki Linnakangas to use unsigned int not int64. Back-patch to 9.4, where tuplesort.c grew the ability to sort as many as INT_MAX tuples in-memory (commit 263865a). Discussion: https://postgr.es/m/20170629161637.1478.93109@wrigleys.postgresql.org
1 parent 0a2d07c commit 09c5988

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

src/backend/utils/sort/tuplesort.c

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3800,7 +3800,7 @@ tuplesort_heap_siftup(Tuplesortstate *state, bool checkIndex)
38003800
{
38013801
SortTuple *memtuples = state->memtuples;
38023802
SortTuple *tuple;
3803-
int i,
3803+
unsigned int i,
38043804
n;
38053805

38063806
Assert(!checkIndex || state->currentRun == RUN_FIRST);
@@ -3809,12 +3809,17 @@ tuplesort_heap_siftup(Tuplesortstate *state, bool checkIndex)
38093809

38103810
CHECK_FOR_INTERRUPTS();
38113811

3812+
/*
3813+
* state->memtupcount is "int", but we use "unsigned int" for i, j, n.
3814+
* This prevents overflow in the "2 * i + 1" calculation, since at the top
3815+
* of the loop we must have i < n <= INT_MAX <= UINT_MAX/2.
3816+
*/
38123817
n = state->memtupcount;
38133818
tuple = &memtuples[n]; /* tuple that must be reinserted */
38143819
i = 0; /* i is where the "hole" is */
38153820
for (;;)
38163821
{
3817-
int j = 2 * i + 1;
3822+
unsigned int j = 2 * i + 1;
38183823

38193824
if (j >= n)
38203825
break;

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy