Thanks to visit codestin.com
Credit goes to github.com

Skip to content

gh-114685: Check flags in PyObject_GetBuffer() #114707

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Lib/test/test_buffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -4585,6 +4585,12 @@ def test_c_buffer(self):
buf.__release_buffer__(mv)
self.assertEqual(buf.references, 0)

@unittest.skipIf(_testcapi is None, "requires _testcapi")
def test_c_buffer_invalid_flags(self):
buf = _testcapi.testBuf()
self.assertRaises(SystemError, buf.__buffer__, PyBUF_READ)
self.assertRaises(SystemError, buf.__buffer__, PyBUF_WRITE)

def test_inheritance(self):
class A(bytearray):
def __buffer__(self, flags):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:c:func:`PyObject_GetBuffer` now raises a :exc:`SystemError` if called with
:c:macro:`PyBUF_READ` or :c:macro:`PyBUF_WRITE` as flags. These flags should
only be used with the ``PyMemoryView_*`` C API.
6 changes: 4 additions & 2 deletions Modules/_testcapi/buffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,10 @@ static int
testbuf_getbuf(testBufObject *self, Py_buffer *view, int flags)
{
int buf = PyObject_GetBuffer(self->obj, view, flags);
Py_SETREF(view->obj, Py_NewRef(self));
self->references++;
if (buf == 0) {
Py_SETREF(view->obj, Py_NewRef(self));
self->references++;
}
return buf;
}

Expand Down
6 changes: 6 additions & 0 deletions Objects/abstract.c
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,12 @@ PyObject_AsWriteBuffer(PyObject *obj,
int
PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
{
if (flags != PyBUF_SIMPLE) { /* fast path */
if (flags == PyBUF_READ || flags == PyBUF_WRITE) {
PyErr_BadInternalCall();
return -1;
}
}
PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;

if (pb == NULL || pb->bf_getbuffer == NULL) {
Expand Down