From: Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> Date: Mon, 29 Mar 2021 23:03:16 +0000 (-0700) Subject: bpo-43660: Fix crash when displaying exceptions with custom values for sys.stderr... X-Git-Tag: v3.8.9~10 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=ba7f8638f93b5d999b25d8556ca19bdc2e12f359;p=thirdparty%2FPython%2Fcpython.git bpo-43660: Fix crash when displaying exceptions with custom values for sys.stderr (GH-25075) (cherry picked from commit 09b90a037d18f5d4acdf1b14082e57bda78e85d3) Co-authored-by: Pablo Galindo --- diff --git a/Lib/test/test_sys.py b/Lib/test/test_sys.py index af0e54bd0e23..140c65aa3bfa 100644 --- a/Lib/test/test_sys.py +++ b/Lib/test/test_sys.py @@ -1441,6 +1441,21 @@ class SizeofTest(unittest.TestCase): self.assertIsNone(cur.firstiter) self.assertIsNone(cur.finalizer) + def test_changing_sys_stderr_and_removing_reference(self): + # If the default displayhook doesn't take a strong reference + # to sys.stderr the following code can crash. See bpo-43660 + # for more details. + code = textwrap.dedent(''' + import sys + class MyStderr: + def write(self, s): + sys.stderr = None + sys.stderr = MyStderr() + 1/0 + ''') + rc, out, err = assert_python_failure('-c', code) + self.assertEqual(out, b"") + self.assertEqual(err, b"") if __name__ == "__main__": unittest.main() diff --git a/Misc/NEWS.d/next/Core and Builtins/2021-03-29-19-50-34.bpo-43660.scTgag.rst b/Misc/NEWS.d/next/Core and Builtins/2021-03-29-19-50-34.bpo-43660.scTgag.rst new file mode 100644 index 000000000000..98419501d9e7 --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2021-03-29-19-50-34.bpo-43660.scTgag.rst @@ -0,0 +1,3 @@ +Fix crash that happens when replacing ``sys.stderr`` with a callable that +can remove the object while an exception is being printed. Patch by Pablo +Galindo. diff --git a/Python/pythonrun.c b/Python/pythonrun.c index 3831e81ee9b8..c55e7674a665 100644 --- a/Python/pythonrun.c +++ b/Python/pythonrun.c @@ -1034,8 +1034,9 @@ PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb) if (file == Py_None) { return; } - + Py_INCREF(file); _PyErr_Display(file, exception, value, tb); + Py_DECREF(file); } PyObject *