Skip to content

Commit 5939970

Browse files
Nicolas Pitrenashif
authored andcommitted
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 <[email protected]>
1 parent c822e0a commit 5939970

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

lib/os/heap.c

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -368,12 +368,13 @@ void *sys_heap_aligned_realloc(struct sys_heap *heap, void *ptr,
368368
/* Fallback: allocate and copy */
369369
void *ptr2 = sys_heap_aligned_alloc(heap, align, bytes);
370370

371-
if (ptr2 == NULL) {
372-
return NULL;
373-
}
371+
if (ptr2 != NULL) {
372+
size_t prev_size = chunk_size(h, c) * CHUNK_UNIT
373+
- chunk_header_bytes(h) - align_gap;
374374

375-
memcpy(ptr2, ptr, bytes);
376-
sys_heap_free(heap, ptr);
375+
memcpy(ptr2, ptr, MIN(prev_size, bytes));
376+
sys_heap_free(heap, ptr);
377+
}
377378
return ptr2;
378379
}
379380

0 commit comments

Comments
 (0)