https://github.com/python/cpython/commit/6c5596c7199792ea1e8cf26f65da8cd0023c0473
commit: 6c5596c7199792ea1e8cf26f65da8cd0023c0473
branch: main
author: Sergey Miryanov <[email protected]>
committer: sergey-miryanov <[email protected]>
date: 2026-11-07T06:23:41Z
summary:

GH-159101: Fix UAF when tp_finalize changes the base class (#159888)

Co-authored-by: Peter Bierma <[email protected]>

files:
A 
Misc/NEWS.d/next/Core_and_Builtins/2026-10-20-20-38-38.gh-issue-159101.vFwrZY.rst
M Objects/object.c
M Objects/typeobject.c

diff --git 
a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-20-20-38-38.gh-issue-159101.vFwrZY.rst
 
b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-20-20-38-38.gh-issue-159101.vFwrZY.rst
new file mode 100644
index 000000000000000..33beb8d571d7eca
--- /dev/null
+++ 
b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-20-20-38-38.gh-issue-159101.vFwrZY.rst
@@ -0,0 +1,2 @@
+Fix use-after-free when :meth:`~object.__del__` changes the base class. Patch 
by
+Sergey Miryanov.
diff --git a/Objects/object.c b/Objects/object.c
index 757e54aa1d487d7..0695cc090c979c4 100644
--- a/Objects/object.c
+++ b/Objects/object.c
@@ -583,13 +583,13 @@ PyObject_CallFinalizer(PyObject *self)
     if (tp->tp_finalize == NULL)
         return;
     /* tp_finalize should only be called once. */
-    if (_PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
-        return;
-
-    tp->tp_finalize(self);
     if (_PyType_IS_GC(tp)) {
+        if (_PyGC_FINALIZED(self))
+            return;
+
         _PyGC_SET_FINALIZED(self);
     }
+    tp->tp_finalize(self);
 }
 
 int
diff --git a/Objects/typeobject.c b/Objects/typeobject.c
index 66c7bc7f8902fc3..9833c338679d33f 100644
--- a/Objects/typeobject.c
+++ b/Objects/typeobject.c
@@ -2827,6 +2827,10 @@ subtype_dealloc(PyObject *self)
         }
         _PyObject_GC_UNTRACK(self);
     }
+
+    /* Extract the type again; tp_finalize may have changed it */
+    type = Py_TYPE(self);
+
     /*
       If we added a weaklist, we clear it. Do this *before* calling tp_del,
       clearing slots, or clearing the instance dict.

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to