Coverage Report

Created: 2026-05-16 06:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/weakrefobject.c
Line
Count
Source
1
#include "Python.h"
2
#include "pycore_critical_section.h"
3
#include "pycore_lock.h"
4
#include "pycore_modsupport.h"    // _PyArg_NoKwnames()
5
#include "pycore_object.h"        // _PyObject_GET_WEAKREFS_LISTPTR()
6
#include "pycore_pyerrors.h"      // _PyErr_ChainExceptions1()
7
#include "pycore_pystate.h"
8
#include "pycore_weakref.h"       // _PyWeakref_GET_REF()
9
10
#ifdef Py_GIL_DISABLED
11
/*
12
 * Thread-safety for free-threaded builds
13
 * ======================================
14
 *
15
 * In free-threaded builds we need to protect mutable state of:
16
 *
17
 * - The weakref (wr_object, hash, wr_callback)
18
 * - The referenced object (its head-of-list pointer)
19
 * - The linked list of weakrefs
20
 *
21
 * For now we've chosen to address this in a straightforward way:
22
 *
23
 * - The weakref's hash is protected using the weakref's per-object lock.
24
 * - The other mutable is protected by a striped lock keyed on the referenced
25
 *   object's address.
26
 * - The striped lock must be locked using `_Py_LOCK_DONT_DETACH` in order to
27
 *   support atomic deletion from WeakValueDictionaries. As a result, we must
28
 *   be careful not to perform any operations that could suspend while the
29
 *   lock is held.
30
 *
31
 * Since the world is stopped when the GC runs, it is free to clear weakrefs
32
 * without acquiring any locks.
33
 */
34
35
#endif
36
37
#define GET_WEAKREFS_LISTPTR(o) \
38
50.1M
        ((PyWeakReference **) _PyObject_GET_WEAKREFS_LISTPTR(o))
39
40
41
Py_ssize_t
42
_PyWeakref_GetWeakrefCount(PyObject *obj)
43
30.1k
{
44
30.1k
    if (!_PyType_SUPPORTS_WEAKREFS(Py_TYPE(obj))) {
45
0
        return 0;
46
0
    }
47
48
30.1k
    LOCK_WEAKREFS(obj);
49
30.1k
    Py_ssize_t count = 0;
50
30.1k
    PyWeakReference *head = *GET_WEAKREFS_LISTPTR(obj);
51
60.3k
    while (head != NULL) {
52
30.1k
        ++count;
53
30.1k
        head = head->wr_next;
54
30.1k
    }
55
30.1k
    UNLOCK_WEAKREFS(obj);
56
30.1k
    return count;
57
30.1k
}
58
59
static PyObject *weakref_vectorcall(PyObject *self, PyObject *const *args, size_t nargsf, PyObject *kwnames);
60
61
static void
62
init_weakref(PyWeakReference *self, PyObject *ob, PyObject *callback)
63
1.36M
{
64
1.36M
    self->hash = -1;
65
1.36M
    self->wr_object = ob;
66
1.36M
    self->wr_prev = NULL;
67
1.36M
    self->wr_next = NULL;
68
1.36M
    self->wr_callback = Py_XNewRef(callback);
69
1.36M
    self->vectorcall = weakref_vectorcall;
70
#ifdef Py_GIL_DISABLED
71
    self->weakrefs_lock = &WEAKREF_LIST_LOCK(ob);
72
    _PyObject_SetMaybeWeakref(ob);
73
    _PyObject_SetMaybeWeakref((PyObject *)self);
74
#endif
75
1.36M
}
76
77
// Clear the weakref and steal its callback into `callback`, if provided.
78
static void
79
clear_weakref_lock_held(PyWeakReference *self, PyObject **callback)
80
1.63M
{
81
1.63M
    if (self->wr_object != Py_None) {
82
1.33M
        PyWeakReference **list = GET_WEAKREFS_LISTPTR(self->wr_object);
83
1.33M
        if (*list == self) {
84
            /* If 'self' is the end of the list (and thus self->wr_next ==
85
               NULL) then the weakref list itself (and thus the value of *list)
86
               will end up being set to NULL. */
87
1.33M
            FT_ATOMIC_STORE_PTR(*list, self->wr_next);
88
1.33M
        }
89
1.33M
        FT_ATOMIC_STORE_PTR(self->wr_object, Py_None);
90
1.33M
        if (self->wr_prev != NULL) {
91
554
            self->wr_prev->wr_next = self->wr_next;
92
554
        }
93
1.33M
        if (self->wr_next != NULL) {
94
357k
            self->wr_next->wr_prev = self->wr_prev;
95
357k
        }
96
1.33M
        self->wr_prev = NULL;
97
1.33M
        self->wr_next = NULL;
98
1.33M
    }
99
1.63M
    if (callback != NULL) {
100
1.36M
        *callback = self->wr_callback;
101
1.36M
        self->wr_callback = NULL;
102
1.36M
    }
103
1.63M
}
104
105
// Clear the weakref and its callback
106
static void
107
clear_weakref(PyObject *op)
108
1.33M
{
109
1.33M
    PyWeakReference *self = _PyWeakref_CAST(op);
110
1.33M
    PyObject *callback = NULL;
111
112
    // self->wr_object may be Py_None if the GC cleared the weakref, so lock
113
    // using the pointer in the weakref.
114
1.33M
    LOCK_WEAKREFS_FOR_WR(self);
115
1.33M
    clear_weakref_lock_held(self, &callback);
116
1.33M
    UNLOCK_WEAKREFS_FOR_WR(self);
117
1.33M
    Py_XDECREF(callback);
118
1.33M
}
119
120
121
/* Cyclic gc uses this to *just* clear the passed-in reference, leaving
122
 * the callback intact and uncalled.  It must be possible to call self's
123
 * tp_dealloc() after calling this, so self has to be left in a sane enough
124
 * state for that to work.  We expect tp_dealloc to decref the callback
125
 * then.  The reason for not letting clear_weakref() decref the callback
126
 * right now is that if the callback goes away, that may in turn trigger
127
 * another callback (if a weak reference to the callback exists) -- running
128
 * arbitrary Python code in the middle of gc is a disaster.  The convolution
129
 * here allows gc to delay triggering such callbacks until the world is in
130
 * a sane state again.
131
 */
