gh-142665: fix UAF when accessing a memoryview concurrently mutates the underlying buffer

This commit is contained in:
Bénédikt Tran 2026-01-01 12:40:57 +01:00
parent 7f6c16a956
commit 243db4d01a
3 changed files with 13 additions and 3 deletions

View file

@ -685,13 +685,17 @@ def __bool__(self):
with self.assertRaises(ValueError):
m[MyIndex()]
# Other exceptions can be raised when working on a released buffer.
# See https://github.com/python/cpython/issues/142665.
ba = None
m = memoryview(bytearray(b'\xff'*size))
self.assertEqual(list(m[:MyIndex()]), [255] * 4)
with self.assertRaises(BufferError):
m[:MyIndex()]
ba = None
m = memoryview(bytearray(b'\xff'*size))
self.assertEqual(list(m[MyIndex():8]), [255] * 4)
with self.assertRaises(BufferError):
m[MyIndex():8]
ba = None
m = memoryview(bytearray(b'\xff'*size)).cast('B', (64, 2))

View file

@ -0,0 +1,3 @@
Fix use-after-free crashes when slicing a :class:`memoryview` or
accessing the elements of a sliced view concurrently mutates the
underlying buffer. Patch by Bénédikt Tran.

View file

@ -2623,7 +2623,10 @@ memory_subscript(PyObject *_self, PyObject *key)
if (sliced == NULL)
return NULL;
if (init_slice(&sliced->view, key, 0) < 0) {
self->exports++;
int rc = init_slice(&sliced->view, key, 0);
self->exports--;
if (rc < 0) {
Py_DECREF(sliced);
return NULL;
}