Coverage Report

Created: 2026-01-10 06:41

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
54.4M
        ((PyWeakReference **) _PyObject_GET_WEAKREFS_LISTPTR(o))
39
40
41
Py_ssize_t
42
_PyWeakref_GetWeakrefCount(PyObject *obj)
43
25.6k
{
44
25.6k
    if (!_PyType_SUPPORTS_WEAKREFS(Py_TYPE(obj))) {
45
0
        return 0;
46
0
    }
47
48
25.6k
    LOCK_WEAKREFS(obj);
49
25.6k
    Py_ssize_t count = 0;
50
25.6k
    PyWeakReference *head = *GET_WEAKREFS_LISTPTR(obj);
51
51.2k
    while (head != NULL) {
52
25.6k
        ++count;
53
25.6k
        head = head->wr_next;
54
25.6k
    }
55
25.6k
    UNLOCK_WEAKREFS(obj);
56
25.6k
    return count;
57
25.6k
}
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
295k
{
64
295k
    self->hash = -1;
65
295k
    self->wr_object = ob;
66
295k
    self->wr_prev = NULL;
67
295k
    self->wr_next = NULL;
68
295k
    self->wr_callback = Py_XNewRef(callback);
69
295k
    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
295k
}
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
546k
{
81
546k
    if (self->wr_object != Py_None) {
82
276k
        PyWeakReference **list = GET_WEAKREFS_LISTPTR(self->wr_object);
83
276k
        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
275k
            FT_ATOMIC_STORE_PTR(*list, self->wr_next);
88
275k
        }
89
276k
        FT_ATOMIC_STORE_PTR(self->wr_object, Py_None);
90
276k
        if (self->wr_prev != NULL) {
91
333
            self->wr_prev->wr_next = self->wr_next;
92
333
        }
93
276k
        if (self->wr_next != NULL) {
94
52
            self->wr_next->wr_prev = self->wr_prev;
95
52
        }
96
276k
        self->wr_prev = NULL;
97
276k
        self->wr_next = NULL;
98
276k
    }
99
546k
    if (callback != NULL) {
100
301k
        *callback = self->wr_callback;
101
301k
        self->wr_callback = NULL;
102
301k
    }
103
546k
}
104
105
// Clear the weakref and its callback
106
static void
107
clear_weakref(PyObject *op)
108
276k
{
109
276k
    PyWeakReference *self = _PyWeakref_CAST(op);
110
276k
    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
276k
    LOCK_WEAKREFS_FOR_WR(self);
115
276k
    clear_weakref_lock_held(self, &callback);
116
276k
    UNLOCK_WEAKREFS_FOR_WR(self);
117
276k
    Py_XDECREF(callback);
118
276k
}
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
245k
{
135
245k
    assert(self != NULL);
136
245k
    assert(PyWeakref_Check(self));
137
245k
    clear_weakref_lock_held(self, NULL);
138
245k
}
139
140
static void
141
weakref_dealloc(PyObject *self)
142
276k
{
143
276k
    PyObject_GC_UnTrack(self);
144
276k
    clear_weakref(self);
145
276k
    Py_TYPE(self)->tp_free(self);
146
276k
}
147
148
149
static int
150
gc_traverse(PyObject *op, visitproc visit, void *arg)
151
2.10M
{
152
2.10M
    PyWeakReference *self = _PyWeakref_CAST(op);
153
2.10M
    Py_VISIT(self->wr_callback);
154
2.10M
    return 0;
155
2.10M
}
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
18.2k
{
175
18.2k
    if (!_PyArg_NoKwnames("weakref", kwnames)) {
176
0
        return NULL;
177
0
    }
178
18.2k
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
179
18.2k
    if (!_PyArg_CheckPositional("weakref", nargs, 0, 0)) {
180
0
        return NULL;
181
0
    }
182
18.2k
    PyObject *obj = _PyWeakref_GET_REF(self);
183
18.2k
    if (obj == NULL) {
184
0
        Py_RETURN_NONE;
185
0
    }
186
18.2k
    return obj;
187
18.2k
}
188
189
static Py_hash_t
190
weakref_hash_lock_held(PyWeakReference *self)
191
25.4k
{
192
25.4k
    if (self->hash != -1)
193
23.0k
        return self->hash;
194
2.45k
    PyObject* obj = _PyWeakref_GET_REF((PyObject*)self);
195
2.45k
    if (obj == NULL) {
196
0
        PyErr_SetString(PyExc_TypeError, "weak object has gone away");
197
0
        return -1;
198
0
    }
199
2.45k
    self->hash = PyObject_Hash(obj);
200
2.45k
    Py_DECREF(obj);
201
2.45k
    return self->hash;
202
2.45k
}
203
204
static Py_hash_t
205
weakref_hash(PyObject *op)
206
25.4k
{
207
25.4k
    PyWeakReference *self = _PyWeakref_CAST(op);
208
25.4k
    Py_hash_t hash;
209
25.4k
    Py_BEGIN_CRITICAL_SECTION(self);
210
25.4k
    hash = weakref_hash_lock_held(self);
211
25.4k
    Py_END_CRITICAL_SECTION();
212
25.4k
    return hash;
213
25.4k
}
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
11.4k
{
247
11.4k
    if ((op != Py_EQ && op != Py_NE) ||
248
11.4k
        !PyWeakref_Check(self) ||
249
11.4k
        !PyWeakref_Check(other)) {
250
0
        Py_RETURN_NOTIMPLEMENTED;
251
0
    }
252
11.4k
    PyObject* obj = _PyWeakref_GET_REF(self);
253
11.4k
    PyObject* other_obj = _PyWeakref_GET_REF(other);
254
11.4k
    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
11.4k
    PyObject* res = PyObject_RichCompare(obj, other_obj, op);
266
11.4k
    Py_DECREF(obj);
267
11.4k
    Py_DECREF(other_obj);
268
11.4k
    return res;
269
11.4k
}
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
830k
{
280
830k
    *refp = NULL;
281
830k
    *proxyp = NULL;
282
283
830k
    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
272k
        if (PyWeakref_CheckRefExact(head)) {
288
272k
            *refp = head;
289
272k
            head = head->wr_next;
290
272k
        }
291
272k
        if (head != NULL
292
23.7k
            && head->wr_callback == NULL
293
0
            && PyWeakref_CheckProxy(head)) {
294
0
            *proxyp = head;
295
            /* head = head->wr_next; */
296
0
        }
297
272k
    }
