[issue45545] chdir __exit__ is not safe

Jeremy report at bugs.python.org
Thu Oct 21 11:58:55 EDT 2021


Jeremy <ucodery at gmail.com> added the comment:

>If os.chdir is in os.supports_fd, the context manager can use dirfd = os.open(os.getcwd(), os.O_RDONLY). Using an fd should also work around the deleted directory case, though POSIX doesn't specify whether fchdir() succeeds in this case. It does in Linux, and the resulting state is the same as deleting the current working directory.

Yes, I was considering an open fd to guarantee to return to the old pwd as long as it existed. I said as much on the mailing list, but was uncertain if it was possible do deadlock holding on to arbitrary directory handles. If it's possible at all to deadlock, and I think it is, I don't think we can use this; not in a stdlib implementation. The reason for the deadlock is too hidden from the user and debugging it would be difficult. It would be fine for a user implementation where they understood the implications and made other guarantees about their traversals, but we can't be sure everyone using this implementation would read an understand this limitation.

I hadn't considered systems that don't support fd vops. I also hadn't considered crossing mount points and if that could cause any additional error cases. I don't think it can, not that we could correct in user-space and with just using os.chdir().

>In Windows, SetCurrentDirectoryW() resolves the full path. So the result from os.getcwd() should always work with os.chdir(). The context manager could prevent the original directory from getting deleted by opening it without delete sharing (e.g. via _winapi.CreateFile). Though it may be more reasonable to just let it fail to restore the original working directory.

Thanks, I am much less familiar with these APIs. So I believe you are saying the implementation as is will work in all reasonable cases for Windows.
I think attempting to move back to a directory that has been removed should be an error. Especially if we give the same behavior on Linux. Producing a FileNotFoundError gives the user the power to decide if they do in fact want to handle that differently.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45545>
_______________________________________


More information about the Python-bugs-list mailing list