Skip to content
Open
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
68 changes: 67 additions & 1 deletion Lib/test/test_io/test_free_threading.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from unittest import SkipTest, TestCase
from test.support import Py_GIL_DISABLED, threading_helper
from test.support.threading_helper import run_concurrently
from random import randint
from random import Random, randint
from sys import getsizeof

if not Py_GIL_DISABLED:
Expand Down Expand Up @@ -181,6 +181,72 @@ def reader():
with threading_helper.start_threads(threads):
pass

@threading_helper.requires_working_threading()
@threading_helper.reap_threads
def test_concurrent_write_and_replace_shared_bytes(self):
# gh-163204: Detaching a shared bytes buffer in unshare_buffer_lock_held()
# must not decref the replaced buffer before write() finishes, because
# Py_DECREF can suspend the critical section in free-threaded builds.
data = bytes(range(256)) * 4
shared = [self.ioclass(data)]
nthreads = 4
loops = 2000
barrier = threading.Barrier(nthreads)

def worker(tid):
rng = Random(501 * 1000 + tid)
barrier.wait()
for _ in range(loops):
if rng.randrange(2):
shared[0].write(b"x" * rng.randrange(1024))
else:
shared[0] = self.ioclass(data)

threads = [threading.Thread(target=worker, args=(i,))
for i in range(nthreads)]
with threading_helper.start_threads(threads):
pass

@threading_helper.requires_working_threading()
@threading_helper.reap_threads
def test_concurrent_unshare_getvalue_getbuffer_and_close(self):
# gh-163204: Sibling paths (getvalue, getbuffer, truncate, __init__)
# must also defer Py_DECREF of the replaced shared buffer until locked
# state updates complete.
data = bytes(range(256)) * 4
shared = [self.ioclass(data)]
nthreads = 4
loops = 1000
barrier = threading.Barrier(nthreads)

def worker(tid):
rng = Random(163204 * 100 + tid)
barrier.wait()
for _ in range(loops):
bio = shared[0]
op = rng.randrange(6)
try:
if op == 0:
bio.write(b"x" * rng.randrange(512))
elif op == 1:
bio.truncate(rng.randrange(256))
elif op == 2:
bio.getvalue()
elif op == 3:
with bio.getbuffer():
pass
elif op == 4:
bio.close()
else:
shared[0] = self.ioclass(data)
except (ValueError, BufferError):
pass

threads = [threading.Thread(target=worker, args=(i,))
for i in range(nthreads)]
with threading_helper.start_threads(threads):
pass


class IncrementalNewlineDecoderTest(TestCase):
def make_decoder(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix a race condition in :class:`io.BytesIO` in free-threaded builds where
detaching a shared internal buffer could suspend the active critical section
during ``Py_DECREF`` of the replaced ``bytes`` object, leading to buffer
overflows or crashes during concurrent writes and buffer operations.
41 changes: 29 additions & 12 deletions Modules/_io/bytesio.c
Original file line number Diff line number Diff line change
Expand Up @@ -162,22 +162,27 @@ scan_eol_lock_held(bytesio *self, Py_ssize_t len)

/* Internal routine for detaching the shared buffer of BytesIO objects.
The caller should ensure that the 'size' argument is non-negative and
not lesser than self->string_size. Returns 0 on success, -1 otherwise. */
not lesser than self->string_size. Returns 0 on success, -1 otherwise.
On success, *old_buf receives a strong reference to the replaced buffer so
the caller can defer Py_XDECREF() until after it finishes using locked
state (in free-threaded builds, Py_DECREF can suspend critical sections). */
static int
unshare_buffer_lock_held(bytesio *self, size_t size)
unshare_buffer_lock_held(bytesio *self, size_t size, PyObject **old_buf)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);

PyObject *new_buf;
assert(SHARED_BUF(self));
assert(FT_ATOMIC_LOAD_SSIZE_RELAXED(self->exports) == 0);
assert(size >= (size_t)self->string_size);
assert(*old_buf == NULL);
new_buf = PyBytes_FromStringAndSize(NULL, size);
if (new_buf == NULL)
return -1;
memcpy(PyBytes_AS_STRING(new_buf), PyBytes_AS_STRING(self->buf),
self->string_size);
Py_SETREF(self->buf, new_buf);
*old_buf = self->buf;
self->buf = new_buf;
clear_shared_buf(self);
return 0;
}
Expand All @@ -186,7 +191,7 @@ unshare_buffer_lock_held(bytesio *self, size_t size)
The caller should ensure that the 'size' argument is non-negative. Returns
0 on success, -1 otherwise. */
static int
resize_buffer_lock_held(bytesio *self, size_t size)
resize_buffer_lock_held(bytesio *self, size_t size, PyObject **old_buf)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);

