Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/gc.c
Line
Count
Source
1
//  This implements the reference cycle garbage collector.
2
//  The Python module interface to the collector is in gcmodule.c.
3
//  See InternalDocs/garbage_collector.md for more infromation.
4
5
#include "Python.h"
6
#include "pycore_ceval.h"         // _Py_set_eval_breaker_bit()
7
#include "pycore_dict.h"          // _PyInlineValuesSize()
8
#include "pycore_genobject.h"     // _PyGen_FinalizerIsNoop()
9
#include "pycore_initconfig.h"    // _PyStatus_OK()
10
#include "pycore_context.h"
11
#include "pycore_interp.h"        // PyInterpreterState.gc
12
#include "pycore_interpframe.h"   // _PyFrame_GetLocalsArray()
13
#include "pycore_object.h"
14
#include "pycore_object_alloc.h"  // _PyObject_MallocWithType()
15
#include "pycore_pyerrors.h"
16
#include "pycore_pystate.h"       // _PyThreadState_GET()
17
#include "pycore_tuple.h"         // _PyTuple_MaybeUntrack()
18
#include "pycore_weakref.h"       // _PyWeakref_ClearRef()
19
#include "pydtrace.h"
20
21
#if !defined(Py_GIL_DISABLED)
22
23
typedef struct _gc_runtime_state GCState;
24
25
#ifdef Py_DEBUG
26
#  define GC_DEBUG
27
#endif
28
29
1.54G
#define GC_NEXT _PyGCHead_NEXT
30
155M
#define GC_PREV _PyGCHead_PREV
31
32
// update_refs() set this bit for all objects in current generation.
33
// subtract_refs() and move_unreachable() uses this to distinguish
34
// visited object is in GCing or not.
35
//
36
// move_unreachable() removes this flag from reachable objects.
37
// Only unreachable objects have this flag.
38
//
39
// No objects in interpreter have this flag after GC ends.
40
3.10G
#define PREV_MASK_COLLECTING   _PyGC_PREV_MASK_COLLECTING
41
42
// Lowest bit of _gc_next is used for UNREACHABLE flag.
43
//
44
// This flag represents the object is in unreachable list in move_unreachable()
45
//
46
// Although this flag is used only in move_unreachable(), move_unreachable()
47
// doesn't clear this flag to skip unnecessary iteration.
48
// move_legacy_finalizers() removes this flag instead.
49
// Between them, unreachable list is not normal list and we can not use
50
// most gc_list_* functions for it.
51
607M
#define NEXT_MASK_UNREACHABLE  (1)
52
53
3.24G
#define AS_GC(op) _Py_AS_GC(op)
54
1.85G
#define FROM_GC(gc) _Py_FROM_GC(gc)
55
56
// Automatically choose the generation that needs collecting.
57
300k
#define GENERATION_AUTO (-1)
58
59
static inline int
60
gc_is_collecting(PyGC_Head *g)
61
1.88G
{
62
1.88G
    return (g->_gc_prev & PREV_MASK_COLLECTING) != 0;
63
1.88G
}
64
65
static inline void
66
gc_clear_collecting(PyGC_Head *g)
67
608M
{
68
608M
    g->_gc_prev &= ~PREV_MASK_COLLECTING;
69
608M
}
70
71
static inline Py_ssize_t
72
gc_get_refs(PyGC_Head *g)
73
1.61G
{
74
1.61G
    return (Py_ssize_t)(g->_gc_prev >> _PyGC_PREV_SHIFT);
75
1.61G
}
76
77
static inline void
78
gc_set_refs(PyGC_Head *g, Py_ssize_t refs)
79
366M
{
80
366M
    g->_gc_prev = (g->_gc_prev & ~_PyGC_PREV_MASK)
81
366M
        | ((uintptr_t)(refs) << _PyGC_PREV_SHIFT);
82
366M
}
83
84
static inline void
85
gc_reset_refs(PyGC_Head *g, Py_ssize_t refs)
86
612M
{
87
612M
    g->_gc_prev = (g->_gc_prev & _PyGC_PREV_MASK_FINALIZED)
88
612M
        | PREV_MASK_COLLECTING
89
612M
        | ((uintptr_t)(refs) << _PyGC_PREV_SHIFT);
90
612M
}
91
92
static inline void
93
gc_decref(PyGC_Head *g)
94
538M
{
95
538M
    _PyObject_ASSERT_WITH_MSG(FROM_GC(g),
96
538M
                              gc_get_refs(g) > 0,
97
538M
                              "refcount is too small");
98
538M
    g->_gc_prev -= 1 << _PyGC_PREV_SHIFT;
99
538M
}
100
101
102
299k
#define GEN_HEAD(gcstate, n) (&(gcstate)->generations[n].head)
103
104
105
static GCState *
106
get_gc_state(void)
107
676M
{
108
676M
    PyInterpreterState *interp = _PyInterpreterState_GET();
109
676M
    return &interp->gc;
110
676M
}
111
112
113
void
114
_PyGC_InitState(GCState *gcstate)
115
37
{
116
37
#define INIT_HEAD(GEN) \
117
148
    do { \
118
148
        GEN.head._gc_next = (uintptr_t)&GEN.head; \
119
148
        GEN.head._gc_prev = (uintptr_t)&GEN.head; \
120
148
    } while (0)
121
122
148
    for (int i = 0; i < NUM_GENERATIONS; i++) {
123
111
        assert(gcstate->generations[i].count == 0);
124
111
        INIT_HEAD(gcstate->generations[i]);
125
111
    };
126
37
    gcstate->generation0 = GEN_HEAD(gcstate, 0);
127
37
    INIT_HEAD(gcstate->permanent_generation);
128
129
37
#undef INIT_HEAD
130
37
}
131
132
133
PyStatus
134
_PyGC_Init(PyInterpreterState *interp)
135
37
{
136
37
    GCState *gcstate = &interp->gc;
137
138
37
    gcstate->generation_stats = PyMem_RawCalloc(1, sizeof(struct gc_stats));
139
37
    if (gcstate->generation_stats == NULL) {
140
0
        return _PyStatus_NO_MEMORY();
141
0
    }
142
143
37
    gcstate->garbage = PyList_New(0);
144
37
    if (gcstate->garbage == NULL) {
145
0
        return _PyStatus_NO_MEMORY();
146
0
    }
147
148
37
    gcstate->callbacks = PyList_New(0);
149
37
    if (gcstate->callbacks == NULL) {
150
0
        return _PyStatus_NO_MEMORY();
151
0
    }
152
153
37
    return _PyStatus_OK();
154
37
}
155
156
157
/*
158
_gc_prev values
159
---------------
160
161
Between collections, _gc_prev is used for doubly linked list.
162
163
Lowest two bits of _gc_prev are used for flags.
164
PREV_MASK_COLLECTING is used only while collecting and cleared before GC ends
165
or _PyObject_GC_UNTRACK() is called.
166
167
During a collection, _gc_prev is temporary used for gc_refs, and the gc list
168
is singly linked until _gc_prev is restored.
169
170
gc_refs
171
    At the start of a collection, update_refs() copies the true refcount
172
    to gc_refs, for each object in the generation being collected.
173
    subtract_refs() then adjusts gc_refs so that it equals the number of
174
    times an object is referenced directly from outside the generation
175
    being collected.
176
177
PREV_MASK_COLLECTING
178
    Objects in generation being collected are marked PREV_MASK_COLLECTING in
179
    update_refs().
180
181
182
_gc_next values
183
---------------
184
185
_gc_next takes these values:
186
187
0
188
    The object is not tracked
189
190
!= 0
191
    Pointer to the next object in the GC list.
192
    Additionally, lowest bit is used temporary for
193
    NEXT_MASK_UNREACHABLE flag described below.
194
195
NEXT_MASK_UNREACHABLE
196
    move_unreachable() then moves objects not reachable (whether directly or
197
    indirectly) from outside the generation into an "unreachable" set and
198
    set this flag.
199
200
    Objects that are found to be reachable have gc_refs set to 1.
201
    When this flag is set for the reachable object, the object must be in
202
    "unreachable" set.
203
    The flag is unset and the object is moved back to "reachable" set.
204
205
    move_legacy_finalizers() will remove this flag from "unreachable" set.
206
*/
207
208
/*** list functions ***/
209
210
static inline void
211
gc_list_init(PyGC_Head *list)
212
1.24M
{
213
    // List header must not have flags.
214
    // We can assign pointer by simple cast.
215
1.24M
    list->_gc_prev = (uintptr_t)list;
216
1.24M
    list->_gc_next = (uintptr_t)list;
217
1.24M
}
218
219
static inline int
220
gc_list_is_empty(PyGC_Head *list)
221
8.81M
{
222
8.81M
    return (list->_gc_next == (uintptr_t)list);
223
8.81M
}
224
225
/* Append `node` to `list`. */
226
static inline void
227
gc_list_append(PyGC_Head *node, PyGC_Head *list)
228
69.9M
{
229
69.9M
    PyGC_Head *last = (PyGC_Head *)list->_gc_prev;
230
231
    // last <-> node
232
69.9M
    _PyGCHead_SET_PREV(node, last);
233
69.9M
    _PyGCHead_SET_NEXT(last, node);
234
235
    // node <-> list
236
69.9M
    _PyGCHead_SET_NEXT(node, list);
237
69.9M
    list->_gc_prev = (uintptr_t)node;
238
69.9M
}
239
240
/* Remove `node` from the gc list it's currently in. */
241
static inline void
242
gc_list_remove(PyGC_Head *node)
243
0
{
244
0
    PyGC_Head *prev = GC_PREV(node);
245
0
    PyGC_Head *next = GC_NEXT(node);
246
247
0
    _PyGCHead_SET_NEXT(prev, next);
248
0
    _PyGCHead_SET_PREV(next, prev);
249
250
0
    node->_gc_next = 0; /* object is not currently tracked */
251
0
}
252
253
/* Move `node` from the gc list it's currently in (which is not explicitly
254
 * named here) to the end of `list`.  This is semantically the same as
255
 * gc_list_remove(node) followed by gc_list_append(node, list).
256
 */
257
static void
258
gc_list_move(PyGC_Head *node, PyGC_Head *list)
259
7.20M
{
260
    /* Unlink from current list. */
261
7.20M
    PyGC_Head *from_prev = GC_PREV(node);
262
7.20M
    PyGC_Head *from_next = GC_NEXT(node);
263
7.20M
    _PyGCHead_SET_NEXT(from_prev, from_next);
264
7.20M
    _PyGCHead_SET_PREV(from_next, from_prev);
265
266
    /* Relink at end of new list. */
267
    // list must not have flags.  So we can skip macros.
268
7.20M
    PyGC_Head *to_prev = (PyGC_Head*)list->_gc_prev;
269
7.20M
    _PyGCHead_SET_PREV(node, to_prev);
270
7.20M
    _PyGCHead_SET_NEXT(to_prev, node);
271
7.20M
    list->_gc_prev = (uintptr_t)node;
272
7.20M
    _PyGCHead_SET_NEXT(node, list);
273
7.20M
}
274
275
/* append list `from` onto list `to`; `from` becomes an empty list */
276
static void
277
gc_list_merge(PyGC_Head *from, PyGC_Head *to)
278
559k
{
279
559k
    assert(from != to);
280
559k
    if (!gc_list_is_empty(from)) {
281
146k
        PyGC_Head *to_tail = GC_PREV(to);
282
146k
        PyGC_Head *from_head = GC_NEXT(from);
283
146k
        PyGC_Head *from_tail = GC_PREV(from);
284
146k
        assert(from_head != from);
285
146k
        assert(from_tail != from);
286
287
146k
        _PyGCHead_SET_NEXT(to_tail, from_head);
288
146k
        _PyGCHead_SET_PREV(from_head, to_tail);
289
290
146k
        _PyGCHead_SET_NEXT(from_tail, to);
291
146k
        _PyGCHead_SET_PREV(to, from_tail);
292
146k
    }
293
559k
    gc_list_init(from);
294
559k
}
295
296
static Py_ssize_t
297
gc_list_size(PyGC_Head *list)
298
273k
{
299
273k
    PyGC_Head *gc;
300
273k
    Py_ssize_t n = 0;
301
5.65M
    for (gc = GC_NEXT(list); gc != list; gc = GC_NEXT(gc)) {
302
5.37M
        n++;
303
5.37M
    }
304
273k
    return n;
305
273k
}
306
307
/* Walk the list and mark all objects as non-collecting */
308
static inline void
309
gc_list_clear_collecting(PyGC_Head *collectable)
310
1.28k
{
311
1.28k
    PyGC_Head *gc;
312
3.04M
    for (gc = GC_NEXT(collectable); gc != collectable; gc = GC_NEXT(gc)) {
313
3.04M
        gc_clear_collecting(gc);
314
3.04M
    }
315
1.28k
}
316
317
/* Append objects in a GC list to a Python list.
318
 * Return 0 if all OK, < 0 if error (out of memory for list)
319
 */
