]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-38031: Fix a possible assertion failure in _io.FileIO() (#GH-5688)
authorZackery Spytz <zspytz@gmail.com>
Fri, 25 Nov 2022 12:55:26 +0000 (04:55 -0800)
committerGitHub <noreply@github.com>
Fri, 25 Nov 2022 12:55:26 +0000 (12:55 +0000)
Lib/test/test_io.py
Misc/NEWS.d/next/Core and Builtins/2019-09-04-19-09-49.bpo-38031.Yq4L72.rst [new file with mode: 0644]
Modules/_io/fileio.c

index bc6071febe6144f4c0aa420e3608c65727057c9e..c927f15aafef72d88b0fc3e0eb7c9a1cbcf32b9b 100644 (file)
@@ -888,6 +888,14 @@ class IOTest(unittest.TestCase):
             open('non-existent', 'r', opener=badopener)
         self.assertEqual(str(cm.exception), 'opener returned -2')
 
+    def test_opener_invalid_fd(self):
+        # Check that OSError is raised with error code EBADF if the
+        # opener returns an invalid file descriptor (see gh-82212).
+        fd = os_helper.make_bad_fd()
+        with self.assertRaises(OSError) as cm:
+            self.open('foo', opener=lambda name, flags: fd)
+        self.assertEqual(cm.exception.errno, errno.EBADF)
+
     def test_fileio_closefd(self):
         # Issue #4841
         with self.open(__file__, 'rb') as f1, \
diff --git a/Misc/NEWS.d/next/Core and Builtins/2019-09-04-19-09-49.bpo-38031.Yq4L72.rst b/Misc/NEWS.d/next/Core and Builtins/2019-09-04-19-09-49.bpo-38031.Yq4L72.rst
new file mode 100644 (file)
index 0000000..b596437
--- /dev/null
@@ -0,0 +1,2 @@
+Fix a possible assertion failure in :class:`io.FileIO` when the opener
+returns an invalid file descriptor.
index 00859978e8cd6cc13c589fee55ac76e5f2ee6cca..659297ef1b1d302fe581b1ed752246a5729044fa 100644 (file)
@@ -485,8 +485,12 @@ _io_FileIO___init___impl(fileio *self, PyObject *nameobj, const char *mode,
     ret = -1;
     if (!fd_is_own)
         self->fd = -1;
-    if (self->fd >= 0)
+    if (self->fd >= 0) {
+        PyObject *exc, *val, *tb;
+        PyErr_Fetch(&exc, &val, &tb);
         internal_close(self);
+        _PyErr_ChainExceptions(exc, val, tb);
+    }
 
  done:
 #ifdef MS_WINDOWS