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
7 changes: 4 additions & 3 deletions msgpack/_packer.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,11 @@ cdef class Packer:
raise TypeError("default must be a callable.")
self._default = default

# Clear the borrowed pointer before replacing its owner so a failed
# conversion below cannot leave it pointing at a freed object.
self.unicode_errors = NULL
self._berrors = unicode_errors
if unicode_errors is None:
self.unicode_errors = NULL
else:
if unicode_errors is not None:
self.unicode_errors = self._berrors

# returns -2 when default should(o) be called
Expand Down
5 changes: 5 additions & 0 deletions msgpack/_unpacker.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,11 @@ cdef class Unpacker:
if self.buf != NULL:
PyMem_Free(self.buf)
self.buf = NULL
self.buf_size = self.buf_head = self.buf_tail = 0
# ctx.user borrows the objects below. Drop those pointers before the
# attributes are replaced so a failed __init__ cannot leave them dangling.
self.ctx.user.object_hook = self.ctx.user.list_hook = self.ctx.user.ext_hook = <PyObject*>NULL
self.ctx.user.unicode_errors = NULL

self.object_hook = object_hook
self.object_pairs_hook = object_pairs_hook
Expand Down
14 changes: 14 additions & 0 deletions test/test_pack.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,3 +220,17 @@ def __int__(self):
buf_size = Counting()
Packer(buf_size=buf_size)
assert buf_size.count == 1


@pytest.mark.skipif(
Packer.__module__ == "msgpack.fallback",
reason="unicode_errors is converted to char* only in the C extension",
)
def test_failed_reinit_drops_old_unicode_errors():
packer = Packer(unicode_errors="".join(["surrogate", "escape"]))
# The old error handler name is released before the new one fails to convert.
with pytest.raises(TypeError):
packer.__init__(unicode_errors=1)
assert packer.pack("abc") == packb("abc")
with pytest.raises(UnicodeEncodeError):
packer.pack("abc\udcff")
14 changes: 14 additions & 0 deletions test/test_unpack.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,17 @@ def test_unpack_raises_extra_data_on_stream_with_trailing_bytes():
unpack(stream)
assert exc_info.value.unpacked == 100
assert exc_info.value.extra == packb(200)


@mark.skipif(
Unpacker.__module__ == "msgpack.fallback",
reason="specific to C extension reinit",
)
def test_unpacker_failed_reinit_drops_old_hooks():
unpacker = Unpacker(object_hook=lambda d: "hook")
# unicode_errors is converted after the old object_hook was released.
with raises(TypeError):
unpacker.__init__(unicode_errors=1)
gc.collect()
unpacker.feed(b"\x80")
assert unpacker.unpack() == {}
Loading