Skip to content

[3.8] bpo-42924: Fix incorrect copy in bytearray_repeat (GH-24208) #24212

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 26, 2021
Merged
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
10 changes: 10 additions & 0 deletions Lib/test/test_bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1592,6 +1592,16 @@ def test_iterator_length_hint(self):
# Shouldn't raise an error
self.assertEqual(list(it), [])

def test_repeat_after_setslice(self):
# bpo-42924: * used to copy from the wrong memory location
b = bytearray(b'abc')
b[:2] = b'x'
b1 = b * 1
b3 = b * 3
self.assertEqual(b1, b'xc')
self.assertEqual(b1, b)
self.assertEqual(b3, b'xcxcxc')


class AssortedBytesTest(unittest.TestCase):
#
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix ``bytearray`` repetition incorrectly copying data from the start of the buffer, even if the data is offset within the buffer (e.g. after reassigning a slice at the start of the ``bytearray`` to a shorter byte string).
6 changes: 4 additions & 2 deletions Objects/bytearrayobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,7 @@ bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
PyByteArrayObject *result;
Py_ssize_t mysize;
Py_ssize_t size;
const char *buf;

if (count < 0)
count = 0;
Expand All @@ -340,13 +341,14 @@ bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
return PyErr_NoMemory();
size = mysize * count;
result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
buf = PyByteArray_AS_STRING(self);
if (result != NULL && size != 0) {
if (mysize == 1)
memset(result->ob_bytes, self->ob_bytes[0], size);
memset(result->ob_bytes, buf[0], size);
else {
Py_ssize_t i;
for (i = 0; i < count; i++)
memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
memcpy(result->ob_bytes + i*mysize, buf, mysize);
}
}
return (PyObject *)result;
Expand Down