git: a8aaf8039f2d - main - cp: Avoid closing an invalid file descriptor.
- Go to: [ bottom of page ] [ top of archives ] [ this month ]
Date: Sun, 18 May 2025 19:10:37 UTC
The branch main has been updated by des:
URL: https://cgit.FreeBSD.org/src/commit/?id=a8aaf8039f2dd029ddf7fd396e047eb0bd3c8904
commit a8aaf8039f2dd029ddf7fd396e047eb0bd3c8904
Author: Dag-Erling Smørgrav <des@FreeBSD.org>
AuthorDate: 2025-05-18 19:09:58 +0000
Commit: Dag-Erling Smørgrav <des@FreeBSD.org>
CommitDate: 2025-05-18 19:10:08 +0000
cp: Avoid closing an invalid file descriptor.
* At the end of copy(), we always close to.dir, even though it can be
AT_FDCWD (in the file-to-file case) or even -1 (if we failed to open
or create the destination directory). While closing an invalid file
descriptor is harmless, it's still bad form.
* In the DIR_TO_DNE case, initialize to.dir to -1 to guard against the
case where mkdir() fails so we never assign anything to to.dir and
end up (harmlessly, luckily) closing stdin on our way to the exit.
Coverity ID: 1609954
Fixes: 82fc0d09e862
Sponsored by: Klara, Inc.
Reviewed by: markj
Differential Revision: https://reviews.freebsd.org/D50391
---
bin/cp/cp.c | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)
diff --git a/bin/cp/cp.c b/bin/cp/cp.c
index c76654f7df41..03b3a7a7bf41 100644
--- a/bin/cp/cp.c
+++ b/bin/cp/cp.c
@@ -296,6 +296,11 @@ copy(char *argv[], enum op type, int fts_options, struct stat *root_stat)
sep = strchr(to.base, '\0');
sep[0] = '/';
sep[1] = '\0';
+ } else {
+ /*
+ * We will create the destination directory imminently.
+ */
+ to.dir = -1;
}
if ((ftsp = fts_open(argv, fts_options, NULL)) == NULL)
@@ -633,8 +638,9 @@ copy(char *argv[], enum op type, int fts_options, struct stat *root_stat)
}
if (errno)
err(1, "fts_read");
- fts_close(ftsp);
- close(to.dir);
+ (void)fts_close(ftsp);
+ if (to.dir != AT_FDCWD && to.dir >= 0)
+ (void)close(to.dir);
free(recpath);
return (rval);
}