Skip to content

Commit 7e69916

Browse files
committed
gh-153210: Fix array module import crash under a memory pressure
1 parent ef4d3f3 commit 7e69916

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
@@ -42,6 +42,23 @@ def test_bad_constructor(self):
4242
self.assertRaises(ValueError, array.array, 'x')
4343
self.assertRaises(ValueError, array.array, 'Z')
4444

45+
@support.cpython_only
46+
def test_does_not_crash_on_broken_imports(self):
47+
# gh-153210
48+
code = """if 1:
49+
import collections.abc
50+
51+
del collections.abc.MutableSequence
52+
53+
try:
54+
import array # it used to crash before
55+
except AttributeError:
56+
pass
57+
else:
58+
raise AssertionError('AttributeError was not raised')
59+
"""
60+
script_helper.assert_python_ok('-c', code)
61+
4562
@support.cpython_only
4663
def test_disallow_instantiation(self):
4764
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
@@ -3401,22 +3401,15 @@ array_modexec(PyObject *m)
34013401
CREATE_TYPE(m, state->ArrayIterType, &arrayiter_spec);
34023402
Py_SET_TYPE(state->ArrayIterType, &PyType_Type);
34033403

3404-
if (PyModule_AddObjectRef(m, "ArrayType",
3405-
(PyObject *)state->ArrayType) < 0) {
3406-
return -1;
3407-
}
3408-
34093404
PyObject *mutablesequence = PyImport_ImportModuleAttrString(
34103405
"collections.abc", "MutableSequence");
34113406
if (!mutablesequence) {
3412-
Py_DECREF((PyObject *)state->ArrayType);
34133407
return -1;
34143408
}
34153409
PyObject *res = PyObject_CallMethod(mutablesequence, "register", "O",
34163410
(PyObject *)state->ArrayType);
34173411
Py_DECREF(mutablesequence);
34183412
if (!res) {
3419-
Py_DECREF((PyObject *)state->ArrayType);
34203413
return -1;
34213414
}
34223415
Py_DECREF(res);

0 commit comments

Comments
 (0)