Skip to content

Commit 512f67c

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 ca906f6 commit 512f67c

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
@@ -3490,19 +3490,24 @@ tuplesort_heap_replace_top(Tuplesortstate *state, SortTuple *tuple,
34903490
bool checkIndex)
34913491
{
34923492
SortTuple *memtuples = state->memtuples;
3493-
int i,
3493+
unsigned int i,
34943494
n;
34953495

34963496
Assert(!checkIndex || state->currentRun == RUN_FIRST);
34973497
Assert(state->memtupcount >= 1);
34983498

34993499
CHECK_FOR_INTERRUPTS();
35003500

3501+
/*
3502+
* state->memtupcount is "int", but we use "unsigned int" for i, j, n.
3503+
* This prevents overflow in the "2 * i + 1" calculation, since at the top
3504+
* of the loop we must have i < n <= INT_MAX <= UINT_MAX/2.
3505+
*/
35013506
n = state->memtupcount;
35023507
i = 0; /* i is where the "hole" is */
35033508
for (;;)
35043509
{
3505-
int j = 2 * i + 1;
3510+
unsigned int j = 2 * i + 1;
35063511

35073512
if (j >= n)
35083513
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