8000 Use `Py_TryIncref` when returning the ref · python/cpython@6a50381 · GitHub
[go: up one dir, main page]

Skip to content
10000

Commit 6a50381

Browse files
committed
Use Py_TryIncref when returning the ref
The `is_dead` check from the default build is insufficient, since the refcount may go to zero between when we check and when we incref. More generally, `Py_NewRef` is unsafe to use if you have a borrowed refernce.
1 parent ccaeded commit 6a50381

File tree

3 files changed

+7
-3
lines changed

3 files changed

+7
-3
lines changed

Include/internal/pycore_object.h

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,6 @@ PyAPI_FUNC(void) _Py_NO_RETURN _Py_FatalRefcountErrorFunc(
8787
PyAPI_DATA(Py_ssize_t) _Py_RefTotal;
8888

8989
extern void _Py_AddRefTotal(PyInterpreterState *, Py_ssize_t);
90-
extern void _Py_IncRefTotal(PyInterpreterState *);
9190
extern void _Py_DecRefTotal(PyInterpreterState *);
9291

9392
# define _Py_DEC_REFTOTAL(interp) \

Include/internal/pycore_weakref.h

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,13 +58,17 @@ static inline PyObject* _PyWeakref_GET_REF(PyObject *ref_obj)
5858
goto end;
5959
}
6060

61+
#if !defined(Py_GIL_DISABLED)
6162
if (_is_dead(obj)) {
6263
goto end;
6364
}
64-
#if !defined(Py_GIL_DISABLED)
6565
assert(Py_REFCNT(obj) > 0);
66-
#endif
6766
ret = Py_NewRef(obj);
67+
#else
68+
if (_Py_TryIncref(&obj, obj)) {
69+
ret = obj;
70+
}
71+
#endif
6872
end:
6973
Py_END_CRITICAL_SECTION();
7074
return ret;

Include/object.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -766,6 +766,7 @@ PyAPI_FUNC(void) _Py_NegativeRefcount(const char *filename, int lineno,
766766
PyObject *op);
767767
PyAPI_FUNC(void) _Py_INCREF_IncRefTotal(void);
768768
PyAPI_FUNC(void) _Py_DECREF_DecRefTotal(void);
769+
PyAPI_FUNC(void) _Py_IncRefTotal(PyInterpreterState *);
769770
#endif // Py_REF_DEBUG && !Py_LIMITED_API
770771

771772
PyAPI_FUNC(void) _Py_Dealloc(PyObject *);

0 commit comments

Comments
 (0)
0