c5d972
commit 75fe6d1a1620d84e0e487868feba9b2c0f109610
c5d972
Author: Siddhesh Poyarekar <siddhesh@sourceware.org>
c5d972
Date:   Wed May 12 10:13:41 2021 +0530
c5d972
c5d972
    support: Close fds in copy_func
c5d972
    
c5d972
    copy_func may leave file descriptors open on error, so close them on
c5d972
    function exit.
c5d972
c5d972
diff --git a/support/shell-container.c b/support/shell-container.c
c5d972
index 3869e14683fb74dd..f0a9814ae230d167 100644
c5d972
--- a/support/shell-container.c
c5d972
+++ b/support/shell-container.c
c5d972
@@ -93,8 +93,9 @@ copy_func (char **argv)
c5d972
 {
c5d972
   char *sname = argv[0];
c5d972
   char *dname = argv[1];
c5d972
-  int sfd, dfd;
c5d972
+  int sfd = -1, dfd = -1;
c5d972
   struct stat st;
c5d972
+  int ret = 1;
c5d972
 
c5d972
   sfd = open (sname, O_RDONLY);
c5d972
   if (sfd < 0)
c5d972
@@ -108,7 +109,7 @@ copy_func (char **argv)
c5d972
     {
c5d972
       fprintf (stderr, "cp: unable to fstat %s: %s\n",
c5d972
 	       sname, strerror (errno));
c5d972
-      return 1;
c5d972
+      goto out;
c5d972
     }
c5d972
 
c5d972
   dfd = open (dname, O_WRONLY | O_TRUNC | O_CREAT, 0600);
c5d972
@@ -116,22 +117,26 @@ copy_func (char **argv)
c5d972
     {
c5d972
       fprintf (stderr, "cp: unable to open %s for writing: %s\n",
c5d972
 	       dname, strerror (errno));
c5d972
-      return 1;
c5d972
+      goto out;
c5d972
     }
c5d972
 
c5d972
   if (support_copy_file_range (sfd, 0, dfd, 0, st.st_size, 0) != st.st_size)
c5d972
     {
c5d972
       fprintf (stderr, "cp: cannot copy file %s to %s: %s\n",
c5d972
 	       sname, dname, strerror (errno));
c5d972
-      return 1;
c5d972
+      goto out;
c5d972
     }
c5d972
 
c5d972
-  close (sfd);
c5d972
-  close (dfd);
c5d972
-
c5d972
+  ret = 0;
c5d972
   chmod (dname, st.st_mode & 0777);
c5d972
 
c5d972
-  return 0;
c5d972
+out:
c5d972
+  if (sfd >= 0)
c5d972
+    close (sfd);
c5d972
+  if (dfd >= 0)
c5d972
+    close (dfd);
c5d972
+
c5d972
+  return ret;
c5d972
 
c5d972
 }
c5d972