298
830k
}
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
1.80k
{
304
1.80k
    newref->wr_prev = prev;
305
1.80k
    newref->wr_next = prev->wr_next;
306
1.80k
    if (prev->wr_next != NULL)
307
734
        prev->wr_next->wr_prev = newref;
308
1.80k
    prev->wr_next = newref;
309
1.80k
}
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
294k
{
317
294k
    PyWeakReference *next = *list;
318
319
294k
    newref->wr_prev = NULL;
320
294k
    newref->wr_next = next;
321
294k
    if (next != NULL)
322
0
        next->wr_prev = newref;
323
294k
    *list = newref;
324
294k
}
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
553k
{
333
553k
    if (callback != NULL) {
334
19.2k
        return NULL;
335
19.2k
    }
336
337
534k
    PyWeakReference *ref, *proxy;
338
534k
    get_basic_refs(list, &ref, &proxy);
339
340
534k
    PyWeakReference *cand = NULL;
341
534k
    if (type == &_PyWeakref_RefType) {
342
534k
        cand = ref;
343
534k
    }
344
534k
    if ((type == &_PyWeakref_ProxyType) ||
345
534k
        (type == &_PyWeakref_CallableProxyType)) {
346
0
        cand = proxy;
347
0
    }
348
349
534k
    if (cand != NULL && _Py_TryIncref((PyObject *) cand)) {
350
270k
        return cand;
351
270k
    }
352
263k
    return NULL;
353
534k
}
354
355
static int
356
is_basic_ref(PyWeakReference *ref)
357
347k
{
358
347k
    return (ref->wr_callback == NULL) && PyWeakref_CheckRefExact(ref);
359
347k
}
360
361
static int
362
is_basic_proxy(PyWeakReference *proxy)
363
83.4k
{
364
83.4k
    return (proxy->wr_callback == NULL) && PyWeakref_CheckProxy(proxy);
365
83.4k
}
366
367
static int
368
is_basic_ref_or_proxy(PyWeakReference *wr)
369
51.2k
{
370
51.2k
    return is_basic_ref(wr) || is_basic_proxy(wr);
371
51.2k
}
372
373
/* Insert `newref` in the appropriate position in `list` */
374
static void
375
insert_weakref(PyWeakReference *newref, PyWeakReference **list)
376
295k
{
377
295k
    PyWeakReference *ref, *proxy;
378
295k
    get_basic_refs(*list, &ref, &proxy);
379
380
295k
    PyWeakReference *prev;
381
295k
    if (is_basic_ref(newref)) {
382
263k
        prev = NULL;
383
263k
    }
384
32.2k
    else if (is_basic_proxy(newref)) {
385
0
        prev = ref;
386
0
    }
387
32.2k
    else {
388
32.2k
        prev = (proxy == NULL) ? ref : proxy;
389
32.2k
    }
390
391
295k
    if (prev == NULL) {
392
294k
        insert_head(newref, list);
393
294k
    }
394
1.80k
    else {
395
1.80k
        insert_after(newref, prev);
396
1.80k
    }
397
295k
}
398
399
static PyWeakReference *
400
allocate_weakref(PyTypeObject *type, PyObject *obj, PyObject *callback)
401
295k
{
402
295k
    PyWeakReference *newref = (PyWeakReference *) type->tp_alloc(type, 0);
403
295k
    if (newref == NULL) {
404
0
        return NULL;
405
0
    }
406
295k
    init_weakref(newref, obj, callback);
407
295k
    return newref;
408
295k
}
409
410
static PyWeakReference *
411
get_or_create_weakref(PyTypeObject *type, PyObject *obj, PyObject *callback)
412
566k
{
413
566k
    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
566k
    if (callback == Py_None)
420
0
        callback = NULL;
421
422
566k
    PyWeakReference **list = GET_WEAKREFS_LISTPTR(obj);
423
566k
    if ((type == &_PyWeakref_RefType) ||
424
13.0k
        (type == &_PyWeakref_ProxyType) ||
425
13.0k
        (type == &_PyWeakref_CallableProxyType))
426
553k
    {
427
553k
        LOCK_WEAKREFS(obj);
428
553k
        PyWeakReference *basic_ref = try_reuse_basic_ref(*list, type, callback);
429
553k
        if (basic_ref != NULL) {
430
270k
            UNLOCK_WEAKREFS(obj);
431
270k
            return basic_ref;
432
270k
        }
433
282k
        PyWeakReference *newref = allocate_weakref(type, obj, callback);
434
282k
        if (newref == NULL) {
435
0
            UNLOCK_WEAKREFS(obj);
436
0
            return NULL;
437
0
        }
438
282k
        insert_weakref(newref, list);
439
282k
        UNLOCK_WEAKREFS(obj);
440
282k
        return newref;
441
282k
    }
442
13.0k
    else {
443
        // We may not be able to safely allocate inside the lock
444
13.0k
        PyWeakReference *newref = allocate_weakref(type, obj, callback);
445
13.0k
        if (newref == NULL) {
446
0
            return NULL;
447
0
        }
448
13.0k
        LOCK_WEAKREFS(obj);
449
13.0k
        insert_weakref(newref, list);
450
13.0k
        UNLOCK_WEAKREFS(obj);
451
13.0k
        return newref;
452
13.0k
    }
453
566k
}
454
455
static int
456
parse_weakref_init_args(const char *funcname, PyObject *args, PyObject *kwargs,
457
                        PyObject **obp, PyObject **callbackp)
