Skip to content

Commit fc840db

Browse files
[3.15] gh-153210: Fix array module import crash under a memory pressure (GH-153238) (#153249)
gh-153210: Fix `array` module import crash under a memory pressure (GH-153238) (cherry picked from commit 12ed8b1) Co-authored-by: sobolevn <mail@sobolevn.me>
1 parent 60ced36 commit fc840db

3 files changed

Lines changed: 19 additions & 8 deletions

File tree

Lib/test/test_array.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import collections.abc
66
import unittest
77
from test import support
8-
from test.support import import_helper
8+
from test.support import import_helper, script_helper
99
from test.support import os_helper
1010
from test.support import _2G
1111
from test.support import subTests
@@ -49,6 +49,23 @@ def test_bad_constructor(self):
4949
self.assertRaises(ValueError, array.array, 'x')
5050
self.assertRaises(ValueError, array.array, 'Z')
5151

52+
@support.cpython_only
53+
def test_does_not_crash_on_broken_imports(self):
54+
# gh-153210
55+
code = """if 1:
56+
import collections.abc
57+
58+
del collections.abc.MutableSequence
59+
60+
try:
61+
import array # it used to crash before
62+
except AttributeError:
63+
pass
64+
else:
65+
raise AssertionError('AttributeError was not raised')
66+
"""
67+
script_helper.assert_python_ok('-c', code)
68+
5269
@support.cpython_only
5370
def test_disallow_instantiation(self):
5471
my_array = array.array("I")
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix crash on :mod:`array` import under a memory pressure.

Modules/arraymodule.c

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3502,22 +3502,15 @@ array_modexec(PyObject *m)
35023502
CREATE_TYPE(m, state->ArrayIterType, &arrayiter_spec);
35033503
Py_SET_TYPE(state->ArrayIterType, &PyType_Type);
35043504

3505-
if (PyModule_AddObjectRef(m, "ArrayType",
3506-
(PyObject *)state->ArrayType) < 0) {
3507-
return -1;
3508-
}
3509-
35103505
PyObject *mutablesequence = PyImport_ImportModuleAttrString(
35113506
"collections.abc", "MutableSequence");
35123507
if (!mutablesequence) {
3513-
Py_DECREF((PyObject *)state->ArrayType);
35143508
return -1;
35153509
}
35163510
PyObject *res = PyObject_CallMethod(mutablesequence, "register", "O",
35173511
(PyObject *)state->ArrayType);
35183512
Py_DECREF(mutablesequence);
35193513
if (!res) {
3520-
Py_DECREF((PyObject *)state->ArrayType);
35213514
return -1;
35223515
}
35233516
Py_DECREF(res);

0 commit comments

Comments
 (0)