From 3d93fed0aab85f5a7a64088026822ea55cc63541 Mon Sep 17 00:00:00 2001 From: Yoctopuce Date: Thu, 13 Jun 2024 11:23:57 +0200 Subject: [PATCH] py/objarray: Fix buffer overflow in case of memory allocation failure. If `array.append()` fails with an exception due to heap exhaustion, the next attempt to grow the buffer will cause a buffer overflow because the free slot count is increased before performing the allocation, and will stay as if the allocation succeeded. Signed-off-by: Yoctopuce --- py/objarray.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/py/objarray.c b/py/objarray.c index 803af2cd270c7..9d68aa70616ca 100644 --- a/py/objarray.c +++ b/py/objarray.c @@ -392,8 +392,9 @@ static mp_obj_t array_append(mp_obj_t self_in, mp_obj_t arg) { if (self->free == 0) { size_t item_sz = mp_binary_get_size('@', self->typecode, NULL); // TODO: alloc policy - self->free = 8; - self->items = m_renew(byte, self->items, item_sz * self->len, item_sz * (self->len + self->free)); + size_t add_cnt = 8; + self->items = m_renew(byte, self->items, item_sz * self->len, item_sz * (self->len + add_cnt)); + self->free = add_cnt; mp_seq_clear(self->items, self->len + 1, self->len + self->free, item_sz); } mp_binary_set_val_array(self->typecode, self->items, self->len, arg);