320
static int
321
append_objects(PyObject *py_list, PyGC_Head *gc_list)
322
0
{
323
0
    PyGC_Head *gc;
324
0
    for (gc = GC_NEXT(gc_list); gc != gc_list; gc = GC_NEXT(gc)) {
325
0
        PyObject *op = FROM_GC(gc);
326
0
        if (op != py_list) {
327
0
            if (PyList_Append(py_list, op)) {
328
0
                return -1; /* exception */
329
0
            }
330
0
        }
331
0
    }
332
0
    return 0;
333
0
}
334
335
// Constants for validate_list's flags argument.
336
enum flagstates {collecting_clear_unreachable_clear,
337
                 collecting_clear_unreachable_set,
338
                 collecting_set_unreachable_clear,
339
                 collecting_set_unreachable_set};
340
341
#ifdef GC_DEBUG
342
// validate_list checks list consistency.  And it works as document
343
// describing when flags are expected to be set / unset.
344
// `head` must be a doubly-linked gc list, although it's fine (expected!) if
345
// the prev and next pointers are "polluted" with flags.
346
// What's checked:
347
// - The `head` pointers are not polluted.
348
// - The objects' PREV_MASK_COLLECTING and NEXT_MASK_UNREACHABLE flags are all
349
//   `set or clear, as specified by the 'flags' argument.
350
// - The prev and next pointers are mutually consistent.
351
static void
352
validate_list(PyGC_Head *head, enum flagstates flags)
353
{
354
    assert((head->_gc_prev & PREV_MASK_COLLECTING) == 0);
355
    assert((head->_gc_next & NEXT_MASK_UNREACHABLE) == 0);
356
    uintptr_t prev_value = 0, next_value = 0;
357
    switch (flags) {
358
        case collecting_clear_unreachable_clear:
359
            break;
360
        case collecting_set_unreachable_clear:
361
            prev_value = PREV_MASK_COLLECTING;
362
            break;
363
        case collecting_clear_unreachable_set:
364
            next_value = NEXT_MASK_UNREACHABLE;
365
            break;
366
        case collecting_set_unreachable_set:
367
            prev_value = PREV_MASK_COLLECTING;
368
            next_value = NEXT_MASK_UNREACHABLE;
369
            break;
370
        default:
371
            assert(! "bad internal flags argument");
372
    }
373
    PyGC_Head *prev = head;
374
    PyGC_Head *gc = GC_NEXT(head);
375
    while (gc != head) {
376
        PyGC_Head *trueprev = GC_PREV(gc);
377
        PyGC_Head *truenext = (PyGC_Head *)(gc->_gc_next  & ~NEXT_MASK_UNREACHABLE);
378
        assert(truenext != NULL);
379
        assert(trueprev == prev);
380
        assert((gc->_gc_prev & PREV_MASK_COLLECTING) == prev_value);
381
        assert((gc->_gc_next & NEXT_MASK_UNREACHABLE) == next_value);
382
        prev = gc;
383
        gc = truenext;
384
    }
385
    assert(prev == GC_PREV(head));
386
}
387
#else
388
1.23M
#define validate_list(x, y) do{}while(0)
389
#endif
390
391
/*** end of list stuff ***/
392
393
394
/* Set all gc_refs = ob_refcnt.  After this, gc_refs is > 0 and
395
 * PREV_MASK_COLLECTING bit is set for all objects in containers.
396
 */
397
static Py_ssize_t
398
update_refs(PyGC_Head *containers)
399
138k
{
400
138k
    PyGC_Head *next;
401
138k
    PyGC_Head *gc = GC_NEXT(containers);
402
138k
    Py_ssize_t candidates = 0;
403
404
612M
    while (gc != containers) {
405
612M
        next = GC_NEXT(gc);
406
612M
        PyObject *op = FROM_GC(gc);
407
612M
        if (_Py_IsImmortal(op)) {
408
0
            assert(!_Py_IsStaticImmortal(op));
409
0
            _PyObject_GC_UNTRACK(op);
410
0
            gc = next;
411
0
            continue;
412
0
        }
413
612M
        gc_reset_refs(gc, Py_REFCNT(op));
414
        /* Python's cyclic gc should never see an incoming refcount
415
         * of 0:  if something decref'ed to 0, it should have been
416
         * deallocated immediately at that time.
417
         * Possible cause (if the assert triggers):  a tp_dealloc
418
         * routine left a gc-aware object tracked during its teardown
419
         * phase, and did something-- or allowed something to happen --
420
         * that called back into Python.  gc can trigger then, and may
421
         * see the still-tracked dying object.  Before this assert
422
         * was added, such mistakes went on to allow gc to try to
423
         * delete the object again.  In a debug build, that caused
424
         * a mysterious segfault, when _Py_ForgetReference tried
425
         * to remove the object from the doubly-linked list of all
426
         * objects a second time.  In a release build, an actual
427
         * double deallocation occurred, which leads to corruption
428
         * of the allocator's internal bookkeeping pointers.  That's
429
         * so serious that maybe this should be a release-build
430
         * check instead of an assert?
431
         */
432
612M
        _PyObject_ASSERT(op, gc_get_refs(gc) != 0);
433
612M
        gc = next;
434
612M
        candidates++;
435
612M
    }
436
138k
    return candidates;
437
138k
}
438
439
/* A traversal callback for subtract_refs. */
440
static int
441
visit_decref(PyObject *op, void *parent)
442
2.42G
{
443
2.42G
    OBJECT_STAT_INC(object_visits);
444
2.42G
    _PyObject_ASSERT(_PyObject_CAST(parent), !_PyObject_IsFreed(op));
445
446
2.42G
    if (_PyObject_IS_GC(op)) {
447
951M
        PyGC_Head *gc = AS_GC(op);
448
        /* We're only interested in gc_refs for objects in the
449
         * generation being collected, which can be recognized
450
         * because only they have positive gc_refs.
451
         */
452
951M
        if (gc_is_collecting(gc)) {
453
538M
            gc_decref(gc);
454
538M
        }
455
951M
    }
456
2.42G
    return 0;
457
2.42G
}
458
459
int
460
_PyGC_VisitStackRef(_PyStackRef *ref, visitproc visit, void *arg)
461
4.72M
{
462
    // This is a bit tricky! We want to ignore stackrefs with embedded
463
    // refcounts when computing the incoming references, but otherwise treat
464
    // them like normal.
465
4.72M
    assert(!PyStackRef_IsTaggedInt(*ref));
466
4.72M
    if (!PyStackRef_RefcountOnObject(*ref) && (visit == visit_decref)) {
467
273k
        return 0;
468
273k
    }
469
4.45M
    Py_VISIT(PyStackRef_AsPyObjectBorrow(*ref));
470
4.45M
    return 0;
471
4.45M
}
472
473
int
474
_PyGC_VisitFrameStack(_PyInterpreterFrame *frame, visitproc visit, void *arg)
475
829k
{
476
829k
    _PyStackRef *ref = _PyFrame_GetLocalsArray(frame);
477
    /* locals and stack */
478
5.44M
    for (; ref < frame->stackpointer; ref++) {
479
4.61M
        if (!PyStackRef_IsTaggedInt(*ref)) {
480
4.60M
            _Py_VISIT_STACKREF(*ref);
481
4.60M
        }
482
4.61M
    }
483
829k
    return 0;
484
829k
}
485
486
/* Subtract internal references from gc_refs.  After this, gc_refs is >= 0
487
 * for all objects in containers. The ones with gc_refs > 0 are directly
488
 * reachable from outside containers, and so can't be collected.
489
 */
490
static void
491
subtract_refs(PyGC_Head *containers)
492
138k
{
493
138k
    traverseproc traverse;
494
138k
    PyGC_Head *gc = GC_NEXT(containers);
495
612M
    for (; gc != containers; gc = GC_NEXT(gc)) {
496
612M
        PyObject *op = FROM_GC(gc);
497
612M
        traverse = Py_TYPE(op)->tp_traverse;
498
612M
        (void) traverse(op,
499
612M
                        visit_decref,
500
612M
                        op);
501
612M
    }
502
138k
}
503
504
/* A traversal callback for move_unreachable. */
505
static int
506
visit_reachable(PyObject *op, void *arg)
507
2.39G
{
508
2.39G
    PyGC_Head *reachable = arg;
509
2.39G
    OBJECT_STAT_INC(object_visits);
510
2.39G
    if (!_PyObject_IS_GC(op)) {
511
1.45G
        return 0;
512
1.45G
    }
513
514
935M
    PyGC_Head *gc = AS_GC(op);
515
935M
    const Py_ssize_t gc_refs = gc_get_refs(gc);
516
517
    // Ignore objects in other generation.
518
    // This also skips objects "to the left" of the current position in
519
    // move_unreachable's scan of the 'young' list - they've already been
520
    // traversed, and no longer have the PREV_MASK_COLLECTING flag.
521
935M
    if (! gc_is_collecting(gc)) {
522
563M
        return 0;
523
563M
    }
524
    // It would be a logic error elsewhere if the collecting flag were set on
525
    // an untracked object.
526
371M
    _PyObject_ASSERT(op, gc->_gc_next != 0);
527
528
371M
    if (gc->_gc_next & NEXT_MASK_UNREACHABLE) {
529
        /* This had gc_refs = 0 when move_unreachable got
530
         * to it, but turns out it's reachable after all.
531
         * Move it back to move_unreachable's 'young' list,
532
         * and move_unreachable will eventually get to it
533
         * again.
534
         */
535
        // Manually unlink gc from unreachable list because the list functions
536
        // don't work right in the presence of NEXT_MASK_UNREACHABLE flags.
537
69.9M
        PyGC_Head *prev = GC_PREV(gc);
538
69.9M
        PyGC_Head *next = (PyGC_Head*)(gc->_gc_next & ~NEXT_MASK_UNREACHABLE);
539
69.9M
        _PyObject_ASSERT(FROM_GC(prev),
540
69.9M
                         prev->_gc_next & NEXT_MASK_UNREACHABLE);
541
69.9M
        _PyObject_ASSERT(FROM_GC(next),
542
69.9M
                         next->_gc_next & NEXT_MASK_UNREACHABLE);
543
69.9M
        prev->_gc_next = gc->_gc_next;  // copy NEXT_MASK_UNREACHABLE
544
69.9M
        _PyGCHead_SET_PREV(next, prev);
545
546
69.9M
        gc_list_append(gc, reachable);
547
69.9M
        gc_set_refs(gc, 1);
548
69.9M
    }
549
301M
    else if (gc_refs == 0) {
550
        /* This is in move_unreachable's 'young' list, but
551
         * the traversal hasn't yet gotten to it.  All
552
         * we need to do is tell move_unreachable that it's
553
         * reachable.
554
         */
555
296M
        gc_set_refs(gc, 1);
556
296M
    }
557
    /* Else there's nothing to do.
558
     * If gc_refs > 0, it must be in move_unreachable's 'young'
559
     * list, and move_unreachable will eventually get to it.
560
     */
561
5.54M
    else {
562
5.54M
        _PyObject_ASSERT_WITH_MSG(op, gc_refs > 0, "refcount is too small");
563
5.54M
    }
564
371M
    return 0;
565
935M
}
566
567
/* Move the unreachable objects from young to unreachable.  After this,
568
 * all objects in young don't have PREV_MASK_COLLECTING flag and
569
 * unreachable have the flag.
570
 * All objects in young after this are directly or indirectly reachable
571
 * from outside the original young; and all objects in unreachable are
572
 * not.
573
 *
574
 * This function restores _gc_prev pointer.  young and unreachable are
575
 * doubly linked list after this function.
576
 * But _gc_next in unreachable list has NEXT_MASK_UNREACHABLE flag.
577
 * So we can not gc_list_* functions for unreachable until we remove the flag.
578
 */
