Skip to content

Commit c75894a

Browse files
[3.13] gh-128961: Fix exhausted array iterator crash in __setstate__() (GH-128962) (#128976)
(cherry picked from commit 4dade05) Co-authored-by: Tomasz Pytel <[email protected]>
1 parent d8a4426 commit c75894a

File tree

3 files changed

+19
-5
lines changed

3 files changed

+19
-5
lines changed

Lib/test/test_array.py

+8
Original file line numberDiff line numberDiff line change
@@ -1665,5 +1665,13 @@ def test_tolist(self, size):
16651665
self.assertEqual(ls[:8], list(example[:8]))
16661666
self.assertEqual(ls[-8:], list(example[-8:]))
16671667

1668+
def test_gh_128961(self):
1669+
a = array.array('i')
1670+
it = iter(a)
1671+
list(it)
1672+
it.__setstate__(0)
1673+
self.assertRaises(StopIteration, next, it)
1674+
1675+
16681676
if __name__ == "__main__":
16691677
unittest.main()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a crash when setting state on an exhausted :class:`array.array` iterator.

Modules/arraymodule.c

+10-5
Original file line numberDiff line numberDiff line change
@@ -3074,11 +3074,16 @@ array_arrayiterator___setstate__(arrayiterobject *self, PyObject *state)
30743074
Py_ssize_t index = PyLong_AsSsize_t(state);
30753075
if (index == -1 && PyErr_Occurred())
30763076
return NULL;
3077-
if (index < 0)
3078-
index = 0;
3079-
else if (index > Py_SIZE(self->ao))
3080-
index = Py_SIZE(self->ao); /* iterator exhausted */
3081-
self->index = index;
3077+
arrayobject *ao = self->ao;
3078+
if (ao != NULL) {
3079+
if (index < 0) {
3080+
index = 0;
3081+
}
3082+
else if (index > Py_SIZE(ao)) {
3083+
index = Py_SIZE(ao); /* iterator exhausted */
3084+
}
3085+
self->index = index;
3086+
}
30823087
Py_RETURN_NONE;
30833088
}
30843089

0 commit comments

Comments
 (0)