diff --git a/Lib/test/test_memoryview.py b/Lib/test/test_memoryview.py index 656318668e6d6e..f7b7cf3a8e5e65 100644 --- a/Lib/test/test_memoryview.py +++ b/Lib/test/test_memoryview.py @@ -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)) diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-01-01-12-22-35.gh-issue-142665.7YCUBF.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-01-01-12-22-35.gh-issue-142665.7YCUBF.rst new file mode 100644 index 00000000000000..bf2d7ea20e6c97 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-01-01-12-22-35.gh-issue-142665.7YCUBF.rst @@ -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. diff --git a/Objects/memoryobject.c b/Objects/memoryobject.c index f3b7e4a396b4a1..f703d708148115 100644 --- a/Objects/memoryobject.c +++ b/Objects/memoryobject.c @@ -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; }