Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7d7f40c

Browse files
committed
Issue #15247: FileIO now raises an error when given a file descriptor pointing to a directory.
2 parents 5cf896f + 9235b25 commit 7d7f40c

3 files changed

Lines changed: 16 additions & 12 deletions

File tree

Lib/test/test_fileio.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,14 @@ def testOpendir(self):
128128
else:
129129
self.fail("Should have raised IOError")
130130

131+
@unittest.skipIf(os.name == 'nt', "test only works on a POSIX-like system")
132+
def testOpenDirFD(self):
133+
fd = os.open('.', os.O_RDONLY)
134+
with self.assertRaises(IOError) as cm:
135+
_FileIO(fd, 'r')
136+
os.close(fd)
137+
self.assertEqual(cm.exception.errno, errno.EISDIR)
138+
131139
#A set of functions testing that we get expected behaviour if someone has
132140
#manually closed the internal file descriptor. First, a decorator:
133141
def ClosedFD(func):

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ Core and Builtins
2323
Library
2424
-------
2525

26+
- Issue #15247: FileIO now raises an error when given a file descriptor
27+
pointing to a directory.
28+
2629
- Issue #15261: Stop os.stat(fd) crashing on Windows when fd not open.
2730

2831
- Issue #15166: Implement imp.get_tag() using sys.implementation.cache_tag.

Modules/_io/fileio.c

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -169,22 +169,15 @@ fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
169169
directories, so we need a check. */
170170

171171
static int
172-
dircheck(fileio* self, const char *name)
172+
dircheck(fileio* self, PyObject *nameobj)
173173
{
174174
#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
175175
struct stat buf;
176176
if (self->fd < 0)
177177
return 0;
178178
if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
179-
char *msg = strerror(EISDIR);
180-
PyObject *exc;
181-
if (internal_close(self))
182-
return -1;
183-
184-
exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
185-
EISDIR, msg, name);
186-
PyErr_SetObject(PyExc_IOError, exc);
187-
Py_XDECREF(exc);
179+
errno = EISDIR;
180+
PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
188181
return -1;
189182
}
190183
#endif
@@ -406,9 +399,9 @@ fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
406399
PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
407400
goto error;
408401
}
409-
if (dircheck(self, name) < 0)
410-
goto error;
411402
}
403+
if (dircheck(self, nameobj) < 0)
404+
goto error;
412405

413406
#if defined(MS_WINDOWS) || defined(__CYGWIN__)
414407
/* don't translate newlines (\r\n <=> \n) */

0 commit comments

Comments
 (0)