Skip to content

[3.8] bpo-42780: Fix set_inheritable() for O_PATH file descriptors on Linux (GH-24172) #24277

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Lib/test/test_os.py
Original file line number Diff line number Diff line change
Expand Up @@ -3513,6 +3513,33 @@ def test_set_inheritable_cloexec(self):
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 = support.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)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix os.set_inheritable() for O_PATH file descriptors on Linux.
7 changes: 7 additions & 0 deletions Python/fileutils.c
Original file line number Diff line number Diff line change
Expand Up @@ -1165,6 +1165,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);
Expand Down