132
void
133
_PyWeakref_ClearRef(PyWeakReference *self)
134
267k
{
135
267k
    assert(self != NULL);
136
267k
    assert(PyWeakref_Check(self));
137
267k
    clear_weakref_lock_held(self, NULL);
138
267k
}
139
140
static void
141
weakref_dealloc(PyObject *self)
142
1.33M
{
143
1.33M
    PyObject_GC_UnTrack(self);
144
1.33M
    clear_weakref(self);
145
1.33M
    Py_TYPE(self)->tp_free(self);
146
1.33M
}
147
148
149
static int
150
gc_traverse(PyObject *op, visitproc visit, void *arg)
151
1.47M
{
152
1.47M
    PyWeakReference *self = _PyWeakref_CAST(op);
153
1.47M
    Py_VISIT(self->wr_callback);
154
1.47M
    return 0;
155
1.47M
}
156
157
158
static int
159
gc_clear(PyObject *op)
160
0
{
161
0
    PyWeakReference *self = _PyWeakref_CAST(op);
162
0
    PyObject *callback;
163
    // The world is stopped during GC in free-threaded builds. It's safe to
164
    // call this without holding the lock.
165
0
    clear_weakref_lock_held(self, &callback);
166
0
    Py_XDECREF(callback);
167
0
    return 0;
168
0
}
169
170
171
static PyObject *
172
weakref_vectorcall(PyObject *self, PyObject *const *args,
173
                   size_t nargsf, PyObject *kwnames)
174
394k
{
175
394k
    if (!_PyArg_NoKwnames("weakref", kwnames)) {
176
0
        return NULL;
177
0
    }
178
394k
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
179
394k
    if (!_PyArg_CheckPositional("weakref", nargs, 0, 0)) {
180
0
        return NULL;
181
0
    }
182
394k
    PyObject *obj = _PyWeakref_GET_REF(self);
183
394k
    if (obj == NULL) {
184
0
        Py_RETURN_NONE;
185
0
    }
186
394k
    return obj;
187
394k
}
188
189
static Py_hash_t
190
weakref_hash_lock_held(PyWeakReference *self)
191
1.27M
{
192
1.27M
    if (self->hash != -1)
193
199k
        return self->hash;
194
1.07M
    PyObject* obj = _PyWeakref_GET_REF((PyObject*)self);
195
1.07M
    if (obj == NULL) {
196
0
        PyErr_SetString(PyExc_TypeError, "weak object has gone away");
197
0
        return -1;
198
0
    }
199
1.07M
    self->hash = PyObject_Hash(obj);
200
1.07M
    Py_DECREF(obj);
201
1.07M
    return self->hash;
202
1.07M
}
203
204
static Py_hash_t
205
weakref_hash(PyObject *op)
206
1.27M
{
207
1.27M
    PyWeakReference *self = _PyWeakref_CAST(op);
208
1.27M
    Py_hash_t hash;
209
1.27M
    Py_BEGIN_CRITICAL_SECTION(self);
210
1.27M
    hash = weakref_hash_lock_held(self);
211
1.27M
    Py_END_CRITICAL_SECTION();
212
1.27M
    return hash;
213
1.27M
}
214
215
static PyObject *
216
weakref_repr(PyObject *self)
217
0
{
218
0
    PyObject* obj = _PyWeakref_GET_REF(self);
219
0
    if (obj == NULL) {
220
0
        return PyUnicode_FromFormat("<weakref at %p; dead>", self);
221
0
    }
222
223
0
    PyObject *name = _PyObject_LookupSpecial(obj, &_Py_ID(__name__));
224
0
    PyObject *repr;
225
0
    if (name == NULL || !PyUnicode_Check(name)) {
226
0
        repr = PyUnicode_FromFormat(
227
0
            "<weakref at %p; to '%T' at %p>",
228
0
            self, obj, obj);
229
0
    }
230
0
    else {
231
0
        repr = PyUnicode_FromFormat(
232
0
            "<weakref at %p; to '%T' at %p (%U)>",
233
0
            self, obj, obj, name);
234
0
    }
235
0
    Py_DECREF(obj);
236
0
    Py_XDECREF(name);
237
0
    return repr;
238
0
}
239
240
/* Weak references only support equality, not ordering. Two weak references
241
   are equal if the underlying objects are equal. If the underlying object has
242
   gone away, they are equal if they are identical. */
243
244
static PyObject *
245
weakref_richcompare(PyObject* self, PyObject* other, int op)
246
441k
{
247
441k
    if ((op != Py_EQ && op != Py_NE) ||
248
441k
        !PyWeakref_Check(self) ||
249
441k
        !PyWeakref_Check(other)) {
250
0
        Py_RETURN_NOTIMPLEMENTED;
251
0
    }
252
441k
    PyObject* obj = _PyWeakref_GET_REF(self);
253
441k
    PyObject* other_obj = _PyWeakref_GET_REF(other);
254
441k
    if (obj == NULL || other_obj == NULL) {
255
0
        Py_XDECREF(obj);
256
0
        Py_XDECREF(other_obj);
257
0
        int res = (self == other);
258
0
        if (op == Py_NE)
259
0
            res = !res;
260
0
        if (res)
261
0
            Py_RETURN_TRUE;
262
0
        else
263
0
            Py_RETURN_FALSE;
264
0
    }
265
441k
    PyObject* res = PyObject_RichCompare(obj, other_obj, op);
266
441k
    Py_DECREF(obj);
267
441k
    Py_DECREF(other_obj);
268
441k
    return res;
269
441k
}
270
271
/* Given the head of an object's list of weak references, extract the
272
 * two callback-less refs (ref and proxy).  Used to determine if the
273
 * shared references exist and to determine the back link for newly
274
 * inserted references.
275
 */
276
static void
277
get_basic_refs(PyWeakReference *head,
278
               PyWeakReference **refp, PyWeakReference **proxyp)
