File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -143,10 +143,11 @@ cdef class Packer:
143143 raise TypeError (" default must be a callable." )
144144 self ._default = default
145145
146+ # Clear the borrowed pointer before replacing its owner so a failed
147+ # conversion below cannot leave it pointing at a freed object.
148+ self .unicode_errors = NULL
146149 self ._berrors = unicode_errors
147- if unicode_errors is None :
148- self .unicode_errors = NULL
149- else :
150+ if unicode_errors is not None :
150151 self .unicode_errors = self ._berrors
151152
152153 # returns -2 when default should(o) be called
Original file line number Diff line number Diff line change @@ -353,6 +353,11 @@ cdef class Unpacker:
353353 if self .buf != NULL :
354354 PyMem_Free(self .buf)
355355 self .buf = NULL
356+ self .buf_size = self .buf_head = self .buf_tail = 0
357+ # ctx.user borrows the objects below. Drop those pointers before the
358+ # attributes are replaced so a failed __init__ cannot leave them dangling.
359+ self .ctx.user.object_hook = self .ctx.user.list_hook = self .ctx.user.ext_hook = < PyObject* > NULL
360+ self .ctx.user.unicode_errors = NULL
356361
357362 self .object_hook = object_hook
358363 self .object_pairs_hook = object_pairs_hook
Original file line number Diff line number Diff line change @@ -220,3 +220,17 @@ def __int__(self):
220220 buf_size = Counting ()
221221 Packer (buf_size = buf_size )
222222 assert buf_size .count == 1
223+
224+
225+ @pytest .mark .skipif (
226+ Packer .__module__ == "msgpack.fallback" ,
227+ reason = "unicode_errors is converted to char* only in the C extension" ,
228+ )
229+ def test_failed_reinit_drops_old_unicode_errors ():
230+ packer = Packer (unicode_errors = "" .join (["surrogate" , "escape" ]))
231+ # The old error handler name is released before the new one fails to convert.
232+ with pytest .raises (TypeError ):
233+ packer .__init__ (unicode_errors = 1 )
234+ assert packer .pack ("abc" ) == packb ("abc" )
235+ with pytest .raises (UnicodeEncodeError ):
236+ packer .pack ("abc\udcff " )
Original file line number Diff line number Diff line change @@ -185,3 +185,17 @@ def test_unpack_raises_extra_data_on_stream_with_trailing_bytes():
185185 unpack (stream )
186186 assert exc_info .value .unpacked == 100
187187 assert exc_info .value .extra == packb (200 )
188+
189+
190+ @mark .skipif (
191+ Unpacker .__module__ == "msgpack.fallback" ,
192+ reason = "specific to C extension reinit" ,
193+ )
194+ def test_unpacker_failed_reinit_drops_old_hooks ():
195+ unpacker = Unpacker (object_hook = lambda d : "hook" )
196+ # unicode_errors is converted after the old object_hook was released.
197+ with raises (TypeError ):
198+ unpacker .__init__ (unicode_errors = 1 )
199+ gc .collect ()
200+ unpacker .feed (b"\x80 " )
201+ assert unpacker .unpack () == {}
You can’t perform that action at this time.
0 commit comments