579
static Py_ssize_t
580
move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)
581
138k
{
582
138k
    Py_ssize_t reachable = 0;
583
    // previous elem in the young list, used for restore gc_prev.
584
138k
    PyGC_Head *prev = young;
585
138k
    PyGC_Head *gc = GC_NEXT(young);
586
587
    /* Invariants:  all objects "to the left" of us in young are reachable
588
     * (directly or indirectly) from outside the young list as it was at entry.
589
     *
590
     * All other objects from the original young "to the left" of us are in
591
     * unreachable now, and have NEXT_MASK_UNREACHABLE.  All objects to the
592
     * left of us in 'young' now have been scanned, and no objects here
593
     * or to the right have been scanned yet.
594
     */
595
596
682M
    while (gc != young) {
597
682M
        if (gc_get_refs(gc)) {
598
            /* gc is definitely reachable from outside the
599
             * original 'young'.  Mark it as such, and traverse
600
             * its pointers to find any other objects that may
601
             * be directly reachable from it.  Note that the
602
             * call to tp_traverse may append objects to young,
603
             * so we have to wait until it returns to determine
604
             * the next object to visit.
605
             */
606
603M
            PyObject *op = FROM_GC(gc);
607
603M
            traverseproc traverse = Py_TYPE(op)->tp_traverse;
608
603M
            _PyObject_ASSERT_WITH_MSG(op, gc_get_refs(gc) > 0,
609
603M
                                      "refcount is too small");
610
            // NOTE: visit_reachable may change gc->_gc_next when
611
            // young->_gc_prev == gc.  Don't do gc = GC_NEXT(gc) before!
612
603M
            (void) traverse(op,
613
603M
                    visit_reachable,
614
603M
                    (void *)young);
615
            // relink gc_prev to prev element.
616
603M
            _PyGCHead_SET_PREV(gc, prev);
617
            // gc is not COLLECTING state after here.
618
603M
            gc_clear_collecting(gc);
619
603M
            if (PyTuple_CheckExact(op)) {
620
                // Untracking gc overwrites the gc_refs of the next object.
621
283M
                PyGC_Head *next = GC_NEXT(gc);
622
283M
                uintptr_t next_refs = next->_gc_prev;
623
283M
                _PyTuple_MaybeUntrack(op);
624
283M
                next->_gc_prev = next_refs;
625
283M
                if (gc->_gc_next != 0) {
626
265M
                    prev = gc;
627
265M
                    reachable++;
628
265M
                }
629
283M
            }
630
320M
            else {
631
320M
                prev = gc;
632
320M
                reachable++;
633
320M
            }
634
603M
        }
635
78.4M
        else {
636
            /* This *may* be unreachable.  To make progress,
637
             * assume it is.  gc isn't directly reachable from
638
             * any object we've already traversed, but may be
639
             * reachable from an object we haven't gotten to yet.
640
             * visit_reachable will eventually move gc back into
641
             * young if that's so, and we'll see it again.
642
             */
643
            // Move gc to unreachable.
644
            // No need to gc->next->prev = prev because it is single linked.
645
78.4M
            prev->_gc_next = gc->_gc_next;
646
647
            // We can't use gc_list_append() here because we use
648
            // NEXT_MASK_UNREACHABLE here.
649
78.4M
            PyGC_Head *last = GC_PREV(unreachable);
650
            // NOTE: Since all objects in unreachable set has
651
            // NEXT_MASK_UNREACHABLE flag, we set it unconditionally.
652
            // But this may pollute the unreachable list head's 'next' pointer
653
            // too. That's semantically senseless but expedient here - the
654
            // damage is repaired when this function ends.
655
78.4M
            last->_gc_next = (NEXT_MASK_UNREACHABLE | (uintptr_t)gc);
656
78.4M
            _PyGCHead_SET_PREV(gc, last);
657
78.4M
            gc->_gc_next = (NEXT_MASK_UNREACHABLE | (uintptr_t)unreachable);
658
78.4M
            unreachable->_gc_prev = (uintptr_t)gc;
659
78.4M
        }
660
682M
        gc = (PyGC_Head*)prev->_gc_next;
661
682M
    }
662
    // young->_gc_prev must be last element remained in the list.
663
138k
    young->_gc_prev = (uintptr_t)prev;
664
    // don't let the pollution of the list head's next pointer leak
665
138k
    unreachable->_gc_next &= ~NEXT_MASK_UNREACHABLE;
666
138k
    return reachable;
667
138k
}
668
669
/* Return true if object has a pre-PEP 442 finalization method. */
670
static int
671
has_legacy_finalizer(PyObject *op)
672
5.37M
{
673
5.37M
    return Py_TYPE(op)->tp_del != NULL;
674
5.37M
}
675
676
/* Move the objects in unreachable with tp_del slots into `finalizers`.
677
 *
678
 * This function also removes NEXT_MASK_UNREACHABLE flag
679
 * from _gc_next in unreachable.
680
 */
681
static void
682
move_legacy_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers)
683
136k
{
684
136k
    PyGC_Head *gc, *next;
685
136k
    _PyObject_ASSERT(
686
136k
        FROM_GC(unreachable),
687
136k
        (unreachable->_gc_next & NEXT_MASK_UNREACHABLE) == 0);
688
689
    /* March over unreachable.  Move objects with finalizers into
690
     * `finalizers`.
691
     */
692
5.51M
    for (gc = GC_NEXT(unreachable); gc != unreachable; gc = next) {
693
5.37M
        PyObject *op = FROM_GC(gc);
694
695
5.37M
        _PyObject_ASSERT(op, gc->_gc_next & NEXT_MASK_UNREACHABLE);
696
5.37M
        gc->_gc_next &= ~NEXT_MASK_UNREACHABLE;
697
5.37M
        next = (PyGC_Head*)gc->_gc_next;
698
699
5.37M
        if (has_legacy_finalizer(op)) {
700
0
            gc_clear_collecting(gc);
701
0
            gc_list_move(gc, finalizers);
702
0
        }
703
5.37M
    }
704
136k
}
705
706
static inline void
707
clear_unreachable_mask(PyGC_Head *unreachable)
708
1.28k
{
709
    /* Check that the list head does not have the unreachable bit set */
710
1.28k
    _PyObject_ASSERT(
711
1.28k
        FROM_GC(unreachable),
712
1.28k
        ((uintptr_t)unreachable & NEXT_MASK_UNREACHABLE) == 0);
713
1.28k
    _PyObject_ASSERT(
714
1.28k
        FROM_GC(unreachable),
715
1.28k
        (unreachable->_gc_next & NEXT_MASK_UNREACHABLE) == 0);
716
717
1.28k
    PyGC_Head *gc, *next;
718
3.04M
    for (gc = GC_NEXT(unreachable); gc != unreachable; gc = next) {
719
3.04M
        _PyObject_ASSERT((PyObject*)FROM_GC(gc), gc->_gc_next & NEXT_MASK_UNREACHABLE);
720
3.04M
        gc->_gc_next &= ~NEXT_MASK_UNREACHABLE;
721
3.04M
        next = (PyGC_Head*)gc->_gc_next;
722
3.04M
    }
723
1.28k
    validate_list(unreachable, collecting_set_unreachable_clear);
724
1.28k
}
725
726
/* A traversal callback for move_legacy_finalizer_reachable. */
727
static int
728
visit_move(PyObject *op, void *arg)
729
0
{
730
0
    PyGC_Head *tolist = arg;
731
0
    OBJECT_STAT_INC(object_visits);
732
0
    if (_PyObject_IS_GC(op)) {
733
0
        PyGC_Head *gc = AS_GC(op);
734
0
        if (gc_is_collecting(gc)) {
735
0
            gc_list_move(gc, tolist);
736
0
            gc_clear_collecting(gc);
737
0
        }
738
0
    }
739
0
    return 0;
740
0
}
741
742
/* Move objects that are reachable from finalizers, from the unreachable set
743
 * into finalizers set.
744
 */
745
static void
746
move_legacy_finalizer_reachable(PyGC_Head *finalizers)
747
136k
{
748
136k
    traverseproc traverse;
749
136k
    PyGC_Head *gc = GC_NEXT(finalizers);
750
136k
    for (; gc != finalizers; gc = GC_NEXT(gc)) {
751
        /* Note that the finalizers list may grow during this. */
752
0
        traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
753
0
        (void) traverse(FROM_GC(gc),
754
0
                        visit_move,
755
0
                        (void *)finalizers);
756
0
    }
757
136k
}
758
759
/* Handle weakref callbacks.  Note that it's possible for such weakrefs to be
760
 * outside the unreachable set -- indeed, those are precisely the weakrefs
761
 * whose callbacks must be invoked.  See gc_weakref.txt for overview & some
762
 * details.
763
 *
764
 * The clearing of weakrefs is suble and must be done carefully, as there was
765
 * previous bugs related to this.  First, weakrefs to the unreachable set of
766
 * objects must be cleared before we start calling `tp_clear`.  If we don't,
767
 * those weakrefs can reveal unreachable objects to Python-level code and that
768
 * is not safe.  Many objects are not usable after `tp_clear` has been called
769
 * and could even cause crashes if accessed (see bpo-38006 and gh-91636 as
770
 * example bugs).
771
 *
772
 * Weakrefs with callbacks always need to be cleared before executing the
773
 * callback.  That's because sometimes a callback will call the ref object,
774
 * to check if the reference is actually dead (KeyedRef does this, for
775
 * example).  We want to indicate that it is dead, even though it is possible
776
 * a finalizer might resurrect it.  Clearing also prevents the callback from
777
 * executing more than once.
778
 *
779
 * Since Python 2.3, all weakrefs to cyclic garbage have been cleared *before*
780
 * calling finalizers.  However, since tp_subclasses started being necessary
781
 * to invalidate caches (e.g. by PyType_Modified), that clearing has created
782
 * a bug.  If the weakref to the subclass is cleared before a finalizer is
783
 * called, the cache may not be correctly invalidated.  That can lead to
784
 * segfaults since the caches can refer to deallocated objects (GH-135552
785
 * is an example).  Now, we delay the clear of weakrefs without callbacks
786
 * until *after* finalizers have been executed.  That means weakrefs without
787
 * callbacks are still usable while finalizers are being executed.
788
 *
789
 * The weakrefs that are inside the unreachable set must also be cleared.
790
 * The reason this is required is not immediately obvious.  If the weakref
791
 * refers to an object outside of the unreachable set, that object might go
792
 * away when we start clearing objects.  Normally, the object should also be
793
 * part of the unreachable set but that's not true in the case of incomplete
794
 * or missing `tp_traverse` methods.  When that object goes away, the callback
795
 * for weakref can be executed and that could reveal unreachable objects to
796
 * Python-level code.  See bpo-38006 as an example bug.
797
 */
798
static int
799
handle_weakref_callbacks(PyGC_Head *unreachable, PyGC_Head *old,
800
                        bool *needs_resurrection_check)
