]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-102179: Fix `os.dup2` error reporting for negative fds (#102180)
authorAlexey Izbyshev <izbyshev@ispras.ru>
Sat, 4 Mar 2023 14:24:08 +0000 (17:24 +0300)
committerGitHub <noreply@github.com>
Sat, 4 Mar 2023 14:24:08 +0000 (19:54 +0530)
Lib/test/test_os.py
Misc/NEWS.d/next/Library/2023-02-23-15-06-01.gh-issue-102179.P6KQ4c.rst [new file with mode: 0644]
Modules/posixmodule.c

index deea207bfdadd9dfcd82ad4a436dfff8cec1d7f4..792794ca10948920d98bc949d758faa0591126ac 100644 (file)
@@ -2221,6 +2221,26 @@ class TestInvalidFD(unittest.TestCase):
     def test_dup2(self):
         self.check(os.dup2, 20)
 
+    @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()')
+    @unittest.skipIf(
+        support.is_emscripten,
+        "dup2() with negative fds is broken on Emscripten (see gh-102179)"
+    )
+    def test_dup2_negative_fd(self):
+        valid_fd = os.open(__file__, os.O_RDONLY)
+        self.addCleanup(os.close, valid_fd)
+        fds = [
+            valid_fd,
+            -1,
+            -2**31,
+        ]
+        for fd, fd2 in itertools.product(fds, repeat=2):
+            if fd != fd2:
+                with self.subTest(fd=fd, fd2=fd2):
+                    with self.assertRaises(OSError) as ctx:
+                        os.dup2(fd, fd2)
+                    self.assertEqual(ctx.exception.errno, errno.EBADF)
+
     @unittest.skipUnless(hasattr(os, 'fchmod'), 'test needs os.fchmod()')
     def test_fchmod(self):
         self.check(os.fchmod, 0)
diff --git a/Misc/NEWS.d/next/Library/2023-02-23-15-06-01.gh-issue-102179.P6KQ4c.rst b/Misc/NEWS.d/next/Library/2023-02-23-15-06-01.gh-issue-102179.P6KQ4c.rst
new file mode 100644 (file)
index 0000000..f77493e
--- /dev/null
@@ -0,0 +1 @@
+Fix :func:`os.dup2` error message for negative fds.
index 937233a3bd0779e59a34c59c75bf5175fa34ab86..7beb2cee64a05c69959408c9709673a5316992b0 100644 (file)
@@ -9795,11 +9795,6 @@ os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
     static int dup3_works = -1;
 #endif
 
-    if (fd < 0 || fd2 < 0) {
-        posix_error();
-        return -1;
-    }
-
     /* dup2() can fail with EINTR if the target FD is already open, because it
      * then has to be closed. See os_close_impl() for why we don't handle EINTR
      * upon close(), and therefore below.