Skip to content

Commit

Permalink
nshlib/nsh_parse: Closing fds opened for redirection if necessary
Browse files Browse the repository at this point in the history
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 <wangjianyu3@xiaomi.com>
  • Loading branch information
JianyuWang0623 authored and xiaoxiang781216 committed Jan 16, 2025
1 parent 8dac325 commit 86e7e17
Showing 1 changed file with 19 additions and 13 deletions.
32 changes: 19 additions & 13 deletions nshlib/nsh_parse.c
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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);
}

/****************************************************************************
Expand Down

0 comments on commit 86e7e17

Please sign in to comment.