279
2.40M
{
280
2.40M
    *refp = NULL;
281
2.40M
    *proxyp = NULL;
282
283
2.40M
    if (head != NULL && head->wr_callback == NULL) {
284
        /* We need to be careful that the "basic refs" aren't
285
           subclasses of the main types.  That complicates this a
286
           little. */
287
392k
        if (PyWeakref_CheckRefExact(head)) {
288
392k
            *refp = head;
289
392k
            head = head->wr_next;
290
392k
        }
291
392k
        if (head != NULL
292
159k
            && head->wr_callback == NULL
293
0
            && PyWeakref_CheckProxy(head)) {
294
0
            *proxyp = head;
295
            /* head = head->wr_next; */
296
0
        }
297
392k
    }
298
2.40M
}
299
300
/* Insert 'newref' in the list after 'prev'.  Both must be non-NULL. */
301
static void
302
insert_after(PyWeakReference *newref, PyWeakReference *prev)
303
2.69k
{
304
2.69k
    newref->wr_prev = prev;
305
2.69k
    newref->wr_next = prev->wr_next;
306
2.69k
    if (prev->wr_next != NULL)
307
1.17k
        prev->wr_next->wr_prev = newref;
308
2.69k
    prev->wr_next = newref;
309
2.69k
}
310
311
/* Insert 'newref' at the head of the list; 'list' points to the variable
312
 * that stores the head.
313
 */
314
static void
315
insert_head(PyWeakReference *newref, PyWeakReference **list)
316
1.35M
{
317
1.35M
    PyWeakReference *next = *list;
318
319
1.35M
    newref->wr_prev = NULL;
320
1.35M
    newref->wr_next = next;
321
1.35M
    if (next != NULL)
322
357k
        next->wr_prev = newref;
323
1.35M
    *list = newref;
324
1.35M
}
325
326
/* See if we can reuse either the basic ref or proxy in list instead of
327
 * creating a new weakref
328
 */
329
static PyWeakReference *
330
try_reuse_basic_ref(PyWeakReference *list, PyTypeObject *type,
331
                    PyObject *callback)
332
1.73M
{
333
1.73M
    if (callback != NULL) {
334
693k
        return NULL;
335
693k
    }
336
337
1.04M
    PyWeakReference *ref, *proxy;
338
1.04M
    get_basic_refs(list, &ref, &proxy);
339
340
1.04M
    PyWeakReference *cand = NULL;
341
1.04M
    if (type == &_PyWeakref_RefType) {
342
1.04M
        cand = ref;
343
1.04M
    }
344
1.04M
    if ((type == &_PyWeakref_ProxyType) ||
345
1.04M
        (type == &_PyWeakref_CallableProxyType)) {
346
0
        cand = proxy;
347
0
    }
348
349
1.04M
    if (cand != NULL && _Py_TryIncref((PyObject *) cand)) {
350
389k
        return cand;
351
389k
    }
352
652k
    return NULL;
353
1.04M
}
354
355
static int
356
is_basic_ref(PyWeakReference *ref)
357
1.42M
{
358
1.42M
    return (ref->wr_callback == NULL) && PyWeakref_CheckRefExact(ref);
359
1.42M
}
360
361
static int
362
is_basic_proxy(PyWeakReference *proxy)
363
770k
{
364
770k
    return (proxy->wr_callback == NULL) && PyWeakref_CheckProxy(proxy);
365
770k
}
366
367
static int
368
is_basic_ref_or_proxy(PyWeakReference *wr)
369
60.3k
{
370
60.3k
    return is_basic_ref(wr) || is_basic_proxy(wr);
371
60.3k
}
372
373
/* Insert `newref` in the appropriate position in `list` */
374
static void
375
insert_weakref(PyWeakReference *newref, PyWeakReference **list)
376
1.36M
{
377
1.36M
    PyWeakReference *ref, *proxy;
378
1.36M
    get_basic_refs(*list, &ref, &proxy);
379
380
1.36M
    PyWeakReference *prev;
381
1.36M
    if (is_basic_ref(newref)) {
382
652k
        prev = NULL;
383
652k
    }
384
709k
    else if (is_basic_proxy(newref)) {
385
0
        prev = ref;
386
0
    }
387
709k
    else {
388
709k
        prev = (proxy == NULL) ? ref : proxy;
389
709k
    }
390
391
1.36M
    if (prev == NULL) {
392
1.35M
        insert_head(newref, list);
393
1.35M
    }
394
2.69k
    else {
395
2.69k
        insert_after(newref, prev);
396
2.69k
    }
397
1.36M
}
398
399
static PyWeakReference *
400
allocate_weakref(PyTypeObject *type, PyObject *obj, PyObject *callback)
401
1.36M
{
402
1.36M
    PyWeakReference *newref = (PyWeakReference *) type->tp_alloc(type, 0);
403
1.36M
    if (newref == NULL) {
404
0
        return NULL;
405
0
    }
406
1.36M
    init_weakref(newref, obj, callback);
407
1.36M
    return newref;
408
1.36M
}
409
410
static PyWeakReference *
411
get_or_create_weakref(PyTypeObject *type, PyObject *obj, PyObject *callback)
412
1.75M
{
413
1.75M
    if (!_PyType_SUPPORTS_WEAKREFS(Py_TYPE(obj))) {
414
0
        PyErr_Format(PyExc_TypeError,
415
0
                     "cannot create weak reference to '%s' object",
416
0
                     Py_TYPE(obj)->tp_name);
417
0
        return NULL;
418
0
    }
419
1.75M
    if (callback == Py_None)
420
0
        callback = NULL;
421
422
1.75M
    PyWeakReference **list = GET_WEAKREFS_LISTPTR(obj);
423
1.75M
    if ((type == &_PyWeakref_RefType) ||
424
16.1k
        (type == &_PyWeakref_ProxyType) ||
425
16.1k
        (type == &_PyWeakref_CallableProxyType))
426
1.73M
    {
427
1.73M
        LOCK_WEAKREFS(obj);
428
1.73M
        PyWeakReference *basic_ref = try_reuse_basic_ref(*list, type, callback);
429
1.73M
        if (basic_ref != NULL) {
430
389k
            UNLOCK_WEAKREFS(obj);
431
389k
            return basic_ref;
432
389k
        }
433
1.34M
        PyWeakReference *newref = allocate_weakref(type, obj, callback);
434
1.34M
        if (newref == NULL) {
435
0
            UNLOCK_WEAKREFS(obj);
436
0
            return NULL;
437
0
        }
438
1.34M
        insert_weakref(newref, list);
439
1.34M
        UNLOCK_WEAKREFS(obj);
440
1.34M
        return newref;
441
1.34M
    }
442
16.1k
    else {
443
        // We may not be able to safely allocate inside the lock
444
16.1k
        PyWeakReference *newref = allocate_weakref(type, obj, callback);
445
16.1k
        if (newref == NULL) {
446
0
            return NULL;
447
0
        }
448
16.1k
        LOCK_WEAKREFS(obj);
449
16.1k
        insert_weakref(newref, list);
450
16.1k
        UNLOCK_WEAKREFS(obj);
451
16.1k
        return newref;
452
16.1k
    }
453
1.75M
}
454
455
static int
456
parse_weakref_init_args(const char *funcname, PyObject *args, PyObject *kwargs,
457
                        PyObject **obp, PyObject **callbackp)
