From 5fb47c1fabd4ca6a58ff47174110065a33c10b83 Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Mon, 19 Oct 2026 13:41:29 -0700 Subject: [PATCH] gh-159739: Reject the minimum dynamic formatting width Backport to 3.15 and 3.14 (adapt the str formatting fix to Objects/unicodeobject.c on 3.14). --- Lib/test/test_format.py | 2 ++ .../2026-10-19-20-38-17.gh-issue-159739.78e530.rst | 2 ++ Objects/bytesobject.c | 4 ++++ Objects/unicode_format.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 a69a69537d568da..eff0e95c3af7f47 100644 --- a/Lib/test/test_format.py +++ b/Lib/test/test_format.py @@ -324,6 +324,8 @@ def test_common_format(self): "format argument 1: too big for width") test_exc_common('%*r', (-2**1000, 1), OverflowError, "format argument 1: too big for width") + test_exc_common('%*r', (-maxsize - 1, 1), OverflowError, + "format argument 1: too big for width") test_exc_common('%.*r', (2**1000, 1), OverflowError, "format argument 1: too big for precision") test_exc_common('%.*r', (-2**1000, 1), OverflowError, 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 bfd54176e5f662c..242a0f3096f11b7 100644 --- a/Objects/bytesobject.c +++ b/Objects/bytesobject.c @@ -852,6 +852,10 @@ _PyBytes_FormatEx(const char *format, Py_ssize_t format_len, goto error; } if (width < 0) { + if (width == PY_SSIZE_T_MIN) { + FORMAT_ERROR(PyExc_OverflowError, "too big for width%s", ""); + goto error; + } flags |= F_LJUST; width = -width; } diff --git a/Objects/unicode_format.c b/Objects/unicode_format.c index caadf18f6a5d30c..b090a68d2bda9f7 100644 --- a/Objects/unicode_format.c +++ b/Objects/unicode_format.c @@ -564,6 +564,10 @@ unicode_format_arg_parse(struct unicode_formatter_t *ctx, return -1; } if (arg->width < 0) { + if (arg->width == PY_SSIZE_T_MIN) { + FORMAT_ERROR(PyExc_OverflowError, "too big for width%s", ""); + return -1; + } arg->flags |= F_LJUST; arg->width = -arg->width; }