[3.14] gh-140061: Use _PyObject_IsUniquelyReferenced() to check if objects are uniquely referenced (gh-140062) (gh-140157)

The previous `Py_REFCNT(x) == 1` checks can have data races in the free
threaded build. `_PyObject_IsUniquelyReferenced(x)` is a more conservative
check that is safe in the free threaded build and is identical to
`Py_REFCNT(x) == 1` in the default GIL-enabled build.
(cherry picked from commit 32c264982e)

Co-authored-by: Sergey Miryanov <sergey.miryanov@gmail.com>
This commit is contained in:
Miss Islington (bot) 2025-10-15 16:49:17 +02:00 committed by GitHub
parent 6b94c7ceeb
commit 045e34964a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 29 additions and 36 deletions

View file

@ -11,6 +11,7 @@
#include "pycore_code.h" // _PyCode_New()
#include "pycore_hashtable.h" // _Py_hashtable_t
#include "pycore_long.h" // _PyLong_IsZero()
#include "pycore_object.h" // _PyObject_IsUniquelyReferenced
#include "pycore_pystate.h" // _PyInterpreterState_GET()
#include "pycore_setobject.h" // _PySet_NextEntryRef()
#include "pycore_unicodeobject.h" // _PyUnicode_InternImmortal()
@ -388,7 +389,7 @@ w_ref(PyObject *v, char *flag, WFILE *p)
* But we use TYPE_REF always for interned string, to PYC file stable
* as possible.
*/
if (Py_REFCNT(v) == 1 &&
if (_PyObject_IsUniquelyReferenced(v) &&
!(PyUnicode_CheckExact(v) && PyUnicode_CHECK_INTERNED(v))) {
return 0;
}