Skip to content
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
14 changes: 14 additions & 0 deletions Lib/test/test_memoryio.py
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,20 @@ def test_getbuffer(self):
memio.close()
self.assertRaises(ValueError, memio.getbuffer)

def test_getbuffer_empty(self):
memio = self.ioclass()
buf = memio.getbuffer()
self.assertEqual(bytes(buf), b"")
# Trying to change the size of the BytesIO while a buffer is exported
# raises a BufferError.
self.assertRaises(BufferError, memio.write, b'x')
buf2 = memio.getbuffer()
self.assertRaises(BufferError, memio.write, b'x')
buf.release()
self.assertRaises(BufferError, memio.write, b'x')
buf2.release()
memio.write(b'x')

def test_read1(self):
buf = self.buftype("1234567890")
self.assertEqual(self.ioclass(buf).read1(), buf)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix crash in :meth:`io.BytesIO.getbuffer` called repeatedly for empty
BytesIO.
7 changes: 4 additions & 3 deletions Modules/_io/bytesio.c
Original file line number Diff line number Diff line change
Expand Up @@ -126,12 +126,13 @@ unshare_buffer(bytesio *self, size_t size)
static int
resize_buffer(bytesio *self, size_t size)
{
assert(self->buf != NULL);
assert(self->exports == 0);

/* Here, unsigned types are used to avoid dealing with signed integer
overflow, which is undefined in C. */
size_t alloc = PyBytes_GET_SIZE(self->buf);

assert(self->buf != NULL);

/* For simplicity, stay in the range of the signed type. Anyway, Python
doesn't allow strings to be longer than this. */
if (size > PY_SSIZE_T_MAX)
Expand Down Expand Up @@ -1074,7 +1075,7 @@ bytesiobuf_getbuffer(bytesiobuf *obj, Py_buffer *view, int flags)
"bytesiobuf_getbuffer: view==NULL argument is obsolete");
return -1;
}
if (SHARED_BUF(b)) {
if (b->exports == 0 && SHARED_BUF(b)) {
if (unshare_buffer(b, b->string_size) < 0)
return -1;
}
Expand Down