Skip to contentSkip to conversation

tools: fix NULL_AFTER_DEREF in image-host.c

PATCH In review Anton Moryakov 2 participants 2 messages Jan 30, 2025 – Feb 11, 2025

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 tools: fix NULL_AFTER_DEREF in image-host.c

Report of the static analyzer:
1. NULL_AFTER_DEREF Pointer 'str', which is dereferenced at image-host.c:688 by calling function 'strdup', is compared to a NULL value at image-host.c:691.
2. NULL_AFTER_DEREF Pointer 'list', which is dereferenced at image-host.c:689, is compared to a NULL value at image-host.c:691.

Corrections explained:
1. Checking for NULL before using pointers: The if (!list || !str) check is now performed before calling strdup and realloc, which prevents null pointer dereferences.
2. Checking the result of strdup: strdup can return NULL if memory allocation fails. This also needs to be checked.
3. Checking the result of realloc: If realloc returns NULL, then memory has not been allocated and dup must be freed to avoid memory leaks.

Triggers found by static analyzer Svace.

Signed-off-by Anton Moryakov <ant.v.moryakov at gmail.com>
---
 tools/image-host.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
tools/image-host.c +12 -2
index 84095d760c..821c8db616 100644
@@ -716,11 +716,21 @@ static int strlist_add(struct strlist *list, const char *str)
 {
 	char *dup;
 
+	if (!list || !str)
+		return -1;
+
 	dup = strdup(str);
+	if(!dup)
+		return -1;
+
 	list->strings = realloc(list->strings,
 				(list->count + 1) * sizeof(char *));
-	if (!list || !str)
-		return -1;
+	if (!list->strings)
+    {
+        free(dup);  
+        return -1;
+    }
+	
 	list->strings[list->count++] = dup;
 
 	return 0;
Signature · 1 line
2.30.2
#1 lore raw
Quoted 10 lines · Anton Moryakov

Report of the static analyzer:
1. NULL_AFTER_DEREF Pointer 'str', which is dereferenced at image-host.c:688 by calling function 'strdup', is compared to a NULL value at image-host.c:691.
2. NULL_AFTER_DEREF Pointer 'list', which is dereferenced at image-host.c:689, is compared to a NULL value at image-host.c:691.

Corrections explained:
1. Checking for NULL before using pointers: The if (!list || !str) check is now performed before calling strdup and realloc, which prevents null pointer dereferences.
2. Checking the result of strdup: strdup can return NULL if memory allocation fails. This also needs to be checked.
3. Checking the result of realloc: If realloc returns NULL, then memory has not been allocated and dup must be freed to avoid memory leaks.

[...]

Applied to u-boot/next, thanks!

Signature · 1 line
Tom