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
41 changes: 41 additions & 0 deletions Lib/test/test_asyncgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,47 @@ def test_aiter_callable_exhausted(self):
with self.assertRaises(StopAsyncIteration):
self.loop.run_until_complete(anext(it))

def test_aiter_callable_reentrant_sentinel_compare(self):
stop = False
destroyed = []
compared = []

async def produce():
return Result()

def fetch():
nonlocal stop
if stop:
raise StopAsyncIteration
return produce()

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

def __eq__(self, other):
nonlocal stop
stop = True
aw = ait.__anext__()
try:
aw.__await__().send(None)
except StopAsyncIteration:
pass
return NotImplemented

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

ait = aiter(fetch, Sentinel())
with self.assertRaises(StopIteration) as cm:
ait.__anext__().__await__().send(None)
self.assertIsInstance(cm.exception.value, Result)
self.assertEqual(compared, [True])
with self.assertRaises(StopAsyncIteration):
ait.__anext__().__await__().send(None)

def test_aiter_callable_lazy(self):
# The callable is only called when the awaitable is awaited
calls = []
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:`aiter` when comparing
the sentinel. A reentrant equality comparison could exhaust the iterator and
free the sentinel 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 @@ -641,7 +641,9 @@ acallawaitable_handle_error(acallawaitableobject *aw)
}
int ok = 0;
if (it->it_sentinel != NULL) {
ok = PyObject_RichCompareBool(it->it_sentinel, value, Py_EQ);
PyObject *sentinel = Py_NewRef(it->it_sentinel);
ok = PyObject_RichCompareBool(sentinel, value, Py_EQ);
Py_DECREF(sentinel);
}
if (ok == 0) {
(void)_PyGen_SetStopIterationValue(value);
Expand Down
Loading