Skip to content

Commit bf2bd8f

Browse files
authored
bpo-25750: fix refcounts in type_getattro() (GH-6118) (GH-9091)
When calling tp_descr_get(self, obj, type), make sure that we own a strong reference to "self". (cherry picked from commit 8f73548)
1 parent 9734024 commit bf2bd8f

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix rare Python crash due to bad refcounting in ``type_getattro()`` if a
2+
descriptor deletes itself from the class. Patch by Jeroen Demeyer.

Objects/typeobject.c

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2611,6 +2611,7 @@ type_getattro(PyTypeObject *type, PyObject *name)
26112611
PyTypeObject *metatype = Py_TYPE(type);
26122612
PyObject *meta_attribute, *attribute;
26132613
descrgetfunc meta_get;
2614+
PyObject* res;
26142615

26152616
if (!PyString_Check(name)) {
26162617
PyErr_Format(PyExc_TypeError,
@@ -2632,36 +2633,41 @@ type_getattro(PyTypeObject *type, PyObject *name)
26322633
meta_attribute = _PyType_Lookup(metatype, name);
26332634

26342635
if (meta_attribute != NULL) {
2636+
Py_INCREF(meta_attribute);
26352637
meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
26362638

26372639
if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
26382640
/* Data descriptors implement tp_descr_set to intercept
26392641
* writes. Assume the attribute is not overridden in
26402642
* type's tp_dict (and bases): call the descriptor now.
26412643
*/
2642-
return meta_get(meta_attribute, (PyObject *)type,
2643-
(PyObject *)metatype);
2644+
res = meta_get(meta_attribute, (PyObject *)type,
2645+
(PyObject *)metatype);
2646+
Py_DECREF(meta_attribute);
2647+
return res;
26442648
}
2645-
Py_INCREF(meta_attribute);
26462649
}
26472650

26482651
/* No data descriptor found on metatype. Look in tp_dict of this
26492652
* type and its bases */
26502653
attribute = _PyType_Lookup(type, name);
26512654
if (attribute != NULL) {
26522655
/* Implement descriptor functionality, if any */
2653-
descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
2656+
descrgetfunc local_get;
2657+
Py_INCREF(attribute);
2658+
local_get = Py_TYPE(attribute)->tp_descr_get;
26542659

26552660
Py_XDECREF(meta_attribute);
26562661

26572662
if (local_get != NULL) {
26582663
/* NULL 2nd argument indicates the descriptor was
26592664
* found on the target object itself (or a base) */
2660-
return local_get(attribute, (PyObject *)NULL,
2661-
(PyObject *)type);
2665+
res = local_get(attribute, (PyObject *)NULL,
2666+
(PyObject *)type);
2667+
Py_DECREF(attribute);
2668+
return res;
26622669
}
26632670

2664-
Py_INCREF(attribute);
26652671
return attribute;
26662672
}
26672673

0 commit comments

Comments
 (0)