Skip to content

Commit aef4552

Browse files
[3.14] gh-142554: avoid divmod crashes due to bad _pylong.int_divmod (GH-142673) (#142696)
gh-142554: avoid `divmod` crashes due to bad `_pylong.int_divmod` (GH-142673) (cherry picked from commit 4e41636) Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
1 parent 7297d3a commit aef4552

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
@@ -4339,10 +4339,10 @@ pylong_int_divmod(PyLongObject *v, PyLongObject *w,
43394339
if (result == NULL) {
43404340
return -1;
43414341
}
4342-
if (!PyTuple_Check(result)) {
4342+
if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 2) {
43434343
Py_DECREF(result);
43444344
PyErr_SetString(PyExc_ValueError,
4345-
"tuple is required from int_divmod()");
4345+
"tuple of length 2 is required from int_divmod()");
43464346
return -1;
43474347
}
43484348
PyObject *q = PyTuple_GET_ITEM(result, 0);

0 commit comments

Comments
 (0)