gh-153296: Fix thread-safety data race in io.StringIO iterator#153368
Open
Twix1288 wants to merge 3 commits into
Open
gh-153296: Fix thread-safety data race in io.StringIO iterator#153368Twix1288 wants to merge 3 commits into
Twix1288 wants to merge 3 commits into
Conversation
|
Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool. If this change has little impact on Python users, wait for a maintainer to apply the |
3851a6a to
21fafe9
Compare
This reverts commit 8ba4fe6.
Author
|
PR is done and tests are complete, should be good to go. Thanks! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR fixes a TSAN-reported data race and segmentation fault when iterating over an
io.StringIOobject while it is being concurrently mutated (e.g., viawrite()).Details
In the free-threaded build,
io.StringIOmemory safety is typically enforced automatically via Argument Clinic wrappers that acquirePy_BEGIN_CRITICAL_SECTION(self)for operations likereadlineandwrite.However, the
__next__method triggered during loop iteration bypasses these wrappers. It is implemented in C asstringio_iternext, directly assigned to thetp_iternextslot. Previously, this slot accessed the string buffer (self->buf) and advancedself->poswithout acquiring the object lock.If another thread concurrently called
write(), it would execute with the lock held but with its underlyingself->posmutating asynchronously. This led to out-of-boundsmemsetwrites and use-after-free conditions.This fix conceptually mirrors the implementation used for
io.BytesIO: it splits the internal logic intostringio_iternext_lock_heldand adds a wrapperstringio_iternextthat properly secures the object's critical section.stringio_iternext#153296