From acfbb9febd024475bdcb4ebbe2ec8c0e9a652275 Mon Sep 17 00:00:00 2001 From: Damien George Date: Thu, 15 Aug 2019 23:02:04 +1000 Subject: [PATCH] py/objarray: Fix amount of free space in array when doing slice assign. Prior to this patch the amount of free space in an array (including bytearray) was not being maintained correctly for the case of slice assignment which changed the size of the array. Under certain cases (as encoded in the new test) it was possible that the array could grow beyond its allocated memory block and corrupt the heap. Fixes issue #4127. --- py/objarray.c | 3 ++- tests/basics/bytearray_slice_assign.py | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/py/objarray.c b/py/objarray.c index 4e58d8e5da..c19617d4e1 100644 --- a/py/objarray.c +++ b/py/objarray.c @@ -445,7 +445,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value if (len_adj > o->free) { // TODO: alloc policy; at the moment we go conservative o->items = m_renew(byte, o->items, (o->len + o->free) * item_sz, (o->len + len_adj) * item_sz); - o->free = 0; + o->free = len_adj; dest_items = o->items; } mp_seq_replace_slice_grow_inplace(dest_items, o->len, @@ -458,6 +458,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value mp_seq_clear(dest_items, o->len + len_adj, o->len, item_sz); // TODO: alloc policy after shrinking } + o->free -= len_adj; o->len += len_adj; return mp_const_none; #else diff --git a/tests/basics/bytearray_slice_assign.py b/tests/basics/bytearray_slice_assign.py index 7f7d1d119a..fa7878e10d 100644 --- a/tests/basics/bytearray_slice_assign.py +++ b/tests/basics/bytearray_slice_assign.py @@ -59,3 +59,10 @@ print(b) b = bytearray(2) b[1:1] = b"12345" print(b) + +# Growth of bytearray via slice extension +b = bytearray(b'12345678') +b.append(57) # expand and add a bit of unused space at end of the bytearray +for i in range(400): + b[-1:] = b'ab' # grow slowly into the unused space +print(len(b), b)