]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.13] gh-109700: fix interpreter finalization while handling memory error (GH-136342...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Mon, 7 Jul 2025 07:37:35 +0000 (09:37 +0200)
committerGitHub <noreply@github.com>
Mon, 7 Jul 2025 07:37:35 +0000 (07:37 +0000)
gh-109700: fix interpreter finalization while handling memory error (GH-136342)
(cherry picked from commit 0c3e3da19570424649c33c0c2c29dc12541935e7)

Co-authored-by: Kumar Aditya <kumaraditya@python.org>
Python/pylifecycle.c

index a8852a88f94a37b938e9ef157088501f456d743d..5e420bdf3377c8fe4eb81dfbe736e25a8d7c5fb7 100644 (file)
@@ -1717,8 +1717,10 @@ finalize_modules(PyThreadState *tstate)
 #endif
 
     // Stop watching __builtin__ modifications
-    PyDict_Unwatch(0, interp->builtins);
-
+    if (PyDict_Unwatch(0, interp->builtins) < 0) {
+        // might happen if interp is cleared before watching the __builtin__
+        PyErr_Clear();
+    }
     PyObject *modules = _PyImport_GetModules(interp);
     if (modules == NULL) {
         // Already done
@@ -2385,15 +2387,13 @@ new_interpreter(PyThreadState **tstate_p,
 error:
     *tstate_p = NULL;
     if (tstate != NULL) {
-        PyThreadState_Clear(tstate);
-        _PyThreadState_Detach(tstate);
-        PyThreadState_Delete(tstate);
+        Py_EndInterpreter(tstate);
+    } else {
+        PyInterpreterState_Delete(interp);
     }
     if (save_tstate != NULL) {
         _PyThreadState_Attach(save_tstate);
     }
-    PyInterpreterState_Delete(interp);
-
     return status;
 }