Skip to content

Commit

Permalink
gh-101037: Fix potential memory underallocation for zeros of int subt…
Browse files Browse the repository at this point in the history
…ypes (#101038)

This PR fixes object allocation in long_subtype_new to ensure that there's at least one digit in all cases, and makes sure that the value of that digit is copied over from the source long.

Needs backport to 3.11, but not any further: the change to require at least one digit was only introduced for Python 3.11.

Fixes #101037.
  • Loading branch information
mdickinson authored Jan 21, 2023
1 parent 9e94767 commit 401fdf9
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Include/cpython/longintrepr.h
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ typedef long stwodigits; /* signed variant of twodigits */
0 <= ob_digit[i] <= MASK.
The allocation function takes care of allocating extra memory
so that ob_digit[0] ... ob_digit[abs(ob_size)-1] are actually available.
We always allocate memory for at least one digit, so accessing ob_digit[0]
is always safe. However, in the case ob_size == 0, the contents of
ob_digit[0] may be undefined.
CAUTION: Generic code manipulating subtypes of PyVarObject has to
aware that ints abuse ob_size's sign bit.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix potential memory underallocation issue for instances of :class:`int`
subclasses with value zero.
5 changes: 5 additions & 0 deletions Objects/longobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -5638,6 +5638,11 @@ long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
n = Py_SIZE(tmp);
if (n < 0)
n = -n;
/* Fast operations for single digit integers (including zero)
* assume that there is always at least one digit present. */
if (n == 0) {
n = 1;
}
newobj = (PyLongObject *)type->tp_alloc(type, n);
if (newobj == NULL) {
Py_DECREF(tmp);
Expand Down

0 comments on commit 401fdf9

Please sign in to comment.