Skip to content

Commit c06f74f

Browse files
bpo-38031: Fix a possible assertion failure in _io.FileIO() (GH-GH-5688)
(cherry picked from commit d386115) Co-authored-by: Zackery Spytz <[email protected]>
1 parent 5b74084 commit c06f74f

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
@@ -492,8 +492,12 @@ _Py_COMP_DIAG_POP
492492
ret = -1;
493493
if (!fd_is_own)
494494
self->fd = -1;
495-
if (self->fd >= 0)
495+
if (self->fd >= 0) {
496+
PyObject *exc, *val, *tb;
497+
PyErr_Fetch(&exc, &val, &tb);
496498
internal_close(self);
499+
_PyErr_ChainExceptions(exc, val, tb);
500+
}
497501

498502
done:
499503
#ifdef MS_WINDOWS

0 commit comments

Comments
 (0)