Skip to content
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

gh-104371: Fix calls to __release_buffer__ while an exception is active #104378

Merged
merged 3 commits into from
May 12, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
13 changes: 13 additions & 0 deletions Lib/test/test_buffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -4749,6 +4749,19 @@ def __buffer__(self, flags):
c.clear()
self.assertIs(c.buffer, None)

def test_release_buffer_with_exception_set(self):
class A:
def __buffer__(self, flags):
return memoryview(bytes(8))
def __release_buffer__(self, view):
pass

b = bytearray(8)
with memoryview(b):
# now b.extend will raise an exception due to exports
with self.assertRaises(BufferError):
b.extend(A())


if __name__ == "__main__":
unittest.main()
19 changes: 18 additions & 1 deletion Objects/typeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -9115,8 +9115,9 @@ releasebuffer_maybe_call_super(PyObject *self, Py_buffer *buffer)
}

static void
releasebuffer_call_python(PyObject *self, Py_buffer *buffer)
releasebuffer_call_python_inner(PyObject *self, Py_buffer *buffer)
{
assert(!PyErr_Occurred());
PyObject *mv;
bool is_buffer_wrapper = Py_TYPE(buffer->obj) == &_PyBufferWrapper_Type;
if (is_buffer_wrapper) {
Expand Down Expand Up @@ -9157,6 +9158,22 @@ releasebuffer_call_python(PyObject *self, Py_buffer *buffer)
Py_DECREF(mv);
}

static void
releasebuffer_call_python(PyObject *self, Py_buffer *buffer)
JelleZijlstra marked this conversation as resolved.
Show resolved Hide resolved
{
// bf_releasebuffer may be called while an exception is already active.
// We have no way to report additional errors up the stack, because
// this slot returns void, so we simply stash away the active exception
// and restore it after the call to Python returns.
PyObject *type, *value, *traceback;
PyErr_Fetch(&type, &value, &traceback);
kumaraditya303 marked this conversation as resolved.
Show resolved Hide resolved

releasebuffer_call_python_inner(self, buffer);
assert(!PyErr_Occurred());
kumaraditya303 marked this conversation as resolved.
Show resolved Hide resolved

PyErr_Restore(type, value, traceback);
}

/*
* bf_releasebuffer is very delicate, because we need to ensure that
* C bf_releasebuffer slots are called correctly (or we'll leak memory),
Expand Down