diff options
author | Mark Dickinson <dickinsm@gmail.com> | 2010-06-11 16:56:34 (GMT) |
---|---|---|
committer | Mark Dickinson <dickinsm@gmail.com> | 2010-06-11 16:56:34 (GMT) |
commit | ab4096f2f9cc3f2a06e24d8dbe9c3e8e0ba155f0 (patch) | |
tree | 535bc73bf3c05c67c928e1d13cd6c519c1e9e832 | |
parent | 1c164a6f85865ab6c84d4bfb6bfbf1dde6169603 (diff) | |
download | cpython-ab4096f2f9cc3f2a06e24d8dbe9c3e8e0ba155f0.zip cpython-ab4096f2f9cc3f2a06e24d8dbe9c3e8e0ba155f0.tar.gz cpython-ab4096f2f9cc3f2a06e24d8dbe9c3e8e0ba155f0.tar.bz2 |
Avoid possible undefined behaviour from signed overflow.
-rw-r--r-- | Lib/test/test_struct.py | 5 | ||||
-rw-r--r-- | Modules/_struct.c | 9 |
2 files changed, 11 insertions, 3 deletions
diff --git a/Lib/test/test_struct.py b/Lib/test/test_struct.py index b9faa28..70eed6e 100644 --- a/Lib/test/test_struct.py +++ b/Lib/test/test_struct.py @@ -506,6 +506,11 @@ class StructTest(unittest.TestCase): for c in [b'\x01', b'\x7f', b'\xff', b'\x0f', b'\xf0']: self.assertTrue(struct.unpack('>?', c)[0]) + def test_count_overflow(self): + hugecount = '{}b'.format(sys.maxsize+1) + self.assertRaises(struct.error, struct.calcsize, hugecount) + + if IS32BIT: def test_crasher(self): self.assertRaises(MemoryError, struct.pack, "357913941b", "a") diff --git a/Modules/_struct.c b/Modules/_struct.c index 2e594e8..e05fb73 100644 --- a/Modules/_struct.c +++ b/Modules/_struct.c @@ -1186,14 +1186,17 @@ prepare_s(PyStructObject *self) if ('0' <= c && c <= '9') { num = c - '0'; while ('0' <= (c = *s++) && c <= '9') { - x = num*10 + (c - '0'); - if (x/10 != num) { + /* overflow-safe version of + if (num*10 + (c - '0') > PY_SSIZE_T_MAX) { ... } */ + if (num >= PY_SSIZE_T_MAX / 10 && ( + num > PY_SSIZE_T_MAX / 10 || + (c - '0') > PY_SSIZE_T_MAX % 10)) { PyErr_SetString( StructError, "overflow in item count"); return -1; } - num = x; + num = num*10 + (c - '0'); } if (c == '\0') { PyErr_SetString(StructError, |