]> granicus.if.org Git - python/commitdiff
bpo-36791: Safer detection of integer overflow in sum(). (GH-13080)
authorSerhiy Storchaka <storchaka@gmail.com>
Sun, 5 May 2019 11:26:23 +0000 (14:26 +0300)
committerGitHub <noreply@github.com>
Sun, 5 May 2019 11:26:23 +0000 (14:26 +0300)
Python/bltinmodule.c

index 7a2b259cbd89c80b70c279ec2ead929b66c80afa..047cca057b41ae5c46cf8e4c7763b4e69c263ede 100644 (file)
@@ -2375,9 +2375,11 @@ builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
             }
             if (PyLong_CheckExact(item)) {
                 long b = PyLong_AsLongAndOverflow(item, &overflow);
-                long x = i_result + b;
-                if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
-                    i_result = x;
+                if (overflow == 0 &&
+                    (i_result >= 0 ? (b <= LONG_MAX - i_result)
+                                   : (b >= LONG_MIN - i_result)))
+                {
+                    i_result += b;
                     Py_DECREF(item);
                     continue;
                 }