Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions Lib/test/test_itertools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1505,6 +1505,26 @@ def test_zip_longest_result_gc(self):
gc.collect()
self.assertTrue(gc.is_tracked(next(it)))

def test_zip_longest_reentrant_iterator(self):
# A re-entrant iterator exhaust must not cause use-after-free.
class ExhaustingIter:
def __init__(self, it, sibling):
self.it = it
self.sibling = sibling
self.first = True
def __iter__(self):
return self
def __next__(self):
val = next(self.it)
if self.first:
self.first = False
for _ in self.sibling:
pass
return val
sib = iter([2, 3])
zl = zip_longest(ExhaustingIter(iter([1, 4]), sib), sib)
list(zl)

@support.cpython_only
def test_pairwise_result_gc(self):
# Ditto for pairwise.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix use-after-free in :func:`itertools.zip_longest` when a re-entrant
iterator callback exhausts a sibling iterator. Patch by tonghuaroot.
18 changes: 14 additions & 4 deletions Modules/itertoolsmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -3977,19 +3977,24 @@ zip_longest_next_lock_held(PyObject *op)
if (it == NULL) {
item = Py_NewRef(lz->fillvalue);
} else {
Py_INCREF(it);
item = PyIter_Next(it);
if (item == NULL) {
lz->numactive -= 1;
if (lz->numactive == 0 || PyErr_Occurred()) {
lz->numactive = 0;
Py_DECREF(it);
Py_DECREF(result);
return NULL;
} else {
item = Py_NewRef(lz->fillvalue);
PyTuple_SET_ITEM(lz->ittuple, i, NULL);
Py_DECREF(it);
if (PyTuple_GET_ITEM(lz->ittuple, i) != NULL) {
PyTuple_SET_ITEM(lz->ittuple, i, NULL);
Py_DECREF(it);
}
}
}
Py_DECREF(it);
}
olditem = PyTuple_GET_ITEM(result, i);
PyTuple_SET_ITEM(result, i, item);
Expand All @@ -4007,19 +4012,24 @@ zip_longest_next_lock_held(PyObject *op)
if (it == NULL) {
item = Py_NewRef(lz->fillvalue);
} else {
Py_INCREF(it);
item = PyIter_Next(it);
if (item == NULL) {
lz->numactive -= 1;
if (lz->numactive == 0 || PyErr_Occurred()) {
lz->numactive = 0;
Py_DECREF(it);
Py_DECREF(result);
return NULL;
} else {
item = Py_NewRef(lz->fillvalue);
PyTuple_SET_ITEM(lz->ittuple, i, NULL);
Py_DECREF(it);
if (PyTuple_GET_ITEM(lz->ittuple, i) != NULL) {
PyTuple_SET_ITEM(lz->ittuple, i, NULL);
Py_DECREF(it);
}
}
}
Py_DECREF(it);
}
PyTuple_SET_ITEM(result, i, item);
}
Expand Down
Loading