Demo:
>>> import os
>>> os.chdir(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 14] Bad address: -1
>>> os.chdir(-2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 9] Bad file descriptor: -2
Functions in os supporting either path or file descriptor argument (os.supports_fd) usually use the following code pattern to distinguish between those cases:
if (path->fd != -1)
result = fchdir(path->fd);
else
result = chdir(path->narrow);
However, _fd_converter used by path_converter internally doesn't give any special meaning to -1 and allows any negative file descriptors. Therefore, if a user passes -1 to such function, path->narrow, which is NULL, will be used.
I see two ways to fix this.
1) Make some flag in path_t indicating that it should be treated as fd and make all users check that flag.
2) Make _fd_converter raise an exception for negative descriptors.
Also, I have to mention an inconsistency in reporting of bad descriptors. A handful of os functions uses fildes_converter for descriptors, which uses PyObject_AsFileDescriptor, which in turn is used in other places in Python as well (e.g. in fcntl module). PyObject_AsFileDescriptor raises a ValueError for negative descriptors instead of OSError raised by most os functions in this case.
>>> os.fchdir(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: file descriptor cannot be a negative integer (-1)
|