Coverage Report

Created: 2025-11-09 06:26

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