Skip to content

Commit 9345dc1

Browse files
miss-islingtonvstinnerJelleZijlstra
authored
[3.12] gh-126594: Fix typeobject.c wrap_buffer() cast (GH-126754) (#127005)
gh-126594: Fix typeobject.c wrap_buffer() cast (GH-126754) Reject flags smaller than INT_MIN. (cherry picked from commit 84f07c3) Co-authored-by: Victor Stinner <vstinner@python.org> Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
1 parent 126acc1 commit 9345dc1

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
@@ -4442,6 +4442,21 @@ def test_pybuffer_size_from_format(self):
44424442
self.assertEqual(_testcapi.PyBuffer_SizeFromFormat(format),
44434443
struct.calcsize(format))
44444444

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

44464461
class TestPythonBufferProtocol(unittest.TestCase):
44474462
def test_basic(self):

Objects/typeobject.c

+3-3
Original file line numberDiff line numberDiff line change
@@ -8207,13 +8207,13 @@ wrap_buffer(PyObject *self, PyObject *args, void *wrapped)
82078207
if (flags == -1 && PyErr_Occurred()) {
82088208
return NULL;
82098209
}
8210-
if (flags > INT_MAX) {
8210+
if (flags > INT_MAX || flags < INT_MIN) {
82118211
PyErr_SetString(PyExc_OverflowError,
8212-
"buffer flags too large");
8212+
"buffer flags out of range");
82138213
return NULL;
82148214
}
82158215

8216-
return _PyMemoryView_FromBufferProc(self, Py_SAFE_DOWNCAST(flags, Py_ssize_t, int),
8216+
return _PyMemoryView_FromBufferProc(self, (int)flags,
82178217
(getbufferproc)wrapped);
82188218
}
82198219

0 commit comments

Comments
 (0)