Skip to content

Commit c75dc2d

Browse files
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 <wangjianyu3@xiaomi.com>
1 parent c27607e commit c75dc2d

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed

nshlib/nsh_parse.c

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -500,6 +500,8 @@ static int nsh_execute(FAR struct nsh_vtbl_s *vtbl,
500500
int argc, FAR char *argv[],
501501
FAR const struct nsh_param_s *param)
502502
{
503+
int fd_out = STDOUT_FILENO;
504+
int fd_in = STDIN_FILENO;
503505
int ret;
504506

505507
/* DO NOT CHANGE THE ORDERING OF THE FOLLOWING STEPS
@@ -645,9 +647,6 @@ static int nsh_execute(FAR struct nsh_vtbl_s *vtbl,
645647
{
646648
uint8_t save[SAVE_SIZE];
647649

648-
int fd_in = STDIN_FILENO;
649-
int fd_out = STDOUT_FILENO;
650-
651650
/* Redirected output? */
652651

653652
if (vtbl->np.np_redir_out)
@@ -665,7 +664,8 @@ static int nsh_execute(FAR struct nsh_vtbl_s *vtbl,
665664
{
666665
nsh_error(vtbl, g_fmtcmdfailed, argv[0], "open",
667666
NSH_ERRNO);
668-
return nsh_saveresult(vtbl, true);
667+
ret = errno;
668+
goto close_redir;
669669
}
670670
}
671671
else
@@ -691,7 +691,8 @@ static int nsh_execute(FAR struct nsh_vtbl_s *vtbl,
691691
{
692692
nsh_error(vtbl, g_fmtcmdfailed, argv[0], "open",
693693
NSH_ERRNO);
694-
return nsh_saveresult(vtbl, true);
694+
ret = errno;
695+
goto close_redir;
695696
}
696697
}
697698
else
@@ -724,22 +725,27 @@ static int nsh_execute(FAR struct nsh_vtbl_s *vtbl,
724725
{
725726
nsh_undirect(vtbl, save);
726727
}
728+
}
727729

728-
/* Mark errors so that it is possible to test for non-zero return
729-
* values in nsh scripts.
730-
*/
730+
close_redir:
731731

732-
if (ret < 0)
733-
{
734-
return nsh_saveresult(vtbl, true);
735-
}
732+
/* Closing fds opened for redirection if necessary */
733+
734+
if (fd_out > STDOUT_FILENO)
735+
{
736+
close(fd_out);
737+
}
738+
739+
if (fd_in > STDIN_FILENO)
740+
{
741+
close(fd_in);
736742
}
737743

738744
/* Return success if the command succeeded (or at least, starting of the
739745
* command task succeeded).
740746
*/
741747

742-
return nsh_saveresult(vtbl, false);
748+
return nsh_saveresult(vtbl, ret != OK);
743749
}
744750

745751
/****************************************************************************

0 commit comments

Comments
 (0)