From 5fecfe0f42ae389dc962981334aa1f2d28272e53 Mon Sep 17 00:00:00 2001 From: James Cowgill Date: Thu, 4 May 2017 14:29:48 +0100 Subject: [PATCH 1/2] memory: switch loop condition around in blas_memory_free Before this commit, the "position < NUM_BUFFERS" loop condition from blas_memory_free will be completely optimized away by GCC. This is because the condition can only be false after undefined behavior has already been invoked (reading past the end of an array). As a consequence of this bug, GCC also removes the subsequent if statement and all the code after the error label because all of it is dead. This commit switches the loop condition around so it works as intended. --- driver/others/memory.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/driver/others/memory.c b/driver/others/memory.c index 0ac44f6f5..6c62c686e 100644 --- a/driver/others/memory.c +++ b/driver/others/memory.c @@ -1164,8 +1164,8 @@ void blas_memory_free(void *free_area){ position = 0; LOCK_COMMAND(&alloc_lock); - while ((memory[position].addr != free_area) - && (position < NUM_BUFFERS)) position++; + while ((position < NUM_BUFFERS) && (memory[position].addr != free_area)) + position++; if (memory[position].addr != free_area) goto error; From 59c97cfee4cf2873bccf646eb5906b24627b01f6 Mon Sep 17 00:00:00 2001 From: James Cowgill Date: Fri, 5 May 2017 10:33:56 +0100 Subject: [PATCH 2/2] memory: Fix buffer overflow when position == NUM_BUFFERS --- driver/others/memory.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/driver/others/memory.c b/driver/others/memory.c index 6c62c686e..8564b285b 100644 --- a/driver/others/memory.c +++ b/driver/others/memory.c @@ -1015,7 +1015,7 @@ void *blas_memory_alloc(int procpos){ mypos = WhereAmI(); position = mypos; - while (position > NUM_BUFFERS) position >>= 1; + while (position >= NUM_BUFFERS) position >>= 1; do { if (!memory[position].used && (memory[position].pos == mypos)) {