Skip to content

Commit 9da98c0

Browse files
gh-111174: Fix crash in getbuffer() called repeatedly for empty BytesIO (GH-111210)
1 parent f6a45a0 commit 9da98c0

File tree

3 files changed

+20
-3
lines changed

3 files changed

+20
-3
lines changed

Lib/test/test_memoryio.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,20 @@ def test_getbuffer(self):
463463
memio.close()
464464
self.assertRaises(ValueError, memio.getbuffer)
465465

466+
def test_getbuffer_empty(self):
467+
memio = self.ioclass()
468+
buf = memio.getbuffer()
469+
self.assertEqual(bytes(buf), b"")
470+
# Trying to change the size of the BytesIO while a buffer is exported
471+
# raises a BufferError.
472+
self.assertRaises(BufferError, memio.write, b'x')
473+
buf2 = memio.getbuffer()
474+
self.assertRaises(BufferError, memio.write, b'x')
475+
buf.release()
476+
self.assertRaises(BufferError, memio.write, b'x')
477+
buf2.release()
478+
memio.write(b'x')
479+
466480
def test_read1(self):
467481
buf = self.buftype("1234567890")
468482
self.assertEqual(self.ioclass(buf).read1(), buf)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix crash in :meth:`io.BytesIO.getbuffer` called repeatedly for empty
2+
BytesIO.

Modules/_io/bytesio.c

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -126,12 +126,13 @@ unshare_buffer(bytesio *self, size_t size)
126126
static int
127127
resize_buffer(bytesio *self, size_t size)
128128
{
129+
assert(self->buf != NULL);
130+
assert(self->exports == 0);
131+
129132
/* Here, unsigned types are used to avoid dealing with signed integer
130133
overflow, which is undefined in C. */
131134
size_t alloc = PyBytes_GET_SIZE(self->buf);
132135

133-
assert(self->buf != NULL);
134-
135136
/* For simplicity, stay in the range of the signed type. Anyway, Python
136137
doesn't allow strings to be longer than this. */
137138
if (size > PY_SSIZE_T_MAX)
@@ -1074,7 +1075,7 @@ bytesiobuf_getbuffer(bytesiobuf *obj, Py_buffer *view, int flags)
10741075
"bytesiobuf_getbuffer: view==NULL argument is obsolete");
10751076
return -1;
10761077
}
1077-
if (SHARED_BUF(b)) {
1078+
if (b->exports == 0 && SHARED_BUF(b)) {
10781079
if (unshare_buffer(b, b->string_size) < 0)
10791080
return -1;
10801081
}

0 commit comments

Comments
 (0)