Skip to content

Commit d28bb62

Browse files
Issue #24097: Fixed crash in object.__reduce__() if slot name is freed inside
__getattr__. Original patch by Antoine Pitrou.
1 parent 33e7ea5 commit d28bb62

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

Lib/test/test_descr.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4988,6 +4988,23 @@ def __repr__(self):
49884988
objcopy2 = deepcopy(objcopy)
49894989
self._assert_is_copy(obj, objcopy2)
49904990

4991+
def test_issue24097(self):
4992+
# Slot name is freed inside __getattr__ and is later used.
4993+
class S(str): # Not interned
4994+
pass
4995+
class A:
4996+
__slotnames__ = [S('spam')]
4997+
def __getattr__(self, attr):
4998+
if attr == 'spam':
4999+
A.__slotnames__[:] = [S('spam')]
5000+
return 42
5001+
else:
5002+
raise AttributeError
5003+
5004+
import copyreg
5005+
expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None)
5006+
self.assertEqual(A().__reduce__(2), expected) # Shouldn't crash
5007+
49915008

49925009
class SharedKeyTests(unittest.TestCase):
49935010

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ Release date: tba
1010
Core and Builtins
1111
-----------------
1212

13+
- Issue #24097: Fixed crash in object.__reduce__() if slot name is freed inside
14+
__getattr__.
15+
1316
- Issue #24731: Fixed crash on converting objects with special methods
1417
__bytes__, __trunc__, and __float__ returning instances of subclasses of
1518
bytes, int, and float to subclasses of bytes, int, and float correspondingly.

Objects/typeobject.c

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3768,8 +3768,10 @@ _PyObject_GetState(PyObject *obj)
37683768
PyObject *name, *value;
37693769

37703770
name = PyList_GET_ITEM(slotnames, i);
3771+
Py_INCREF(name);
37713772
value = PyObject_GetAttr(obj, name);
37723773
if (value == NULL) {
3774+
Py_DECREF(name);
37733775
if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
37743776
goto error;
37753777
}
@@ -3778,6 +3780,7 @@ _PyObject_GetState(PyObject *obj)
37783780
}
37793781
else {
37803782
int err = PyDict_SetItem(slots, name, value);
3783+
Py_DECREF(name);
37813784
Py_DECREF(value);
37823785
if (err) {
37833786
goto error;

0 commit comments

Comments
 (0)