lib/os/heap: fix out-of-bounds usage of memcpy() in sys_heap_realloc()

The sys_heap_realloc() code falls back to allocating new memory
and copying the existing data over when it cannot adjust the size
in place. However the size of the data to copy should be the old
size and not the new size if we're extending the allocation.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
This commit is contained in:
Nicolas Pitre 2021-01-26 13:54:36 -05:00 committed by Anas Nashif
parent c822e0abbd
commit 593997046b

View file

@ -368,12 +368,13 @@ void *sys_heap_aligned_realloc(struct sys_heap *heap, void *ptr,
/* Fallback: allocate and copy */
void *ptr2 = sys_heap_aligned_alloc(heap, align, bytes);
if (ptr2 == NULL) {
return NULL;
}
if (ptr2 != NULL) {
size_t prev_size = chunk_size(h, c) * CHUNK_UNIT
- chunk_header_bytes(h) - align_gap;
memcpy(ptr2, ptr, bytes);
sys_heap_free(heap, ptr);
memcpy(ptr2, ptr, MIN(prev_size, bytes));
sys_heap_free(heap, ptr);
}
return ptr2;
}