Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-95778: Add pre-check for int-to-str conversion #96537

Merged
merged 14 commits into from
Sep 4, 2022
Merged
19 changes: 17 additions & 2 deletions Objects/longobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ medium_value(PyLongObject *x)
#define IS_SMALL_UINT(ival) ((ival) < _PY_NSMALLPOSINTS)

#define _MAX_STR_DIGITS_ERROR_FMT "Exceeds the limit (%d) for integer string conversion: value has %zd digits"
#define _MAX_STR_DIGITS_ERROR_FMT2 "Exceeds the limit (%d) for integer string conversion"

static inline void
_Py_DECREF_INT(PyLongObject *op)
Expand Down Expand Up @@ -1758,6 +1759,20 @@ long_to_decimal_string_internal(PyObject *aa,
size_a = Py_ABS(Py_SIZE(a));
negative = Py_SIZE(a) < 0;

/* quick and dirty pre-check for overflowing the digit limit,
based on the inequality 10/3 >= log2(10) */
if (size_a >= 10 * _PY_LONG_MAX_STR_DIGITS_THRESHOLD
/ (3 * PyLong_SHIFT) + 2) {
PyInterpreterState *interp = _PyInterpreterState_GET();
int max_str_digits = interp->int_max_str_digits;
if ((max_str_digits > 0) && (size_a >= 10 * max_str_digits
/ (3 * PyLong_SHIFT) + 2)) {
PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT2,
max_str_digits);
return -1;
}
}

/* quick and dirty upper bound for the number of digits
required to express a in base _PyLong_DECIMAL_BASE:

Expand Down Expand Up @@ -1823,8 +1838,8 @@ long_to_decimal_string_internal(PyObject *aa,
Py_ssize_t strlen_nosign = strlen - negative;
if ((max_str_digits > 0) && (strlen_nosign > max_str_digits)) {
Py_DECREF(scratch);
PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT,
max_str_digits, strlen_nosign);
PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT2,
max_str_digits);
return -1;
}
}
Expand Down