From: Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> Date: Sat, 18 Jan 2025 10:14:07 +0000 (+0100) Subject: [3.12] gh-128961: Fix exhausted array iterator crash in __setstate__() (GH-128962... X-Git-Tag: v3.12.9~66 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=405f6d72bb21c94cd4491559d2377db5b41091f0;p=thirdparty%2FPython%2Fcpython.git [3.12] gh-128961: Fix exhausted array iterator crash in __setstate__() (GH-128962) (#128977) (cherry picked from commit 4dade055f4e18a7e91bc70293abb4db745ad16ca) Co-authored-by: Tomasz Pytel --- diff --git a/Lib/test/test_array.py b/Lib/test/test_array.py index 9c21cf035b19..9b4847bf11ab 100755 --- a/Lib/test/test_array.py +++ b/Lib/test/test_array.py @@ -1609,5 +1609,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 d24c5989af36..090a7b841c93 100644 --- a/Modules/arraymodule.c +++ b/Modules/arraymodule.c @@ -2966,11 +2966,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; }