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 <wengzhe@xiaomi.com>
This commit is contained in:
Zhe Weng 2023-08-01 19:56:21 +08:00 committed by Xiang Xiao
parent f50d2cdbe3
commit 396ab2e931

View File

@ -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;