When __length_hint__() returns 0 for non-empty iterator, the data can be
written past the shared 0-terminated buffer, corrupting it.
with self.assertRaises(BufferError):
ba.rsplit(evil)
+ def test_extend_empty_buffer_overflow(self):
+ # gh-143003
+ class EvilIter:
+ def __iter__(self):
+ return self
+ def __next__(self):
+ return next(source)
+ def __length_hint__(self):
+ return 0
+
+ # Use ASCII digits so float() takes the fast path that expects a NUL terminator.
+ source = iter(b'42')
+ ba = bytearray()
+ ba.extend(EvilIter())
+
+ self.assertRaises(ValueError, float, bytearray())
+
def test_hex_use_after_free(self):
# Prevent UAF in bytearray.hex(sep) with re-entrant sep.__len__.
# Regression test for https://github.com/python/cpython/issues/143195.
--- /dev/null
+Fix an overflow of the shared empty buffer in :meth:`bytearray.extend` when
+``__length_hint__()`` returns 0 for non-empty iterator.
Py_DECREF(bytearray_obj);
return NULL;
}
- buf[len++] = value;
Py_DECREF(item);
if (len >= buf_size) {
Py_DECREF(bytearray_obj);
return PyErr_NoMemory();
}
- addition = len >> 1;
+ addition = len ? len >> 1 : 1;
if (addition > PyByteArray_SIZE_MAX - len)
buf_size = PyByteArray_SIZE_MAX;
else
have invalidated it. */
buf = PyByteArray_AS_STRING(bytearray_obj);
}
+ buf[len++] = value;
}
Py_DECREF(it);