458
2.21M
{
459
2.21M
    return PyArg_UnpackTuple(args, funcname, 1, 2, obp, callbackp);
460
2.21M
}
461
462
static PyObject *
463
weakref___new__(PyTypeObject *type, PyObject *args, PyObject *kwargs)
464
1.10M
{
465
1.10M
    PyObject *ob, *callback = NULL;
466
1.10M
    if (parse_weakref_init_args("__new__", args, kwargs, &ob, &callback)) {
467
1.10M
        return (PyObject *)get_or_create_weakref(type, ob, callback);
468
1.10M
    }
469
0
    return NULL;
470
1.10M
}
471
472
static int
473
weakref___init__(PyObject *self, PyObject *args, PyObject *kwargs)
474
1.10M
{
475
1.10M
    PyObject *tmp;
476
477
1.10M
    if (!_PyArg_NoKeywords("ref", kwargs))
478
0
        return -1;
479
480
1.10M
    if (parse_weakref_init_args("__init__", args, kwargs, &tmp, &tmp))
481
1.10M
        return 0;
482
0
    else
483
0
        return -1;
484
1.10M
}
485
486
487
static PyMemberDef weakref_members[] = {
488
    {"__callback__", _Py_T_OBJECT, offsetof(PyWeakReference, wr_callback), Py_READONLY},
489
    {NULL} /* Sentinel */
490
};
491
492
static PyMethodDef weakref_methods[] = {
493
    {"__class_getitem__",    Py_GenericAlias,
494
    METH_O|METH_CLASS,       PyDoc_STR("See PEP 585")},
495
    {NULL} /* Sentinel */
496
};
497
498
PyTypeObject
499
_PyWeakref_RefType = {
500
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
501
    .tp_name = "weakref.ReferenceType",
502
    .tp_basicsize = sizeof(PyWeakReference),
503
    .tp_dealloc = weakref_dealloc,
504
    .tp_vectorcall_offset = offsetof(PyWeakReference, vectorcall),
505
    .tp_call = PyVectorcall_Call,
506
    .tp_repr = weakref_repr,
507
    .tp_hash = weakref_hash,
508
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
509
                Py_TPFLAGS_HAVE_VECTORCALL | Py_TPFLAGS_BASETYPE,
510
    .tp_traverse = gc_traverse,
511
    .tp_clear = gc_clear,
512
    .tp_richcompare = weakref_richcompare,
513
    .tp_methods = weakref_methods,
514
    .tp_members = weakref_members,
515
    .tp_init = weakref___init__,
516
    .tp_alloc = PyType_GenericAlloc,
517
    .tp_new = weakref___new__,
518
    .tp_free = PyObject_GC_Del,
519
};
520
521
522
static bool
523
proxy_check_ref(PyObject *obj)
524
0
{
525
0
    if (obj == NULL) {
526
0
        PyErr_SetString(PyExc_ReferenceError,
527
0
                        "weakly-referenced object no longer exists");
528
0
        return false;
529
0
    }
530
0
    return true;
531
0
}
532
533
534
/* If a parameter is a proxy, check that it is still "live" and wrap it,
535
 * replacing the original value with the raw object.  Raises ReferenceError
536
 * if the param is a dead proxy.
537
 */
538
#define UNWRAP(o) \
539
0
        if (PyWeakref_CheckProxy(o)) { \
540
0
            o = _PyWeakref_GET_REF(o); \
541
0
            if (!proxy_check_ref(o)) { \
542
0
                return NULL; \
543
0
            } \
544
0
        } \
545
0
        else { \
546
0
            Py_INCREF(o); \
547
0
        }
548
549
#define WRAP_UNARY(method, generic) \
550
    static PyObject * \
551
0
    method(PyObject *proxy) { \
552
0
        UNWRAP(proxy); \
553
0
        PyObject* res = generic(proxy); \
554
0
        Py_DECREF(proxy); \
555
0
        return res; \
556
0
    }
557
558
#define WRAP_BINARY(method, generic) \
559
    static PyObject * \
560
0
    method(PyObject *x, PyObject *y) { \
561
0
        UNWRAP(x); \
562
0
        UNWRAP(y); \
563
0
        PyObject* res = generic(x, y); \
564
0
        Py_DECREF(x); \
565
0
        Py_DECREF(y); \
566
0
        return res; \
567
0
    }
568
569
/* Note that the third arg needs to be checked for NULL since the tp_call
570
 * slot can receive NULL for this arg.
571
 */
572
#define WRAP_TERNARY(method, generic) \
573
    static PyObject * \
574
0
    method(PyObject *proxy, PyObject *v, PyObject *w) { \
575
0
        UNWRAP(proxy); \
576
0
        UNWRAP(v); \
577
0
        if (w != NULL) { \
578
0
            UNWRAP(w); \
579
0
        } \
580
0
        PyObject* res = generic(proxy, v, w); \
581
0
        Py_DECREF(proxy); \
582
0
        Py_DECREF(v); \
583
0
        Py_XDECREF(w); \
584
0
        return res; \
585
0
    }
586
587
#define WRAP_METHOD(method, SPECIAL) \
588
    static PyObject * \
