bpo-43660: Fix crash when displaying exceptions with custom values for sys.stderr (GH-25075) (GH-25083)

(cherry picked from commit 09b90a037d)

Co-authored-by: Pablo Galindo <Pablogsal@gmail.com>

Co-authored-by: Pablo Galindo <Pablogsal@gmail.com>
This commit is contained in:
Miss Islington (bot) 2021-03-29 16:24:33 -07:00 committed by GitHub
parent acb584958e
commit ff4715a733
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 20 additions and 1 deletions

View file

@ -1417,6 +1417,21 @@ def test_asyncgen_hooks(self):
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()

View file

@ -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.

View file

@ -1072,8 +1072,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 *