From 396ab2e93153f93001f9d9a8007dc4dfc81c7e72 Mon Sep 17 00:00:00 2001 From: Zhe Weng Date: Tue, 1 Aug 2023 19:56:21 +0800 Subject: [PATCH] nsh/alias: Fix compiler warning Got use-after-free warning under GCC 12 with `-O3` option, and I found that `nsh_strcat` may realloc `ptr`, then `cmdline` may point to invalid memory. Let `cmdline` point to the reallocated `ptr` may solve the problem. Tested by `alias ll='ls -l'` and `ll /` on sim. GCC output: CC: binfmt_unloadmodule.c In function 'nsh_aliasexpand', inlined from 'nsh_argument' at nsh_parse.c:1879:20: nsh_parse.c:1196:23: error: pointer 'ptr' used after 'realloc' [-Werror=use-after-free] 1196 | ptr = cmdline + len; | ~~~~~~~~^~~~~~~~~~~~~~~ In function 'nsh_strcat', inlined from 'nsh_aliasexpand' at nsh_parse.c:1190:21, inlined from 'nsh_argument' at nsh_parse.c:1879:20: nsh_parse.c:1100:27: note: call to 'realloc' here 1100 | argument = (FAR char *)realloc(s1, allocsize); | ^~~~~~~~~~~~~~~~~~~~~~ Signed-off-by: Zhe Weng --- nshlib/nsh_parse.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nshlib/nsh_parse.c b/nshlib/nsh_parse.c index fb57ed3e3..1ea88d846 100644 --- a/nshlib/nsh_parse.c +++ b/nshlib/nsh_parse.c @@ -1181,16 +1181,16 @@ static FAR char *nsh_aliasexpand(FAR struct nsh_vtbl_s *vtbl, if ((ptr = strdup(alias->value)) != NULL) { - /* Set the new command line (expanded alias) */ - - cmdline = ptr; - /* Then concatenate the old command line with the new */ ptr = nsh_strcat(vtbl, ptr, " "); ptr = nsh_strcat(vtbl, ptr, *saveptr); NSH_MEMLIST_ADD(memlist, ptr); + /* Set the new command line (expanded alias) */ + + cmdline = ptr; + /* NULL terminate the new command */ ptr = cmdline + len;