589
0
    method(PyObject *proxy, PyObject *Py_UNUSED(ignored)) { \
590
0
            UNWRAP(proxy); \
591
0
            PyObject* res = PyObject_CallMethodNoArgs(proxy, &_Py_ID(SPECIAL)); \
592
0
            Py_DECREF(proxy); \
593
0
            return res; \
594
0
        }
595
596
597
/* direct slots */
598
599
0
WRAP_BINARY(proxy_getattr, PyObject_GetAttr)
600
0
WRAP_UNARY(proxy_str, PyObject_Str)
601
0
WRAP_TERNARY(proxy_call, PyObject_Call)
602
603
static PyObject *
604
proxy_repr(PyObject *proxy)
605
0
{
606
0
    PyObject *obj = _PyWeakref_GET_REF(proxy);
607
0
    PyObject *repr;
608
0
    if (obj != NULL) {
609
0
        repr = PyUnicode_FromFormat(
610
0
            "<weakproxy at %p; to '%T' at %p>",
611
0
            proxy, obj, obj);
612
0
        Py_DECREF(obj);
613
0
    }
614
0
    else {
615
0
        repr = PyUnicode_FromFormat(
616
0
            "<weakproxy at %p; dead>",
617
0
            proxy);
618
0
    }
619
0
    return repr;
620
0
}
621
622
623
static int
624
proxy_setattr(PyObject *proxy, PyObject *name, PyObject *value)
625
0
{
626
0
    PyObject *obj = _PyWeakref_GET_REF(proxy);
627
0
    if (!proxy_check_ref(obj)) {
628
0
        return -1;
629
0
    }
630
0
    int res = PyObject_SetAttr(obj, name, value);
631
0
    Py_DECREF(obj);
632
0
    return res;
633
0
}
634
635
static PyObject *
636
proxy_richcompare(PyObject *proxy, PyObject *v, int op)
637
0
{
638
0
    UNWRAP(proxy);
639
0
    UNWRAP(v);
640
0
    PyObject* res = PyObject_RichCompare(proxy, v, op);
641
0
    Py_DECREF(proxy);
642
0
    Py_DECREF(v);
643
0
    return res;
644
0
}
645
646
/* number slots */
647
0
WRAP_BINARY(proxy_add, PyNumber_Add)
648
0
WRAP_BINARY(proxy_sub, PyNumber_Subtract)
649
0
WRAP_BINARY(proxy_mul, PyNumber_Multiply)
650
0
WRAP_BINARY(proxy_floor_div, PyNumber_FloorDivide)
651
0
WRAP_BINARY(proxy_true_div, PyNumber_TrueDivide)
652
0
WRAP_BINARY(proxy_mod, PyNumber_Remainder)
653
0
WRAP_BINARY(proxy_divmod, PyNumber_Divmod)
654
0
WRAP_TERNARY(proxy_pow, PyNumber_Power)
655
0
WRAP_UNARY(proxy_neg, PyNumber_Negative)
656
0
WRAP_UNARY(proxy_pos, PyNumber_Positive)
657
0
WRAP_UNARY(proxy_abs, PyNumber_Absolute)
658
0
WRAP_UNARY(proxy_invert, PyNumber_Invert)
659
0
WRAP_BINARY(proxy_lshift, PyNumber_Lshift)
660
0
WRAP_BINARY(proxy_rshift, PyNumber_Rshift)
661
0
WRAP_BINARY(proxy_and, PyNumber_And)
662
0
WRAP_BINARY(proxy_xor, PyNumber_Xor)
663
0
WRAP_BINARY(proxy_or, PyNumber_Or)
664
0
WRAP_UNARY(proxy_int, PyNumber_Long)
665
0
WRAP_UNARY(proxy_float, PyNumber_Float)
666
0
WRAP_BINARY(proxy_iadd, PyNumber_InPlaceAdd)
667
0
WRAP_BINARY(proxy_isub, PyNumber_InPlaceSubtract)
668
0
WRAP_BINARY(proxy_imul, PyNumber_InPlaceMultiply)
669
0
WRAP_BINARY(proxy_ifloor_div, PyNumber_InPlaceFloorDivide)
670
0
WRAP_BINARY(proxy_itrue_div, PyNumber_InPlaceTrueDivide)
671
0
WRAP_BINARY(proxy_imod, PyNumber_InPlaceRemainder)
672
0
WRAP_TERNARY(proxy_ipow, PyNumber_InPlacePower)
673
0
WRAP_BINARY(proxy_ilshift, PyNumber_InPlaceLshift)
674
0
WRAP_BINARY(proxy_irshift, PyNumber_InPlaceRshift)
675
0
WRAP_BINARY(proxy_iand, PyNumber_InPlaceAnd)
676
0
WRAP_BINARY(proxy_ixor, PyNumber_InPlaceXor)
677
0
WRAP_BINARY(proxy_ior, PyNumber_InPlaceOr)
678
0
WRAP_UNARY(proxy_index, PyNumber_Index)
679
0
WRAP_BINARY(proxy_matmul, PyNumber_MatrixMultiply)
680
0
WRAP_BINARY(proxy_imatmul, PyNumber_InPlaceMatrixMultiply)
681
682
static int
683
proxy_bool(PyObject *proxy)
684
0
{
685
0
    PyObject *o = _PyWeakref_GET_REF(proxy);
686
0
    if (!proxy_check_ref(o)) {
687
0
        return -1;
688
0
    }
689
0
    int res = PyObject_IsTrue(o);
690
0
    Py_DECREF(o);
691
0
    return res;
692
0
}
693
694
static void
695
proxy_dealloc(PyObject *self)
696
0
{
697
0
    PyObject_GC_UnTrack(self);
698
0
    clear_weakref(self);
699
0
    PyObject_GC_Del(self);
700
0
}
701
702
/* sequence slots */
703
704
static int
705
proxy_contains(PyObject *proxy, PyObject *value)
706
0
{
707
0
    PyObject *obj = _PyWeakref_GET_REF(proxy);
708
0
    if (!proxy_check_ref(obj)) {
709
0
        return -1;
710
0
    }
711
0
    int res = PySequence_Contains(obj, value);
712
0
    Py_DECREF(obj);
713
0
    return res;
714
0
}
715
716
/* mapping slots */
717
718
static Py_ssize_t
719
proxy_length(PyObject *proxy)
720
0
{
721
0
    PyObject *obj = _PyWeakref_GET_REF(proxy);
722
0
    if (!proxy_check_ref(obj)) {
723
0
        return -1;
724
0
    }
725
0
    Py_ssize_t res = PyObject_Length(obj);
726
0
    Py_DECREF(obj);
727
0
    return res;
728
0
}
729
730
0
WRAP_BINARY(proxy_getitem, PyObject_GetItem)
731
732
static int
733
proxy_setitem(PyObject *proxy, PyObject *key, PyObject *value)
734
0
{
735
0
    PyObject *obj = _PyWeakref_GET_REF(proxy);
736
0
    if (!proxy_check_ref(obj)) {
737
0
        return -1;
738
0
    }
739
0
    int res;
740
0
    if (value == NULL) {
741
0
        res = PyObject_DelItem(obj, key);
742
0
    } else {
743
0
        res = PyObject_SetItem(obj, key, value);
744
0
    }
745
0
    Py_DECREF(obj);
746
0
    return res;
747
0
}
748
749
/* iterator slots */
750
751
static PyObject *
752
proxy_iter(PyObject *proxy)
753
0
{
754
0
    PyObject *obj = _PyWeakref_GET_REF(proxy);
755
0
    if (!proxy_check_ref(obj)) {
756
0
        return NULL;
757
0
    }
758
0
    PyObject* res = PyObject_GetIter(obj);
759
0
    Py_DECREF(obj);
760
0
    return res;
761
0
}
762
763
static PyObject *
764
proxy_iternext(PyObject *proxy)
765
0
{
766
0
    PyObject *obj = _PyWeakref_GET_REF(proxy);
767
0
    if (!proxy_check_ref(obj)) {
768
0
        return NULL;
769
0
    }
770
0
    if (!PyIter_Check(obj)) {
771
0
        PyErr_Format(PyExc_TypeError,
772
0
            "Weakref proxy referenced a non-iterator '%.200s' object",
773
0
            Py_TYPE(obj)->tp_name);
774
0
        Py_DECREF(obj);
775
0
        return NULL;
776
0
    }
777
0
    PyObject* res = PyIter_Next(obj);
778
0
    Py_DECREF(obj);
779
0
    return res;
780
0
}
781
782
783
0
WRAP_METHOD(proxy_bytes, __bytes__)
784
0
WRAP_METHOD(proxy_reversed, __reversed__)
785
786
787
static PyMethodDef proxy_methods[] = {
788
        {"__bytes__", proxy_bytes, METH_NOARGS},
789
        {"__reversed__", proxy_reversed, METH_NOARGS},
790
        {NULL, NULL}
791
};
792
793
794
static PyNumberMethods proxy_as_number = {
795
    proxy_add,              /*nb_add*/
796
    proxy_sub,              /*nb_subtract*/
797
    proxy_mul,              /*nb_multiply*/
798
    proxy_mod,              /*nb_remainder*/
799
    proxy_divmod,           /*nb_divmod*/
800
    proxy_pow,              /*nb_power*/
801
    proxy_neg,              /*nb_negative*/
802
    proxy_pos,              /*nb_positive*/
803
    proxy_abs,              /*nb_absolute*/
804
    proxy_bool,             /*nb_bool*/
805
    proxy_invert,           /*nb_invert*/
806
    proxy_lshift,           /*nb_lshift*/
807
    proxy_rshift,           /*nb_rshift*/
808
    proxy_and,              /*nb_and*/
809
    proxy_xor,              /*nb_xor*/
810
    proxy_or,               /*nb_or*/
811
    proxy_int,              /*nb_int*/
812
    0,                      /*nb_reserved*/
813
    proxy_float,            /*nb_float*/
814
    proxy_iadd,             /*nb_inplace_add*/
815
    proxy_isub,             /*nb_inplace_subtract*/
816
    proxy_imul,             /*nb_inplace_multiply*/
817
    proxy_imod,             /*nb_inplace_remainder*/
818
    proxy_ipow,             /*nb_inplace_power*/
819
    proxy_ilshift,          /*nb_inplace_lshift*/
820
    proxy_irshift,          /*nb_inplace_rshift*/
821
    proxy_iand,             /*nb_inplace_and*/
822
    proxy_ixor,             /*nb_inplace_xor*/
823
    proxy_ior,              /*nb_inplace_or*/
824
    proxy_floor_div,        /*nb_floor_divide*/
825
    proxy_true_div,         /*nb_true_divide*/
826
    proxy_ifloor_div,       /*nb_inplace_floor_divide*/
827
    proxy_itrue_div,        /*nb_inplace_true_divide*/
828
    proxy_index,            /*nb_index*/
829
    proxy_matmul,           /*nb_matrix_multiply*/
830
    proxy_imatmul,          /*nb_inplace_matrix_multiply*/
831
};
832
833
static PySequenceMethods proxy_as_sequence = {
834
    proxy_length,               /*sq_length*/
835
    0,                          /*sq_concat*/
836
    0,                          /*sq_repeat*/
837
    0,                          /*sq_item*/
838
    0,                          /*sq_slice*/
839
    0,                          /*sq_ass_item*/
840
    0,                          /*sq_ass_slice*/
841
    proxy_contains,             /* sq_contains */
842
};
843
844
static PyMappingMethods proxy_as_mapping = {
845
    proxy_length,                 /*mp_length*/
846
    proxy_getitem,                /*mp_subscript*/
847
    proxy_setitem,                /*mp_ass_subscript*/
848
};
849
850
851
PyTypeObject
852
_PyWeakref_ProxyType = {
853
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
854
    "weakref.ProxyType",
855
    sizeof(PyWeakReference),
856
    0,
857
    /* methods */
858
    proxy_dealloc,                      /* tp_dealloc */
859
    0,                                  /* tp_vectorcall_offset */
860
    0,                                  /* tp_getattr */
861
    0,                                  /* tp_setattr */
862
    0,                                  /* tp_as_async */
863
    proxy_repr,                         /* tp_repr */
864
    &proxy_as_number,                   /* tp_as_number */
865
    &proxy_as_sequence,                 /* tp_as_sequence */
866
    &proxy_as_mapping,                  /* tp_as_mapping */
867
// Notice that tp_hash is intentionally omitted as proxies are "mutable" (when the reference dies).
868
    0,                                  /* tp_hash */
869
    0,                                  /* tp_call */
870
    proxy_str,                          /* tp_str */
871
    proxy_getattr,                      /* tp_getattro */
872
    proxy_setattr,                      /* tp_setattro */
873
    0,                                  /* tp_as_buffer */
874
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
875
    0,                                  /* tp_doc */
876
    gc_traverse,                        /* tp_traverse */
877
    gc_clear,                           /* tp_clear */
878
    proxy_richcompare,                  /* tp_richcompare */
879
    0,                                  /* tp_weaklistoffset */
880
    proxy_iter,                         /* tp_iter */
881
    proxy_iternext,                     /* tp_iternext */
882
    proxy_methods,                      /* tp_methods */
883
};
884
885
886
PyTypeObject
887
_PyWeakref_CallableProxyType = {
888
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
889
    "weakref.CallableProxyType",
890
    sizeof(PyWeakReference),
891
    0,
892
    /* methods */
893
    proxy_dealloc,                      /* tp_dealloc */
894
    0,                                  /* tp_vectorcall_offset */
895
    0,                                  /* tp_getattr */
896
    0,                                  /* tp_setattr */
897
    0,                                  /* tp_as_async */
898
    proxy_repr,                         /* tp_repr */
899
    &proxy_as_number,                   /* tp_as_number */
900
    &proxy_as_sequence,                 /* tp_as_sequence */
901
    &proxy_as_mapping,                  /* tp_as_mapping */
902
    0,                                  /* tp_hash */
903
    proxy_call,                         /* tp_call */
904
    proxy_str,                          /* tp_str */
905
    proxy_getattr,                      /* tp_getattro */
906
    proxy_setattr,                      /* tp_setattro */
907
    0,                                  /* tp_as_buffer */
908
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
909
    0,                                  /* tp_doc */
910
    gc_traverse,                        /* tp_traverse */
911
    gc_clear,                           /* tp_clear */
912
    proxy_richcompare,                  /* tp_richcompare */
913
    0,                                  /* tp_weaklistoffset */
914
    proxy_iter,                         /* tp_iter */
915
    proxy_iternext,                     /* tp_iternext */
916
};
917
918
PyObject *
919
PyWeakref_NewRef(PyObject *ob, PyObject *callback)
920
646k
{
921
646k
    return (PyObject *)get_or_create_weakref(&_PyWeakref_RefType, ob,
922
646k
                                             callback);
923
646k
}
924
925
PyObject *
926
PyWeakref_NewProxy(PyObject *ob, PyObject *callback)
927
0
{
928
0
    PyTypeObject *type = &_PyWeakref_ProxyType;
929
0
    if (PyCallable_Check(ob)) {
930
0
        type = &_PyWeakref_CallableProxyType;
931
0
    }
932
0
    return (PyObject *)get_or_create_weakref(type, ob, callback);
933
0
}
934
935
int
936
PyWeakref_IsDead(PyObject *ref)
937
0
{
938
0
    if (ref == NULL) {
939
0
        PyErr_BadInternalCall();
940
0
        return -1;
941
0
    }
942
0
    if (!PyWeakref_Check(ref)) {
943
0
        PyErr_Format(PyExc_TypeError, "expected a weakref, got %T", ref);
944
0
        return -1;
945
0
    }
946
0
    return _PyWeakref_IS_DEAD(ref);
947
0
}
948
949
int
950
PyWeakref_GetRef(PyObject *ref, PyObject **pobj)
951
25.7k
{
952
25.7k
    if (ref == NULL) {
953
0
        *pobj = NULL;
954
0
        PyErr_BadInternalCall();
955
0
        return -1;
956
0
    }
957
25.7k
    if (!PyWeakref_Check(ref)) {
958
0
        *pobj = NULL;
959
0
        PyErr_SetString(PyExc_TypeError, "expected a weakref");
960
0
        return -1;
961
0
    }
962
25.7k
    *pobj = _PyWeakref_GET_REF(ref);
963
25.7k
    return (*pobj != NULL);
964
25.7k
}
965
966
967
/* removed in 3.15, but kept for stable ABI compatibility */
968
PyAPI_FUNC(PyObject *)
969
PyWeakref_GetObject(PyObject *ref)
970
0
{
971
0
    if (ref == NULL || !PyWeakref_Check(ref)) {
972
0
        PyErr_BadInternalCall();
973
0
        return NULL;
974
0
    }
975
0
    PyObject *obj = _PyWeakref_GET_REF(ref);
976
0
    if (obj == NULL) {
977
0
        return Py_None;
978
0
    }
979
0
    Py_DECREF(obj);
980
0
    return obj;  // borrowed reference
981
0
}
982
983
/* Note that there's an inlined copy-paste of handle_callback() in gcmodule.c's
984
 * handle_weakrefs().
985
 */
