[U-Boot] [PATCH 8/8] hashtable: Fix zero-sized array undefined behavior

Eugeniu Rosca roscaeugeniu at gmail.com
Mon Aug 20 00:00:32 UTC 2018


Enabling CONFIG_UBSAN=y, below runtime warning occurs both in sandbox
and R-Car H3 Salvator-X U-Boot:

=====================================================================
UBSAN: Undefined behaviour in lib/hashtable.c:784:8
variable length array bound value 0 <= 0
=====================================================================

It has a slightly different wording when compiling sandbox U-Boot
with "gcc-8 -fsanitize=undefined -lubsan":

-----8<-----
lib/hashtable.c:784:8: runtime error: \
  variable length array bound evaluates to non-positive value 0
-----8<-----

Fix the error by making sure that localvars[] can't take a negative or
zero size.

Fixes: d5370febbcbc ("env: delete selected vars not present in imported env")
Signed-off-by: Eugeniu Rosca <erosca at de.adit-jv.com>
---
 include/search.h | 2 +-
 lib/hashtable.c  | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/include/search.h b/include/search.h
index 5d07b49073cc..417dacdb4482 100644
--- a/include/search.h
+++ b/include/search.h
@@ -99,7 +99,7 @@ extern ssize_t hexport_r(struct hsearch_data *__htab,
  */
 extern int himport_r(struct hsearch_data *__htab,
 		     const char *__env, size_t __size, const char __sep,
-		     int __flag, int __crlf_is_lf, int nvars,
+		     int __flag, int __crlf_is_lf, unsigned int nvars,
 		     char * const vars[]);
 
 /* Walk the whole table calling the callback on each element */
diff --git a/lib/hashtable.c b/lib/hashtable.c
index 1c48692b69ed..f35d2022f630 100644
--- a/lib/hashtable.c
+++ b/lib/hashtable.c
@@ -778,10 +778,10 @@ static int drop_var_from_set(const char *name, int nvars, char * vars[])
 
 int himport_r(struct hsearch_data *htab,
 		const char *env, size_t size, const char sep, int flag,
-		int crlf_is_lf, int nvars, char * const vars[])
+		int crlf_is_lf, unsigned int nvars, char * const vars[])
 {
 	char *data, *sp, *dp, *name, *value;
-	char *localvars[nvars];
+	char *localvars[nvars + 1];
 	int i;
 
 	/* Test for correct arguments.  */
-- 
2.18.0



More information about the U-Boot mailing list