]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.11] gh-101037: Fix potential memory underallocation for zeros of int subtypes...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sat, 21 Jan 2023 10:54:09 +0000 (02:54 -0800)
committerGitHub <noreply@github.com>
Sat, 21 Jan 2023 10:54:09 +0000 (10:54 +0000)
gh-101037: Fix potential memory underallocation for zeros of int subtypes (GH-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 GH-101037.
(cherry picked from commit 401fdf9c851eb61229250ebffa942adca99b36d1)

Co-authored-by: Mark Dickinson <dickinsm@gmail.com>
Include/cpython/longintrepr.h
Misc/NEWS.d/next/Core and Builtins/2023-01-14-17-03-08.gh-issue-101037.9ATNuf.rst [new file with mode: 0644]
Objects/longobject.c

index 68dbf9c4382dc5d49b1f98ec54cb9f1259ac0e49..6d52427508b5fe4fc5414673d273a4ecfd587dcf 100644 (file)
@@ -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.
diff --git a/Misc/NEWS.d/next/Core and Builtins/2023-01-14-17-03-08.gh-issue-101037.9ATNuf.rst b/Misc/NEWS.d/next/Core and Builtins/2023-01-14-17-03-08.gh-issue-101037.9ATNuf.rst
new file mode 100644 (file)
index 0000000..a487566
--- /dev/null
@@ -0,0 +1,2 @@
+Fix potential memory underallocation issue for instances of :class:`int`
+subclasses with value zero.
index c8dd5761a3ceefdb68215bd7e23d47350ea68b6f..84c05e8aabdfdabac0b7b622afa1e8d38d8ae4a0 100644 (file)
@@ -5415,6 +5415,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);