gh-151707: fix race conditions in FileIO#151708
Conversation
vstinner
left a comment
There was a problem hiding this comment.
I'm not sure that it's the right approach. While the change makes sure that int fd integer is not modified in parallel, it doesn't ensure that the file descriptor is not closed before/while we are using it.
For example, FileIO.isatty() gets int fd, check that it's >= 0, and then call isatty().
If another thread calls close(fd) in parallel, after >= 0 check and before isatty() call, isatty() fails with EBADF.
It's even worse if the file descriptor is recycled for a new unrelated file.
Maybe it would be safer to the whole method in a critical section. It would prevent calling FileIO.close() in parallel: the call would be serialized.
@cmaloney: What do you think?
|
Oh, the TSan tests failed. Example: |
I guess we have an answer 😁 |
What is this PR?
Fixes #151707.
Note that the PR itself does a bit more than just fix the race condition. It introduces new helper functions around the
self->fdto avoid race conditions altogether, in the same fashion as thesocketmodule.cfile (and updates every relevant usage site to call into those helpers).cpython/Modules/socketmodule.c
Lines 566 to 592 in 46b5e3e
FileIOunder free-threading #151707