Skip to content

Commit

Permalink
[libc++] Fix double file closing in std::filesystem::remove_all().
Browse files Browse the repository at this point in the history
According to Linux documentation (see e.g. https://linux.die.net/man/3/closedir):

> A successful call to `closedir()` also closes the underlying file
> descriptor associated with `dirp`.

Thus, calling `close()` after a successful call to `closedir()` is at
best redundant. Worse, should a different thread open a file in-between
the calls to `closedir()` and `close()` and get the same file descriptor,
the call to `close()` might actually close a different file than was
intended.

rdar://89251874

Differential Revision: https://reviews.llvm.org/D120453
  • Loading branch information
var-const authored and ldionne committed Feb 28, 2022
1 parent 3104994 commit 3906ebf
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion libcxx/src/filesystem/operations.cpp
Expand Up @@ -1416,12 +1416,14 @@ uintmax_t remove_all_impl(int parent_directory, const path& p, error_code& ec) {
if (fd != -1) {
// If that worked, iterate over the contents of the directory and
// remove everything in it, recursively.
scope_exit close_fd([=] { ::close(fd); });
DIR* stream = ::fdopendir(fd);
if (stream == nullptr) {
::close(fd);
ec = detail::capture_errno();
return 0;
}
// Note: `::closedir` will also close the associated file descriptor, so
// there should be no call to `close(fd)`.
scope_exit close_stream([=] { ::closedir(stream); });

uintmax_t count = 0;
Expand Down

0 comments on commit 3906ebf

Please sign in to comment.