Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion Lib/pickle.py
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,9 @@ def __init__(self, file, protocol=None, *, fix_imports=True,
# Ids of objects reached so far only through weak references; any
# left at the end of dump() is an error. See save_weakref.
self._weak_only = set()
# The id of the referent and the size of the memo at the start of
# the innermost weak save in progress, or None. See save_weakref.
self._weak_saving = None
self.proto = int(protocol)
self.bin = protocol >= 1
self.fast = 0
Expand Down Expand Up @@ -1306,7 +1309,26 @@ def save_weakref(self, obj):
# Build the 1-tuple (referent,); TUPLE1 needs protocol 2.
if self.proto < 2:
write(MARK)
save(referent, weak=True)
if anchored or self.fast:
save(referent, weak=True)
else:
# The referent is not in the memo yet. If the innermost weak save
# in progress is a save of this same referent and nothing has been
# memoized since it started, saving the referent again would
# repeat the same steps without end: its reduce arguments contain
# a weak reference to it, as for an instance of a weakref.ref
# subclass reduced by copyreg._reduce_ex(). This relies on an
# object being reduced the same way each time. Fast mode does
# not support self-referential objects in any case.
saving = id(referent), len(self.memo)
if saving == self._weak_saving:
raise TypeError(
f"cannot pickle {type(referent).__name__!r} object")
outer, self._weak_saving = self._weak_saving, saving
try:
save(referent, weak=True)
finally:
self._weak_saving = outer
if not anchored and id(referent) in self.memo:
self._weak_only.add(id(referent))
write(TUPLE1 if self.proto >= 2 else TUPLE)
Expand Down
50 changes: 50 additions & 0 deletions Lib/test/pickletester.py
Original file line number Diff line number Diff line change
Expand Up @@ -1817,6 +1817,10 @@ class WeakrefTarget:
__hash__ = None


class WeakrefSubclass(weakref.ref):
pass


class AbstractPicklingErrorTests:
# Subclass must define self.dumps, self.pickler.

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

def test_weakref_subclass(self):
# With protocols 0 and 1 the reduce arguments of the instance contain
# a weak reference to the instance itself.
obj = WeakrefTarget()
wr = WeakrefSubclass(obj)
msg = "cannot pickle 'WeakrefSubclass' object"
for proto in protocols:
with self.subTest(proto=proto):
with self.assertRaisesRegex(TypeError, msg):
self.dumps([obj, wr], proto)
with self.assertRaisesRegex(TypeError, msg):
self.dumps([obj, weakref.ref(wr), wr], proto)

def test_weakref_to_self_in_reduce_args(self):
# The object cannot be created without a weak reference to itself.
obj = K(None)
obj.value = weakref.ref(obj)
msg = "cannot pickle 'K' object"
for proto in protocols:
with self.subTest(proto=proto):
with self.assertRaisesRegex(TypeError, msg):
self.dumps(obj, proto)
with self.assertRaisesRegex(TypeError, msg):
self.dumps([obj.value, obj], proto)

def test_weakref_without_strong_ref(self):
# The error names the distinct referent types: bounded however many
# referents there are, and not requiring them to be hashable.
Expand Down Expand Up @@ -3651,6 +3680,27 @@ def test_weakref(self):
wr2, obj2 = self.loads(self.dumps([wr, obj], proto))
self.assertIs(wr2(), obj2)

def test_weakref_in_reduce_args(self):
if self.py_version < (3, 16):
self.skipTest('not supported in Python < 3.16')
# The object is created from a list containing a weak reference to
# the object.
value = []
obj = K(value)
wr = weakref.ref(obj)
value.append(wr)
for proto in protocols:
with self.subTest(proto=proto):
obj2, wr2 = self.loads(self.dumps([obj, wr], proto))
self.assertIsInstance(obj2, K)
self.assertIs(wr2(), obj2)
self.assertIs(obj2.value[0], wr2)
# Identity holds regardless of pickling order.
wr2, obj2 = self.loads(self.dumps([wr, obj], proto))
self.assertIsInstance(obj2, K)
self.assertIs(wr2(), obj2)
self.assertIs(obj2.value[0], wr2)

def test_weakref_callback(self):
if self.py_version < (3, 16):
self.skipTest('not supported in Python < 3.16')
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_pickle.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,7 @@ class SizeofTests(unittest.TestCase):
check_sizeof = support.check_sizeof

def test_pickler(self):
basesize = support.calcobjsize('7P2n3i2n4i2P1n')
basesize = support.calcobjsize('7P2n3i2n4i2P1nPn')
p = _pickle.Pickler(io.BytesIO())
self.assertEqual(object.__sizeof__(p), basesize)
MT_size = struct.calcsize('3nP0n')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Fix infinite recursion when pickling an instance of a :class:`weakref.ref`
subclass with protocol 0 or 1 if the subclass does not define its own
reduction method. :exc:`TypeError` is raised again instead of
:exc:`RecursionError`. In most cases this also applies to other objects that
cannot be created without a weak reference to themselves.
41 changes: 39 additions & 2 deletions Modules/_pickle.c
Original file line number Diff line number Diff line change
Expand Up @@ -658,6 +658,11 @@ typedef struct PicklerObject {
Py_ssize_t weak_only_count; /* Number of memo entries flagged weak-only;
any left at the end of dump() are pickling
errors. */
PyObject *weak_referent; /* Referent of the innermost weak save in
progress, or NULL. Borrowed and only
compared by identity; save_weakref() holds
a reference while it is set. */
Py_ssize_t weak_memo_size; /* Size of the memo when that save started. */
} PicklerObject;

typedef struct UnpicklerObject {
Expand Down Expand Up @@ -1184,6 +1189,8 @@ _Pickler_New(PickleState *st)
self->fast_memo = NULL;
self->buffer_callback = NULL;
self->weak_only_count = 0;
self->weak_referent = NULL;
self->weak_memo_size = 0;

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

if (save_object(st, self, referent, 0, 1) < 0)
goto done;
if (anchored || self->fast) {
if (save_object(st, self, referent, 0, 1) < 0)
goto done;
}
else {
/* The referent is not in the memo yet. If the innermost weak save in
progress is a save of this same referent and nothing has been
memoized since it started, saving the referent again would repeat
the same steps without end: its reduce arguments contain a weak
reference to it, as for an instance of a weakref.ref subclass
reduced by copyreg._reduce_ex(). This relies on an object being
reduced the same way each time. Fast mode does not support
self-referential objects in any case. */
Py_ssize_t memo_size = PyMemoTable_Size(self->memo);
if (self->weak_referent == referent &&
self->weak_memo_size == memo_size)
{
PyErr_Format(PyExc_TypeError,
"cannot pickle '%.200s' object",
Py_TYPE(referent)->tp_name);
goto done;
}
PyObject *outer_referent = self->weak_referent;
Py_ssize_t outer_memo_size = self->weak_memo_size;
self->weak_referent = referent;
self->weak_memo_size = memo_size;
int res = save_object(st, self, referent, 0, 1);
self->weak_referent = outer_referent;
self->weak_memo_size = outer_memo_size;
if (res < 0)
goto done;
}

if (!anchored) {
Py_ssize_t *value = PyMemoTable_Get(self->memo, referent);
Expand Down
Loading