From 86e7e177922d6ebf4b7878de0d2d09e0edd5ce27 Mon Sep 17 00:00:00 2001 From: wangjianyu3 Date: Wed, 18 Dec 2024 17:26:03 +0800 Subject: [PATCH] nshlib/nsh_parse: Closing fds opened for redirection if necessary Coverity Log CID 1612743: (#1 of 1): Resource leak (RESOURCE_LEAK) 12. leaked_handle: The handle variable fd_out goes out of scope and leaks the handle. Signed-off-by: wangjianyu3 --- nshlib/nsh_parse.c | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/nshlib/nsh_parse.c b/nshlib/nsh_parse.c index b9b1dd101..7362a6cd7 100644 --- a/nshlib/nsh_parse.c +++ b/nshlib/nsh_parse.c @@ -500,6 +500,8 @@ static int nsh_execute(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char *argv[], FAR const struct nsh_param_s *param) { + int fd_out = STDOUT_FILENO; + int fd_in = STDIN_FILENO; int ret; /* DO NOT CHANGE THE ORDERING OF THE FOLLOWING STEPS @@ -645,9 +647,6 @@ static int nsh_execute(FAR struct nsh_vtbl_s *vtbl, { uint8_t save[SAVE_SIZE]; - int fd_in = STDIN_FILENO; - int fd_out = STDOUT_FILENO; - /* Redirected output? */ if (vtbl->np.np_redir_out) @@ -665,7 +664,8 @@ static int nsh_execute(FAR struct nsh_vtbl_s *vtbl, { nsh_error(vtbl, g_fmtcmdfailed, argv[0], "open", NSH_ERRNO); - return nsh_saveresult(vtbl, true); + ret = errno; + goto close_redir; } } else @@ -691,7 +691,8 @@ static int nsh_execute(FAR struct nsh_vtbl_s *vtbl, { nsh_error(vtbl, g_fmtcmdfailed, argv[0], "open", NSH_ERRNO); - return nsh_saveresult(vtbl, true); + ret = errno; + goto close_redir; } } else @@ -724,22 +725,27 @@ static int nsh_execute(FAR struct nsh_vtbl_s *vtbl, { nsh_undirect(vtbl, save); } + } - /* Mark errors so that it is possible to test for non-zero return - * values in nsh scripts. - */ +close_redir: - if (ret < 0) - { - return nsh_saveresult(vtbl, true); - } + /* Closing fds opened for redirection if necessary */ + + if (fd_out > STDOUT_FILENO) + { + close(fd_out); + } + + if (fd_in > STDIN_FILENO) + { + close(fd_in); } /* Return success if the command succeeded (or at least, starting of the * command task succeeded). */ - return nsh_saveresult(vtbl, false); + return nsh_saveresult(vtbl, ret != OK); } /****************************************************************************