458
61.0k
{
459
61.0k
    return PyArg_UnpackTuple(args, funcname, 1, 2, obp, callbackp);
460
61.0k
}
461
462
static PyObject *
463
weakref___new__(PyTypeObject *type, PyObject *args, PyObject *kwargs)
464
30.5k
{
465
30.5k
    PyObject *ob, *callback = NULL;
466
30.5k
    if (parse_weakref_init_args("__new__", args, kwargs, &ob, &callback)) {
467
30.5k
        return (PyObject *)get_or_create_weakref(type, ob, callback);
468
30.5k
    }
469
0
    return NULL;
470
30.5k
}
471
472
static int
473
weakref___init__(PyObject *self, PyObject *args, PyObject *kwargs)
474
30.5k
{
475
30.5k
    PyObject *tmp;
476
477
30.5k
    if (!_PyArg_NoKeywords("ref", kwargs))
478
0
        return -1;
479
480
30.5k
    if (parse_weakref_init_args("__init__", args, kwargs, &tmp, &tmp))
481
30.5k
        return 0;
482
0
    else
483
0
        return -1;
484
30.5k
}
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
536k
{
921
536k
    return (PyObject *)get_or_create_weakref(&_PyWeakref_RefType, ob,
922
536k
                                             callback);
923
536k
}
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
677
{
952
677
    if (ref == NULL) {
953
0
        *pobj = NULL;
954
0
        PyErr_BadInternalCall();
955
0
        return -1;
956
0
    }
957
677
    if (!PyWeakref_Check(ref)) {
958
0
        *pobj = NULL;
959
0
        PyErr_SetString(PyExc_TypeError, "expected a weakref");
960
0
        return -1;
961
0
    }
962
677
    *pobj = _PyWeakref_GET_REF(ref);
963
677
    return (*pobj != NULL);
964
677
}
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
25.6k
{
989
25.6k
    PyObject *cbresult = PyObject_CallOneArg(callback, (PyObject *)ref);
990
991
25.6k
    if (cbresult == NULL) {
992
0
        PyErr_FormatUnraisable("Exception ignored while "
993
0
                               "calling weakref callback %R", callback);
994
0
    }
995
25.6k
    else {
996
25.6k
        Py_DECREF(cbresult);
997
25.6k
    }
998
25.6k
}
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
53.6M
{
1009
53.6M
    PyWeakReference **list;
1010
1011
53.6M
    if (object == NULL
1012
53.6M
        || !_PyType_SUPPORTS_WEAKREFS(Py_TYPE(object))
1013
53.6M
        || Py_REFCNT(object) != 0)
1014
0
    {
1015
0
        PyErr_BadInternalCall();
1016
0
        return;
1017
0
    }
1018
1019
53.6M
    list = GET_WEAKREFS_LISTPTR(object);
1020
53.6M
    if (FT_ATOMIC_LOAD_PTR(*list) == NULL) {
1021
        // Fast path for the common case
1022
53.5M
        return;
1023
53.5M
    }
1024
1025
    /* Remove the callback-less basic and proxy references, which always appear
1026
       at the head of the list.
1027
    */
1028
51.2k
    for (int done = 0; !done;) {
1029
25.6k
        LOCK_WEAKREFS(object);
1030
25.6k
        if (*list != NULL && is_basic_ref_or_proxy(*list)) {
1031
0
            PyObject *callback;
1032
0
            clear_weakref_lock_held(*list, &callback);
1033
0
            assert(callback == NULL);
1034
0
        }
1035
25.6k
        done = (*list == NULL) || !is_basic_ref_or_proxy(*list);
1036
25.6k
        UNLOCK_WEAKREFS(object);
1037
25.6k
    }
1038
1039
    /* Deal with non-canonical (subtypes or refs with callbacks) references. */
1040
25.6k
    Py_ssize_t num_weakrefs = _PyWeakref_GetWeakrefCount(object);
1041
25.6k
    if (num_weakrefs == 0) {
1042
0
        return;
1043
0
    }
1044
1045
25.6k
    PyObject *exc = PyErr_GetRaisedException();
1046
25.6k
    PyObject *tuple = PyTuple_New(num_weakrefs * 2);
1047
25.6k
    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
25.6k
    Py_ssize_t num_items = 0;
1056
51.2k
    for (int done = 0; !done;) {
1057
25.6k
        PyObject *callback = NULL;
1058
25.6k
        LOCK_WEAKREFS(object);
1059
25.6k
        PyWeakReference *cur = *list;
1060
25.6k
        if (cur != NULL) {
1061
25.6k
            clear_weakref_lock_held(cur, &callback);
1062
25.6k
            if (_Py_TryIncref((PyObject *) cur)) {
1063
25.6k
                assert(num_items / 2 < num_weakrefs);
1064
25.6k
                PyTuple_SET_ITEM(tuple, num_items, (PyObject *) cur);
1065
25.6k
                PyTuple_SET_ITEM(tuple, num_items + 1, callback);
1066
25.6k
                num_items += 2;
1067
25.6k
                callback = NULL;
1068
25.6k
            }
1069
25.6k
        }
1070
25.6k
        done = (*list == NULL);
1071
25.6k
        UNLOCK_WEAKREFS(object);
1072
1073
25.6k
        Py_XDECREF(callback);
1074
25.6k
    }
1075
1076
51.2k
    for (Py_ssize_t i = 0; i < num_items; i += 2) {
1077
25.6k
        PyObject *callback = PyTuple_GET_ITEM(tuple, i + 1);
1078
25.6k
        if (callback != NULL) {
1079
25.6k
            PyObject *weakref = PyTuple_GET_ITEM(tuple, i);
1080
25.6k
            handle_callback((PyWeakReference *)weakref, callback);
1081
25.6k
        }
1082
25.6k
    }
1083
1084
25.6k
    Py_DECREF(tuple);
1085
1086
25.6k
    assert(!PyErr_Occurred());
1087
25.6k
    PyErr_SetRaisedException(exc);
1088
25.6k
}
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
9.28k
{
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
9.28k
    PyWeakReference **list = _PyObject_GET_WEAKREFS_LISTPTR_FROM_OFFSET(obj);
1124
9.28k
    LOCK_WEAKREFS(obj);
1125
9.28k
    while (*list) {
1126
0
        _PyWeakref_ClearRef(*list);
1127
0
    }
1128
9.28k
    UNLOCK_WEAKREFS(obj);
1129
9.28k
}
1130
1131
int
1132
_PyWeakref_IsDead(PyObject *weakref)
1133
0
{
1134
0
    return _PyWeakref_IS_DEAD(weakref);
1135
0
}