Skip to content

Commit 243db4d

Browse files
committed
gh-142665: fix UAF when accessing a memoryview concurrently mutates the underlying buffer
1 parent 7f6c16a commit 243db4d

File tree

3 files changed

+13
-3
lines changed

3 files changed

+13
-3
lines changed

Lib/test/test_memoryview.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -685,13 +685,17 @@ def __bool__(self):
685685
with self.assertRaises(ValueError):
686686
m[MyIndex()]
687687

688+
# Other exceptions can be raised when working on a released buffer.
689+
# See https://github.com/python/cpython/issues/142665.
688690
ba = None
689691
m = memoryview(bytearray(b'\xff'*size))
690-
self.assertEqual(list(m[:MyIndex()]), [255] * 4)
692+
with self.assertRaises(BufferError):
693+
m[:MyIndex()]
691694

692695
ba = None
693696
m = memoryview(bytearray(b'\xff'*size))
694-
self.assertEqual(list(m[MyIndex():8]), [255] * 4)
697+
with self.assertRaises(BufferError):
698+
m[MyIndex():8]
695699

696700
ba = None
697701
m = memoryview(bytearray(b'\xff'*size)).cast('B', (64, 2))
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix use-after-free crashes when slicing a :class:`memoryview` or
2+
accessing the elements of a sliced view concurrently mutates the
3+
underlying buffer. Patch by Bénédikt Tran.

Objects/memoryobject.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2623,7 +2623,10 @@ memory_subscript(PyObject *_self, PyObject *key)
26232623
if (sliced == NULL)
26242624
return NULL;
26252625

2626-
if (init_slice(&sliced->view, key, 0) < 0) {
2626+
self->exports++;
2627+
int rc = init_slice(&sliced->view, key, 0);
2628+
self->exports--;
2629+
if (rc < 0) {
26272630
Py_DECREF(sliced);
26282631
return NULL;
26292632
}

0 commit comments

Comments
 (0)