Skip to content

Commit c2c44c0

Browse files
sobolevnvstinner
andcommitted
[3.13] pythongh-126980: Fix bytearray.__buffer__ crash on PyBUF_{READ,WRITE} (pythonGH-126981)
(cherry picked from commit 3932e1d) Co-authored-by: sobolevn <[email protected]> Co-authored-by: Victor Stinner <[email protected]>
1 parent dd222a4 commit c2c44c0

File tree

3 files changed

+17
-4
lines changed

3 files changed

+17
-4
lines changed

Lib/test/test_buffer.py

+8
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
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

+6-4
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,17 @@ _getbytevalue(PyObject* arg, int *value)
4444
static int
4545
bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
4646
{
47-
void *ptr;
4847
if (view == NULL) {
4948
PyErr_SetString(PyExc_BufferError,
5049
"bytearray_getbuffer: view==NULL argument is obsolete");
5150
return -1;
5251
}
53-
ptr = (void *) PyByteArray_AS_STRING(obj);
54-
/* cannot fail if view != NULL and readonly == 0 */
55-
(void)PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
52+
53+
void *ptr = (void *) PyByteArray_AS_STRING(obj);
54+
if (PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags) < 0) {
55+
return -1;
56+
}
57+
5658
obj->ob_exports++;
5759
return 0;
5860
}

0 commit comments

Comments
 (0)