Expand Down Expand Up @@ -223,7 +228,7 @@ resize_buffer_lock_held(bytesio *self, size_t size)
}

if (SHARED_BUF(self)) {
if (unshare_buffer_lock_held(self, alloc) < 0)
if (unshare_buffer_lock_held(self, alloc, old_buf) < 0)
return -1;
}
else {
Expand All @@ -250,6 +255,7 @@ write_bytes_lock_held(bytesio *self, PyObject *b)

Py_buffer buf;
Py_ssize_t len;
PyObject *old_buf = NULL;
if (PyObject_GetBuffer(b, &buf, PyBUF_CONTIG_RO) < 0) {
return -1;
}
Expand All @@ -267,13 +273,14 @@ write_bytes_lock_held(bytesio *self, PyObject *b)
assert(self->pos >= 0);
size_t endpos = (size_t)self->pos + len;
if (endpos > (size_t)PyBytes_GET_SIZE(self->buf)) {
if (resize_buffer_lock_held(self, endpos) < 0) {
if (resize_buffer_lock_held(self, endpos, &old_buf) < 0) {
len = -1;
goto done;
}
}
else if (SHARED_BUF(self)) {
if (unshare_buffer_lock_held(self, Py_MAX(endpos, (size_t)self->string_size)) < 0) {
if (unshare_buffer_lock_held(self, Py_MAX(endpos, (size_t)self->string_size),
&old_buf) < 0) {
len = -1;
goto done;
}
Expand Down Expand Up @@ -305,6 +312,7 @@ write_bytes_lock_held(bytesio *self, PyObject *b)

done:
PyBuffer_Release(&buf);
Py_XDECREF(old_buf);
return len;
}

Expand Down Expand Up @@ -429,9 +437,10 @@ _io_BytesIO_getvalue_impl(bytesio *self)
return PyBytes_FromStringAndSize(PyBytes_AS_STRING(self->buf),
self->string_size);

PyObject *old_buf = NULL;
if (self->string_size != PyBytes_GET_SIZE(self->buf)) {
if (SHARED_BUF(self)) {
if (unshare_buffer_lock_held(self, self->string_size) < 0)
if (unshare_buffer_lock_held(self, self->string_size, &old_buf) < 0)
return NULL;
}
else {
Expand All @@ -440,7 +449,9 @@ _io_BytesIO_getvalue_impl(bytesio *self)
}
}
set_shared_buf(self);
return Py_NewRef(self->buf);
PyObject *res = Py_NewRef(self->buf);
Py_XDECREF(old_buf);
return res;
}

/*[clinic input]
Expand Down Expand Up @@ -770,11 +781,13 @@ _io_BytesIO_truncate_impl(bytesio *self, PyObject *size)

if (new_size < self->string_size) {
Py_ssize_t old_string_size = self->string_size;
PyObject *old_buf = NULL;
self->string_size = new_size;
if (resize_buffer_lock_held(self, new_size) < 0) {
if (resize_buffer_lock_held(self, new_size, &old_buf) < 0) {
self->string_size = old_string_size;
return NULL;
}
Py_XDECREF(old_buf);
}

return PyLong_FromSsize_t(new_size);
Expand Down Expand Up @@ -1144,9 +1157,11 @@ _io_BytesIO___init___impl(bytesio *self, PyObject *initvalue)

if (initvalue && initvalue != Py_None) {
if (PyBytes_CheckExact(initvalue)) {
Py_XSETREF(self->buf, Py_NewRef(initvalue));
PyObject *old_buf = self->buf;
self->buf = Py_NewRef(initvalue);
clear_shared_buf(self);
self->string_size = PyBytes_GET_SIZE(initvalue);
Py_XDECREF(old_buf);
}
else {
PyObject *res;
Expand Down Expand Up @@ -1280,8 +1295,9 @@ bytesiobuf_getbuffer_lock_held(PyObject *op, Py_buffer *view, int flags)
if (check_closed(b)) {
return -1;
}
PyObject *old_buf = NULL;
if (FT_ATOMIC_LOAD_SSIZE_RELAXED(b->exports) == 0 && SHARED_BUF(b)) {
if (unshare_buffer_lock_held(b, b->string_size) < 0)
if (unshare_buffer_lock_held(b, b->string_size, &old_buf) < 0)
return -1;
}

Expand All @@ -1293,6 +1309,7 @@ bytesiobuf_getbuffer_lock_held(PyObject *op, Py_buffer *view, int flags)
while the buffer is exported. */
view->internal = Py_NewRef(b->buf);
FT_ATOMIC_ADD_SSIZE(b->exports, 1);
Py_XDECREF(old_buf);
return 0;
}

Expand Down
Loading