Skip to content

Commit 4e41636

Browse files
authored
gh-142554: avoid divmod crashes due to bad _pylong.int_divmod (#142673)
1 parent 39ecb17 commit 4e41636

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

Lib/test/test_int.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -778,6 +778,18 @@ def test_pylong_int_divmod(self):
778778
a, b = divmod(n*3 + 1, n)
779779
assert a == 3 and b == 1
780780

781+
@support.cpython_only # tests implementation details of CPython.
782+
@unittest.skipUnless(_pylong, "_pylong module required")
783+
def test_pylong_int_divmod_crash(self):
784+
# Regression test for https://github.com/python/cpython/issues/142554.
785+
bad_int_divmod = lambda a, b: (1,)
786+
# 'k' chosen such that divmod(2**(2*k), 2**k) uses _pylong.int_divmod()
787+
k = 10_000
788+
a, b = (1 << (2 * k)), (1 << k)
789+
with mock.patch.object(_pylong, "int_divmod", wraps=bad_int_divmod):
790+
msg = r"tuple of length 2 is required from int_divmod\(\)"
791+
self.assertRaisesRegex(ValueError, msg, divmod, a, b)
792+
781793
def test_pylong_str_to_int(self):
782794
v1 = 1 << 100_000
783795
s = str(v1)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a crash in :func:`divmod` when :func:`!_pylong.int_divmod` does not
2+
return a tuple of length two exactly. Patch by Bénédikt Tran.

Objects/longobject.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4434,10 +4434,10 @@ pylong_int_divmod(PyLongObject *v, PyLongObject *w,
44344434
if (result == NULL) {
44354435
return -1;
44364436
}
4437-
if (!PyTuple_Check(result)) {
4437+
if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 2) {
44384438
Py_DECREF(result);
44394439
PyErr_SetString(PyExc_ValueError,
4440-
"tuple is required from int_divmod()");
4440+
"tuple of length 2 is required from int_divmod()");
44414441
return -1;
44424442
}
44434443
PyObject *q = PyTuple_GET_ITEM(result, 0);

0 commit comments

Comments
 (0)