Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix possible use after free in cases where a method's definition has the same lifetime as its ``self``.
6 changes: 5 additions & 1 deletion Objects/methodobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -173,12 +173,16 @@ meth_dealloc(PyObject *self)
if (m->m_weakreflist != NULL) {
PyObject_ClearWeakRefs((PyObject*) m);
}
// We need to access ml_flags here rather than later.
// `m` might have the same lifetime
Copy link
Contributor

@hawkinsp hawkinsp Apr 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m->m_ml I think here, but yes.

You are also right that probably we should update the API documentation to clarify this is an acceptable thing to do.

// as `m_self` when it's dynamically allocated.
int ml_flags = m->m_ml->ml_flags;
// Dereference class before m_self: PyCFunction_GET_CLASS accesses
// PyMethodDef m_ml, which could be kept alive by m_self
Py_XDECREF(PyCFunction_GET_CLASS(m));
Py_XDECREF(m->m_self);
Py_XDECREF(m->m_module);
if (m->m_ml->ml_flags & METH_METHOD) {
if (ml_flags & METH_METHOD) {
assert(Py_IS_TYPE(self, &PyCMethod_Type));
_Py_FREELIST_FREE(pycmethodobject, m, PyObject_GC_Del);
}
Expand Down
Loading