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 <[email protected]>
  • Loading branch information
JianyuWang0623 committed Dec 18, 2024
1 parent 9c8a96a commit c9b8bfa
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 @@ -635,9 +637,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 @@ -655,7 +654,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 @@ -681,7 +681,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 @@ -714,22 +715,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 (vtbl->np.np_redir_out && param->file_out && fd_out > STDOUT_FILENO)
{
close(fd_out);
}

if (vtbl->np.np_redir_in && param->file_in && 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 c9b8bfa

Please sign in to comment.