Skip to content

Commit 3fae84f

Browse files
sobolevnvstinner
andauthored
[3.13] gh-126980: Fix bytearray.__buffer__ crash on PyBUF_{READ,WRITE} (GH-126981) (#127023)
(cherry picked from commit 3932e1d) Co-authored-by: Victor Stinner <[email protected]>
1 parent dd222a4 commit 3fae84f

File tree

3 files changed

+15
-4
lines changed

3 files changed

+15
-4
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: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,15 @@ _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+
void *ptr = (void *) PyByteArray_AS_STRING(obj);
53+
if (PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags) < 0) {
54+
return -1;
55+
}
5656
obj->ob_exports++;
5757
return 0;
5858
}

0 commit comments

Comments
 (0)