[3.13] _struct.c: Fix UB from integer overflow in prepare_s (GH-145158) (#145163)

`_struct.c`: Fix UB from integer overflow in `prepare_s` (GH-145158)

Avoid possible undefined behaviour from signed overflow in `struct` module

As discovered via oss-fuzz.
(cherry picked from commit fd0400585e)

Co-authored-by: Stan Ulbrych <89152624+StanFromIreland@users.noreply.github.com>
This commit is contained in:
Miss Islington (bot) 2026-02-24 02:16:45 +01:00 committed by GitHub
parent 0acd41f398
commit dd355045f6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 14 additions and 1 deletions

View file

@ -547,6 +547,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)

View file

@ -0,0 +1,2 @@
Avoid undefined behaviour from signed integer overflow when parsing format
strings in the :mod:`struct` module.

View file

@ -1478,7 +1478,15 @@ prepare_s(PyStructObject *self)
case 's': /* fall through */
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;