Skip to content

Commit e5b8386

Browse files
committed
gh-152912: Fix audit hook exception check in sys.addaudithook()
sys.addaudithook() checks the exception from existing hooks against PyExc_Exception instead of PyExc_RuntimeError. Any Exception subclass is silently swallowed, blocking new hook installations without propagating the error. The C API and documentation specify RuntimeError only.
1 parent 31864bd commit e5b8386

4 files changed

Lines changed: 16 additions & 2 deletions

File tree

Lib/test/audit-tests.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,16 @@ def test_block_add_hook_baseexception():
109109
pass
110110

111111

112+
def test_block_add_hook_valueerror():
113+
# Non-RuntimeError exceptions (like ValueError) should propagate out
114+
with assertRaises(ValueError):
115+
with TestHook(
116+
raise_on_events="sys.addaudithook", exc_type=ValueError
117+
) as hook1:
118+
with TestHook() as hook2:
119+
pass
120+
121+
112122
def test_marshal():
113123
import marshal
114124
o = ("a", "b", "c", 1, 2, 3)

Lib/test/test_audit.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,9 @@ def test_block_add_hook(self):
5858
def test_block_add_hook_baseexception(self):
5959
self.do_test("test_block_add_hook_baseexception")
6060

61+
def test_block_add_hook_valueerror(self):
62+
self.do_test("test_block_add_hook_valueerror")
63+
6164
def test_marshal(self):
6265
import_helper.import_module("marshal")
6366

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
`sys.addaudithook()` now correctly suppresses only :exc:`RuntimeError` instead of all :exc:`Exception` subclasses when an existing audit hook raises during hook registration. Patch by Yeongu Kim.

Python/sysmodule.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -527,8 +527,8 @@ sys_addaudithook_impl(PyObject *module, PyObject *hook)
527527

528528
/* Invoke existing audit hooks to allow them an opportunity to abort. */
529529
if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) {
530-
if (_PyErr_ExceptionMatches(tstate, PyExc_Exception)) {
531-
/* We do not report errors derived from Exception */
530+
if (_PyErr_ExceptionMatches(tstate, PyExc_RuntimeError)) {
531+
/* We do not report errors derived from RuntimeError */
532532
_PyErr_Clear(tstate);
533533
Py_RETURN_NONE;
534534
}

0 commit comments

Comments
 (0)