Skip to content

Commit

Permalink
Issue python#23985: Fix a possible buffer overrun when deleting a sli…
Browse files Browse the repository at this point in the history
…ce from the front of a bytearray and then appending some other bytes data.

Patch by Martin Panter.
  • Loading branch information
pitrou committed May 19, 2015
2 parents 94e44ed + 2545411 commit ef64847
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 6 deletions.
16 changes: 16 additions & 0 deletions Lib/test/test_bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -993,6 +993,22 @@ def test_setslice_extend(self):
b.extend(range(100, 110))
self.assertEqual(list(b), list(range(10, 110)))

def test_fifo_overrun(self):
# Test for issue #23985, a buffer overrun when implementing a FIFO
# Build Python in pydebug mode for best results.
b = bytearray(10)
b.pop() # Defeat expanding buffer off-by-one quirk
del b[:1] # Advance start pointer without reallocating
b += bytes(2) # Append exactly the number of deleted bytes
del b # Free memory buffer, allowing pydebug verification

def test_del_expand(self):
# Reducing the size should not expand the buffer (issue #23985)
b = bytearray(10)
size = sys.getsizeof(b)
del b[:1]
self.assertLessEqual(sys.getsizeof(b), size)

def test_extended_set_del_slice(self):
indices = (0, None, 1, 3, 19, 300, 1<<333, -1, -2, -31, -300)
for start in indices:
Expand Down
3 changes: 3 additions & 0 deletions Misc/NEWS
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ Release date: 2015-05-24
Core and Builtins
-----------------

- Issue #23985: Fix a possible buffer overrun when deleting a slice from
the front of a bytearray and then appending some other bytes data.

- Issue #24102: Fixed exception type checking in standard error handlers.

- Issue #15027: The UTF-32 encoder is now 3x to 7x faster.
Expand Down
8 changes: 2 additions & 6 deletions Objects/bytearrayobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ PyByteArray_Resize(PyObject *self, Py_ssize_t requested_size)
return -1;
}

if (size + logical_offset + 1 < alloc) {
if (size + logical_offset + 1 <= alloc) {
/* Current buffer is large enough to host the requested size,
decide on a strategy. */
if (size < alloc / 2) {
Expand Down Expand Up @@ -331,11 +331,7 @@ bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
PyBuffer_Release(&vo);
return PyErr_NoMemory();
}
if (size < self->ob_alloc) {
Py_SIZE(self) = size;
PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0'; /* Trailing null byte */
}
else if (PyByteArray_Resize((PyObject *)self, size) < 0) {
if (PyByteArray_Resize((PyObject *)self, size) < 0) {
PyBuffer_Release(&vo);
return NULL;
}
Expand Down

0 comments on commit ef64847

Please sign in to comment.