Repository navigation
gh-163204: Defer Py_DECREF when detaching shared BytesIO buffer - #163235
dev-erebus wants to merge 1 commit into
Conversation
|
Thank you for your interest in contributing to Python. This is a community-driven project, and we want it to be a welcoming place to learn and collaborate. Contributors are responsible for reviewing and understanding what they submit, checking its claims, and being able to explain changes in their own words. This helps reviewers focus on the contribution and leaves more time to support other contributors. This contribution appears to have been authored with AI assistance. Please explain your contribution in your own words and describe how you checked its correctness. Please read our guidelines for using AI tools. |
|
I focused on tracing the C heap overflow (_PyBytes_CheckOverflow and debug pad bytes overwritten with 0x78), which at first looked isolated to BytesIO.write(). Inspecting the failure path showed the root cause is inside unshare_buffer_lock_held() in Modules/_io/bytesio.c: Py_SETREF(self->buf, new_buf) calls Py_DECREF(old_buf) mid-operation, and because old_buf is owned by the main thread it hits _Py_DecRefShared() -> _Py_brc_queue_object() -> PyMutex_Lock(&bucket->mutex) (_PY_LOCK_DETACH), suspending the critical section and unlocking self mid-call. Another thread can then mutate self (pos, buf, or close()), causing write_bytes_lock_held() to overflow self->buf on memcpy when it resumes. Checking sibling call sites in bytesio.c (getvalue, getbuffer, truncate, init) showed the same suspension window (NULL deref on concurrent close or stale string_size). Once the exact breaking points were confirmed locally with a temporary trap right after Py_SETREF (showing self->pos and self->buf changing mid-call), I devised a minimal fix (AI assisted): return old_buf via an out-parameter from unshare_buffer_lock_held() / resize_buffer_lock_held() and defer Py_XDECREF(old_buf) until after locked state updates finish in all five callers. Before committing to my PR branch, I made sure I understood every change and validated it locally: reproduced the crash before the fix, then passed 5/5 stress seeds, test_io.test_free_threading -R 3:3 (0 refleaks), and full test_io on free-threaded debug, 3/3 stress seeds plus test_io under ASan, and test_memoryio on a regular GIL debug build. AI assistance was used for:
Note: I take full responsibility for the authorship and any changes in this PR. |
Root Cause
In free-threaded builds (
--disable-gil),unshare_buffer_lock_held()inModules/_io/bytesio.creplacedself->bufviaPy_SETREF(self->buf, new_buf)while holdingPy_BEGIN_CRITICAL_SECTION(self).When the replaced buffer (
old_buf) is owned by another thread (for example, a sharedbytesobject created on the main thread and passed toio.BytesIO(DATA)across worker threads), thePy_DECREF(old_buf)insidePy_SETREFenters_Py_DecRefShared()->_Py_brc_queue_object(), which acquiresPyMutex_Lock(&bucket->mutex)with_PY_LOCK_DETACH(and may also synchronously drain/decref queued objects if the owning thread is detached). Contention on that mutex detaches the thread state and suspends all active critical sections (_PyCriticalSection_SuspendAll), temporarily releasingself's lock mid-operation.While suspended, another thread can acquire
self, mutateself->pos/self->string_size/self->buf, markself->bufshared, orclose()self. When the original thread resumes:unshare_buffer_lock_held()callsclear_shared_buf(self)on the wrong buffer.write_bytes_lock_held()executesmemcpy()using a staleendpos/buffer-capacity assumption, causing a heap buffer overflow (_PyBytes_CheckOverflow/_PyMem_DebugRawReallocin debug builds,SIGSEGVin release builds)._io_BytesIO_getvalue_impl(),bytesiobuf_getbuffer_lock_held(),_io_BytesIO_truncate_impl(), and_io_BytesIO___init___impl()viaPy_XSETREF) face analogous concurrent-close NULL dereference, stalestring_size, or shared-buffer export races.Fix
unshare_buffer_lock_held()andresize_buffer_lock_held()to return the displaced buffer via aPyObject **old_bufout-parameter instead of callingPy_SETREF/Py_DECREFmid-operation, keepingself->buf = new_bufandclear_shared_buf(self)atomic under the critical section.Py_XDECREF(old_buf)until after all locked state reads/writes complete in all five callers (write_bytes_lock_held,_io_BytesIO_getvalue_impl,_io_BytesIO_truncate_impl,_io_BytesIO___init___impl, andbytesiobuf_getbuffer_lock_held).Lib/test/test_io/test_free_threading.pycovering concurrentBytesIO.write()+ replacingBytesIO(<existing bytes>)and sibling unshare/getvalue/getbuffer/truncate/close paths.Verification
7d6e165): Issue reproducer aborted in<1swith_PyBytes_CheckOverflow(free-threaded debug) and_PyMem_DebugRawRealloc: bad trailing pad byte(free-threaded debug + ASan).--disable-gil --with-pydebug): reproducer passed 5/5 seeds (75s total),test_io.test_free_threading -R 3:3passed 10/10 with 0 refcount leaks, fulltest_iopassed (600 tests).--disable-gil --with-pydebug --with-address-sanitizer): reproducer passed 3/3 seeds (45s total),test_io.test_free_threadingandtest_io.test_memoryiopassed (118 tests, 0 ASan diagnostics).--with-pydebug): clean zero-warning build,test_io.test_memoryiopassed (108 tests).make patchcheckpassed.BytesIO.write()and replacing the sharedBytesIO(<existing bytes>)from several threads #163204