Subject: bug#10305: coreutils-8.14, "rm -r" fails with EBADF

From: "Joachim Schmitz" <[email-masked]>
Date: Mon, 19 Dec 2011 14:22:03 +0100

BTW: Seems I have a similar problem with tar-1.26. Not with tar-1.25 though.

Trying to spot the relevant diff between the two and relating them to the problem I have in coretuils:

diff -BbENru tar-1.25/gnu/dup2.c tar-1.26/gnu/dup2.c
--- tar-1.25/gnu/dup2.c 2010-05-06 15:18:52.000000000 -0500
+++ tar-1.26/gnu/dup2.c 2011-03-12 03:14:28.000000000 -0600
...
@@ -61,6 +61,10 @@
       errno = EBADF;
       return -1;
     }
+# elif !defined __linux__
+  /* On Haiku, dup2 (fd, fd) mistakenly clears FD_CLOEXEC.  */
+  if (fd == desired_fd)
+    return fcntl (fd, F_GETFL) == -1 ? -1 : fd;
 # endif
   result = dup2 (fd, desired_fd);
 # ifdef __linux__
diff -BbENru tar-1.25/gnu/fcntl.c tar-1.26/gnu/fcntl.c
--- tar-1.25/gnu/fcntl.c        2010-05-06 15:18:52.000000000 -0500
+++ tar-1.26/gnu/fcntl.c        2011-03-12 03:14:28.000000000 -0600
...
@@ -189,7 +189,21 @@
           errno = EINVAL;
         else
           {
+            /* Haiku alpha 2 loses fd flags on original.  */
+            int flags = fcntl (fd, F_GETFD);
+            if (flags < 0)
+              {
+                result = -1;
+                break;
+              }
             result = fcntl (fd, action, target);
+            if (0 <= result && fcntl (fd, F_SETFD, flags) == -1)
+              {
+                int saved_errno = errno;
+                close (result);
+                result = -1;
+                errno = saved_errno;
+              }
 # if REPLACE_FCHDIR
             if (0 <= result)
               result = _gl_register_dup (fd, result);
diff -BbENru tar-1.25/gnu/fdopendir.c tar-1.26/gnu/fdopendir.c
--- tar-1.25/gnu/fdopendir.c    2011-02-04 05:31:35.000000000 -0600
+++ tar-1.26/gnu/fdopendir.c    2011-03-12 03:14:28.000000000 -060
...
@@ -63,7 +67,24 @@
 DIR *
 fdopendir (int fd)
 {
-  return fdopendir_with_dup (fd, -1);
+  DIR *dir = fdopendir_with_dup (fd, -1, NULL);
+
+  if (! REPLACE_FCHDIR && ! dir)
+    {
+      int saved_errno = errno;
+      if (EXPECTED_ERRNO (saved_errno))
+        {
+          struct saved_cwd cwd;
+          if (save_cwd (&cwd) != 0)
+            openat_save_fail (errno);
+          dir = fdopendir_with_dup (fd, -1, &cwd);
+          saved_errno = errno;
+          free_cwd (&cwd);
+          errno = saved_errno;
+        }
+    }
+
+  return dir;
 }

 /* Like fdopendir, except that if OLDER_DUPFD is not -1, it is known

Etc.pp... so we seem to be looking at the same problem, don't we?