From 10a770cf65ebbc0a292d50bcb274ef8d830da59a Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Tue, 20 Oct 2026 10:46:11 -0700 Subject: [PATCH] [3.14] gh-159739: Reject the minimum dynamic formatting width (GH-159780) Adapt the str formatting fix to Objects/unicodeobject.c and use the error wording already present in the 3.14 formatters. (cherry picked from commit 95f94d04d8772f926b6a9bc1e38b67218a1dba7a) --- Lib/test/test_format.py | 2 ++ .../2026-10-19-20-38-17.gh-issue-159739.78e530.rst | 2 ++ Objects/bytesobject.c | 4 ++++ Objects/unicodeobject.c | 4 ++++ 4 files changed, 12 insertions(+) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-10-19-20-38-17.gh-issue-159739.78e530.rst diff --git a/Lib/test/test_format.py b/Lib/test/test_format.py index 120c719b5eb79e1..bc6eac99310a9c3 100644 --- a/Lib/test/test_format.py +++ b/Lib/test/test_format.py @@ -287,6 +287,8 @@ def test_common_format(self): "%i format: a real number is required, not str") test_exc_common('%i', b'1', TypeError, "%i format: a real number is required, not bytes") + test_exc_common('%*r', (-maxsize - 1, 1), OverflowError, + "width too big") def test_str_format(self): testformat("%r", "\u0378", "'\\u0378'") # non printable diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-19-20-38-17.gh-issue-159739.78e530.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-19-20-38-17.gh-issue-159739.78e530.rst new file mode 100644 index 000000000000000..999efdac87f9745 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-19-20-38-17.gh-issue-159739.78e530.rst @@ -0,0 +1,2 @@ +Raise :exc:`OverflowError` when the absolute value of a dynamic printf-style +formatting width is too large. diff --git a/Objects/bytesobject.c b/Objects/bytesobject.c index 63730630e68497f..307a015a119b9fb 100644 --- a/Objects/bytesobject.c +++ b/Objects/bytesobject.c @@ -752,6 +752,10 @@ _PyBytes_FormatEx(const char *format, Py_ssize_t format_len, if (width == -1 && PyErr_Occurred()) goto error; if (width < 0) { + if (width == PY_SSIZE_T_MIN) { + PyErr_SetString(PyExc_OverflowError, "width too big"); + goto error; + } flags |= F_LJUST; width = -width; } diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c index 8023bed17d3ea99..d62ea36ed70d68f 100644 --- a/Objects/unicodeobject.c +++ b/Objects/unicodeobject.c @@ -15150,6 +15150,10 @@ unicode_format_arg_parse(struct unicode_formatter_t *ctx, if (arg->width == -1 && PyErr_Occurred()) return -1; if (arg->width < 0) { + if (arg->width == PY_SSIZE_T_MIN) { + PyErr_SetString(PyExc_OverflowError, "width too big"); + return -1; + } arg->flags |= F_LJUST; arg->width = -arg->width; }