Skip to content

Commit 04b8631

Browse files
bpo-42015: Reorder dereferencing calls in meth_dealloc, to make sure m_self is kept alive long enough (GH-22670)
1 parent 24a54c0 commit 04b8631

File tree

2 files changed

+7
-2
lines changed

2 files changed

+7
-2
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix potential crash in deallocating method objects when dynamically
2+
allocated `PyMethodDef`'s lifetime is managed through the ``self``
3+
argument of a `PyCFunction`.

Objects/methodobject.c

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,9 +164,11 @@ meth_dealloc(PyCFunctionObject *m)
164164
if (m->m_weakreflist != NULL) {
165165
PyObject_ClearWeakRefs((PyObject*) m);
166166
}
167+
// Dereference class before m_self: PyCFunction_GET_CLASS accesses
168+
// PyMethodDef m_ml, which could be kept alive by m_self
169+
Py_XDECREF(PyCFunction_GET_CLASS(m));
167170
Py_XDECREF(m->m_self);
168171
Py_XDECREF(m->m_module);
169-
Py_XDECREF(PyCFunction_GET_CLASS(m));
170172
PyObject_GC_Del(m);
171173
}
172174

@@ -243,9 +245,9 @@ meth_get__qualname__(PyCFunctionObject *m, void *closure)
243245
static int
244246
meth_traverse(PyCFunctionObject *m, visitproc visit, void *arg)
245247
{
248+
Py_VISIT(PyCFunction_GET_CLASS(m));
246249
Py_VISIT(m->m_self);
247250
Py_VISIT(m->m_module);
248-
Py_VISIT(PyCFunction_GET_CLASS(m));
249251
return 0;
250252
}
251253

0 commit comments

Comments
 (0)