801
136k
{
802
136k
    PyGC_Head *gc;
803
136k
    PyGC_Head wrcb_to_call;     /* weakrefs with callbacks to call */
804
136k
    PyGC_Head *next;
805
136k
    int num_freed = 0;
806
807
136k
    gc_list_init(&wrcb_to_call);
808
809
    /* Find all weakrefs with callbacks and move into `wrcb_to_call` if the
810
     * callback needs to be invoked. We make another pass over wrcb_to_call,
811
     * invoking callbacks, after this pass completes.
812
     */
813
5.51M
    for (gc = GC_NEXT(unreachable); gc != unreachable; gc = next) {
814
5.37M
        PyWeakReference **wrlist;
815
816
5.37M
        PyObject *op = FROM_GC(gc);
817
5.37M
        next = GC_NEXT(gc);
818
819
5.37M
        if (! _PyType_SUPPORTS_WEAKREFS(Py_TYPE(op))) {
820
3.70M
            continue;
821
3.70M
        }
822
823
        /* It supports weakrefs.  Does it have any?
824
         *
825
         * This is never triggered for static types so we can avoid the
826
         * (slightly) more costly _PyObject_GET_WEAKREFS_LISTPTR().
827
         */
828
1.67M
        wrlist = _PyObject_GET_WEAKREFS_LISTPTR_FROM_OFFSET(op);
829
830
        /* `op` may have some weakrefs.  March over the list and move the
831
         * weakrefs with callbacks that must be called into wrcb_to_call.
832
         */
833
1.67M
        PyWeakReference *next_wr;
834
1.96M
        for (PyWeakReference *wr = *wrlist; wr != NULL; wr = next_wr) {
835
            // Get the next list element to get iterator progress if we omit
836
            // clearing of the weakref (because _PyWeakref_ClearRef changes
837
            // next pointer in the wrlist).
838
288k
            next_wr = wr->wr_next;
839
840
288k
            if (wr->wr_callback == NULL) {
841
                /* no callback */
842
268k
                continue;
843
268k
            }
844
845
            // Clear the weakref.  See the comments above this function for
846
            // reasons why we need to clear weakrefs that have callbacks.
847
            // Note that _PyWeakref_ClearRef clears the weakref but leaves the
848
            // callback pointer intact.  Obscure: it also changes *wrlist.
849
20.8k
            _PyObject_ASSERT((PyObject *)wr, wr->wr_object == op);
850
20.8k
            _PyWeakref_ClearRef(wr);
851
20.8k
            _PyObject_ASSERT((PyObject *)wr, wr->wr_object == Py_None);
852
853
            /* Headache time.  `op` is going away, and is weakly referenced by
854
             * `wr`, which has a callback.  Should the callback be invoked?  If wr
855
             * is also trash, no:
856
             *
857
             * 1. There's no need to call it.  The object and the weakref are
858
             *    both going away, so it's legitimate to pretend the weakref is
859
             *    going away first.  The user has to ensure a weakref outlives its
860
             *    referent if they want a guarantee that the wr callback will get
861
             *    invoked.
862
             *
863
             * 2. It may be catastrophic to call it.  If the callback is also in
864
             *    cyclic trash (CT), then although the CT is unreachable from
865
             *    outside the current generation, CT may be reachable from the
866
             *    callback.  Then the callback could resurrect insane objects.
867
             *
868
             * Since the callback is never needed and may be unsafe in this
869
             * case, wr is simply left in the unreachable set.  Note that
870
             * clear_weakrefs() will ensure its callback will not trigger
871
             * inside delete_garbage().
872
             *
873
             * OTOH, if wr isn't part of CT, we should invoke the callback:  the
874
             * weakref outlived the trash.  Note that since wr isn't CT in this
875
             * case, its callback can't be CT either -- wr acted as an external
876
             * root to this generation, and therefore its callback did too.  So
877
             * nothing in CT is reachable from the callback either, so it's hard
878
             * to imagine how calling it later could create a problem for us.  wr
879
             * is moved to wrcb_to_call in this case.
880
             */
881
20.8k
            if (gc_is_collecting(AS_GC((PyObject *)wr))) {
882
0
                continue;
883
0
            }
884
885
            /* Create a new reference so that wr can't go away
886
             * before we can process it again.
887
             */
888
20.8k
            Py_INCREF(wr);
889
890
            /* Move wr to wrcb_to_call, for the next pass. */
891
20.8k
            PyGC_Head *wrasgc = AS_GC((PyObject *)wr);
892
            // wrasgc is reachable, but next isn't, so they can't be the same
893
20.8k
            _PyObject_ASSERT((PyObject *)wr, wrasgc != next);
894
20.8k
            gc_list_move(wrasgc, &wrcb_to_call);
895
20.8k
        }
896
1.67M
    }
897
898
    /* Invoke the callbacks we decided to honor.  It's safe to invoke them
899
     * because they can't reference unreachable objects.
900
     */
901
136k
    if (!*needs_resurrection_check) {
902
136k
        *needs_resurrection_check = !gc_list_is_empty(&wrcb_to_call);
903
136k
    }
904
157k
    while (! gc_list_is_empty(&wrcb_to_call)) {
905
20.8k
        PyObject *temp;
906
20.8k
        PyObject *callback;
907
908
20.8k
        gc = (PyGC_Head*)wrcb_to_call._gc_next;
909
20.8k
        PyObject *op = FROM_GC(gc);
910
20.8k
        _PyObject_ASSERT(op, PyWeakref_Check(op));
911
20.8k
        PyWeakReference *wr = (PyWeakReference *)op;
912
20.8k
        callback = wr->wr_callback;
913
20.8k
        _PyObject_ASSERT(op, callback != NULL);
914
915
        /* copy-paste of weakrefobject.c's handle_callback() */
916
20.8k
        temp = PyObject_CallOneArg(callback, (PyObject *)wr);
917
20.8k
        if (temp == NULL) {
918
0
            PyErr_FormatUnraisable("Exception ignored on "
919
0
                                   "calling weakref callback %R", callback);
920
0
        }
921
20.8k
        else {
922
20.8k
            Py_DECREF(temp);
923
20.8k
        }
924
925
        /* Give up the reference we created in the first pass.  When
926
         * op's refcount hits 0 (which it may or may not do right now),
927
         * op's tp_dealloc will decref op->wr_callback too.  Note
928
         * that the refcount probably will hit 0 now, and because this
929
         * weakref was reachable to begin with, gc didn't already
930
         * add it to its count of freed objects.  Example:  a reachable
931
         * weak value dict maps some key to this reachable weakref.
932
         * The callback removes this key->weakref mapping from the
933
         * dict, leaving no other references to the weakref (excepting
934
         * ours).
935
         */
936
20.8k
        Py_DECREF(op);
937
20.8k
        if (wrcb_to_call._gc_next == (uintptr_t)gc) {
938
            /* object is still alive -- move it */
939
0
            gc_list_move(gc, old);
940
0
        }
941
20.8k
        else {
942
20.8k
            ++num_freed;
943
20.8k
        }
944
20.8k
    }
945
946
136k
    return num_freed;
947
136k
}
948
949
/* Clear all weakrefs to unreachable objects.  When this returns, no object in
950
 * `unreachable` is weakly referenced anymore.  See the comments above
951
 * handle_weakref_callbacks() for why these weakrefs need to be cleared.
952
 */
953
static void
954
clear_weakrefs(PyGC_Head *unreachable)
955
136k
{
956
136k
    PyGC_Head *gc;
957
136k
    PyGC_Head *next;
958
959
5.51M
    for (gc = GC_NEXT(unreachable); gc != unreachable; gc = next) {
960
5.37M
        PyWeakReference **wrlist;
961
962
5.37M
        PyObject *op = FROM_GC(gc);
963
5.37M
        next = GC_NEXT(gc);
964
965
5.37M
        if (PyWeakref_Check(op)) {
966
            /* A weakref inside the unreachable set is always cleared. See
967
             * the comments above handle_weakref_callbacks() for why these
968
             * must be cleared.
969
             */
970
8
            _PyWeakref_ClearRef((PyWeakReference *)op);
971
8
        }
972
973
5.37M
        if (! _PyType_SUPPORTS_WEAKREFS(Py_TYPE(op))) {
974
3.70M
            continue;
975
3.70M
        }
976
977
        /* It supports weakrefs.  Does it have any?
978
         *
979
         * This is never triggered for static types so we can avoid the
980
         * (slightly) more costly _PyObject_GET_WEAKREFS_LISTPTR().
981
         */
982
1.67M
        wrlist = _PyObject_GET_WEAKREFS_LISTPTR_FROM_OFFSET(op);
983
984
        /* `op` may have some weakrefs.  March over the list, clear
985
         * all the weakrefs.
986
         */
987
1.94M
        for (PyWeakReference *wr = *wrlist; wr != NULL; wr = *wrlist) {
988
            /* _PyWeakref_ClearRef clears the weakref but leaves
989
             * the callback pointer intact.  Obscure:  it also
990
             * changes *wrlist.
991
             */
992
268k
            _PyObject_ASSERT((PyObject *)wr, wr->wr_object == op);
993
268k
            _PyWeakref_ClearRef(wr);
994
268k
            _PyObject_ASSERT((PyObject *)wr, wr->wr_object == Py_None);
995
268k
        }
996
1.67M
    }
997
136k
}
998
999
/* "gc: " + " <" + " 0x" + 16 hex digits + ">\n" + NUL, excluding msg and
1000
 * tp_name */
1001
0
#define DEBUG_LINE_FIXED_LEN 32
1002
1003
static char *
1004
debug_cycle(const char *msg, PyObject *op)
1005
0
{
1006
0
    const char *name = Py_TYPE(op)->tp_name;
1007
0
    size_t size = strlen(msg) + strlen(name) + DEBUG_LINE_FIXED_LEN;
1008
0
    char *line = PyMem_RawMalloc(size);
1009
0
    if (line == NULL) {
1010
0
        return NULL;
1011
0
    }
1012
    /* Not %p: its output is platform-specific (no "0x" prefix on Windows). */
1013
0
    PyOS_snprintf(line, size, "gc: %s <%s 0x%" PRIxPTR ">\n",
1014
0
                  msg, name, (uintptr_t)op);
1015
0
    return line;
1016
0
}
1017
1018
/* Format a line for each object in `list` before printing any of them,
1019
 * since sys.stderr.write() can run Python code that frees objects in the
1020
 * list.
1021
 */
1022
static Py_ssize_t
1023
debug_cycles(const char *msg, PyGC_Head *list)
1024
0
{
1025
0
    Py_ssize_t n = gc_list_size(list);
1026
0
    if (n == 0) {
1027
0
        return n;
1028
0
    }
1029
1030
0
    char **lines = PyMem_RawCalloc(n, sizeof(char *));
1031
0
    if (lines == NULL) {
1032
0
        return n;
1033
0
    }
1034
1035
0
    Py_ssize_t i = 0;
1036
0
    for (PyGC_Head *gc = GC_NEXT(list); gc != list; gc = GC_NEXT(gc), i++) {
1037
0
        lines[i] = debug_cycle(msg, FROM_GC(gc));
1038
0
    }
1039
1040
0
    for (i = 0; i < n; i++) {
1041
0
        if (lines[i] != NULL) {
1042
0
            PySys_FormatStderr("%s", lines[i]);
1043
0
        }
1044
0
        PyMem_RawFree(lines[i]);
1045
0
    }
1046
0
    PyMem_RawFree(lines);
1047
0
    return n;
1048
0
}
1049
1050
/* Handle uncollectable garbage (cycles with tp_del slots, and stuff reachable
1051
 * only from such cycles).
1052
 * If _PyGC_DEBUG_SAVEALL, all objects in finalizers are appended to the module
1053
 * garbage list (a Python list), else only the objects in finalizers with
1054
 * __del__ methods are appended to garbage.  All objects in finalizers are
1055
 * merged into the old list regardless.
1056
 */
1057
static void
1058
handle_legacy_finalizers(PyThreadState *tstate,
1059
                         GCState *gcstate,
1060
                         PyGC_Head *finalizers, PyGC_Head *old)
1061
136k
{
1062
136k
    assert(!_PyErr_Occurred(tstate));
1063
136k
    assert(gcstate->garbage != NULL);
1064
1065
136k
    PyGC_Head *gc = GC_NEXT(finalizers);
1066
136k
    for (; gc != finalizers; gc = GC_NEXT(gc)) {
1067
0
        PyObject *op = FROM_GC(gc);
1068
1069
0
        if ((gcstate->debug & _PyGC_DEBUG_SAVEALL) || has_legacy_finalizer(op)) {
1070
0
            if (PyList_Append(gcstate->garbage, op) < 0) {
1071
0
                _PyErr_Clear(tstate);
1072
0
                break;
1073
0
            }
1074
0
        }
1075
0
    }
1076
1077
136k
    gc_list_merge(finalizers, old);
1078
136k
}
1079
1080
/* Run first-time finalizers (if any) on all the objects in collectable.
1081
 * Note that this may remove some (or even all) of the objects from the
1082
 * list, due to refcounts falling to 0.
1083
 */
1084
static void
1085
finalize_garbage(PyThreadState *tstate, PyGC_Head *collectable,
1086
                 bool *needs_resurrection_check)
1087
136k
{
1088
136k
    destructor finalize;
1089
136k
    PyGC_Head seen;
1090
1091
    /* While we're going through the loop, `finalize(op)` may cause op, or
1092
     * other objects, to be reclaimed via refcounts falling to zero.  So
1093
     * there's little we can rely on about the structure of the input
1094
     * `collectable` list across iterations.  For safety, we always take the
1095
     * first object in that list and move it to a temporary `seen` list.
1096
     * If objects vanish from the `collectable` and `seen` lists we don't
1097
     * care.
1098
     */
1099
136k
    gc_list_init(&seen);
1100
1101
5.51M
    while (!gc_list_is_empty(collectable)) {
1102
5.37M
        PyGC_Head *gc = GC_NEXT(collectable);
1103
5.37M
        PyObject *op = FROM_GC(gc);
1104
5.37M
        gc_list_move(gc, &seen);
1105
5.37M
        if (!_PyGC_FINALIZED(op) &&
1106
5.37M
            (finalize = Py_TYPE(op)->tp_finalize) != NULL)
1107
2
        {
1108
2
            if (!_PyGen_FinalizerIsNoop(op)) {
1109
2
                *needs_resurrection_check = true;
1110
2
            }
1111
2
            _PyGC_SET_FINALIZED(op);
1112
2
            Py_INCREF(op);
1113
2
            finalize(op);
1114
2
            assert(!_PyErr_Occurred(tstate));
1115
2
            Py_DECREF(op);
1116
2
        }
1117
5.37M
    }
1118
136k
    gc_list_merge(&seen, collectable);
1119
136k
}
1120
1121
/* Break reference cycles by clearing the containers involved.  This is
1122
 * tricky business as the lists can be changing and we don't know which
1123
 * objects may be freed.  It is possible I screwed something up here.
1124
 */
1125
static void
1126
delete_garbage(PyThreadState *tstate, GCState *gcstate,
1127
               PyGC_Head *collectable, PyGC_Head *old)
