Skip to content

Commit 3932e1d

Browse files
sobolevnvstinner
andauthored
gh-126980: Fix bytearray.__buffer__ crash on PyBUF_{READ,WRITE} (#126981)
Co-authored-by: Victor Stinner <[email protected]>
1 parent 4d77197 commit 3932e1d

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

Lib/test/test_buffer.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4439,6 +4439,14 @@ def test_issue_7385(self):
44394439
x = ndarray([1,2,3], shape=[3], flags=ND_GETBUF_FAIL)
44404440
self.assertRaises(BufferError, memoryview, x)
44414441

4442+
def test_bytearray_release_buffer_read_flag(self):
4443+
# See https://github.com/python/cpython/issues/126980
4444+
obj = bytearray(b'abc')
4445+
with self.assertRaises(SystemError):
4446+
obj.__buffer__(inspect.BufferFlags.READ)
4447+
with self.assertRaises(SystemError):
4448+
obj.__buffer__(inspect.BufferFlags.WRITE)
4449+
44424450
@support.cpython_only
44434451
def test_pybuffer_size_from_format(self):
44444452
# basic tests
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix :meth:`~object.__buffer__` of :class:`bytearray` crashing when
2+
:attr:`~inspect.BufferFlags.READ` or :attr:`~inspect.BufferFlags.WRITE` are
3+
passed as flags.

Objects/bytearrayobject.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,9 @@ bytearray_getbuffer(PyObject *self, Py_buffer *view, int flags)
5252
}
5353

5454
void *ptr = (void *) PyByteArray_AS_STRING(obj);
55-
/* cannot fail if view != NULL and readonly == 0 */
56-
(void)PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
55+
if (PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags) < 0) {
56+
return -1;
57+
}
5758
obj->ob_exports++;
5859
return 0;
5960
}

0 commit comments

Comments
 (0)