Skip to content

Commit 52937c2

Browse files
authored
bpo-46070: _PyGC_Fini() untracks objects (GH-30577) (GH-30580)
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)
1 parent 4ddd5da commit 52937c2

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
@@ -2149,12 +2149,36 @@ _PyGC_DumpShutdownStats(PyThreadState *tstate)
21492149
}
21502150
}
21512151

2152+
2153+
static void
2154+
gc_fini_untrack(PyGC_Head *list)
2155+
{
2156+
PyGC_Head *gc;
2157+
for (gc = GC_NEXT(list); gc != list; gc = GC_NEXT(list)) {
2158+
PyObject *op = FROM_GC(gc);
2159+
_PyObject_GC_UNTRACK(op);
2160+
}
2161+
}
2162+
2163+
21522164
void
21532165
_PyGC_Fini(PyThreadState *tstate)
21542166
{
21552167
GCState *gcstate = &tstate->interp->gc;
21562168
Py_CLEAR(gcstate->garbage);
21572169
Py_CLEAR(gcstate->callbacks);
2170+
2171+
if (!_Py_IsMainInterpreter(tstate)) {
2172+
// bpo-46070: Explicitly untrack all objects currently tracked by the
2173+
// GC. Otherwise, if an object is used later by another interpreter,
2174+
// calling PyObject_GC_UnTrack() on the object crashs if the previous
2175+
// or the next object of the PyGC_Head structure became a dangling
2176+
// pointer.
2177+
for (int i = 0; i < NUM_GENERATIONS; i++) {
2178+
PyGC_Head *gen = GEN_HEAD(gcstate, i);
2179+
gc_fini_untrack(gen);
2180+
}
2181+
}
21582182
}
21592183

21602184
/* for debugging */

0 commit comments

Comments
 (0)