gh-109894: Fix initialization of static `MemoryError` in subinterpreter (gh-110911)

Fixes #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

---------

Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com>
This commit is contained in:
Radislav Chugunov 2023-10-24 02:06:59 +03:00 committed by GitHub
parent 96cbd1e1db
commit 47d3e2ed93
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 16 additions and 4 deletions

View File

@ -177,6 +177,7 @@ extern PyTypeObject _PyExc_MemoryError;
}, \ }, \
.last_resort_memory_error = { \ .last_resort_memory_error = { \
_PyObject_HEAD_INIT(&_PyExc_MemoryError) \ _PyObject_HEAD_INIT(&_PyExc_MemoryError) \
.args = (PyObject*)&_Py_SINGLETON(tuple_empty) \
}, \ }, \
}, \ }, \
}, \ }, \

View File

@ -1791,6 +1791,20 @@ class ExceptionTests(unittest.TestCase):
gc_collect() gc_collect()
def test_memory_error_in_subinterp(self):
# gh-109894: subinterpreters shouldn't count on last resort memory error
# when MemoryError is raised through PyErr_NoMemory() call,
# and should preallocate memory errors as does the main interpreter.
# interp.static_objects.last_resort_memory_error.args
# should be initialized to empty tuple to avoid crash on attempt to print it.
code = f"""if 1:
import _testcapi
_testcapi.run_in_subinterp(\"[0]*{sys.maxsize}\")
exit(0)
"""
rc, _, err = script_helper.assert_python_ok("-c", code)
self.assertIn(b'MemoryError', err)
class NameErrorTests(unittest.TestCase): class NameErrorTests(unittest.TestCase):
def test_name_error_has_name(self): def test_name_error_has_name(self):

View File

@ -0,0 +1 @@
Fixed crash due to improperly initialized static :exc:`MemoryError` in subinterpreter.

View File

@ -3700,10 +3700,6 @@ _PyExc_FiniTypes(PyInterpreterState *interp)
PyStatus PyStatus
_PyExc_InitGlobalObjects(PyInterpreterState *interp) _PyExc_InitGlobalObjects(PyInterpreterState *interp)
{ {
if (!_Py_IsMainInterpreter(interp)) {
return _PyStatus_OK();
}
if (preallocate_memerrors() < 0) { if (preallocate_memerrors() < 0) {
return _PyStatus_NO_MEMORY(); return _PyStatus_NO_MEMORY();
} }