diff options
author | Mark Dickinson <mdickinson@enthought.com> | 2011-12-01 15:27:04 (GMT) |
---|---|---|
committer | Mark Dickinson <mdickinson@enthought.com> | 2011-12-01 15:27:04 (GMT) |
commit | 47862d4c0ea5dc75c2f094f071847aca378dab9d (patch) | |
tree | e11d1c97e468bf1d8e483af8cb98972220519b0e /Python/formatter_unicode.c | |
parent | 0a54cf12a09d731cd043f814142744f5de0a91ee (diff) | |
download | cpython-47862d4c0ea5dc75c2f094f071847aca378dab9d.zip cpython-47862d4c0ea5dc75c2f094f071847aca378dab9d.tar.gz cpython-47862d4c0ea5dc75c2f094f071847aca378dab9d.tar.bz2 |
Issue #9530: Fix undefined behaviour due to signed overflow in Python/formatter_unicode.c.
Diffstat (limited to 'Python/formatter_unicode.c')
-rw-r--r-- | Python/formatter_unicode.c | 16 |
1 files changed, 7 insertions, 9 deletions
diff --git a/Python/formatter_unicode.c b/Python/formatter_unicode.c index fda79fc..6deb3cd 100644 --- a/Python/formatter_unicode.c +++ b/Python/formatter_unicode.c @@ -51,7 +51,7 @@ static int get_integer(PyObject *str, Py_ssize_t *pos, Py_ssize_t end, Py_ssize_t *result) { - Py_ssize_t accumulator, digitval, oldaccumulator; + Py_ssize_t accumulator, digitval; int numdigits; accumulator = numdigits = 0; for (;;(*pos)++, numdigits++) { @@ -61,19 +61,17 @@ get_integer(PyObject *str, Py_ssize_t *pos, Py_ssize_t end, if (digitval < 0) break; /* - This trick was copied from old Unicode format code. It's cute, - but would really suck on an old machine with a slow divide - implementation. Fortunately, in the normal case we do not - expect too many digits. + Detect possible overflow before it happens: + + accumulator * 10 + digitval > PY_SSIZE_T_MAX if and only if + accumulator > (PY_SSIZE_T_MAX - digitval) / 10. */ - oldaccumulator = accumulator; - accumulator *= 10; - if ((accumulator+10)/10 != oldaccumulator+1) { + if (accumulator > (PY_SSIZE_T_MAX - digitval) / 10) { PyErr_Format(PyExc_ValueError, "Too many decimal digits in format string"); return -1; } - accumulator += digitval; + accumulator = accumulator * 10 + digitval; } *result = accumulator; return numdigits; |