986
static void
987
handle_callback(PyWeakReference *ref, PyObject *callback)
988
30.1k
{
989
30.1k
    PyObject *cbresult = PyObject_CallOneArg(callback, (PyObject *)ref);
990
991
30.1k
    if (cbresult == NULL) {
992
0
        PyErr_FormatUnraisable("Exception ignored while "
993
0
                               "calling weakref callback %R", callback);
994
0
    }
995
30.1k
    else {
996
30.1k
        Py_DECREF(cbresult);
997
30.1k
    }
998
30.1k
}
999
1000
/* This function is called by the tp_dealloc handler to clear weak references.
1001
 *
1002
 * This iterates through the weak references for 'object' and calls callbacks
1003
 * for those references which have one.  It returns when all callbacks have
1004
 * been attempted.
1005
 */
1006
void
1007
PyObject_ClearWeakRefs(PyObject *object)
1008
46.9M
{
1009
46.9M
    PyWeakReference **list;
1010
1011
46.9M
    if (object == NULL
1012
46.9M
        || !_PyType_SUPPORTS_WEAKREFS(Py_TYPE(object))
1013
46.9M
        || Py_REFCNT(object) != 0)
1014
0
    {
1015
0
        PyErr_BadInternalCall();
1016
0
        return;
1017
0
    }
1018
1019
46.9M
    list = GET_WEAKREFS_LISTPTR(object);
1020
46.9M
    if (FT_ATOMIC_LOAD_PTR(*list) == NULL) {
1021
        // Fast path for the common case
1022
46.9M
        return;
1023
46.9M
    }
1024
1025
    /* Remove the callback-less basic and proxy references, which always appear
1026
       at the head of the list.
1027
    */
1028
60.3k
    for (int done = 0; !done;) {
1029
30.1k
        LOCK_WEAKREFS(object);
1030
30.1k
        if (*list != NULL && is_basic_ref_or_proxy(*list)) {
1031
5
            PyObject *callback;
1032
5
            clear_weakref_lock_held(*list, &callback);
1033
5
            assert(callback == NULL);
1034
5
        }
1035
30.1k
        done = (*list == NULL) || !is_basic_ref_or_proxy(*list);
1036
30.1k
        UNLOCK_WEAKREFS(object);
1037
30.1k
    }
1038
1039
    /* Deal with non-canonical (subtypes or refs with callbacks) references. */
1040
30.1k
    Py_ssize_t num_weakrefs = _PyWeakref_GetWeakrefCount(object);
1041
30.1k
    if (num_weakrefs == 0) {
1042
5
        return;
1043
5
    }
1044
1045
30.1k
    PyObject *exc = PyErr_GetRaisedException();
1046
30.1k
    PyObject *tuple = PyTuple_New(num_weakrefs * 2);
1047
30.1k
    if (tuple == NULL) {
1048
0
        _PyWeakref_ClearWeakRefsNoCallbacks(object);
1049
0
        PyErr_FormatUnraisable("Exception ignored while "
1050
0
                               "clearing object weakrefs");
1051
0
        PyErr_SetRaisedException(exc);
1052
0
        return;
1053
0
    }
1054
1055
30.1k
    Py_ssize_t num_items = 0;
1056
60.3k
    for (int done = 0; !done;) {
1057
30.1k
        PyObject *callback = NULL;
1058
30.1k
        LOCK_WEAKREFS(object);
1059
30.1k
        PyWeakReference *cur = *list;
1060
30.1k
        if (cur != NULL) {
1061
30.1k
            clear_weakref_lock_held(cur, &callback);
1062
30.1k
            if (_Py_TryIncref((PyObject *) cur)) {
1063
30.1k
                assert(num_items / 2 < num_weakrefs);
1064
30.1k
                PyTuple_SET_ITEM(tuple, num_items, (PyObject *) cur);
1065
30.1k
                PyTuple_SET_ITEM(tuple, num_items + 1, callback);
1066
30.1k
                num_items += 2;
1067
30.1k
                callback = NULL;
1068
30.1k
            }
1069
30.1k
        }
1070
30.1k
        done = (*list == NULL);
1071
30.1k
        UNLOCK_WEAKREFS(object);
1072
1073
30.1k
        Py_XDECREF(callback);
1074
30.1k
    }
1075
1076
60.3k
    for (Py_ssize_t i = 0; i < num_items; i += 2) {
1077
30.1k
        PyObject *callback = PyTuple_GET_ITEM(tuple, i + 1);
1078
30.1k
        if (callback != NULL) {
1079
30.1k
            PyObject *weakref = PyTuple_GET_ITEM(tuple, i);
1080
30.1k
            handle_callback((PyWeakReference *)weakref, callback);
1081
30.1k
        }
1082
30.1k
    }
1083
1084
30.1k
    Py_DECREF(tuple);
1085
1086
30.1k
    assert(!PyErr_Occurred());
1087
30.1k
    PyErr_SetRaisedException(exc);
1088
30.1k
}
1089
1090
void
1091
PyUnstable_Object_ClearWeakRefsNoCallbacks(PyObject *obj)
1092
0
{
1093
0
    if (_PyType_SUPPORTS_WEAKREFS(Py_TYPE(obj))) {
1094
0
        _PyWeakref_ClearWeakRefsNoCallbacks(obj);
1095
0
    }
1096
0
}
1097
1098
/* This function is called by _PyStaticType_Dealloc() to clear weak references.
1099
 *
1100
 * This is called at the end of runtime finalization, so we can just
1101
 * wipe out the type's weaklist.  We don't bother with callbacks
1102
 * or anything else.
1103
 */
