Skip to content

Commit a03d287

Browse files
authored
[3.14] gh-159739: Fix reference and error handling in warnings (GH-159758) (#160085)
Do not release the borrowed skip_file_prefixes argument, and stop if allocation of the fallback filename fails. (cherry picked from commit fab1405)
1 parent 6603289 commit a03d287

3 files changed

Lines changed: 18 additions & 1 deletion

File tree

‎Lib/test/test_warnings/__init__.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -663,6 +663,19 @@ def test_skip_file_prefixes_type_errors(self):
663663
with self.assertRaises(TypeError):
664664
warn("msg", skip_file_prefixes="a sequence of strs")
665665

666+
def test_skip_file_prefixes_empty_tuple_subclass(self):
667+
with warnings_state(self.module):
668+
self.module.simplefilter("always")
669+
warn = warning_tests.warnings.warn
670+
class EmptyTuple(tuple):
671+
pass
672+
# Passing an empty tuple subclass used to lead to a crash.
673+
for _ in range(3):
674+
with self.module.catch_warnings(record=True) as w:
675+
warn("msg", skip_file_prefixes=EmptyTuple())
676+
self.assertEqual(len(w), 1)
677+
self.assertEqual(w[-1].filename, __file__)
678+
666679
def test_exec_filename(self):
667680
filename = "<warnings-test>"
668681
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
@@ -1093,6 +1093,9 @@ setup_context(Py_ssize_t stack_level,
10931093
if (f == NULL) {
10941094
globals = interp->sysdict;
10951095
*filename = PyUnicode_FromString("<sys>");
1096+
if (*filename == NULL) {
1097+
return 0;
1098+
}
10961099
*lineno = 0;
10971100
}
10981101
else {
@@ -1237,7 +1240,6 @@ warnings_warn_impl(PyObject *module, PyObject *message, PyObject *category,
12371240
stacklevel = 2;
12381241
}
12391242
} else {
1240-
Py_DECREF((PyObject *)skip_file_prefixes);
12411243
skip_file_prefixes = NULL;
12421244
}
12431245
}

0 commit comments

Comments
 (0)