summaryrefslogtreecommitdiffstats
path: root/Objects
diff options
context:
space:
mode:
authorMark Dickinson <mdickinson@enthought.com>2011-09-24 18:11:53 (GMT)
committerMark Dickinson <mdickinson@enthought.com>2011-09-24 18:11:53 (GMT)
commit36f27c995ad3d8732f51c91f43dacf72823382c6 (patch)
tree94cee4a2c0f4c915fc16e78152572c45ff8974a0 /Objects
parentdc863ddf7924ca6c4771a604b7041562604a85d9 (diff)
downloadcpython-36f27c995ad3d8732f51c91f43dacf72823382c6.zip
cpython-36f27c995ad3d8732f51c91f43dacf72823382c6.tar.gz
cpython-36f27c995ad3d8732f51c91f43dacf72823382c6.tar.bz2
Issue #1621: Fix undefined behaviour from signed overflow in get_integer (stringlib/formatter.h)
Diffstat (limited to 'Objects')
-rw-r--r--Objects/stringlib/formatter.h16
1 files changed, 7 insertions, 9 deletions
diff --git a/Objects/stringlib/formatter.h b/Objects/stringlib/formatter.h
index 4fdc62d..139b56c 100644
--- a/Objects/stringlib/formatter.h
+++ b/Objects/stringlib/formatter.h
@@ -73,7 +73,7 @@ static int
get_integer(STRINGLIB_CHAR **ptr, STRINGLIB_CHAR *end,
Py_ssize_t *result)
{
- Py_ssize_t accumulator, digitval, oldaccumulator;
+ Py_ssize_t accumulator, digitval;
int numdigits;
accumulator = numdigits = 0;
for (;;(*ptr)++, numdigits++) {
@@ -83,19 +83,17 @@ get_integer(STRINGLIB_CHAR **ptr, STRINGLIB_CHAR *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;