Skip to content

Commit e6bb17f

Browse files
bpo-46070: _PyGC_Fini() untracks objects (GH-30577)
Py_EndInterpreter() now explicitly untracks all objects currently tracked by the GC. Previously, if an object was used later by another interpreter, calling PyObject_GC_UnTrack() on the object crashed if the previous or the next object of the PyGC_Head structure became a dangling pointer. (cherry picked from commit 1a4d1c1) Co-authored-by: Victor Stinner <vstinner@python.org>
1 parent 3ce6945 commit e6bb17f

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
:c:func:`Py_EndInterpreter` now explicitly untracks all objects currently
2+
tracked by the GC. Previously, if an object was used later by another
3+
interpreter, calling :c:func:`PyObject_GC_UnTrack` on the object crashed if the
4+
previous or the next object of the :c:type:`PyGC_Head` structure became a
5+
dangling pointer. Patch by Victor Stinner.

Modules/gcmodule.c

+24
Original file line numberDiff line numberDiff line change
@@ -2162,12 +2162,36 @@ _PyGC_DumpShutdownStats(PyInterpreterState *interp)
21622162
}
21632163
}
21642164

2165+
2166+
static void
2167+
gc_fini_untrack(PyGC_Head *list)
2168+
{
2169+
PyGC_Head *gc;
2170+
for (gc = GC_NEXT(list); gc != list; gc = GC_NEXT(list)) {
2171+
PyObject *op = FROM_GC(gc);
2172+
_PyObject_GC_UNTRACK(op);
2173+
}
2174+
}
2175+
2176+
21652177
void
21662178
_PyGC_Fini(PyInterpreterState *interp)
21672179
{
21682180
GCState *gcstate = &interp->gc;
21692181
Py_CLEAR(gcstate->garbage);
21702182
Py_CLEAR(gcstate->callbacks);
2183+
2184+
if (!_Py_IsMainInterpreter(interp)) {
2185+
// bpo-46070: Explicitly untrack all objects currently tracked by the
2186+
// GC. Otherwise, if an object is used later by another interpreter,
2187+
// calling PyObject_GC_UnTrack() on the object crashs if the previous
2188+
// or the next object of the PyGC_Head structure became a dangling
2189+
// pointer.
2190+
for (int i = 0; i < NUM_GENERATIONS; i++) {
2191+
PyGC_Head *gen = GEN_HEAD(gcstate, i);
2192+
gc_fini_untrack(gen);
2193+
}
2194+
}
21712195
}
21722196

21732197
/* for debugging */

0 commit comments

Comments
 (0)