Skip to content

Commit 1d0baf1

Browse files
authored
[3.14] gh-143547: Fix PyErr_FormatUnraisable() fallback (#143557) (#143603)
gh-143547: Fix PyErr_FormatUnraisable() fallback (#143557) Hold a strong reference to 'hook' while calling the default unraisable took to log hook failure. (cherry picked from commit 39a2bcf)
1 parent f264f10 commit 1d0baf1

File tree

3 files changed

+6
-4
lines changed

3 files changed

+6
-4
lines changed

Lib/test/test_sys.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1480,6 +1480,7 @@ def hook_func(args):
14801480
def test_custom_unraisablehook_fail(self):
14811481
_testcapi = import_helper.import_module('_testcapi')
14821482
from _testcapi import err_writeunraisable
1483+
14831484
def hook_func(*args):
14841485
raise Exception("hook_func failed")
14851486

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix :func:`sys.unraisablehook` when the hook raises an exception and changes
2+
:func:`sys.unraisablehook`: hold a strong reference to the old hook. Patch
3+
by Victor Stinner.

Python/errors.c

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1632,6 +1632,7 @@ format_unraisable_v(const char *format, va_list va, PyObject *obj)
16321632
_Py_EnsureTstateNotNULL(tstate);
16331633

16341634
PyObject *err_msg = NULL;
1635+
PyObject *hook = NULL;
16351636
PyObject *exc_type, *exc_value, *exc_tb;
16361637
_PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);
16371638

@@ -1676,7 +1677,6 @@ format_unraisable_v(const char *format, va_list va, PyObject *obj)
16761677
goto error;
16771678
}
16781679

1679-
PyObject *hook;
16801680
if (_PySys_GetOptionalAttr(&_Py_ID(unraisablehook), &hook) < 0) {
16811681
Py_DECREF(hook_args);
16821682
err_msg_str = NULL;
@@ -1689,21 +1689,18 @@ format_unraisable_v(const char *format, va_list va, PyObject *obj)
16891689
}
16901690

16911691
if (_PySys_Audit(tstate, "sys.unraisablehook", "OO", hook, hook_args) < 0) {
1692-
Py_DECREF(hook);
16931692
Py_DECREF(hook_args);
16941693
err_msg_str = "Exception ignored in audit hook";
16951694
obj = NULL;
16961695
goto error;
16971696
}
16981697

16991698
if (hook == Py_None) {
1700-
Py_DECREF(hook);
17011699
Py_DECREF(hook_args);
17021700
goto default_hook;
17031701
}
17041702

17051703
PyObject *res = PyObject_CallOneArg(hook, hook_args);
1706-
Py_DECREF(hook);
17071704
Py_DECREF(hook_args);
17081705
if (res != NULL) {
17091706
Py_DECREF(res);
@@ -1733,6 +1730,7 @@ format_unraisable_v(const char *format, va_list va, PyObject *obj)
17331730
Py_XDECREF(exc_value);
17341731
Py_XDECREF(exc_tb);
17351732
Py_XDECREF(err_msg);
1733+
Py_XDECREF(hook);
17361734
_PyErr_Clear(tstate); /* Just in case */
17371735
}
17381736

0 commit comments

Comments
 (0)