1128
136k
{
1129
136k
    assert(!_PyErr_Occurred(tstate));
1130
1131
2.44M
    while (!gc_list_is_empty(collectable)) {
1132
2.30M
        PyGC_Head *gc = GC_NEXT(collectable);
1133
2.30M
        PyObject *op = FROM_GC(gc);
1134
1135
2.30M
        _PyObject_ASSERT_WITH_MSG(op, Py_REFCNT(op) > 0,
1136
2.30M
                                  "refcount is too small");
1137
1138
2.30M
        if (gcstate->debug & _PyGC_DEBUG_SAVEALL) {
1139
0
            assert(gcstate->garbage != NULL);
1140
0
            if (PyList_Append(gcstate->garbage, op) < 0) {
1141
0
                _PyErr_Clear(tstate);
1142
0
            }
1143
0
        }
1144
2.30M
        else {
1145
2.30M
            inquiry clear;
1146
2.30M
            if ((clear = Py_TYPE(op)->tp_clear) != NULL) {
1147
1.98M
                Py_INCREF(op);
1148
1.98M
                (void) clear(op);
1149
1.98M
                if (_PyErr_Occurred(tstate)) {
1150
0
                    PyErr_FormatUnraisable("Exception ignored in tp_clear of %s",
1151
0
                                           Py_TYPE(op)->tp_name);
1152
0
                }
1153
1.98M
                Py_DECREF(op);
1154
1.98M
            }
1155
2.30M
        }
1156
2.30M
        if (GC_NEXT(collectable) == gc) {
1157
            /* object is still alive, move it, it may die later */
1158
1.80M
            gc_clear_collecting(gc);
1159
1.80M
            gc_list_move(gc, old);
1160
1.80M
        }
1161
2.30M
    }
1162
136k
}
1163
1164
1165
// Show stats for objects in each generations
1166
static void
1167
show_stats_each_generations(GCState *gcstate)
1168
0
{
1169
0
    char buf[100];
1170
0
    size_t pos = 0;
1171
1172
0
    for (int i = 0; i < NUM_GENERATIONS && pos < sizeof(buf); i++) {
1173
0
        pos += PyOS_snprintf(buf+pos, sizeof(buf)-pos,
1174
0
                             " %zd",
1175
0
                             gc_list_size(GEN_HEAD(gcstate, i)));
1176
0
    }
1177
1178
0
    PySys_FormatStderr(
1179
0
        "gc: objects in each generation:%s\n"
1180
0
        "gc: objects in permanent generation: %zd\n",
1181
0
        buf, gc_list_size(&gcstate->permanent_generation.head));
1182
0
}
1183
1184
/* Deduce which objects among "base" are unreachable from outside the list
1185
   and move them to 'unreachable'. The process consist in the following steps:
1186
1187
1. Copy all reference counts to a different field (gc_prev is used to hold
1188
   this copy to save memory).
1189
2. Traverse all objects in "base" and visit all referred objects using
1190
   "tp_traverse" and for every visited object, subtract 1 to the reference
1191
   count (the one that we copied in the previous step). After this step, all
1192
   objects that can be reached directly from outside must have strictly positive
1193
   reference count, while all unreachable objects must have a count of exactly 0.
1194
3. Identify all unreachable objects (the ones with 0 reference count) and move
1195
   them to the "unreachable" list. This step also needs to move back to "base" all
1196
   objects that were initially marked as unreachable but are referred transitively
1197
   by the reachable objects (the ones with strictly positive reference count).
1198
1199
Contracts:
1200
1201
    * The "base" has to be a valid list with no mask set.
1202
1203
    * The "unreachable" list must be uninitialized (this function calls
1204
      gc_list_init over 'unreachable').
1205
1206
IMPORTANT: This function leaves 'unreachable' with the NEXT_MASK_UNREACHABLE
1207
flag set but it does not clear it to skip unnecessary iteration. Before the
1208
flag is cleared (for example, by using 'clear_unreachable_mask' function or
1209
by a call to 'move_legacy_finalizers'), the 'unreachable' list is not a normal
1210
list and we can not use most gc_list_* functions for it. */
1211
static inline Py_ssize_t
1212
deduce_unreachable(PyGC_Head *base, PyGC_Head *unreachable,
1213
138k
                   Py_ssize_t *reachable) {
1214
138k
    validate_list(base, collecting_clear_unreachable_clear);
1215
    /* Using ob_refcnt and gc_refs, calculate which objects in the
1216
     * container set are reachable from outside the set (i.e., have a
1217
     * refcount greater than 0 when all the references within the
1218
     * set are taken into account).
1219
     */
1220
138k
    Py_ssize_t candidates = update_refs(base);  // gc_prev is used for gc_refs
1221
138k
    subtract_refs(base);
1222
1223
    /* Leave everything reachable from outside base in base, and move
1224
     * everything else (in base) to unreachable.
1225
     *
1226
     * NOTE:  This used to move the reachable objects into a reachable
1227
     * set instead.  But most things usually turn out to be reachable,
1228
     * so it's more efficient to move the unreachable things.  It "sounds slick"
1229
     * to move the unreachable objects, until you think about it - the reason it
1230
     * pays isn't actually obvious.
1231
     *
1232
     * Suppose we create objects A, B, C in that order.  They appear in the young
1233
     * generation in the same order.  If B points to A, and C to B, and C is
1234
     * reachable from outside, then the adjusted refcounts will be 0, 0, and 1
1235
     * respectively.
1236
     *
1237
     * When move_unreachable finds A, A is moved to the unreachable list.  The
1238
     * same for B when it's first encountered.  Then C is traversed, B is moved
1239
     * _back_ to the reachable list.  B is eventually traversed, and then A is
1240
     * moved back to the reachable list.
1241
     *
1242
     * So instead of not moving at all, the reachable objects B and A are moved
1243
     * twice each.  Why is this a win?  A straightforward algorithm to move the
1244
     * reachable objects instead would move A, B, and C once each.
1245
     *
1246
     * The key is that this dance leaves the objects in order C, B, A - it's
1247
     * reversed from the original order.  On all _subsequent_ scans, none of
1248
     * them will move.  Since most objects aren't in cycles, this can save an
1249
     * unbounded number of moves across an unbounded number of later collections.
1250
     * It can cost more only the first time the chain is scanned.
1251
     *
1252
     * Drawback:  move_unreachable is also used to find out what's still trash
1253
     * after finalizers may resurrect objects.  In _that_ case most unreachable
1254
     * objects will remain unreachable, so it would be more efficient to move
1255
     * the reachable objects instead.  But this is a one-time cost, probably not
1256
     * worth complicating the code to speed just a little.
1257
     */
1258
138k
    gc_list_init(unreachable);
1259
    // gc_prev is pointer again
1260
138k
    *reachable = move_unreachable(base, unreachable);
1261
138k
    validate_list(base, collecting_clear_unreachable_clear);
1262
138k
    validate_list(unreachable, collecting_set_unreachable_set);
1263
138k
    return candidates;
1264
138k
}
1265
1266
/* Handle objects that may have resurrected after a call to 'finalize_garbage', moving
1267
   them to 'old_generation' and placing the rest on 'still_unreachable'.
1268
1269
   Contracts:
1270
       * After this function 'unreachable' must not be used anymore and 'still_unreachable'
1271
         will contain the objects that did not resurrect.
1272
1273
       * The "still_unreachable" list must be uninitialized (this function calls
1274
         gc_list_init over 'still_unreachable').
1275
1276
IMPORTANT: After a call to this function, the 'still_unreachable' set will have the
1277
PREV_MARK_COLLECTING set, but the objects in this set are going to be removed so
1278
we can skip the expense of clearing the flag to avoid extra iteration. */
1279
static inline void
1280
handle_resurrected_objects(PyGC_Head *unreachable, PyGC_Head* still_unreachable,
1281
                           PyGC_Head *old_generation)
1282
1.28k
{
1283
    // Remove the PREV_MASK_COLLECTING from unreachable
1284
    // to prepare it for a new call to 'deduce_unreachable'
1285
1.28k
    gc_list_clear_collecting(unreachable);
1286
1287
    // After the call to deduce_unreachable, the 'still_unreachable' set will
1288
    // have the PREV_MARK_COLLECTING set, but the objects are going to be
1289
    // removed so we can skip the expense of clearing the flag.
1290
1.28k
    PyGC_Head* resurrected = unreachable;
1291
1.28k
    Py_ssize_t reachable;
1292
1.28k
    deduce_unreachable(resurrected, still_unreachable, &reachable);
1293
1.28k
    clear_unreachable_mask(still_unreachable);
1294
1295
    // Move the resurrected objects to the old generation for future collection.
1296
1.28k
    gc_list_merge(resurrected, old_generation);
1297
1.28k
}
1298
1299
1300
/* Invoke progress callbacks to notify clients that garbage collection
1301
 * is starting or stopping
1302
 */
1303
static void
1304
invoke_gc_callback(PyThreadState *tstate, const char *phase,
1305
                   int generation, struct gc_generation_stats *stats)
1306
273k
{
1307
273k
    assert(!_PyErr_Occurred(tstate));
1308
1309
    /* we may get called very early */
1310
273k
    GCState *gcstate = &tstate->interp->gc;
1311
273k
    if (gcstate->callbacks == NULL) {
1312
0
        return;
1313
0
    }
1314
1315
    /* The local variable cannot be rebound, check it for sanity */
1316
273k
    assert(PyList_CheckExact(gcstate->callbacks));
1317
273k
    PyObject *info = NULL;
1318
273k
    if (PyList_GET_SIZE(gcstate->callbacks) != 0) {
1319
2.58k
        info = Py_BuildValue("{sisnsnsnsd}",
1320
2.58k
            "generation", generation,
1321
2.58k
            "collected", stats->collected,
1322
2.58k
            "uncollectable", stats->uncollectable,
1323
2.58k
            "candidates", stats->candidates,
1324
2.58k
            "duration", stats->duration);
1325
2.58k
        if (info == NULL) {
1326
0
            PyErr_FormatUnraisable("Exception ignored on invoking gc callbacks");
1327
0
            return;
1328
0
        }
1329
2.58k
    }
1330
1331
273k
    PyObject *phase_obj = PyUnicode_FromString(phase);
1332
273k
    if (phase_obj == NULL) {
1333
0
        Py_XDECREF(info);
1334
0
        PyErr_FormatUnraisable("Exception ignored on invoking gc callbacks");
1335
0
        return;
1336
0
    }
1337
1338
273k
    PyObject *stack[] = {phase_obj, info};
1339
276k
    for (Py_ssize_t i=0; i<PyList_GET_SIZE(gcstate->callbacks); i++) {
1340
2.58k
        PyObject *r, *cb = PyList_GET_ITEM(gcstate->callbacks, i);
1341
2.58k
        Py_INCREF(cb); /* make sure cb doesn't go away */
1342
2.58k
        r = PyObject_Vectorcall(cb, stack, 2, NULL);
1343
2.58k
        if (r == NULL) {
1344
0
            PyErr_FormatUnraisable("Exception ignored while "
1345
0
                                   "calling GC callback %R", cb);
1346
0
        }
1347
2.58k
        else {
1348
2.58k
            Py_DECREF(r);
1349
2.58k
        }
1350
2.58k
        Py_DECREF(cb);
1351
2.58k
    }
1352
273k
    Py_DECREF(phase_obj);
1353
273k
    Py_XDECREF(info);
1354
273k
    assert(!_PyErr_Occurred(tstate));
1355
273k
}
1356
1357
1358
/* Find the oldest generation (highest numbered) where the count
1359
 * exceeds the threshold.  Objects in the that generation and
1360
 * generations younger than it will be collected. */
