[PATCH 4/4] ar, ranlib: Don't double close file descriptors

Mark Wielaard mark@klomp.org
Sat Jun 22 23:50:13 GMT 2024


Found by GCC14 -Wanalyzer-fd-double-close.

close always closes the given file descriptor even on error. So don't
try to close a file descriptor again on error (even on EINTR). This
could be bad in a multi-threaded environment.

      * src/ar.c (do_oper_extract): Call close and set newfd to -1.
      (do_oper_delete): Likewise.
      (do_oper_insert): Likewise.
      * src/ranlib.c (handle_file): Likewise.

Signed-off-by: Mark Wielaard <mark@klomp.org>
---
 src/ar.c     | 12 ++++++------
 src/ranlib.c |  4 ++--
 2 files changed, 8 insertions(+), 8 deletions(-)

diff --git a/src/ar.c b/src/ar.c
index fcb8bfb90a9f..9ace28b918d3 100644
--- a/src/ar.c
+++ b/src/ar.c
@@ -808,9 +808,9 @@ cannot rename temporary file to %.*s"),
 	      if (fchown (newfd, st.st_uid, st.st_gid) != 0) { ; }
 	      /* Set the mode of the new file to the same values the
 		 original file has.  */
-	      if (fchmod (newfd, st.st_mode & ALLPERMS) != 0
-		  || close (newfd) != 0)
+	      if (fchmod (newfd, st.st_mode & ALLPERMS) != 0)
 		goto nonew_unlink;
+	      close (newfd);
 	      newfd = -1;
 	      if (rename (tmpfname, arfname) != 0)
 		goto nonew_unlink;
@@ -1061,9 +1061,9 @@ do_oper_delete (const char *arfname, char **argv, int argc,
      setting the mode (which might be reset/ignored if the owner is
      wrong.  */
   if (fchown (newfd, st.st_uid, st.st_gid) != 0) { ; }
-  if (fchmod (newfd, st.st_mode & ALLPERMS) != 0
-      || close (newfd) != 0)
+  if (fchmod (newfd, st.st_mode & ALLPERMS) != 0)
     goto nonew_unlink;
+  close (newfd);
   newfd = -1;
   if (rename (tmpfname, arfname) != 0)
     goto nonew_unlink;
@@ -1547,9 +1547,9 @@ do_oper_insert (int oper, const char *arfname, char **argv, int argc,
 	 setting the modes, or they might be reset/ignored if the
 	 owner is wrong.  */
       if (fchown (newfd, st.st_uid, st.st_gid) != 0) { ; }
-      if (fchmod (newfd, st.st_mode & ALLPERMS) != 0
-	  || close (newfd) != 0)
+      if (fchmod (newfd, st.st_mode & ALLPERMS) != 0)
         goto nonew_unlink;
+      close (newfd);
       newfd = -1;
       if (rename (tmpfname, arfname) != 0)
 	goto nonew_unlink;
diff --git a/src/ranlib.c b/src/ranlib.c
index 7838d69eaec6..073df8c551af 100644
--- a/src/ranlib.c
+++ b/src/ranlib.c
@@ -264,9 +264,9 @@ handle_file (const char *fname)
 	  if (fchown (newfd, st.st_uid, st.st_gid) != 0) { ; }
 	  /* Set the mode of the new file to the same values the
 	     original file has.  */
-	  if (fchmod (newfd, st.st_mode & ALLPERMS) != 0
-	      || close (newfd) != 0)
+	  if (fchmod (newfd, st.st_mode & ALLPERMS) != 0)
 	    goto nonew_unlink;
+	  close (newfd);
 	  newfd = -1;
 	  if (rename (tmpfname, fname) != 0)
 	    goto nonew_unlink;
-- 
2.45.2



More information about the Elfutils-devel mailing list