weakrefobject.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #ifndef Py_CPYTHON_WEAKREFOBJECT_H
  2. # error "this header file must not be included directly"
  3. #endif
  4. /* PyWeakReference is the base struct for the Python ReferenceType, ProxyType,
  5. * and CallableProxyType.
  6. */
  7. struct _PyWeakReference {
  8. PyObject_HEAD
  9. /* The object to which this is a weak reference, or Py_None if none.
  10. * Note that this is a stealth reference: wr_object's refcount is
  11. * not incremented to reflect this pointer.
  12. */
  13. PyObject *wr_object;
  14. /* A callable to invoke when wr_object dies, or NULL if none. */
  15. PyObject *wr_callback;
  16. /* A cache for wr_object's hash code. As usual for hashes, this is -1
  17. * if the hash code isn't known yet.
  18. */
  19. Py_hash_t hash;
  20. /* If wr_object is weakly referenced, wr_object has a doubly-linked NULL-
  21. * terminated list of weak references to it. These are the list pointers.
  22. * If wr_object goes away, wr_object is set to Py_None, and these pointers
  23. * have no meaning then.
  24. */
  25. PyWeakReference *wr_prev;
  26. PyWeakReference *wr_next;
  27. vectorcallfunc vectorcall;
  28. };
  29. PyAPI_FUNC(Py_ssize_t) _PyWeakref_GetWeakrefCount(PyWeakReference *head);
  30. PyAPI_FUNC(void) _PyWeakref_ClearRef(PyWeakReference *self);
  31. static inline PyObject* PyWeakref_GET_OBJECT(PyObject *ref_obj) {
  32. PyWeakReference *ref;
  33. PyObject *obj;
  34. assert(PyWeakref_Check(ref_obj));
  35. ref = _Py_CAST(PyWeakReference*, ref_obj);
  36. obj = ref->wr_object;
  37. // Explanation for the Py_REFCNT() check: when a weakref's target is part
  38. // of a long chain of deallocations which triggers the trashcan mechanism,
  39. // clearing the weakrefs can be delayed long after the target's refcount
  40. // has dropped to zero. In the meantime, code accessing the weakref will
  41. // be able to "see" the target object even though it is supposed to be
  42. // unreachable. See issue gh-60806.
  43. if (Py_REFCNT(obj) > 0) {
  44. return obj;
  45. }
  46. return Py_None;
  47. }
  48. #define PyWeakref_GET_OBJECT(ref) PyWeakref_GET_OBJECT(_PyObject_CAST(ref))