Skip to content

Commit 0aceac5

Browse files
miss-islingtonchgnrdvblurb-it[bot]
authored
[3.12] gh-109894: Fix initialization of static MemoryError in subinterpreter (gh-110911) (gh-111238)
Fixes GH-109894 * set `interp.static_objects.last_resort_memory_error.args` to empty tuple to avoid crash on `PyErr_Display()` call * allow `_PyExc_InitGlobalObjects()` to be called on subinterpreter init --------- (cherry picked from commit 47d3e2e) Co-authored-by: Radislav Chugunov <[email protected]> Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com>
1 parent 1e1a30f commit 0aceac5

File tree

4 files changed

+16
-4
lines changed

4 files changed

+16
-4
lines changed

Include/internal/pycore_runtime_init.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@ extern PyTypeObject _PyExc_MemoryError;
119119
}, \
120120
.last_resort_memory_error = { \
121121
_PyObject_HEAD_INIT(&_PyExc_MemoryError) \
122+
.args = (PyObject*)&_Py_SINGLETON(tuple_empty) \
122123
}, \
123124
}, \
124125
}, \

Lib/test/test_exceptions.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1785,6 +1785,20 @@ class TestException(MemoryError):
17851785

17861786
gc_collect()
17871787

1788+
def test_memory_error_in_subinterp(self):
1789+
# gh-109894: subinterpreters shouldn't count on last resort memory error
1790+
# when MemoryError is raised through PyErr_NoMemory() call,
1791+
# and should preallocate memory errors as does the main interpreter.
1792+
# interp.static_objects.last_resort_memory_error.args
1793+
# should be initialized to empty tuple to avoid crash on attempt to print it.
1794+
code = f"""if 1:
1795+
import _testcapi
1796+
_testcapi.run_in_subinterp(\"[0]*{sys.maxsize}\")
1797+
exit(0)
1798+
"""
1799+
rc, _, err = script_helper.assert_python_ok("-c", code)
1800+
self.assertIn(b'MemoryError', err)
1801+
17881802

17891803
class NameErrorTests(unittest.TestCase):
17901804
def test_name_error_has_name(self):
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fixed crash due to improperly initialized static :exc:`MemoryError` in subinterpreter.

Objects/exceptions.c

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3701,10 +3701,6 @@ _PyExc_FiniTypes(PyInterpreterState *interp)
37013701
PyStatus
37023702
_PyExc_InitGlobalObjects(PyInterpreterState *interp)
37033703
{
3704-
if (!_Py_IsMainInterpreter(interp)) {
3705-
return _PyStatus_OK();
3706-
}
3707-
37083704
if (preallocate_memerrors() < 0) {
37093705
return _PyStatus_NO_MEMORY();
37103706
}

0 commit comments

Comments
 (0)