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
22 changes: 22 additions & 0 deletions Lib/test/test_iter.py
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,28 @@ def spam():
with self.assertRaises(StopIteration):
next(spam.iterator)

def test_calliter_reentrant_sentinel_compare(self):
destroyed = []
compared = []

class Sentinel:
def __del__(self):
destroyed.append(True)

def __eq__(self, other):
it.__setstate__(((), StopIteration))
return NotImplemented

class Result:
def __eq__(self, other):
compared.append(isinstance(other, Sentinel) and not destroyed)
return NotImplemented

it = iter(lambda: Result(), Sentinel())
value = next(it)
self.assertIsInstance(value, Result)
self.assertEqual(compared, [True])

# Test exception propagation through function iterator
def test_exception_function(self):
def spam(state=[0]):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a use-after-free in the two-argument form of :func:`iter` when comparing
the sentinel. A reentrant equality comparison could clear the sentinel and
free it while the comparison was still using it.
4 changes: 3 additions & 1 deletion Objects/iterobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,9 @@ calliter_iternext(PyObject *op)
if (it->it_sentinel == NULL) {
return result; /* Common case, fast path */
}
int ok = PyObject_RichCompareBool(it->it_sentinel, result, Py_EQ);
PyObject *sentinel = Py_NewRef(it->it_sentinel);
int ok = PyObject_RichCompareBool(sentinel, result, Py_EQ);
Py_DECREF(sentinel);
if (ok == 0) {
return result; /* Common case, fast path */
}
Expand Down
Loading