Skip to content

gh-163204: Defer Py_DECREF when detaching shared BytesIO buffer - #163235

Open
dev-erebus wants to merge 1 commit into
python:mainfrom
dev-erebus:fix/gh-163204-bytesio-ft-sharing
Open

dev-erebus wants to merge 1 commit into
python:mainfrom
dev-erebus:fix/gh-163204-bytesio-ft-sharing

Conversation

@dev-erebus

Copy link
Copy Markdown

Root Cause

In free-threaded builds (--disable-gil), unshare_buffer_lock_held() in Modules/_io/bytesio.c replaced self->buf via Py_SETREF(self->buf, new_buf) while holding Py_BEGIN_CRITICAL_SECTION(self).

When the replaced buffer (old_buf) is owned by another thread (for example, a shared bytes object created on the main thread and passed to io.BytesIO(DATA) across worker threads), the Py_DECREF(old_buf) inside Py_SETREF enters _Py_DecRefShared() -> _Py_brc_queue_object(), which acquires PyMutex_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 releasing self's lock mid-operation.

While suspended, another thread can acquire self, mutate self->pos / self->string_size / self->buf, mark self->buf shared, or close() self. When the original thread resumes:

  • unshare_buffer_lock_held() calls clear_shared_buf(self) on the wrong buffer.
  • write_bytes_lock_held() executes memcpy() using a stale endpos/buffer-capacity assumption, causing a heap buffer overflow (_PyBytes_CheckOverflow / _PyMem_DebugRawRealloc in debug builds, SIGSEGV in release builds).
  • Sibling callers (_io_BytesIO_getvalue_impl(), bytesiobuf_getbuffer_lock_held(), _io_BytesIO_truncate_impl(), and _io_BytesIO___init___impl() via Py_XSETREF) face analogous concurrent-close NULL dereference, stale string_size, or shared-buffer export races.

Fix

  • Update unshare_buffer_lock_held() and resize_buffer_lock_held() to return the displaced buffer via a PyObject **old_buf out-parameter instead of calling Py_SETREF / Py_DECREF mid-operation, keeping self->buf = new_buf and clear_shared_buf(self) atomic under the critical section.
  • Defer 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, and bytesiobuf_getbuffer_lock_held).
  • Add regression tests in Lib/test/test_io/test_free_threading.py covering concurrent BytesIO.write() + replacing BytesIO(<existing bytes>) and sibling unshare/getvalue/getbuffer/truncate/close paths.

Verification

  • Before fix (7d6e165): Issue reproducer aborted in <1s with _PyBytes_CheckOverflow (free-threaded debug) and _PyMem_DebugRawRealloc: bad trailing pad byte (free-threaded debug + ASan).
  • After fix:
    • Free-threaded debug (--disable-gil --with-pydebug): reproducer passed 5/5 seeds (75s total), test_io.test_free_threading -R 3:3 passed 10/10 with 0 refcount leaks, full test_io passed (600 tests).
    • Free-threaded debug + ASan (--disable-gil --with-pydebug --with-address-sanitizer): reproducer passed 3/3 seeds (45s total), test_io.test_free_threading and test_io.test_memoryio passed (118 tests, 0 ASan diagnostics).
    • Regular GIL debug (--with-pydebug): clean zero-warning build, test_io.test_memoryio passed (108 tests).
    • make patchcheck passed.

@dev-erebus
dev-erebus requested a review from cmaloney as a code owner December 6, 2026 13:10
@python-cla-bot

python-cla-bot Bot commented Dec 6, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

@bedevere-app

bedevere-app Bot commented Dec 6, 2026

Copy link
Copy Markdown

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.

@dev-erebus

Copy link
Copy Markdown
Author

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:

  • Indexing open issues and checking competing PRs to avoid clashes.
  • Tracing the BRC/critical-section path and auditing sibling call sites in bytesio.c under my supervision.
  • Assisting with drafting the patch, regression test scenarios, and PR write-up, all of which I built, ran, and validated locally.

Note: I take full responsibility for the authorship and any changes in this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI-needs-explanation AI-assisted work that needs further explanation and follow up from the contributor awaiting review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants