Mercurial > cpython-lru_cache-weakref
diff Modules/_struct.c @ 62252:7db7f8442414 legacy-trunk
Fix possible undefined behaviour from signed overflow in struct module.
Backport of revisions 81897, 81898 and 81902 from py3k.
| author | Mark Dickinson <dickinsm@gmail.com> |
|---|---|
| date | Fri, 11 Jun 2010 20:27:05 +0000 |
| parents | fd25030223b0 |
| children | e7da968e3e5a |
line wrap: on
line diff
--- a/Modules/_struct.c Fri Jun 11 19:22:28 2010 +0000 +++ b/Modules/_struct.c Fri Jun 11 20:27:05 2010 +0000 @@ -1188,16 +1188,19 @@ } -/* Align a size according to a format code */ +/* Align a size according to a format code. Return -1 on overflow. */ -static int +static Py_ssize_t align(Py_ssize_t size, char c, const formatdef *e) { + Py_ssize_t extra; + if (e->format == c) { - if (e->alignment) { - size = ((size + e->alignment - 1) - / e->alignment) - * e->alignment; + if (e->alignment && size > 0) { + extra = (e->alignment - 1) - (size - 1) % (e->alignment); + if (extra > PY_SSIZE_T_MAX - size) + return -1; + size += extra; } } return size; @@ -1216,7 +1219,7 @@ const char *s; const char *fmt; char c; - Py_ssize_t size, len, num, itemsize, x; + Py_ssize_t size, len, num, itemsize; fmt = PyString_AS_STRING(self->s_format); @@ -1231,14 +1234,13 @@ if ('0' <= c && c <= '9') { num = c - '0'; while ('0' <= (c = *s++) && c <= '9') { - x = num*10 + (c - '0'); - if (x/10 != num) { - PyErr_SetString( - StructError, - "overflow in item count"); - return -1; - } - num = x; + /* 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)) + goto overflow; + num = num*10 + (c - '0'); } if (c == '\0') break; @@ -1259,13 +1261,13 @@ itemsize = e->size; size = align(size, c, e); - x = num * itemsize; - size += x; - if (x/itemsize != num || size < 0) { - PyErr_SetString(StructError, - "total struct size too long"); - return -1; - } + if (size == -1) + goto overflow; + + /* if (size + num * itemsize > PY_SSIZE_T_MAX) { ... } */ + if (num > (PY_SSIZE_T_MAX - size) / itemsize) + goto overflow; + size += num * itemsize; } /* check for overflow */ @@ -1324,6 +1326,11 @@ codes->size = 0; return 0; + + overflow: + PyErr_SetString(StructError, + "total struct size too long"); + return -1; } static PyObject *
