Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Lib/test/test_long.py
Original file line number Diff line number Diff line change
Expand Up @@ -996,6 +996,16 @@ def test_huge_lshift(self, size):
self.assertEqual(v.bit_count(), 2)
self.assertEqual(v >> size, 5)

@support.cpython_only
def test_huge_lshift_overflow(self):
# The number of digits of the result doesn't fit in Py_ssize_t.
for a in 1, -1, 1 << SHIFT, -1 << SHIFT, 1 << 10*SHIFT:
for ndigits in range(sys.maxsize - 12, sys.maxsize + 1):
for shift in ndigits*SHIFT - 1, ndigits*SHIFT:
with self.subTest(a=a, shift=shift):
with self.assertRaises(OverflowError):
a << shift

def test_huge_rshift(self):
huge_shift = 1 << 1000
self.assertEqual(42 >> huge_shift, 0)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a crash on 32-bit platforms when left shifting an :class:`int` by a
count close to ``sys.maxsize * sys.int_info.bits_per_digit``.
:exc:`OverflowError` is now raised, as for other too large counts.
4 changes: 3 additions & 1 deletion Objects/longobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -5530,7 +5530,9 @@ long_lshift_int64(PyLongObject *a, int64_t shiftby)
return PyLong_FromLong(0);
}
#if PY_SSIZE_T_MAX <= INT64_MAX / PyLong_SHIFT
if (shiftby > (int64_t)PY_SSIZE_T_MAX * PyLong_SHIFT) {
/* Keep wordshift <= MAX_LONG_DIGITS, so that oldsize + wordshift
cannot overflow Py_ssize_t in long_lshift1(). */
if (shiftby > (int64_t)MAX_LONG_DIGITS * PyLong_SHIFT) {
PyErr_SetString(PyExc_OverflowError,
"too many digits in integer");
return NULL;
Expand Down
Loading