Skip to content

Commit 405f6d7

Browse files
[3.12] gh-128961: Fix exhausted array iterator crash in __setstate__() (GH-128962) (#128977)
(cherry picked from commit 4dade05) Co-authored-by: Tomasz Pytel <[email protected]>
1 parent 8a8f5d6 commit 405f6d7

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
@@ -1609,5 +1609,13 @@ def test_tolist(self, size):
16091609
self.assertEqual(ls[:8], list(example[:8]))
16101610
self.assertEqual(ls[-8:], list(example[-8:]))
16111611

1612+
def test_gh_128961(self):
1613+
a = array.array('i')
1614+
it = iter(a)
1615+
list(it)
1616+
it.__setstate__(0)
1617+
self.assertRaises(StopIteration, next, it)
1618+
1619+
16121620
if __name__ == "__main__":
16131621
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
@@ -2966,11 +2966,16 @@ array_arrayiterator___setstate__(arrayiterobject *self, PyObject *state)
29662966
Py_ssize_t index = PyLong_AsSsize_t(state);
29672967
if (index == -1 && PyErr_Occurred())
29682968
return NULL;
2969-
if (index < 0)
2970-
index = 0;
2971-
else if (index > Py_SIZE(self->ao))
2972-
index = Py_SIZE(self->ao); /* iterator exhausted */
2973-
self->index = index;
2969+
arrayobject *ao = self->ao;
2970+
if (ao != NULL) {
2971+
if (index < 0) {
2972+
index = 0;
2973+
}
2974+
else if (index > Py_SIZE(ao)) {
2975+
index = Py_SIZE(ao); /* iterator exhausted */
2976+
}
2977+
self->index = index;
2978+
}
29742979
Py_RETURN_NONE;
29752980
}
29762981

0 commit comments

Comments
 (0)