Issue #15989: Fix several occurrences of integer overflow
when result of PyLong_AsLong() narrowed to int without checks.
diff --git a/Objects/fileobject.c b/Objects/fileobject.c
index e1c47ce..3a31314 100644
--- a/Objects/fileobject.c
+++ b/Objects/fileobject.c
@@ -200,7 +200,7 @@
_Py_IDENTIFIER(fileno);
if (PyLong_Check(o)) {
- fd = PyLong_AsLong(o);
+ fd = _PyLong_AsInt(o);
}
else if ((meth = _PyObject_GetAttrId(o, &PyId_fileno)) != NULL)
{
@@ -210,7 +210,7 @@
return -1;
if (PyLong_Check(fno)) {
- fd = PyLong_AsLong(fno);
+ fd = _PyLong_AsInt(fno);
Py_DECREF(fno);
}
else {
diff --git a/Objects/longobject.c b/Objects/longobject.c
index 5a50f24..1a82b1c6 100644
--- a/Objects/longobject.c
+++ b/Objects/longobject.c
@@ -434,6 +434,24 @@
return result;
}
+/* Get a C int from a long int object or any object that has an __int__
+ method. Return -1 and set an error if overflow occurs. */
+
+int
+_PyLong_AsInt(PyObject *obj)
+{
+ int overflow;
+ long result = PyLong_AsLongAndOverflow(obj, &overflow);
+ if (overflow || result > INT_MAX || result < INT_MIN) {
+ /* XXX: could be cute and give a different
+ message for overflow == -1 */
+ PyErr_SetString(PyExc_OverflowError,
+ "Python int too large to convert to C int");
+ return -1;
+ }
+ return (int)result;
+}
+
/* Get a Py_ssize_t from a long int object.
Returns -1 and sets an error condition if overflow occurs. */
diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c
index 6a12d71..65393d2 100644
--- a/Objects/unicodeobject.c
+++ b/Objects/unicodeobject.c
@@ -13521,7 +13521,7 @@
"* wants int");
return -1;
}
- arg->width = PyLong_AsLong(v);
+ arg->width = PyLong_AsSsize_t(v);
if (arg->width == -1 && PyErr_Occurred())
return -1;
if (arg->width < 0) {
@@ -13568,7 +13568,7 @@
"* wants int");
return -1;
}
- arg->prec = PyLong_AsLong(v);
+ arg->prec = _PyLong_AsInt(v);
if (arg->prec == -1 && PyErr_Occurred())
return -1;
if (arg->prec < 0)