https://github.com/python/cpython/commit/405f6d72bb21c94cd4491559d2377db5b41091f0
commit: 405f6d72bb21c94cd4491559d2377db5b41091f0
branch: 3.12
author: Miss Islington (bot) <[email protected]>
committer: erlend-aasland <[email protected]>
date: 2025-01-18T10:14:07Z
summary:

[3.12] gh-128961: Fix exhausted array iterator crash in __setstate__() 
(GH-128962) (#128977)

(cherry picked from commit 4dade055f4e18a7e91bc70293abb4db745ad16ca)

Co-authored-by: Tomasz Pytel <[email protected]>

files:
A Misc/NEWS.d/next/Library/2025-01-17-21-33-11.gh-issue-128961.XwvyIZ.rst
M Lib/test/test_array.py
M Modules/arraymodule.c

diff --git a/Lib/test/test_array.py b/Lib/test/test_array.py
index 9c21cf035b1975..9b4847bf11abc7 100755
--- a/Lib/test/test_array.py
+++ b/Lib/test/test_array.py
@@ -1609,5 +1609,13 @@ def test_tolist(self, size):
         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 00000000000000..9c985df77743da
--- /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 d24c5989af36fc..090a7b841c93ea 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;
 }
 

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-checkins.python.org/
Member address: [email protected]

Reply via email to