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