Coverage Report

Created: 2025-07-18 06:09

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