1361
static int
1362
gc_select_generation(GCState *gcstate)
1363
150k
{
1364
451k
    for (int i = NUM_GENERATIONS-1; i >= 0; i--) {
1365
437k
        if (gcstate->generations[i].count > gcstate->generations[i].threshold) {
1366
            /* Avoid quadratic performance degradation in number
1367
               of tracked objects (see also issue #4074):
1368
1369
               To limit the cost of garbage collection, there are two strategies;
1370
                 - make each collection faster, e.g. by scanning fewer objects
1371
                 - do less collections
1372
               This heuristic is about the latter strategy.
1373
1374
               In addition to the various configurable thresholds, we only trigger a
1375
               full collection if the ratio
1376
1377
                long_lived_pending / long_lived_total
1378
1379
               is above a given value (hardwired to 25%).
1380
1381
               The reason is that, while "non-full" collections (i.e., collections of
1382
               the young and middle generations) will always examine roughly the same
1383
               number of objects -- determined by the aforementioned thresholds --,
1384
               the cost of a full collection is proportional to the total number of
1385
               long-lived objects, which is virtually unbounded.
1386
1387
               Indeed, it has been remarked that doing a full collection every
1388
               <constant number> of object creations entails a dramatic performance
1389
               degradation in workloads which consist in creating and storing lots of
1390
               long-lived objects (e.g. building a large list of GC-tracked objects would
1391
               show quadratic performance, instead of linear as expected: see issue #4074).
1392
1393
               Using the above ratio, instead, yields amortized linear performance in
1394
               the total number of objects (the effect of which can be summarized
1395
               thusly: "each full garbage collection is more and more costly as the
1396
               number of objects grows, but we do fewer and fewer of them").
1397
1398
               This heuristic was suggested by Martin von Löwis on python-dev in
1399
               June 2008. His original analysis and proposal can be found at:
1400
               http://mail.python.org/pipermail/python-dev/2008-June/080579.html
1401
            */
1402
144k
            if (i == NUM_GENERATIONS - 1
1403
8.43k
                && gcstate->long_lived_pending < gcstate->long_lived_total / 4)
1404
7.46k
            {
1405
7.46k
                continue;
1406
7.46k
            }
1407
136k
            return i;
1408
144k
        }
1409
437k
    }
1410
13.4k
    return -1;
1411
150k
}
1412
1413
static struct gc_generation_stats *
1414
gc_get_stats(GCState *gcstate, int gen)
1415
136k
{
1416
136k
    if (gen == 0) {
1417
124k
        struct gc_young_stats_buffer *buffer = &gcstate->generation_stats->young;
1418
124k
        buffer->index = (buffer->index + 1) % GC_YOUNG_STATS_SIZE;
1419
124k
        struct gc_generation_stats *stats = &buffer->items[buffer->index];
1420
124k
        return stats;
1421
124k
    }
1422
12.2k
    else {
1423
12.2k
        struct gc_old_stats_buffer *buffer = &gcstate->generation_stats->old[gen - 1];
1424
12.2k
        buffer->index = (buffer->index + 1) % GC_OLD_STATS_SIZE;
1425
12.2k
        struct gc_generation_stats *stats = &buffer->items[buffer->index];
1426
12.2k
        return stats;
1427
12.2k
    }
1428
136k
}
1429
1430
static struct gc_generation_stats *
1431
gc_get_prev_stats(GCState *gcstate, int gen)
1432
136k
{
1433
136k
    if (gen == 0) {
1434
124k
        struct gc_young_stats_buffer *buffer = &gcstate->generation_stats->young;
1435
124k
        struct gc_generation_stats *stats = &buffer->items[buffer->index];
1436
124k
        return stats;
1437
124k
    }
1438
12.2k
    else {
1439
12.2k
        struct gc_old_stats_buffer *buffer = &gcstate->generation_stats->old[gen - 1];
1440
12.2k
        struct gc_generation_stats *stats = &buffer->items[buffer->index];
1441
12.2k
        return stats;
1442
12.2k
    }
1443
136k
}
1444
1445
static void
1446
add_stats(GCState *gcstate, int gen, struct gc_generation_stats *stats)
1447
136k
{
1448
136k
    struct gc_stats *generation_stats = gcstate->generation_stats;
1449
136k
    uint32_t seq = _Py_atomic_load_uint32_relaxed(&generation_stats->update_seq);
1450
136k
    assert((seq & 1) == 0);
1451
    /* Odd seq tells the reader that an update is in progress. */
1452
136k
    _Py_atomic_store_uint32_relaxed(&generation_stats->update_seq, seq + 1);
1453
136k
    _Py_atomic_fence_seq_cst();
1454
1455
136k
    struct gc_generation_stats *prev_stats = gc_get_prev_stats(gcstate, gen);
1456
136k
    struct gc_generation_stats *cur_stats = gc_get_stats(gcstate, gen);
1457
1458
136k
    memcpy(cur_stats, prev_stats, sizeof(struct gc_generation_stats));
1459
1460
136k
    cur_stats->ts_start = stats->ts_start;
1461
136k
    cur_stats->collections += 1;
1462
136k
    cur_stats->collected += stats->collected;
1463
136k
    cur_stats->uncollectable += stats->uncollectable;
1464
136k
    cur_stats->candidates += stats->candidates;
1465
1466
136k
    cur_stats->duration += stats->duration;
1467
136k
    cur_stats->heap_size = stats->heap_size;
1468
136k
    cur_stats->ts_stop = stats->ts_stop;
1469
136k
    _Py_atomic_store_uint32_release(&generation_stats->update_seq, seq + 2);
1470
136k
}
1471
1472
/* This is the main function.  Read this to understand how the
1473
 * collection process works. */
