Avoid possible undefined behaviour from signed overflow.

This commit is contained in:
Mark Dickinson 2010-06-11 16:56:34 +00:00
parent 1c164a6f85
commit ab4096f2f9
2 changed files with 11 additions and 3 deletions

View file

@ -506,6 +506,11 @@ class StructTest(unittest.TestCase):
for c in [b'\x01', b'\x7f', b'\xff', b'\x0f', b'\xf0']: for c in [b'\x01', b'\x7f', b'\xff', b'\x0f', b'\xf0']:
self.assertTrue(struct.unpack('>?', c)[0]) 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: if IS32BIT:
def test_crasher(self): def test_crasher(self):
self.assertRaises(MemoryError, struct.pack, "357913941b", "a") self.assertRaises(MemoryError, struct.pack, "357913941b", "a")

View file

@ -1186,14 +1186,17 @@ prepare_s(PyStructObject *self)
if ('0' <= c && c <= '9') { if ('0' <= c && c <= '9') {
num = c - '0'; num = c - '0';
while ('0' <= (c = *s++) && c <= '9') { while ('0' <= (c = *s++) && c <= '9') {
x = num*10 + (c - '0'); /* overflow-safe version of
if (x/10 != num) { 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( PyErr_SetString(
StructError, StructError,
"overflow in item count"); "overflow in item count");
return -1; return -1;
} }
num = x; num = num*10 + (c - '0');
} }
if (c == '\0') { if (c == '\0') {
PyErr_SetString(StructError, PyErr_SetString(StructError,