Skip to contentSkip to conversation

tools/nolibc/stdlib: fix memory error in realloc()

PATCH In review Brennan Xavier McManus 3 participants 3 messages Jan 9, 2024 – Jan 10, 2024 Nolibc header file

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 tools/nolibc/stdlib: fix memory error in realloc()

Pass user_p_len to memcpy() instead of heap->len to prevent realloc() from copying an extra sizeof(heap) bytes from beyond the allocated region.

---

All tests from Ammar's original test program pass:
https://gist.github.com/ammarfaizi2/db0af6aa0b95a0c7478bce64e349f021
This fix was tested with the following added test for realloc():
https://github.com/brennan913/nolibc-test/blob/main/nolibc_test.c#L73-L120

 tools/include/nolibc/stdlib.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/include/nolibc/stdlib.h +1 -1
index bacfd35c5156..5be9d3c7435a 100644
@@ -185,7 +185,7 @@ void *realloc(void *old_ptr, size_t new_size)
 	if (__builtin_expect(!ret, 0))
 		return NULL;
 
-	memcpy(ret, heap->user_p, heap->len);
+	memcpy(ret, heap->user_p, user_p_len);
 	munmap(heap, heap->len);
 	return ret;
 }
Signature · 1 line
2.39.2
Reviewed-by on v1 1/1
#1 lore raw
Quoted 11 lines · Brennan Xavier McManus

Pass user_p_len to memcpy() instead of heap->len to prevent realloc() from copying an extra sizeof(heap) bytes from beyond the allocated region.

---

All tests from Ammar's original test program pass:
https://gist.github.com/ammarfaizi2/db0af6aa0b95a0c7478bce64e349f021
This fix was tested with the following added test for realloc():
https://github.com/brennan913/nolibc-test/blob/main/nolibc_test.c#L73-L120

Hello Brennan,

Thank you for the fix!

Fixes 0e0ff638400be8f497a35b51a4751fd823f6bd6a ("tools/nolibc/stdlib: Implement `malloc()`, `calloc()`, `realloc()` and `free()`")
Signature · 1 line
Ammar Faizi
maintainer
#2 lore raw

Hi,

Quoted 13 lines · Ammar Faizi
Quoted 11 lines · Brennan Xavier McManus

Pass user_p_len to memcpy() instead of heap->len to prevent realloc() from copying an extra sizeof(heap) bytes from beyond the allocated region.

---

All tests from Ammar's original test program pass:
https://gist.github.com/ammarfaizi2/db0af6aa0b95a0c7478bce64e349f021
This fix was tested with the following added test for realloc():
https://github.com/brennan913/nolibc-test/blob/main/nolibc_test.c#L73-L120

Quoted 7 lines

Hello Brennan,

Thank you for the fix!

Fixes 0e0ff638400be8f497a35b51a4751fd823f6bd6a ("tools/nolibc/stdlib: Implement `malloc()`, `calloc()`, `realloc()` and `free()`")

Thanks both for the fix and the review! I've pushed it to the "fixes" branch. Thomas, for now I updated the branch to match "next" (which just got merged) so as to preserve patch ordering, we'll just rebase it once 6.8-rc1 is out.

Willy