Skip to content

Commit

Permalink
nsh/alias: Fix compiler warning
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
wengzhe authored and xiaoxiang781216 committed Aug 1, 2023
1 parent f50d2cd commit 396ab2e
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions nshlib/nsh_parse.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 396ab2e

Please sign in to comment.