From: Tomasz Pytel Date: Sat, 18 Jan 2025 09:55:29 +0000 (-0500) Subject: gh-128961: Fix exhausted array iterator crash in __setstate__() (#128962) X-Git-Tag: v3.14.0a5~385 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=4dade055f4e18a7e91bc70293abb4db745ad16ca;p=thirdparty%2FPython%2Fcpython.git gh-128961: Fix exhausted array iterator crash in __setstate__() (#128962) --- diff --git a/Lib/test/test_array.py b/Lib/test/test_array.py index f621f343eb06..58ea89c4fac8 100755 --- a/Lib/test/test_array.py +++ b/Lib/test/test_array.py @@ -1665,5 +1665,13 @@ class LargeArrayTest(unittest.TestCase): self.assertEqual(ls[:8], list(example[:8])) self.assertEqual(ls[-8:], list(example[-8:])) + def test_gh_128961(self): + a = array.array('i') + it = iter(a) + list(it) + it.__setstate__(0) + self.assertRaises(StopIteration, next, it) + + if __name__ == "__main__": unittest.main() diff --git a/Misc/NEWS.d/next/Library/2025-01-17-21-33-11.gh-issue-128961.XwvyIZ.rst b/Misc/NEWS.d/next/Library/2025-01-17-21-33-11.gh-issue-128961.XwvyIZ.rst new file mode 100644 index 000000000000..9c985df77743 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-01-17-21-33-11.gh-issue-128961.XwvyIZ.rst @@ -0,0 +1 @@ +Fix a crash when setting state on an exhausted :class:`array.array` iterator. diff --git a/Modules/arraymodule.c b/Modules/arraymodule.c index b80c964f20d6..fdbb0f0e8d66 100644 --- a/Modules/arraymodule.c +++ b/Modules/arraymodule.c @@ -3090,11 +3090,16 @@ array_arrayiterator___setstate__(arrayiterobject *self, PyObject *state) Py_ssize_t index = PyLong_AsSsize_t(state); if (index == -1 && PyErr_Occurred()) return NULL; - if (index < 0) - index = 0; - else if (index > Py_SIZE(self->ao)) - index = Py_SIZE(self->ao); /* iterator exhausted */ - self->index = index; + arrayobject *ao = self->ao; + if (ao != NULL) { + if (index < 0) { + index = 0; + } + else if (index > Py_SIZE(ao)) { + index = Py_SIZE(ao); /* iterator exhausted */ + } + self->index = index; + } Py_RETURN_NONE; }