1474
static Py_ssize_t
1475
gc_collect_main(PyThreadState *tstate, int generation, _PyGC_Reason reason)
1476
150k
{
1477
150k
    int i;
1478
150k
    PyGC_Head *young; /* the generation we are examining */
1479
150k
    PyGC_Head *old; /* next older generation */
1480
150k
    PyGC_Head unreachable; /* non-problematic unreachable trash */
1481
150k
    PyGC_Head finalizers;  /* objects with, & reachable from, __del__ */
1482
150k
    GCState *gcstate = &tstate->interp->gc;
1483
1484
    // gc_collect_main() must not be called before _PyGC_Init
1485
    // or after _PyGC_Fini()
1486
150k
    assert(gcstate->garbage != NULL);
1487
150k
    assert(!_PyErr_Occurred(tstate));
1488
1489
150k
    int expected = 0;
1490
150k
    if (!_Py_atomic_compare_exchange_int(&gcstate->collecting, &expected, 1)) {
1491
        // Don't start a garbage collection if one is already in progress.
1492
0
        return 0;
1493
0
    }
1494
150k
    gcstate->frame = tstate->current_frame;
1495
1496
150k
    if (generation == GENERATION_AUTO) {
1497
        // Select the oldest generation that needs collecting. We will collect
1498
        // objects from that generation and all generations younger than it.
1499
150k
        generation = gc_select_generation(gcstate);
1500
150k
        if (generation < 0) {
1501
            // No generation needs to be collected.
1502
13.4k
            _Py_atomic_store_int(&gcstate->collecting, 0);
1503
13.4k
            return 0;
1504
13.4k
        }
1505
150k
    }
1506
1507
150k
    assert(generation >= 0 && generation < NUM_GENERATIONS);
1508
1509
#ifdef Py_STATS
1510
    {
1511
        PyStats *s = _PyStats_GET();
1512
        if (s) {
1513
            s->object_stats.object_visits = 0;
1514
        }
1515
    }
1516
#endif
1517
1518
136k
    GC_STAT_ADD(generation, collections, 1);
1519
1520
136k
    struct gc_generation_stats stats = { 0 };
1521
136k
    if (reason != _Py_GC_REASON_SHUTDOWN) {
1522
136k
        invoke_gc_callback(tstate, "start", generation, &stats);
1523
136k
    }
1524
1525
136k
    stats.heap_size = gcstate->heap_size;
1526
    // ignore error: don't interrupt the GC if reading the clock fails
1527
136k
    (void)PyTime_PerfCounterRaw(&stats.ts_start);
1528
136k
    if (gcstate->debug & _PyGC_DEBUG_STATS) {
1529
0
        PySys_WriteStderr("gc: collecting generation %d...\n", generation);
1530
0
        show_stats_each_generations(gcstate);
1531
0
    }
1532
1533
136k
    if (PyDTrace_GC_START_ENABLED()) {
1534
0
        PyDTrace_GC_START(generation);
1535
0
    }
1536
1537
    /* update collection and allocation counters */
1538
136k
    if (generation+1 < NUM_GENERATIONS) {
1539
135k
        gcstate->generations[generation+1].count += 1;
1540
135k
    }
1541
287k
    for (i = 0; i <= generation; i++) {
1542
150k
        gcstate->generations[i].count = 0;
1543
150k
    }
1544
1545
    /* merge younger generations with one we are currently collecting */
1546
150k
    for (i = 0; i < generation; i++) {
1547
13.2k
        gc_list_merge(GEN_HEAD(gcstate, i), GEN_HEAD(gcstate, generation));
1548
13.2k
    }
1549
1550
    /* handy references */
1551
136k
    young = GEN_HEAD(gcstate, generation);
1552
136k
    if (generation < NUM_GENERATIONS-1) {
1553
135k
        old = GEN_HEAD(gcstate, generation+1);
1554
135k
    }
1555
965
    else {
1556
965
        old = young;
1557
965
    }
1558
136k
    validate_list(old, collecting_clear_unreachable_clear);
1559
1560
136k
    Py_ssize_t reachable;
1561
136k
    stats.candidates = deduce_unreachable(young, &unreachable, &reachable);
1562
1563
    /* Move reachable objects to next generation. */
1564
136k
    if (young != old) {
1565
135k
        if (generation == NUM_GENERATIONS - 2) {
1566
11.3k
            gcstate->long_lived_pending += reachable;
1567
11.3k
        }
1568
135k
        gc_list_merge(young, old);
1569
135k
    }
1570
965
    else {
1571
        // In Python <= 3.13, we called untrack_dicts(young) here to untrack
1572
        // atomic-only dicts (see issue #14775). Python 3.14 removed the lazy
1573
        // dict tracking machinery entirely (GH-127010) -- dicts are always
1574
        // tracked from creation and never untracked by GC. That way, we don't
1575
        // have to restore MAINTAIN_TRACKING across every PyDict_SetItem call
1576
        // site; the cost is slightly more work for full collections on dicts
1577
        // with only atomic values.
1578
965
        gcstate->long_lived_pending = 0;
1579
965
        gcstate->long_lived_total = reachable;
1580
965
    }
1581
1582
    /* All objects in unreachable are trash, but objects reachable from
1583
     * legacy finalizers (e.g. tp_del) can't safely be deleted.
1584
     */
1585
136k
    gc_list_init(&finalizers);
1586
    // NEXT_MASK_UNREACHABLE is cleared here.
1587
    // After move_legacy_finalizers(), unreachable is normal list.
1588
136k
    move_legacy_finalizers(&unreachable, &finalizers);
1589
    /* finalizers contains the unreachable objects with a legacy finalizer;
1590
     * unreachable objects reachable *from* those are also uncollectable,
1591
     * and we move those into the finalizers list too.
1592
     */
1593
136k
    move_legacy_finalizer_reachable(&finalizers);
1594
1595
136k
    validate_list(&finalizers, collecting_clear_unreachable_clear);
1596
136k
    validate_list(&unreachable, collecting_set_unreachable_clear);
1597
1598
136k
    bool needs_resurrection_check = false;
1599
1600
    /* Print debugging information. */
1601
136k
    if (gcstate->debug & _PyGC_DEBUG_COLLECTABLE) {
1602
        /* sys.stderr.write() can resurrect objects. */
1603
0
        needs_resurrection_check = true;
1604
0
        debug_cycles("collectable", &unreachable);
1605
0
    }
1606
1607
    /* Clear weakrefs and invoke callbacks as necessary. */
1608
136k
    stats.collected += handle_weakref_callbacks(&unreachable, old,
1609
136k
                                               &needs_resurrection_check);
1610
136k
    validate_list(old, collecting_clear_unreachable_clear);
1611
136k
    validate_list(&unreachable, collecting_set_unreachable_clear);
1612
1613
    /* Call tp_finalize on objects which have one. */
1614
136k
    finalize_garbage(tstate, &unreachable, &needs_resurrection_check);
1615
1616
    /* Handle any objects that may have resurrected after the call
1617
     * to 'finalize_garbage' and continue the collection with the
1618
     * objects that are still unreachable */
1619
136k
    PyGC_Head final_unreachable;
1620
136k
    if (needs_resurrection_check) {
1621
1.28k
        handle_resurrected_objects(&unreachable, &final_unreachable, old);
1622
1.28k
    }
1623
135k
    else {
1624
        /* No Python code ran during finalization, so the original
1625
         * unreachable set is still valid. */
1626
135k
        gc_list_init(&final_unreachable);
1627
135k
        gc_list_merge(&unreachable, &final_unreachable);
1628
135k
    }
1629
1630
    /* Clear weakrefs to objects in the unreachable set.  No Python-level
1631
     * code must be allowed to access those unreachable objects.  During
1632
     * delete_garbage(), finalizers outside the unreachable set might run
1633
     * and create new weakrefs.  If those weakrefs were not cleared, they
1634
     * could reveal unreachable objects.  Callbacks are not executed.
1635
     */
1636
136k
    clear_weakrefs(&final_unreachable);
1637
1638
    /* Call tp_clear on objects in the final_unreachable set.  This will cause
1639
    * the reference cycles to be broken.  It may also cause some objects
1640
    * in finalizers to be freed.
1641
    */
1642
136k
    stats.collected += gc_list_size(&final_unreachable);
1643
136k
    delete_garbage(tstate, gcstate, &final_unreachable, old);
1644
1645
    /* Collect statistics on uncollectable objects found and print
1646
     * debugging information. */
1647
136k
    if (gcstate->debug & _PyGC_DEBUG_UNCOLLECTABLE) {
1648
0
        stats.uncollectable = debug_cycles("uncollectable", &finalizers);
1649
0
    }
1650
136k
    else {
1651
136k
        stats.uncollectable = gc_list_size(&finalizers);
1652
136k
    }
1653
136k
    (void)PyTime_PerfCounterRaw(&stats.ts_stop);
1654
136k
    stats.duration = PyTime_AsSecondsDouble(stats.ts_stop - stats.ts_start);
1655
136k
    if (gcstate->debug & _PyGC_DEBUG_STATS) {
1656
0
        PySys_WriteStderr(
1657
0
            "gc: done, %zd unreachable, %zd uncollectable, %.4fs elapsed\n",
1658
0
            stats.uncollectable+stats.collected, stats.uncollectable,
1659
0
            stats.duration);
1660
0
    }
1661
1662
    /* Append instances in the uncollectable set to a Python
1663
     * reachable list of garbage.  The programmer has to deal with
1664
     * this if they insist on creating this type of structure.
1665
     */
1666
136k
    handle_legacy_finalizers(tstate, gcstate, &finalizers, old);
1667
136k
    validate_list(old, collecting_clear_unreachable_clear);
1668
1669
    /* Clear free list only during the collection of the highest
1670
     * generation */
1671
136k
    if (generation == NUM_GENERATIONS-1) {
1672
965
        _PyGC_ClearAllFreeLists(tstate->interp);
1673
965
    }
1674
1675
136k
    if (_PyErr_Occurred(tstate)) {
1676
0
        if (reason == _Py_GC_REASON_SHUTDOWN) {
1677
0
            _PyErr_Clear(tstate);
1678
0
        }
1679
0
        else {
1680
0
            PyErr_FormatUnraisable("Exception ignored in garbage collection");
1681
0
        }
1682
0
    }
1683
1684
    /* Update stats */
1685
136k
    add_stats(gcstate, generation, &stats);
1686
136k
    GC_STAT_ADD(generation, objects_collected, stats.collected);
1687
1688
#ifdef Py_STATS
1689
    {
1690
        PyStats *s = _PyStats_GET();
1691
        if (s) {
1692
            GC_STAT_ADD(generation, object_visits,
1693
                s->object_stats.object_visits);
1694
            s->object_stats.object_visits = 0;
1695
        }
1696
    }
1697
#endif
1698
1699
136k
    if (PyDTrace_GC_DONE_ENABLED()) {
1700
0
        PyDTrace_GC_DONE(stats.uncollectable + stats.collected);
1701
0
    }
1702
1703
136k
    if (reason != _Py_GC_REASON_SHUTDOWN) {
1704
136k
        invoke_gc_callback(tstate, "stop", generation, &stats);
1705
136k
    }
1706
1707
136k
    assert(!_PyErr_Occurred(tstate));
1708
136k
    gcstate->frame = NULL;
1709
136k
    _Py_atomic_store_int(&gcstate->collecting, 0);
1710
136k
    return stats.uncollectable + stats.collected;
1711
150k
}
1712
1713
static int
1714
referrersvisit(PyObject* obj, void *arg)
1715
0
{
1716
0
    PyObject *objs = arg;
1717
0
    Py_ssize_t i;
1718
0
    for (i = 0; i < PyTuple_GET_SIZE(objs); i++) {
1719
0
        if (PyTuple_GET_ITEM(objs, i) == obj) {
1720
0
            return 1;
1721
0
        }
1722
0
    }
1723
0
    return 0;
1724
0
}
1725
1726
static int
1727
gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist)
1728
0
{
1729
0
    PyGC_Head *gc;
1730
0
    PyObject *obj;
1731
0
    traverseproc traverse;
1732
0
    for (gc = GC_NEXT(list); gc != list; gc = GC_NEXT(gc)) {
1733
0
        obj = FROM_GC(gc);
1734
0
        traverse = Py_TYPE(obj)->tp_traverse;
1735
0
        if (obj == objs || obj == resultlist) {
1736
0
            continue;
1737
0
        }
1738
0
        if (traverse(obj, referrersvisit, objs)) {
1739
0
            if (PyList_Append(resultlist, obj) < 0) {
1740
0
                return 0; /* error */
1741
0
            }
1742
0
        }
1743
0
    }
1744
0
    return 1; /* no error */
1745
0
}
1746
1747
PyObject *
1748
_PyGC_GetReferrers(PyInterpreterState *interp, PyObject *objs)
1749
0
{
1750
0
    PyObject *result = PyList_New(0);
1751
0
    if (!result) {
1752
0
        return NULL;
1753
0
    }
1754
1755
0
    GCState *gcstate = &interp->gc;
1756
0
    for (int i = 0; i < NUM_GENERATIONS; i++) {
1757
0
        if (!(gc_referrers_for(objs, GEN_HEAD(gcstate, i), result))) {
1758
0
            Py_DECREF(result);
1759
0
            return NULL;
1760
0
        }
1761
0
    }
1762
0
    return result;
1763
0
}
1764
1765
PyObject *
1766
_PyGC_GetObjects(PyInterpreterState *interp, int generation)
1767
0
{
1768
0
    assert(generation >= -1 && generation < NUM_GENERATIONS);
1769
0
    GCState *gcstate = &interp->gc;
1770
1771
0
    PyObject *result = PyList_New(0);
1772
0
    if (result == NULL) {
1773
0
        return NULL;
1774
0
    }
1775
1776
0
    if (generation == -1) {
1777
        /* If generation is -1, get all objects from all generations */
1778
0
        for (int i = 0; i < NUM_GENERATIONS; i++) {
1779
0
            if (append_objects(result, GEN_HEAD(gcstate, i))) {
1780
0
                goto error;
1781
0
            }
1782
0
        }
1783
0
    }
1784
0
    else {
1785
0
        if (append_objects(result, GEN_HEAD(gcstate, generation))) {
1786
0
            goto error;
1787
0
        }
1788
0
    }
1789
1790
0
    return result;
1791
0
error:
1792
0
    Py_DECREF(result);
1793
0
    return NULL;
1794
0
}
1795
1796
void
1797
_PyGC_Freeze(PyInterpreterState *interp)
1798
0
{
1799
0
    GCState *gcstate = &interp->gc;
1800
0
    for (int i = 0; i < NUM_GENERATIONS; ++i) {
1801
0
        gc_list_merge(GEN_HEAD(gcstate, i), &gcstate->permanent_generation.head);
1802
0
        gcstate->generations[i].count = 0;
1803
0
    }
1804
0
}
1805
1806
void
1807
_PyGC_Unfreeze(PyInterpreterState *interp)
1808
0
{
1809
0
    GCState *gcstate = &interp->gc;
1810
0
    gc_list_merge(&gcstate->permanent_generation.head,
1811
0
                  GEN_HEAD(gcstate, NUM_GENERATIONS-1));
1812
0
}
1813
1814
Py_ssize_t
1815
_PyGC_GetFreezeCount(PyInterpreterState *interp)
1816
0
{
1817
0
    GCState *gcstate = &interp->gc;
1818
0
    return gc_list_size(&gcstate->permanent_generation.head);
1819
0
}
1820
1821
/* C API for controlling the state of the garbage collector */
1822
int
1823
PyGC_Enable(void)
1824
0
{
1825
0
    GCState *gcstate = get_gc_state();
1826
0
    int old_state = gcstate->enabled;
1827
0
    gcstate->enabled = 1;
1828
0
    return old_state;
1829
0
}
1830
1831
int
1832
PyGC_Disable(void)
1833
0
{
1834
0
    GCState *gcstate = get_gc_state();
1835
0
    int old_state = gcstate->enabled;
1836
0
    gcstate->enabled = 0;
1837
0
    return old_state;
1838
0
}
1839
1840
int
1841
PyGC_IsEnabled(void)
1842
0
{
1843
0
    GCState *gcstate = get_gc_state();
1844
0
    return gcstate->enabled;
1845
0
}
1846
1847
/* Public API to invoke gc.collect() from C */
1848
Py_ssize_t
1849
PyGC_Collect(void)
1850
0
{
1851
0
    PyThreadState *tstate = _PyThreadState_GET();
1852
0
    GCState *gcstate = &tstate->interp->gc;
1853
1854
0
    if (!gcstate->enabled) {
1855
0
        return 0;
1856
0
    }
1857
1858
0
    Py_ssize_t n;
1859
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
1860
0
    n = gc_collect_main(tstate, NUM_GENERATIONS - 1, _Py_GC_REASON_MANUAL);
1861
0
    _PyErr_SetRaisedException(tstate, exc);
1862
1863
0
    return n;
1864
0
}
1865
1866
Py_ssize_t
1867
_PyGC_Collect(PyThreadState *tstate, int generation, _PyGC_Reason reason)
1868
0
{
1869
0
    return gc_collect_main(tstate, generation, reason);
1870
0
}
1871
1872
void
1873
_PyGC_CollectNoFail(PyThreadState *tstate)
1874
0
{
1875
    /* Ideally, this function is only called on interpreter shutdown,
1876
       and therefore not recursively.  Unfortunately, when there are daemon
1877
       threads, a daemon thread can start a cyclic garbage collection
1878
       during interpreter shutdown (and then never finish it).
1879
       See http://bugs.python.org/issue8713#msg195178 for an example.
1880
       */
1881
0
    gc_collect_main(tstate, NUM_GENERATIONS - 1, _Py_GC_REASON_SHUTDOWN);
1882
0
}
1883
1884
void
1885
_PyGC_DumpShutdownStats(PyInterpreterState *interp)
1886
0
{
1887
0
    GCState *gcstate = &interp->gc;
1888
0
    if (!(gcstate->debug & _PyGC_DEBUG_SAVEALL)
1889
0
        && gcstate->garbage != NULL && PyList_GET_SIZE(gcstate->garbage) > 0) {
1890
0
        const char *message;
1891
0
        if (gcstate->debug & _PyGC_DEBUG_UNCOLLECTABLE) {
1892
0
            message = "gc: %zd uncollectable objects at shutdown";
1893
0
        }
1894
0
        else {
1895
0
            message = "gc: %zd uncollectable objects at shutdown; " \
1896
0
                "use gc.set_debug(gc.DEBUG_UNCOLLECTABLE) to list them";
1897
0
        }
1898
        /* PyErr_WarnFormat does too many things and we are at shutdown,
1899
           the warnings module's dependencies (e.g. linecache) may be gone
1900
           already. */
1901
0
        if (PyErr_WarnExplicitFormat(PyExc_ResourceWarning, "gc", 0,
1902
0
                                     "gc", NULL, message,
1903
0
                                     PyList_GET_SIZE(gcstate->garbage)))
1904
0
        {
1905
0
            PyErr_FormatUnraisable("Exception ignored in GC shutdown");
1906
0
        }
1907
0
        if (gcstate->debug & _PyGC_DEBUG_UNCOLLECTABLE) {
1908
0
            PyObject *repr = NULL, *bytes = NULL;
1909
0
            repr = PyObject_Repr(gcstate->garbage);
1910
0
            if (!repr || !(bytes = PyUnicode_EncodeFSDefault(repr))) {
1911
0
                PyErr_FormatUnraisable("Exception ignored in GC shutdown "
1912
0
                                       "while formatting garbage");
1913
0
            }
1914
0
            else {
1915
0
                PySys_WriteStderr(
1916
0
                    "      %s\n",
1917
0
                    PyBytes_AS_STRING(bytes)
1918
0
                    );
1919
0
            }
1920
0
            Py_XDECREF(repr);
1921
0
            Py_XDECREF(bytes);
1922
0
        }
1923
0
    }
1924
0
}
1925
1926
static void
1927
0
finalize_unlink_gc_head(PyGC_Head *gc) {
1928
0
    PyGC_Head *prev = GC_PREV(gc);
1929
0
    PyGC_Head *next = GC_NEXT(gc);
1930
0
    _PyGCHead_SET_NEXT(prev, next);
1931
0
    _PyGCHead_SET_PREV(next, prev);
1932
0
}
1933
1934
void
1935
_PyGC_Fini(PyInterpreterState *interp)
1936
0
{
1937
0
    GCState *gcstate = &interp->gc;
1938
0
    Py_CLEAR(gcstate->garbage);
1939
0
    Py_CLEAR(gcstate->callbacks);
1940
0
    PyMem_RawFree(gcstate->generation_stats);
1941
0
    gcstate->generation_stats = NULL;
1942
1943
    /* Prevent a subtle bug that affects sub-interpreters that use basic
1944
     * single-phase init extensions (m_size == -1).  Those extensions cause objects
1945
     * to be shared between interpreters, via the PyDict_Update(mdict, m_copy) call
1946
     * in import_find_extension().
1947
     *
1948
     * If they are GC objects, their GC head next or prev links could refer to
1949
     * the interpreter _gc_runtime_state PyGC_Head nodes.  Those nodes go away
1950
     * when the interpreter structure is freed and so pointers to them become
1951
     * invalid.  If those objects are still used by another interpreter and
1952
     * UNTRACK is called on them, a crash will happen.  We untrack the nodes
1953
     * here to avoid that.
1954
     *
1955
     * This bug was originally fixed when reported as gh-90228.  The bug was
1956
     * re-introduced in gh-94673.
1957
     */
1958
0
    for (int i = 0; i < NUM_GENERATIONS; i++) {
1959
0
        finalize_unlink_gc_head(&gcstate->generations[i].head);
1960
0
    }
1961
0
    finalize_unlink_gc_head(&gcstate->permanent_generation.head);
1962
0
}
1963
1964
/* for debugging */
1965
void
1966
_PyGC_Dump(PyGC_Head *g)
1967
0
{
1968
0
    PyObject_Dump(FROM_GC(g));
1969
0
}
1970
1971
1972
#ifdef Py_DEBUG
1973
static int
1974
visit_validate(PyObject *op, void *parent_raw)
1975
{
1976
    PyObject *parent = _PyObject_CAST(parent_raw);
1977
    if (_PyObject_IsFreed(op)) {
1978
        _PyObject_ASSERT_FAILED_MSG(parent,
1979
                                    "PyObject_GC_Track() object is not valid");
1980
    }
1981
    return 0;
1982
}
1983
#endif
1984
1985
1986
/* extension modules might be compiled with GC support so these
1987
   functions must always be available */
