Skip to content

Commit c426815

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 59241fe commit c426815

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
@@ -880,6 +880,14 @@ def badopener(fname, flags):
880880
open('non-existent', 'r', opener=badopener)
881881
self.assertEqual(str(cm.exception), 'opener returned -2')
882882

883+
def test_opener_invalid_fd(self):
884+
# Check that OSError is raised with error code EBADF if the
885+
# opener returns an invalid file descriptor (see gh-82212).
886+
fd = os_helper.make_bad_fd()
887+
with self.assertRaises(OSError) as cm:
888+
self.open('foo', opener=lambda name, flags: fd)
889+
self.assertEqual(cm.exception.errno, errno.EBADF)
890+
883891
def test_fileio_closefd(self):
884892
# Issue #4841
885893
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
@@ -494,8 +494,12 @@ _Py_COMP_DIAG_POP
494494
ret = -1;
495495
if (!fd_is_own)
496496
self->fd = -1;
497-
if (self->fd >= 0)
497+
if (self->fd >= 0) {
498+
PyObject *exc, *val, *tb;
499+
PyErr_Fetch(&exc, &val, &tb);
498500
internal_close(self);
501+
_PyErr_ChainExceptions(exc, val, tb);
502+
}
499503

500504
done:
501505
#ifdef MS_WINDOWS

0 commit comments

Comments
 (0)