Skip to content

Commit d386115

Browse files
authored
bpo-38031: Fix a possible assertion failure in _io.FileIO() (#GH-5688)
1 parent b1dcdef commit d386115

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

Lib/test/test_io.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -888,6 +888,14 @@ def badopener(fname, flags):
888888
open('non-existent', 'r', opener=badopener)
889889
self.assertEqual(str(cm.exception), 'opener returned -2')
890890

891+
def test_opener_invalid_fd(self):
892+
# Check that OSError is raised with error code EBADF if the
893+
# opener returns an invalid file descriptor (see gh-82212).
894+
fd = os_helper.make_bad_fd()
895+
with self.assertRaises(OSError) as cm:
896+
self.open('foo', opener=lambda name, flags: fd)
897+
self.assertEqual(cm.exception.errno, errno.EBADF)
898+
891899
def test_fileio_closefd(self):
892900
# Issue #4841
893901
with self.open(__file__, 'rb') as f1, \
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a possible assertion failure in :class:`io.FileIO` when the opener
2+
returns an invalid file descriptor.

Modules/_io/fileio.c

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -485,8 +485,12 @@ _io_FileIO___init___impl(fileio *self, PyObject *nameobj, const char *mode,
485485
ret = -1;
486486
if (!fd_is_own)
487487
self->fd = -1;
488-
if (self->fd >= 0)
488+
if (self->fd >= 0) {
489+
PyObject *exc, *val, *tb;
490+
PyErr_Fetch(&exc, &val, &tb);
489491
internal_close(self);
492+
_PyErr_ChainExceptions(exc, val, tb);
493+
}
490494

491495
done:
492496
#ifdef MS_WINDOWS

0 commit comments

Comments
 (0)