]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-109894: Fix initialization of static `MemoryError` in subinterpreter (gh-110911)
authorRadislav Chugunov <52372310+chgnrdv@users.noreply.github.com>
Mon, 23 Oct 2023 23:06:59 +0000 (02:06 +0300)
committerGitHub <noreply@github.com>
Mon, 23 Oct 2023 23:06:59 +0000 (17:06 -0600)
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>
Include/internal/pycore_runtime_init.h
Lib/test/test_exceptions.py
Misc/NEWS.d/next/Core and Builtins/2023-10-15-22-18-45.gh-issue-109894.UAmo06.rst [new file with mode: 0644]
Objects/exceptions.c

index 574a3c1a9db66cdea20c905cfa0a1d816bfbb71f..4a48907d9ee2f67c3eb74534197e09f081610ef1 100644 (file)
@@ -177,6 +177,7 @@ extern PyTypeObject _PyExc_MemoryError;
                 }, \
                 .last_resort_memory_error = { \
                     _PyObject_HEAD_INIT(&_PyExc_MemoryError) \
+                    .args = (PyObject*)&_Py_SINGLETON(tuple_empty) \
                 }, \
             }, \
         }, \
index 4031c5ca76c7055182d5a9f7270df3acc1e6c4d1..7f1d5ee9322b4589a898fb1f1a101a7c1f380ba0 100644 (file)
@@ -1791,6 +1791,20 @@ class ExceptionTests(unittest.TestCase):
 
             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):
     def test_name_error_has_name(self):
diff --git a/Misc/NEWS.d/next/Core and Builtins/2023-10-15-22-18-45.gh-issue-109894.UAmo06.rst b/Misc/NEWS.d/next/Core and Builtins/2023-10-15-22-18-45.gh-issue-109894.UAmo06.rst
new file mode 100644 (file)
index 0000000..2148536
--- /dev/null
@@ -0,0 +1 @@
+Fixed crash due to improperly initialized static :exc:`MemoryError` in subinterpreter.
index 48623451c0d2cd41ad829a0fb5af25fab19a5a6b..e3e8e02861d77500bc1224cdc9537d06500eafea 100644 (file)
@@ -3700,10 +3700,6 @@ _PyExc_FiniTypes(PyInterpreterState *interp)
 PyStatus
 _PyExc_InitGlobalObjects(PyInterpreterState *interp)
 {
-    if (!_Py_IsMainInterpreter(interp)) {
-        return _PyStatus_OK();
-    }
-
     if (preallocate_memerrors() < 0) {
         return _PyStatus_NO_MEMORY();
     }