From 58378bae3e67653cef9ee7c67c082c745906340a Mon Sep 17 00:00:00 2001 From: StefanBruens Date: Tue, 15 Nov 2016 05:22:28 +0100 Subject: [PATCH] Fix access to potentially freed memory, always initialize sram buffer - Initialize new buffer, not the buffer which may have been freed during reallocation - growing sram_size without realloc_zero may leave parts of sram_buf unitialized. boot0img created undeterministic images on aarch64, errors were confirmed by valgrind. --- tools/boot0img.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/tools/boot0img.c b/tools/boot0img.c index 8d3040b..5b6a71b 100644 --- a/tools/boot0img.c +++ b/tools/boot0img.c @@ -275,7 +275,7 @@ static void *realloc_zero(void *ptr, ssize_t *sizeptr, ssize_t newsize) ret = realloc(ptr, newsize); if (newsize > *sizeptr) - memset((char*)ptr + *sizeptr, 0, newsize - *sizeptr); + memset((char*)ret + *sizeptr, 0, newsize - *sizeptr); *sizeptr = newsize; @@ -593,9 +593,6 @@ int main(int argc, char **argv) if (!quiet) fprintf(stderr, "%zd Bytes\n", sram_size); - if (arisc_addr) - sram_size += 0x4000; - sram_buf = realloc_zero(sram_buf, &sram_size, ALIGN(sram_size, 512)); @@ -610,6 +607,8 @@ int main(int argc, char **argv) char *endptr; address = strtoul(arisc_addr, &endptr, 0); + sram_buf = realloc_zero(sram_buf, &sram_size, + sram_size + 0x4000); memmove(sram_buf + 0x1000, sram_buf, sram_size - 0x4000); memset(sram_buf, 0, 0x4000); /* OpenRISC: l.j */