Skip to content

gh-162822: Fix bytearray(list) race in the free-threaded build - #162826

Open
JakeHuneau wants to merge 2 commits into
python:mainfrom
JakeHuneau:gh-162822-bytearray-list-race
Open

JakeHuneau wants to merge 2 commits into
python:mainfrom
JakeHuneau:gh-162822-bytearray-list-race

Conversation

@JakeHuneau

@JakeHuneau JakeHuneau commented Nov 29, 2026 •

Copy link
Copy Markdown

In the free-threaded build, bytearray.__init__() read the items of an exact list through PySequence_Fast_ITEMS() without holding the list's lock. Another thread could replace and free an item while _getbytevalue() was converting it.

The fast path now runs under Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST, the same way bytes(list) does (_PyBytes_FromSequence_lock_held). It moved into a helper so that falling back to the iterator path doesn't jump out of the critical section. Items that are exact ints don't run Python code, so nothing runs while the lock is held.

The new test in test_free_threading.test_bytes_object crashed in PyLong_AsLongAndOverflow in 4 of 5 runs on a --disable-gil --with-address-sanitizer build without the fix. With the fix it passed 10 of 10 runs, and test_bytes passes.

bytearray.__init__() read the items of an exact list through
PySequence_Fast_ITEMS() without holding the list's lock, so another
thread could replace and free an item while it was being converted.

Run the fast path under Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST, as
bytes(list) already does.
@python-cla-bot

python-cla-bot Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

Comment thread Objects/bytearrayobject.c Resolved
Co-authored-by: sobolevn <mail@sobolevn.me>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants