From 846fbbfb83c01790aa641b2e2786a498e439e769 Mon Sep 17 00:00:00 2001 From: lul-cas Date: Wed, 23 Sep 2026 21:09:32 -0300 Subject: [PATCH 1/2] gh-158031: Keep the iter sentinel alive during comparison --- Lib/test/test_iter.py | 22 ++++++++++++++++++++++ Objects/iterobject.c | 4 +++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_iter.py b/Lib/test/test_iter.py index fe8617309da29d..6892b30fe9e129 100644 --- a/Lib/test/test_iter.py +++ b/Lib/test/test_iter.py @@ -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]): diff --git a/Objects/iterobject.c b/Objects/iterobject.c index 2d5e3709a27dfb..7a86940632b689 100644 --- a/Objects/iterobject.c +++ b/Objects/iterobject.c @@ -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 */ } From b01ea1fc472baf55f674a1689a6dadd03b1a65d7 Mon Sep 17 00:00:00 2001 From: lul-cas Date: Wed, 23 Sep 2026 21:47:53 -0300 Subject: [PATCH 2/2] gh-158031: Add the NEWS entry for the iter sentinel fix --- .../2026-09-23-21-41-00.gh-issue-158031.nW4pQs.rst | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-09-23-21-41-00.gh-issue-158031.nW4pQs.rst diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-09-23-21-41-00.gh-issue-158031.nW4pQs.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-09-23-21-41-00.gh-issue-158031.nW4pQs.rst new file mode 100644 index 00000000000000..b8464929bf104c --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-09-23-21-41-00.gh-issue-158031.nW4pQs.rst @@ -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.