gh-149816: Fix race in subtype_getweakref in free-threading build#150247
Open
Abhi210 wants to merge 1 commit into
Open
gh-149816: Fix race in subtype_getweakref in free-threading build#150247Abhi210 wants to merge 1 commit into
Abhi210 wants to merge 1 commit into
Conversation
22 tasks
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.
This PR resolves finding 61 from the weakref race tracking issue: "Racy weakref head load before incref in
Objects/typeobject.c".Description
In free-threaded builds,
subtype_getweakref()had a race condition where the weakref list head (*weaklistptr) was loaded and immediately passed toPy_NewRef(). If another thread concurrently triggeredweakref_dealloc(), the weakref could be freed before the incref, leading to a use-after-free (UAF).This PR fixes the issue by:
LOCK_WEAKREFS(obj)/UNLOCK_WEAKREFS(obj)critical section.Py_NewRef()with_Py_TryIncref()to safely handle weakrefs whose refcount has reached zero during the race window.Py_NewRef(Py_None)when the list is empty or the weakref is no longer live, preserving the existing API behavior.Testing
Added regression tests in
Lib/test/test_free_threading/test_weakref.pythat:obj.__weakref__concurrently from reader and mutator threads synchronized withthreading.Barrier.Noneversusweakref.ref).