From e861f75374b023c9a6b35451757d23e713ec4068 Mon Sep 17 00:00:00 2001 From: Thomas Kowalski Date: Tue, 2 Jun 2026 17:21:59 +0200 Subject: [PATCH] fix: use-after-free in `get_data_from_buffer` (#677) --- msgpack/_unpacker.pyx | 7 +++---- msgpack/fallback.py | 2 +- test/test_memoryview.py | 12 ++++++++++++ 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/msgpack/_unpacker.pyx b/msgpack/_unpacker.pyx index 29cdec4..40d1229 100644 --- a/msgpack/_unpacker.pyx +++ b/msgpack/_unpacker.pyx @@ -129,10 +129,9 @@ cdef inline int get_data_from_buffer(object obj, PyBuffer_Release(view) # create a contiguous copy and get buffer contiguous = PyMemoryView_GetContiguous(obj, PyBUF_READ, b'C') - PyObject_GetBuffer(contiguous, view, PyBUF_SIMPLE) - # view must hold the only reference to contiguous, - # so memory is freed when view is released - Py_DECREF(contiguous) + if PyObject_GetBuffer(contiguous, view, PyBUF_SIMPLE) == -1: + raise + buffer_len[0] = view.len buf[0] = view.buf return 1 diff --git a/msgpack/fallback.py b/msgpack/fallback.py index 61d77db..860d94a 100644 --- a/msgpack/fallback.py +++ b/msgpack/fallback.py @@ -328,7 +328,7 @@ class Unpacker: self._buf_checkpoint = 0 # Use extend here: INPLACE_ADD += doesn't reliably typecast memoryview in jython - self._buffer.extend(view) + self._buffer.extend(view if view.contiguous else view.tobytes()) view.release() def _consume(self): diff --git a/test/test_memoryview.py b/test/test_memoryview.py index 0a2a6f5..3f6a39d 100644 --- a/test/test_memoryview.py +++ b/test/test_memoryview.py @@ -97,3 +97,15 @@ def test_multidim_memoryview(): data = view.cast(view.format, (3, 2)) packed = packb(data) assert packed == b"\xc4\x06\x00\x00\x00\x00\x00\x00" + + +def test_unpack_noncontiguous_memoryview(): + # Use a multi-byte value so the padded stride-2 view is non-contiguous. + packed = packb(2**32) + padded = bytearray() + for byte in packed: + padded.append(byte) + padded.append(0) + noncont = memoryview(bytes(padded))[::2] + assert not noncont.c_contiguous + assert unpackb(noncont) == 2**32