Skip to content

Commit 813827b

Browse files
committed
gh-162644: Fix infinite recursion when pickling a weakref.ref subclass with protocol 0 or 1
The pickler now raises TypeError when the weak save of an object leads straight back to a weak save of the same object and nothing has been memoized in between.
1 parent 3b30937 commit 813827b

5 files changed

Lines changed: 118 additions & 4 deletions

File tree

‎Lib/pickle.py‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -489,6 +489,9 @@ def __init__(self, file, protocol=None, *, fix_imports=True,
489489
# Ids of objects reached so far only through weak references; any
490490
# left at the end of dump() is an error. See save_weakref.
491491
self._weak_only = set()
492+
# The id of the referent and the size of the memo at the start of
493+
# the innermost weak save in progress, or None. See save_weakref.
494+
self._weak_saving = None
492495
self.proto = int(protocol)
493496
self.bin = protocol >= 1
494497
self.fast = 0
@@ -1306,7 +1309,26 @@ def save_weakref(self, obj):
13061309
# Build the 1-tuple (referent,); TUPLE1 needs protocol 2.
13071310
if self.proto < 2:
13081311
write(MARK)
1309-
save(referent, weak=True)
1312+
if anchored or self.fast:
1313+
save(referent, weak=True)
1314+
else:
1315+
# The referent is not in the memo yet. If the innermost weak save
1316+
# in progress is a save of this same referent and nothing has been
1317+
# memoized since it started, saving the referent again would
1318+
# repeat the same steps without end: its reduce arguments contain
1319+
# a weak reference to it, as for an instance of a weakref.ref
1320+
# subclass reduced by copyreg._reduce_ex(). This relies on an
1321+
# object being reduced the same way each time. Fast mode does
1322+
# not support self-referential objects in any case.
1323+
saving = id(referent), len(self.memo)
1324+
if saving == self._weak_saving:
1325+
raise TypeError(
1326+
f"cannot pickle {type(referent).__name__!r} object")
1327+
outer, self._weak_saving = self._weak_saving, saving
1328+
try:
1329+
save(referent, weak=True)
1330+
finally:
1331+
self._weak_saving = outer
13101332
if not anchored and id(referent) in self.memo:
13111333
self._weak_only.add(id(referent))
13121334
write(TUPLE1 if self.proto >= 2 else TUPLE)

‎Lib/test/pickletester.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1817,6 +1817,10 @@ class WeakrefTarget:
18171817
__hash__ = None
18181818

18191819

1820+
class WeakrefSubclass(weakref.ref):
1821+
pass
1822+
1823+
18201824
class AbstractPicklingErrorTests:
18211825
# Subclass must define self.dumps, self.pickler.
18221826

@@ -1829,6 +1833,31 @@ def test_unpicklable_weakref_referent(self):
18291833
with self.subTest(proto=proto):
18301834
self.assertRaises(pickle.PicklingError, self.dumps, wr, proto)
18311835

1836+
def test_weakref_subclass(self):
1837+
# With protocols 0 and 1 the reduce arguments of the instance contain
1838+
# a weak reference to the instance itself.
1839+
obj = WeakrefTarget()
1840+
wr = WeakrefSubclass(obj)
1841+
msg = "cannot pickle 'WeakrefSubclass' object"
1842+
for proto in protocols:
1843+
with self.subTest(proto=proto):
1844+
with self.assertRaisesRegex(TypeError, msg):
1845+
self.dumps([obj, wr], proto)
1846+
with self.assertRaisesRegex(TypeError, msg):
1847+
self.dumps([obj, weakref.ref(wr), wr], proto)
1848+
1849+
def test_weakref_to_self_in_reduce_args(self):
1850+
# The object cannot be created without a weak reference to itself.
1851+
obj = K(None)
1852+
obj.value = weakref.ref(obj)
1853+
msg = "cannot pickle 'K' object"
1854+
for proto in protocols:
1855+
with self.subTest(proto=proto):
1856+
with self.assertRaisesRegex(TypeError, msg):
1857+
self.dumps(obj, proto)
1858+
with self.assertRaisesRegex(TypeError, msg):
1859+
self.dumps([obj.value, obj], proto)
1860+
18321861
def test_weakref_without_strong_ref(self):
18331862
# The error names the distinct referent types: bounded however many
18341863
# referents there are, and not requiring them to be hashable.
@@ -3651,6 +3680,27 @@ def test_weakref(self):
36513680
wr2, obj2 = self.loads(self.dumps([wr, obj], proto))
36523681
self.assertIs(wr2(), obj2)
36533682

3683+
def test_weakref_in_reduce_args(self):
3684+
if self.py_version < (3, 16):
3685+
self.skipTest('not supported in Python < 3.16')
3686+
# The object is created from a list containing a weak reference to
3687+
# the object.
3688+
value = []
3689+
obj = K(value)
3690+
wr = weakref.ref(obj)
3691+
value.append(wr)
3692+
for proto in protocols:
3693+
with self.subTest(proto=proto):
3694+
obj2, wr2 = self.loads(self.dumps([obj, wr], proto))
3695+
self.assertIsInstance(obj2, K)
3696+
self.assertIs(wr2(), obj2)
3697+
self.assertIs(obj2.value[0], wr2)
3698+
# Identity holds regardless of pickling order.
3699+
wr2, obj2 = self.loads(self.dumps([wr, obj], proto))
3700+
self.assertIsInstance(obj2, K)
3701+
self.assertIs(wr2(), obj2)
3702+
self.assertIs(obj2.value[0], wr2)
3703+
36543704
def test_weakref_callback(self):
36553705
if self.py_version < (3, 16):
36563706
self.skipTest('not supported in Python < 3.16')

‎Lib/test/test_pickle.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -558,7 +558,7 @@ class SizeofTests(unittest.TestCase):
558558
check_sizeof = support.check_sizeof
559559

560560
def test_pickler(self):
561-
basesize = support.calcobjsize('7P2n3i2n4i2P1n')
561+
basesize = support.calcobjsize('7P2n3i2n4i2P1nPn')
562562
p = _pickle.Pickler(io.BytesIO())
563563
self.assertEqual(object.__sizeof__(p), basesize)
564564
MT_size = struct.calcsize('3nP0n')
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Fix infinite recursion when pickling an instance of a :class:`weakref.ref`
2+
subclass with protocol 0 or 1 if the subclass does not define its own
3+
reduction method. :exc:`TypeError` is raised again instead of
4+
:exc:`RecursionError`. In most cases this also applies to other objects that
5+
cannot be created without a weak reference to themselves.

‎Modules/_pickle.c‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -658,6 +658,11 @@ typedef struct PicklerObject {
658658
Py_ssize_t weak_only_count; /* Number of memo entries flagged weak-only;
659659
any left at the end of dump() are pickling
660660
errors. */
661+
PyObject *weak_referent; /* Referent of the innermost weak save in
662+
progress, or NULL. Borrowed and only
663+
compared by identity; save_weakref() holds
664+
a reference while it is set. */
665+
Py_ssize_t weak_memo_size; /* Size of the memo when that save started. */
661666
} PicklerObject;
662667

663668
typedef struct UnpicklerObject {
@@ -1184,6 +1189,8 @@ _Pickler_New(PickleState *st)
11841189
self->fast_memo = NULL;
11851190
self->buffer_callback = NULL;
11861191
self->weak_only_count = 0;
1192+
self->weak_referent = NULL;
1193+
self->weak_memo_size = 0;
11871194

11881195
PyObject_GC_Track(self);
11891196
return self;
@@ -4699,8 +4706,38 @@ save_weakref(PickleState *st, PicklerObject *self, PyObject *obj)
46994706
if (self->proto < 2 && _Pickler_Write(self, &mark_op, 1) < 0)
47004707
goto done;
47014708

4702-
if (save_object(st, self, referent, 0, 1) < 0)
4703-
goto done;
4709+
if (anchored || self->fast) {
4710+
if (save_object(st, self, referent, 0, 1) < 0)
4711+
goto done;
4712+
}
4713+
else {
4714+
/* The referent is not in the memo yet. If the innermost weak save in
4715+
progress is a save of this same referent and nothing has been
4716+
memoized since it started, saving the referent again would repeat
4717+
the same steps without end: its reduce arguments contain a weak
4718+
reference to it, as for an instance of a weakref.ref subclass
4719+
reduced by copyreg._reduce_ex(). This relies on an object being
4720+
reduced the same way each time. Fast mode does not support
4721+
self-referential objects in any case. */
4722+
Py_ssize_t memo_size = PyMemoTable_Size(self->memo);
4723+
if (self->weak_referent == referent &&
4724+
self->weak_memo_size == memo_size)
4725+
{
4726+
PyErr_Format(PyExc_TypeError,
4727+
"cannot pickle '%.200s' object",
4728+
Py_TYPE(referent)->tp_name);
4729+
goto done;
4730+
}
4731+
PyObject *outer_referent = self->weak_referent;
4732+
Py_ssize_t outer_memo_size = self->weak_memo_size;
4733+
self->weak_referent = referent;
4734+
self->weak_memo_size = memo_size;
4735+
int res = save_object(st, self, referent, 0, 1);
4736+
self->weak_referent = outer_referent;
4737+
self->weak_memo_size = outer_memo_size;
4738+
if (res < 0)
4739+
goto done;
4740+
}
47044741

47054742
if (!anchored) {
47064743
Py_ssize_t *value = PyMemoTable_Get(self->memo, referent);

0 commit comments

Comments
 (0)