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 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
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()
14 changes: 12 additions & 2 deletions Objects/typeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -9117,14 +9117,20 @@ releasebuffer_maybe_call_super(PyObject *self, Py_buffer *buffer)
static void
releasebuffer_call_python(PyObject *self, Py_buffer *buffer)
{
// 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 *exc = PyErr_GetRaisedException();

PyObject *mv;
bool is_buffer_wrapper = Py_TYPE(buffer->obj) == &_PyBufferWrapper_Type;
if (is_buffer_wrapper) {
// Make sure we pass the same memoryview to
// __release_buffer__() that __buffer__() returned.
PyBufferWrapper *bw = (PyBufferWrapper *)buffer->obj;
if (bw->mv == NULL) {
return;
goto end;
}
mv = Py_NewRef(bw->mv);
}
Expand All @@ -9134,7 +9140,7 @@ releasebuffer_call_python(PyObject *self, Py_buffer *buffer)
mv = PyMemoryView_FromBuffer(buffer);
if (mv == NULL) {
PyErr_WriteUnraisable(self);
return;
goto end;
}
// Set the memoryview to restricted mode, which forbids
// users from saving any reference to the underlying buffer
Expand All @@ -9155,6 +9161,10 @@ releasebuffer_call_python(PyObject *self, Py_buffer *buffer)
PyObject_CallMethodNoArgs(mv, &_Py_ID(release));
kumaraditya303 marked this conversation as resolved.
Show resolved Hide resolved
}
Py_DECREF(mv);
end:
assert(!PyErr_Occurred());
kumaraditya303 marked this conversation as resolved.
Show resolved Hide resolved

PyErr_SetRaisedException(exc);
}

/*
Expand Down