Skip to content

Commit 16e1807

Browse files
committed
bpo-25750: fix refcounts in type_getattro()
When calling tp_descr_get(self, obj, type), make sure that we own a reference to "self"
1 parent 09bb918 commit 16e1807

File tree

2 files changed

+13
-6
lines changed

2 files changed

+13
-6
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: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3137,6 +3137,7 @@ type_getattro(PyTypeObject *type, PyObject *name)
31373137
PyTypeObject *metatype = Py_TYPE(type);
31383138
PyObject *meta_attribute, *attribute;
31393139
descrgetfunc meta_get;
3140+
PyObject* res;
31403141

31413142
if (!PyUnicode_Check(name)) {
31423143
PyErr_Format(PyExc_TypeError,
@@ -3158,36 +3159,40 @@ type_getattro(PyTypeObject *type, PyObject *name)
31583159
meta_attribute = _PyType_Lookup(metatype, name);
31593160

31603161
if (meta_attribute != NULL) {
3162+
Py_INCREF(meta_attribute);
31613163
meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
31623164

31633165
if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
31643166
/* Data descriptors implement tp_descr_set to intercept
31653167
* writes. Assume the attribute is not overridden in
31663168
* type's tp_dict (and bases): call the descriptor now.
31673169
*/
3168-
return meta_get(meta_attribute, (PyObject *)type,
3169-
(PyObject *)metatype);
3170+
res = meta_get(meta_attribute, (PyObject *)type,
3171+
(PyObject *)metatype);
3172+
Py_DECREF(meta_attribute);
3173+
return res;
31703174
}
3171-
Py_INCREF(meta_attribute);
31723175
}
31733176

31743177
/* No data descriptor found on metatype. Look in tp_dict of this
31753178
* type and its bases */
31763179
attribute = _PyType_Lookup(type, name);
31773180
if (attribute != NULL) {
31783181
/* Implement descriptor functionality, if any */
3182+
Py_INCREF(attribute);
31793183
descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
31803184

31813185
Py_XDECREF(meta_attribute);
31823186

31833187
if (local_get != NULL) {
31843188
/* NULL 2nd argument indicates the descriptor was
31853189
* found on the target object itself (or a base) */
3186-
return local_get(attribute, (PyObject *)NULL,
3187-
(PyObject *)type);
3190+
res = local_get(attribute, (PyObject *)NULL,
3191+
(PyObject *)type);
3192+
Py_DECREF(attribute);
3193+
return res;
31883194
}
31893195

3190-
Py_INCREF(attribute);
31913196
return attribute;
31923197
}
31933198

0 commit comments

Comments
 (0)