Skip to content

Commit fab1405

Browse files
authored
gh-159739: Fix reference and error handling in warnings (#159758)
Do not release the borrowed skip_file_prefixes argument, and stop if allocation of the fallback filename fails.
1 parent 9c649db commit fab1405

3 files changed

Lines changed: 19 additions & 1 deletion

File tree

‎Lib/test/test_warnings/__init__.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -698,6 +698,20 @@ def test_skip_file_prefixes_type_errors(self):
698698
with self.assertRaises(TypeError):
699699
warn("msg", skip_file_prefixes="a sequence of strs")
700700

701+
def test_skip_file_prefixes_empty_tuple_subclass(self):
702+
with warnings_state(self.module):
703+
self.module.simplefilter("always")
704+
warn = warning_tests.warnings.warn
705+
class EmptyTuple(tuple):
706+
pass
707+
# Passing an empty tuple subclass used to lead to a crash.
708+
for _ in range(3):
709+
with self.module.catch_warnings(record=True) as w:
710+
warn("msg", skip_file_prefixes=EmptyTuple())
711+
self.assertEqual(len(w), 1)
712+
self.assertEqual(w[-1].filename, __file__)
713+
self.assertEqual(w[-1].module, __name__)
714+
701715
def test_exec_filename_module(self):
702716
filename = "<warnings-test>"
703717
codeobj = compile(("import warnings\n"
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a crash in :func:`warnings.warn` when ``skip_file_prefixes`` is an empty tuple subclass.
2+
Propagate allocation errors when creating the fallback filename.

‎Python/_warnings.c‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1053,6 +1053,9 @@ setup_context(Py_ssize_t stack_level,
10531053
if (f == NULL) {
10541054
globals = interp->sysdict;
10551055
*filename = PyUnicode_FromString("<sys>");
1056+
if (*filename == NULL) {
1057+
return 0;
1058+
}
10561059
*lineno = 0;
10571060
}
10581061
else {
@@ -1196,7 +1199,6 @@ warnings_warn_impl(PyObject *module, PyObject *message, PyObject *category,
11961199
stacklevel = 2;
11971200
}
11981201
} else {
1199-
Py_DECREF((PyObject *)skip_file_prefixes);
12001202
skip_file_prefixes = NULL;
12011203
}
12021204
}

0 commit comments

Comments
 (0)