Skip to content

Commit 6665802

Browse files
miss-islingtonsir-sigurd
authored andcommitted
bpo-1621: Avoid signed integer overflow in set_table_resize() (GH-9059) (GH-9198)
Address a C undefined behavior signed integer overflow issue in set object table resizing. Our -fwrapv compiler flag and practical reasons why sets are unlikely to get this large should mean this was never an issue but it was incorrect code that generates code analysis warnings. Co-authored-by: Sergey Fedoseev <[email protected]>
1 parent 76d31a3 commit 6665802

File tree

2 files changed

+5
-8
lines changed

2 files changed

+5
-8
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Do not assume signed integer overflow behavior (C undefined behavior) when
2+
performing set hash table resizing.

Objects/setobject.c

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,6 @@ actually be smaller than the old one.
302302
static int
303303
set_table_resize(PySetObject *so, Py_ssize_t minused)
304304
{
305-
Py_ssize_t newsize;
306305
setentry *oldtable, *newtable, *entry;
307306
Py_ssize_t oldmask = so->mask;
308307
size_t newmask;
@@ -313,13 +312,9 @@ set_table_resize(PySetObject *so, Py_ssize_t minused)
313312

314313
/* Find the smallest table size > minused. */
315314
/* XXX speed-up with intrinsics */
316-
for (newsize = PySet_MINSIZE;
317-
newsize <= minused && newsize > 0;
318-
newsize <<= 1)
319-
;
320-
if (newsize <= 0) {
321-
PyErr_NoMemory();
322-
return -1;
315+
size_t newsize = PySet_MINSIZE;
316+
while (newsize <= (size_t)minused) {
317+
newsize <<= 1; // The largest possible value is PY_SSIZE_T_MAX + 1.
323318
}
324319

325320
/* Get space for a new table. */

0 commit comments

Comments
 (0)