1104
void
1105
_PyStaticType_ClearWeakRefs(PyInterpreterState *interp, PyTypeObject *type)
1106
0
{
1107
0
    managed_static_type_state *state = _PyStaticType_GetState(interp, type);
1108
0
    PyObject **list = _PyStaticType_GET_WEAKREFS_LISTPTR(state);
1109
    // This is safe to do without holding the lock in free-threaded builds;
1110
    // there is only one thread running and no new threads can be created.
1111
0
    while (*list) {
1112
0
        _PyWeakref_ClearRef((PyWeakReference *)*list);
1113
0
    }
1114
0
}
1115
1116
void
1117
_PyWeakref_ClearWeakRefsNoCallbacks(PyObject *obj)
1118
14.2k
{
1119
    /* Modeled after GET_WEAKREFS_LISTPTR().
1120
1121
       This is never triggered for static types so we can avoid the
1122
       (slightly) more costly _PyObject_GET_WEAKREFS_LISTPTR(). */
1123
14.2k
    PyWeakReference **list = _PyObject_GET_WEAKREFS_LISTPTR_FROM_OFFSET(obj);
1124
14.2k
    LOCK_WEAKREFS(obj);
1125
14.2k
    while (*list) {
1126
0
        _PyWeakref_ClearRef(*list);
1127
0
    }
1128
14.2k
    UNLOCK_WEAKREFS(obj);
1129
14.2k
}
1130
1131
int
1132
_PyWeakref_IsDead(PyObject *weakref)
1133
0
{
1134
0
    return _PyWeakref_IS_DEAD(weakref);
1135
0
}