Skip to content

Commit 3ee0743

Browse files
miss-islingtonjdemeyer
authored andcommitted
bpo-25750: fix refcounts in type_getattro() (GH-6118) (GH-9088)
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 1a3eb12 commit 3ee0743

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
@@ -3004,6 +3004,7 @@ type_getattro(PyTypeObject *type, PyObject *name)
30043004
PyTypeObject *metatype = Py_TYPE(type);
30053005
PyObject *meta_attribute, *attribute;
30063006
descrgetfunc meta_get;
3007+
PyObject* res;
30073008

30083009
if (!PyUnicode_Check(name)) {
30093010
PyErr_Format(PyExc_TypeError,
@@ -3025,36 +3026,40 @@ type_getattro(PyTypeObject *type, PyObject *name)
30253026
meta_attribute = _PyType_Lookup(metatype, name);
30263027

30273028
if (meta_attribute != NULL) {
3029+
Py_INCREF(meta_attribute);
30283030
meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
30293031

30303032
if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
30313033
/* Data descriptors implement tp_descr_set to intercept
30323034
* writes. Assume the attribute is not overridden in
30333035
* type's tp_dict (and bases): call the descriptor now.
30343036
*/
3035-
return meta_get(meta_attribute, (PyObject *)type,
3036-
(PyObject *)metatype);
3037+
res = meta_get(meta_attribute, (PyObject *)type,
3038+
(PyObject *)metatype);
3039+
Py_DECREF(meta_attribute);
3040+
return res;
30373041
}
3038-
Py_INCREF(meta_attribute);
30393042
}
30403043

30413044
/* No data descriptor found on metatype. Look in tp_dict of this
30423045
* type and its bases */
30433046
attribute = _PyType_Lookup(type, name);
30443047
if (attribute != NULL) {
30453048
/* Implement descriptor functionality, if any */
3049+
Py_INCREF(attribute);
30463050
descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
30473051

30483052
Py_XDECREF(meta_attribute);
30493053

30503054
if (local_get != NULL) {
30513055
/* NULL 2nd argument indicates the descriptor was
30523056
* found on the target object itself (or a base) */
3053-
return local_get(attribute, (PyObject *)NULL,
3054-
(PyObject *)type);
3057+
res = local_get(attribute, (PyObject *)NULL,
3058+
(PyObject *)type);
3059+
Py_DECREF(attribute);
3060+
return res;
30553061
}
30563062

3057-
Py_INCREF(attribute);
30583063
return attribute;
30593064
}
30603065

0 commit comments

Comments
 (0)