]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-42780: Fix set_inheritable() for O_PATH file descriptors on Linux (GH-24172)
authorcptpcrd <31829097+cptpcrd@users.noreply.github.com>
Wed, 20 Jan 2021 14:05:51 +0000 (09:05 -0500)
committerGitHub <noreply@github.com>
Wed, 20 Jan 2021 14:05:51 +0000 (15:05 +0100)
Lib/test/test_os.py
Misc/NEWS.d/next/Library/2021-01-08-15-49-20.bpo-42780.rtqi6B.rst [new file with mode: 0644]
Python/fileutils.c

index 08d7ab8a30ba7ee80dd7c7f7ef8bbcd615347def..96fddc7d057663eb8dabcfa2f0bd467ab7a7dc8d 100644 (file)
@@ -3881,6 +3881,33 @@ class FDInheritanceTests(unittest.TestCase):
         self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
                          0)
 
+    @unittest.skipUnless(hasattr(os, 'O_PATH'), "need os.O_PATH")
+    def test_get_set_inheritable_o_path(self):
+        fd = os.open(__file__, os.O_PATH)
+        self.addCleanup(os.close, fd)
+        self.assertEqual(os.get_inheritable(fd), False)
+
+        os.set_inheritable(fd, True)
+        self.assertEqual(os.get_inheritable(fd), True)
+
+        os.set_inheritable(fd, False)
+        self.assertEqual(os.get_inheritable(fd), False)
+
+    def test_get_set_inheritable_badf(self):
+        fd = os_helper.make_bad_fd()
+
+        with self.assertRaises(OSError) as ctx:
+            os.get_inheritable(fd)
+        self.assertEqual(ctx.exception.errno, errno.EBADF)
+
+        with self.assertRaises(OSError) as ctx:
+            os.set_inheritable(fd, True)
+        self.assertEqual(ctx.exception.errno, errno.EBADF)
+
+        with self.assertRaises(OSError) as ctx:
+            os.set_inheritable(fd, False)
+        self.assertEqual(ctx.exception.errno, errno.EBADF)
+
     def test_open(self):
         fd = os.open(__file__, os.O_RDONLY)
         self.addCleanup(os.close, fd)
diff --git a/Misc/NEWS.d/next/Library/2021-01-08-15-49-20.bpo-42780.rtqi6B.rst b/Misc/NEWS.d/next/Library/2021-01-08-15-49-20.bpo-42780.rtqi6B.rst
new file mode 100644 (file)
index 0000000..a491690
--- /dev/null
@@ -0,0 +1 @@
+Fix os.set_inheritable() for O_PATH file descriptors on Linux.
index 8dc90fbe2b2e714d17ad773edd6a68439f89be31..f2b4681ea849c53a12fd9746b36a23ec080f94e8 100644 (file)
@@ -1234,6 +1234,13 @@ set_inheritable(int fd, int inheritable, int raise, int *atomic_flag_works)
             return 0;
         }
 
+#ifdef __linux__
+        if (errno == EBADF) {
+            // On Linux, ioctl(FIOCLEX) will fail with EBADF for O_PATH file descriptors
+            // Fall through to the fcntl() path
+        }
+        else
+#endif
         if (errno != ENOTTY && errno != EACCES) {
             if (raise)
                 PyErr_SetFromErrno(PyExc_OSError);