1988
1989
void
1990
PyObject_GC_Track(void *op_raw)
1991
193M
{
1992
193M
    PyObject *op = _PyObject_CAST(op_raw);
1993
193M
    if (_PyObject_GC_IS_TRACKED(op)) {
1994
0
        _PyObject_ASSERT_FAILED_MSG(op,
1995
0
                                    "object already tracked "
1996
0
                                    "by the garbage collector");
1997
0
    }
1998
193M
    _PyObject_GC_TRACK(op);
1999
2000
#ifdef Py_DEBUG
2001
    /* Check that the object is valid: validate objects traversed
2002
       by tp_traverse() */
2003
    traverseproc traverse = Py_TYPE(op)->tp_traverse;
2004
    (void)traverse(op, visit_validate, op);
2005
#endif
2006
193M
}
2007
2008
void
2009
PyObject_GC_UnTrack(void *op_raw)
2010
1.59G
{
2011
1.59G
    PyObject *op = _PyObject_CAST(op_raw);
2012
    /* The code for some objects, such as tuples, is a bit
2013
     * sloppy about when the object is tracked and untracked. */
2014
1.59G
    if (_PyObject_GC_IS_TRACKED(op)) {
2015
1.36G
        _PyObject_GC_UNTRACK(op);
2016
1.36G
    }
2017
1.59G
}
2018
2019
int
2020
PyObject_IS_GC(PyObject *obj)
2021
297k
{
2022
297k
    return _PyObject_IS_GC(obj);
2023
297k
}
2024
2025
void
2026
_Py_ScheduleGC(PyThreadState *tstate)
2027
19.9M
{
2028
19.9M
    if (!_Py_eval_breaker_bit_is_set(tstate, _PY_GC_SCHEDULED_BIT))
2029
150k
    {
2030
150k
        _Py_set_eval_breaker_bit(tstate, _PY_GC_SCHEDULED_BIT);
2031
150k
    }
2032
19.9M
}
2033
2034
void
2035
_PyObject_GC_Link(PyObject *op)
2036
677M
{
2037
677M
    PyGC_Head *gc = AS_GC(op);
2038
    // gc must be correctly aligned
2039
677M
    _PyObject_ASSERT(op, ((uintptr_t)gc & (sizeof(uintptr_t)-1)) == 0);
2040
2041
677M
    PyThreadState *tstate = _PyThreadState_GET();
2042
677M
    GCState *gcstate = &tstate->interp->gc;
2043
677M
    gc->_gc_next = 0;
2044
677M
    gc->_gc_prev = 0;
2045
677M
    gcstate->generations[0].count++; /* number of allocated GC objects */
2046
677M
    if (gcstate->generations[0].count > gcstate->generations[0].threshold &&
2047
19.9M
        gcstate->enabled &&
2048
19.9M
        gcstate->generations[0].threshold &&
2049
19.9M
        !_Py_atomic_load_int_relaxed(&gcstate->collecting) &&
2050
19.9M
        !_PyErr_Occurred(tstate))
2051
19.9M
    {
2052
19.9M
        _Py_ScheduleGC(tstate);
2053
19.9M
    }
2054
677M
}
2055
2056
void
2057
_Py_RunGC(PyThreadState *tstate)
2058
150k
{
2059
150k
    GCState *gcstate = get_gc_state();
2060
150k
    if (!gcstate->enabled) {
2061
0
        return;
2062
0
    }
2063
150k
    gc_collect_main(tstate, GENERATION_AUTO, _Py_GC_REASON_HEAP);
2064
150k
}
2065
2066
static PyObject *
2067
gc_alloc(PyTypeObject *tp, size_t basicsize, size_t presize)
2068
533M
{
2069
533M
    PyThreadState *tstate = _PyThreadState_GET();
2070
533M
    if (basicsize > (size_t)PY_SSIZE_T_MAX - presize) {
2071
0
        return _PyErr_NoMemory(tstate);
2072
0
    }
2073
533M
    size_t size = presize + basicsize;
2074
533M
    char *mem = _PyObject_MallocWithType(tp, size);
2075
533M
    if (mem == NULL) {
2076
0
        return _PyErr_NoMemory(tstate);
2077
0
    }
2078
533M
    ((PyObject **)mem)[0] = NULL;
2079
533M
    ((PyObject **)mem)[1] = NULL;
2080
533M
    PyObject *op = (PyObject *)(mem + presize);
2081
533M
    _PyObject_GC_Link(op);
2082
533M
    return op;
2083
533M
}
2084
2085
2086
PyObject *
2087
_PyObject_GC_New(PyTypeObject *tp)
2088
229M
{
2089
229M
    size_t presize = _PyType_PreHeaderSize(tp);
2090
229M
    size_t size = _PyObject_SIZE(tp);
2091
229M
    if (_PyType_HasFeature(tp, Py_TPFLAGS_INLINE_VALUES)) {
2092
244
        size += _PyInlineValuesSize(tp);
2093
244
    }
2094
229M
    PyObject *op = gc_alloc(tp, size, presize);
2095
229M
    if (op == NULL) {
2096
0
        return NULL;
2097
0
    }
2098
229M
    _PyObject_Init(op, tp);
2099
229M
    if (tp->tp_flags & Py_TPFLAGS_INLINE_VALUES) {
2100
244
        _PyObject_InitInlineValues(op, tp);
2101
244
    }
2102
229M
    return op;
2103
229M
}
2104
2105
PyVarObject *
2106
_PyObject_GC_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
2107
303M
{
2108
303M
    PyVarObject *op;
2109
2110
303M
    if (nitems < 0) {
2111
0
        PyErr_BadInternalCall();
2112
0
        return NULL;
2113
0
    }
2114
303M
    size_t presize = _PyType_PreHeaderSize(tp);
2115
303M
    size_t size = _PyObject_VAR_SIZE(tp, nitems);
2116
303M
    op = (PyVarObject *)gc_alloc(tp, size, presize);
2117
303M
    if (op == NULL) {
2118
0
        return NULL;
2119
0
    }
2120
303M
    _PyObject_InitVar(op, tp, nitems);
2121
303M
    return op;
2122
303M
}
2123
2124
PyObject *
2125
PyUnstable_Object_GC_NewWithExtraData(PyTypeObject *tp, size_t extra_size)
2126
0
{
2127
0
    size_t presize = _PyType_PreHeaderSize(tp);
2128
0
    size_t size = _PyObject_SIZE(tp) + extra_size;
2129
0
    PyObject *op = gc_alloc(tp, size, presize);
2130
0
    if (op == NULL) {
2131
0
        return NULL;
2132
0
    }
2133
0
    memset((char *)op + sizeof(PyObject), 0, size - sizeof(PyObject));
2134
0
    _PyObject_Init(op, tp);
2135
0
    return op;
2136
0
}
2137
2138
PyVarObject *
2139
_PyObject_GC_Resize(PyVarObject *op, Py_ssize_t nitems)
2140
41
{
2141
#ifdef Py_DEBUG
2142
    if (nitems < 0) {
2143
        PyErr_BadInternalCall();
2144
        return NULL;
2145
    }
2146
#endif
2147
2148
41
    const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems);
2149
41
    const size_t presize = _PyType_PreHeaderSize(Py_TYPE(op));
2150
41
    _PyObject_ASSERT((PyObject *)op, !_PyObject_GC_IS_TRACKED(op));
2151
41
    if (basicsize > (size_t)PY_SSIZE_T_MAX - presize) {
2152
0
        return (PyVarObject *)PyErr_NoMemory();
2153
0
    }
2154
41
    char *mem = (char *)op - presize;
2155
41
    mem = (char *)_PyObject_ReallocWithType(Py_TYPE(op), mem, presize + basicsize);
2156
41
    if (mem == NULL) {
2157
0
        return (PyVarObject *)PyErr_NoMemory();
2158
0
    }
2159
41
    op = (PyVarObject *) (mem + presize);
2160
41
    Py_SET_SIZE(op, nitems);
2161
41
    return op;
2162
41
}
2163
2164
void
2165
PyObject_GC_Del(void *op)
2166
676M
{
2167
676M
    size_t presize = _PyType_PreHeaderSize(Py_TYPE(op));
2168
676M
    PyGC_Head *g = AS_GC(op);
2169
676M
    if (_PyObject_GC_IS_TRACKED(op)) {
2170
0
        gc_list_remove(g);
2171
0
        GCState *gcstate = get_gc_state();
2172
0
        gcstate->heap_size--;
2173
#ifdef Py_DEBUG
2174
        PyObject *exc = PyErr_GetRaisedException();
2175
        if (PyErr_WarnExplicitFormat(PyExc_ResourceWarning, "gc", 0,
2176
                                     "gc", NULL,
2177
                                     "Object of type %s is not untracked "
2178
                                     "before destruction",
2179
                                     Py_TYPE(op)->tp_name))
2180
        {
2181
            PyErr_FormatUnraisable("Exception ignored on object deallocation");
2182
        }
2183
        PyErr_SetRaisedException(exc);
2184
#endif
2185
0
    }
2186
676M
    GCState *gcstate = get_gc_state();
2187
676M
    if (gcstate->generations[0].count > 0) {
2188
392M
        gcstate->generations[0].count--;
2189
392M
    }
2190
676M
    PyObject_Free(((char *)op)-presize);
2191
676M
}
2192
2193
int
2194
PyObject_GC_IsTracked(PyObject* obj)
2195
8.94k
{
2196
8.94k
    if (_PyObject_IS_GC(obj) && _PyObject_GC_IS_TRACKED(obj)) {
2197
16
        return 1;
2198
16
    }
2199
8.92k
    return 0;
2200
8.94k
}
2201
2202
int
2203
PyObject_GC_IsFinalized(PyObject *obj)
2204
0
{
2205
0
    if (_PyObject_IS_GC(obj) && _PyGC_FINALIZED(obj)) {
2206
0
         return 1;
2207
0
    }
2208
0
    return 0;
2209
0
}
2210
2211
static int
2212
visit_generation(gcvisitobjects_t callback, void *arg, struct gc_generation *gen)
2213
0
{
2214
0
    PyGC_Head *gc_list, *gc;
2215
0
    gc_list = &gen->head;
2216
0
    for (gc = GC_NEXT(gc_list); gc != gc_list; gc = GC_NEXT(gc)) {
2217
0
        PyObject *op = FROM_GC(gc);
2218
0
        Py_INCREF(op);
2219
0
        int res = callback(op, arg);
2220
0
        Py_DECREF(op);
2221
0
        if (!res) {
2222
0
            return -1;
2223
0
        }
2224
0
    }
2225
0
    return 0;
2226
0
}
2227
2228
void
2229
PyUnstable_GC_VisitObjects(gcvisitobjects_t callback, void *arg)
2230
0
{
2231
0
    GCState *gcstate = get_gc_state();
2232
0
    int original_state = gcstate->enabled;
2233
0
    gcstate->enabled = 0;
2234
0
    for (size_t i = 0; i < NUM_GENERATIONS; i++) {
2235
0
        if (visit_generation(callback, arg, &gcstate->generations[i]) < 0) {
2236
0
            goto done;
2237
0
        }
2238
0
    }
2239
0
    visit_generation(callback, arg, &gcstate->permanent_generation);
2240
0
done:
2241
0
    gcstate->enabled = original_state;
2242
0
}
2243
2244
#endif  // !Py_GIL_DISABLED