From e08d10091997599c884312e82eeba6fdf6695fdf Mon Sep 17 00:00:00 2001 From: Ken Pettit Date: Sat, 12 Jan 2019 10:56:48 -0600 Subject: [PATCH] apps/nshlib/nsh_parse.c: Fixes an error in the NSH parser. There was a bug when executing an nsh shell script which contains a redirection. When the command in the script is executed, it sets the vtbl->np.np_redirect flag (as it should), but then doesn't restore it, leaving it set at the end of the script execution. Then the vtbl->np.np_redirect flag is set when the 'sh' command completes, causing a restore from un-initialized variables, thus leading to a crash. See the code snippet below for an example test case. Test case: NuttShell (NSH) nsh> mkrd -s 1024 40 nsh> mkfatfs /dev/ram0 nsh> mount -t vfat /dev/ram0 /tmp nsh> echo "echo 1 > /dev/null" > /tmp/test.sh nsh> cat /tmp/test.sh echo 1 > /dev/null nsh> sh /tmp/test.sh ... The nsh prompt doesn't get printed. You can type a couple of commands, but then the system will crash because of bad pointers. --- nshlib/nsh_parse.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/nshlib/nsh_parse.c b/nshlib/nsh_parse.c index 57fee2ffa..ee414603d 100644 --- a/nshlib/nsh_parse.c +++ b/nshlib/nsh_parse.c @@ -2332,6 +2332,9 @@ static int nsh_parse_command(FAR struct nsh_vtbl_s *vtbl, FAR char *cmdline) int oflags = 0; int argc; int ret; +#if CONFIG_NFILE_STREAMS > 0 + bool redirect_save; +#endif /* Initialize parser state */ @@ -2500,6 +2503,7 @@ static int nsh_parse_command(FAR struct nsh_vtbl_s *vtbl, FAR char *cmdline) if (strcmp(argv[argc-2], g_redirect1) == 0) { + redirect_save = vtbl->np.np_redirect; vtbl->np.np_redirect = true; oflags = O_WRONLY|O_CREAT|O_TRUNC; redirfile = nsh_getfullpath(vtbl, argv[argc-1]); @@ -2510,6 +2514,7 @@ static int nsh_parse_command(FAR struct nsh_vtbl_s *vtbl, FAR char *cmdline) else if (strcmp(argv[argc-2], g_redirect2) == 0) { + redirect_save = vtbl->np.np_redirect; vtbl->np.np_redirect = true; oflags = O_WRONLY|O_CREAT|O_APPEND; redirfile = nsh_getfullpath(vtbl, argv[argc-1]); @@ -2537,6 +2542,7 @@ static int nsh_parse_command(FAR struct nsh_vtbl_s *vtbl, FAR char *cmdline) if (redirfile) { nsh_freefullpath(redirfile); + vtbl->np.np_redirect = redirect_save; } #endif