Skip to content

Commit 168174c

Browse files
committed
Install defenses against overflow in BuildTupleHashTable().
The planner can sometimes compute very large values for numGroups, and in cases where we have no alternative to building a hashtable, such a value will get fed directly to BuildTupleHashTable as its nbuckets parameter. There were two ways in which that could go bad. First, BuildTupleHashTable declared the parameter as "int" but most callers were passing "long"s, so on 64-bit machines undetected overflow could occur leading to a bogus negative value. The obvious fix for that is to change the parameter to "long", which is what I've done in HEAD. In the back branches that seems a bit risky, though, since third-party code might be calling this function. So for them, just put in a kluge to treat negative inputs as INT_MAX. Second, hash_create can go nuts with extremely large requested table sizes (notably, my_log2 becomes an infinite loop for inputs larger than LONG_MAX/2). What seems most appropriate to avoid that is to bound the initial table size request to work_mem. This fixes bug #6035 reported by Daniel Schreiber. Although the reported case only occurs back to 8.4 since it involves WITH RECURSIVE, I think it's a good idea to install the defenses in all supported branches.
1 parent 30cf86f commit 168174c

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

src/backend/executor/execGrouping.c

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#include "postgres.h"
1616

1717
#include "executor/executor.h"
18+
#include "miscadmin.h"
1819
#include "parser/parse_oper.h"
1920
#include "utils/lsyscache.h"
2021
#include "utils/memutils.h"
@@ -278,9 +279,20 @@ BuildTupleHashTable(int numCols, AttrNumber *keyColIdx,
278279
TupleHashTable hashtable;
279280
HASHCTL hash_ctl;
280281

281-
Assert(nbuckets > 0);
282+
/*
283+
* Many callers pass "long" values for nbuckets, which means that we can
284+
* receive a bogus value on 64-bit machines. It seems unwise to change
285+
* this function's signature in released branches, so instead assume that
286+
* a negative input means long->int overflow occurred.
287+
*/
288+
if (nbuckets <= 0)
289+
nbuckets = INT_MAX;
290+
282291
Assert(entrysize >= sizeof(TupleHashEntryData));
283292

293+
/* Limit initial table size request to not more than work_mem */
294+
nbuckets = Min(nbuckets, (long) ((work_mem * 1024L) / entrysize));
295+
284296
hashtable = (TupleHashTable) MemoryContextAlloc(tablecxt,
285297
sizeof(TupleHashTableData));
286298

0 commit comments

Comments
 (0)