Skip to content

Commit f862f3a

Browse files
bpo-25750: fix refcounts in type_getattro() (GH-6118)
When calling tp_descr_get(self, obj, type), make sure that we own a strong reference to "self". (cherry picked from commit 8f73548) Co-authored-by: jdemeyer <[email protected]>
1 parent 2d3f2dc commit f862f3a

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
@@ -3145,6 +3145,7 @@ type_getattro(PyTypeObject *type, PyObject *name)
31453145
PyTypeObject *metatype = Py_TYPE(type);
31463146
PyObject *meta_attribute, *attribute;
31473147
descrgetfunc meta_get;
3148+
PyObject* res;
31483149

31493150
if (!PyUnicode_Check(name)) {
31503151
PyErr_Format(PyExc_TypeError,
@@ -3166,36 +3167,40 @@ type_getattro(PyTypeObject *type, PyObject *name)
31663167
meta_attribute = _PyType_Lookup(metatype, name);
31673168

31683169
if (meta_attribute != NULL) {
3170+
Py_INCREF(meta_attribute);
31693171
meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
31703172

31713173
if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
31723174
/* Data descriptors implement tp_descr_set to intercept
31733175
* writes. Assume the attribute is not overridden in
31743176
* type's tp_dict (and bases): call the descriptor now.
31753177
*/
3176-
return meta_get(meta_attribute, (PyObject *)type,
3177-
(PyObject *)metatype);
3178+
res = meta_get(meta_attribute, (PyObject *)type,
3179+
(PyObject *)metatype);
3180+
Py_DECREF(meta_attribute);
3181+
return res;
31783182
}
3179-
Py_INCREF(meta_attribute);
31803183
}
31813184

31823185
/* No data descriptor found on metatype. Look in tp_dict of this
31833186
* type and its bases */
31843187
attribute = _PyType_Lookup(type, name);
31853188
if (attribute != NULL) {
31863189
/* Implement descriptor functionality, if any */
3190+
Py_INCREF(attribute);
31873191
descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
31883192

31893193
Py_XDECREF(meta_attribute);
31903194

31913195
if (local_get != NULL) {
31923196
/* NULL 2nd argument indicates the descriptor was
31933197
* found on the target object itself (or a base) */
3194-
return local_get(attribute, (PyObject *)NULL,
3195-
(PyObject *)type);
3198+
res = local_get(attribute, (PyObject *)NULL,
3199+
(PyObject *)type);
3200+
Py_DECREF(attribute);
3201+
return res;
31963202
}
31973203

3198-
Py_INCREF(attribute);
31993204
return attribute;
32003205
}
32013206

0 commit comments

Comments
 (0)