diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-04-09-13-47-33.gh-issue-126703.kXiQHj.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-04-09-13-47-33.gh-issue-126703.kXiQHj.rst new file mode 100644 index 00000000000..d0461e17d0f --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2025-04-09-13-47-33.gh-issue-126703.kXiQHj.rst @@ -0,0 +1 @@ +Fix possible use after free in cases where a method's definition has the same lifetime as its ``self``. diff --git a/Objects/methodobject.c b/Objects/methodobject.c index 1f459dea441..189b026ab33 100644 --- a/Objects/methodobject.c +++ b/Objects/methodobject.c @@ -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->m_ml` might have the same lifetime + // 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); }