Skip to content

Commit 032c25a

Browse files
vstinnerJelleZijlstra
authored andcommitted
pythongh-126594: Fix typeobject.c wrap_buffer() cast (python#126754)
Reject flags smaller than INT_MIN. Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
1 parent 4c36f2b commit 032c25a

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

Lib/test/test_buffer.py

+15
Original file line numberDiff line numberDiff line change
@@ -4446,6 +4446,21 @@ def test_pybuffer_size_from_format(self):
44464446
self.assertEqual(_testcapi.PyBuffer_SizeFromFormat(format),
44474447
struct.calcsize(format))
44484448

4449+
@support.cpython_only
4450+
def test_flags_overflow(self):
4451+
# gh-126594: Check for integer overlow on large flags
4452+
try:
4453+
from _testcapi import INT_MIN, INT_MAX
4454+
except ImportError:
4455+
INT_MIN = -(2 ** 31)
4456+
INT_MAX = 2 ** 31 - 1
4457+
4458+
obj = b'abc'
4459+
for flags in (INT_MIN - 1, INT_MAX + 1):
4460+
with self.subTest(flags=flags):
4461+
with self.assertRaises(OverflowError):
4462+
obj.__buffer__(flags)
4463+
44494464

44504465
class TestPythonBufferProtocol(unittest.TestCase):
44514466
def test_basic(self):

Objects/typeobject.c

+3-3
Original file line numberDiff line numberDiff line change
@@ -9314,13 +9314,13 @@ wrap_buffer(PyObject *self, PyObject *args, void *wrapped)
93149314
if (flags == -1 && PyErr_Occurred()) {
93159315
return NULL;
93169316
}
9317-
if (flags > INT_MAX) {
9317+
if (flags > INT_MAX || flags < INT_MIN) {
93189318
PyErr_SetString(PyExc_OverflowError,
9319-
"buffer flags too large");
9319+
"buffer flags out of range");
93209320
return NULL;
93219321
}
93229322

9323-
return _PyMemoryView_FromBufferProc(self, Py_SAFE_DOWNCAST(flags, Py_ssize_t, int),
9323+
return _PyMemoryView_FromBufferProc(self, (int)flags,
93249324
(getbufferproc)wrapped);
93259325
}
93269326

0 commit comments

Comments
 (0)