Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions Lib/test/test_bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1828,6 +1828,30 @@ def test_setslice_trap(self):
b[8:] = b
self.assertEqual(b, bytearray(list(range(8)) + list(range(256))))

def test_setslice_reentrant_resize(self):
# gh-153578: a buffer argument whose __buffer__ resizes the bytearray
# while the buffer is being acquired must not leave the slice bounds
# with lo > hi, which drove a negative-size memmove (an out-of-bounds
# write) in the setslice path reached through extend().
class Evil:
def __init__(self, resize):
self.resize = resize
def __buffer__(self, flags):
self.resize()
return memoryview(b'ABCDEFGH')
# clear() during __buffer__: extend appends to the emptied bytearray.
b = bytearray(b'x' * 100)
b.extend(Evil(b.clear))
self.assertEqual(b, b'ABCDEFGH')
# partial shrink during __buffer__.
b = bytearray(b'x' * 100)
b.extend(Evil(lambda: b.__delitem__(slice(30, None))))
self.assertEqual(b, b'x' * 30 + b'ABCDEFGH')
# grow during __buffer__: the data lands at the original end.
b = bytearray(b'x' * 10)
b.extend(Evil(lambda: b.extend(b'y' * 100)))
self.assertEqual(b, b'x' * 10 + b'ABCDEFGH' + b'y' * 100)

def test_iconcat(self):
b = bytearray(b"abc")
b1 = b
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix an out-of-bounds write in :meth:`bytearray.extend` when the bytearray is
resized while the argument's :meth:`~object.__buffer__` is being acquired, for
example by another thread. Patch by tonghuaroot.
3 changes: 3 additions & 0 deletions Objects/bytearrayobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -681,8 +681,11 @@ bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
bytes = vbytes.buf;
}

// gh-153578: __buffer__() may have resized self; re-clamp both bounds.
if (lo < 0)
lo = 0;
else if (lo > Py_SIZE(self))
lo = Py_SIZE(self);
if (hi < lo)
hi = lo;
if (hi > Py_SIZE(self))
Expand Down
Loading