From bf5c58fab68a725f010e0e11c098a744f0388d1f Mon Sep 17 00:00:00 2001 From: Stan Ulbrych Date: Mon, 23 Feb 2026 17:45:12 +0000 Subject: [PATCH 1/2] Avoid possible undefined behaviour from signed overflow in `struct` module --- Lib/test/test_struct.py | 3 +++ Modules/_struct.c | 10 +++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_struct.py b/Lib/test/test_struct.py index bffbcb1a60757d..aa793a2c223de9 100644 --- a/Lib/test/test_struct.py +++ b/Lib/test/test_struct.py @@ -552,6 +552,9 @@ def test_count_overflow(self): hugecount2 = '{}b{}H'.format(sys.maxsize//2, sys.maxsize//2) self.assertRaises(struct.error, struct.calcsize, hugecount2) + hugecount3 = '{}i{}q'.format(sys.maxsize // 4, sys.maxsize // 8) + self.assertRaises(struct.error, struct.calcsize, hugecount3) + def test_trailing_counter(self): store = array.array('b', b' '*100) diff --git a/Modules/_struct.c b/Modules/_struct.c index 7d2dfc591a2a58..ae8a8ffb3c005a 100644 --- a/Modules/_struct.c +++ b/Modules/_struct.c @@ -1678,7 +1678,15 @@ prepare_s(PyStructObject *self) case 's': _Py_FALLTHROUGH; case 'p': len++; ncodes++; break; case 'x': break; - default: len += num; if (num) ncodes++; break; + default: + if (num > PY_SSIZE_T_MAX - len) { + goto overflow; + } + len += num; + if (num) { + ncodes++; + } + break; } itemsize = e->size; From 1586f4bddc7d09708f0aadce9f5a7346ce34ad12 Mon Sep 17 00:00:00 2001 From: Stan Ulbrych Date: Mon, 23 Feb 2026 20:53:03 +0000 Subject: [PATCH 2/2] Add news entry --- .../next/Library/2026-02-23-20-52-55.gh-issue-145158.vWJtxI.rst | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2026-02-23-20-52-55.gh-issue-145158.vWJtxI.rst diff --git a/Misc/NEWS.d/next/Library/2026-02-23-20-52-55.gh-issue-145158.vWJtxI.rst b/Misc/NEWS.d/next/Library/2026-02-23-20-52-55.gh-issue-145158.vWJtxI.rst new file mode 100644 index 00000000000000..60a5e4ad1f0ca4 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-02-23-20-52-55.gh-issue-145158.vWJtxI.rst @@ -0,0 +1,2 @@ +Avoid undefined behaviour from signed integer overflow when parsing format +strings in the :mod:`struct` module.