xref: /freebsd/contrib/llvm-project/libcxx/src/filesystem/directory_iterator.cpp (revision a2464ee12761660f50d0b6f59f233949ebcacc87)
1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "__config"
10 #include "filesystem"
11 #include "stack"
12 #include <errno.h>
13 
14 #include "filesystem_common.h"
15 
16 _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
17 
18 using detail::ErrorHandler;
19 
20 #if defined(_LIBCPP_WIN32API)
21 class __dir_stream {
22 public:
23   __dir_stream() = delete;
24   __dir_stream& operator=(const __dir_stream&) = delete;
25 
26   __dir_stream(__dir_stream&& __ds) noexcept : __stream_(__ds.__stream_),
27                                                __root_(move(__ds.__root_)),
28                                                __entry_(move(__ds.__entry_)) {
29     __ds.__stream_ = INVALID_HANDLE_VALUE;
30   }
31 
32   __dir_stream(const path& root, directory_options opts, error_code& ec)
33       : __stream_(INVALID_HANDLE_VALUE), __root_(root) {
34     if (root.native().empty()) {
35       ec = make_error_code(errc::no_such_file_or_directory);
36       return;
37     }
38     __stream_ = ::FindFirstFileW((root / "*").c_str(), &__data_);
39     if (__stream_ == INVALID_HANDLE_VALUE) {
40       ec = detail::make_windows_error(GetLastError());
41       const bool ignore_permission_denied =
42           bool(opts & directory_options::skip_permission_denied);
43       if (ignore_permission_denied &&
44           ec.value() == static_cast<int>(errc::permission_denied))
45         ec.clear();
46       return;
47     }
48     if (!assign())
49       advance(ec);
50   }
51 
52   ~__dir_stream() noexcept {
53     if (__stream_ == INVALID_HANDLE_VALUE)
54       return;
55     close();
56   }
57 
58   bool good() const noexcept { return __stream_ != INVALID_HANDLE_VALUE; }
59 
60   bool advance(error_code& ec) {
61     while (::FindNextFileW(__stream_, &__data_)) {
62       if (assign())
63         return true;
64     }
65     close();
66     return false;
67   }
68 
69   bool assign() {
70     if (!wcscmp(__data_.cFileName, L".") || !wcscmp(__data_.cFileName, L".."))
71       return false;
72     // FIXME: Cache more of this
73     //directory_entry::__cached_data cdata;
74     //cdata.__type_ = get_file_type(__data_);
75     //cdata.__size_ = get_file_size(__data_);
76     //cdata.__write_time_ = get_write_time(__data_);
77     __entry_.__assign_iter_entry(
78         __root_ / __data_.cFileName,
79         directory_entry::__create_iter_result(detail::get_file_type(__data_)));
80     return true;
81   }
82 
83 private:
84   error_code close() noexcept {
85     error_code ec;
86     if (!::FindClose(__stream_))
87       ec = detail::make_windows_error(GetLastError());
88     __stream_ = INVALID_HANDLE_VALUE;
89     return ec;
90   }
91 
92   HANDLE __stream_{INVALID_HANDLE_VALUE};
93   WIN32_FIND_DATAW __data_;
94 
95 public:
96   path __root_;
97   directory_entry __entry_;
98 };
99 #else
100 class __dir_stream {
101 public:
102   __dir_stream() = delete;
103   __dir_stream& operator=(const __dir_stream&) = delete;
104 
105   __dir_stream(__dir_stream&& other) noexcept : __stream_(other.__stream_),
106                                                 __root_(move(other.__root_)),
107                                                 __entry_(move(other.__entry_)) {
108     other.__stream_ = nullptr;
109   }
110 
111   __dir_stream(const path& root, directory_options opts, error_code& ec)
112       : __stream_(nullptr), __root_(root) {
113     if ((__stream_ = ::opendir(root.c_str())) == nullptr) {
114       ec = detail::capture_errno();
115       const bool allow_eacces =
116           bool(opts & directory_options::skip_permission_denied);
117       if (allow_eacces && ec.value() == EACCES)
118         ec.clear();
119       return;
120     }
121     advance(ec);
122   }
123 
124   ~__dir_stream() noexcept {
125     if (__stream_)
126       close();
127   }
128 
129   bool good() const noexcept { return __stream_ != nullptr; }
130 
131   bool advance(error_code& ec) {
132     while (true) {
133       auto str_type_pair = detail::posix_readdir(__stream_, ec);
134       auto& str = str_type_pair.first;
135       if (str == "." || str == "..") {
136         continue;
137       } else if (ec || str.empty()) {
138         close();
139         return false;
140       } else {
141         __entry_.__assign_iter_entry(
142             __root_ / str,
143             directory_entry::__create_iter_result(str_type_pair.second));
144         return true;
145       }
146     }
147   }
148 
149 private:
150   error_code close() noexcept {
151     error_code m_ec;
152     if (::closedir(__stream_) == -1)
153       m_ec = detail::capture_errno();
154     __stream_ = nullptr;
155     return m_ec;
156   }
157 
158   DIR* __stream_{nullptr};
159 
160 public:
161   path __root_;
162   directory_entry __entry_;
163 };
164 #endif
165 
166 // directory_iterator
167 
168 directory_iterator::directory_iterator(const path& p, error_code* ec,
169                                        directory_options opts) {
170   ErrorHandler<void> err("directory_iterator::directory_iterator(...)", ec, &p);
171 
172   error_code m_ec;
173   __imp_ = make_shared<__dir_stream>(p, opts, m_ec);
174   if (ec)
175     *ec = m_ec;
176   if (!__imp_->good()) {
177     __imp_.reset();
178     if (m_ec)
179       err.report(m_ec);
180   }
181 }
182 
183 directory_iterator& directory_iterator::__increment(error_code* ec) {
184   _LIBCPP_ASSERT(__imp_, "Attempting to increment an invalid iterator");
185   ErrorHandler<void> err("directory_iterator::operator++()", ec);
186 
187   error_code m_ec;
188   if (!__imp_->advance(m_ec)) {
189     path root = move(__imp_->__root_);
190     __imp_.reset();
191     if (m_ec)
192       err.report(m_ec, "at root " PATH_CSTR_FMT, root.c_str());
193   }
194   return *this;
195 }
196 
197 directory_entry const& directory_iterator::__dereference() const {
198   _LIBCPP_ASSERT(__imp_, "Attempting to dereference an invalid iterator");
199   return __imp_->__entry_;
200 }
201 
202 // recursive_directory_iterator
203 
204 struct recursive_directory_iterator::__shared_imp {
205   stack<__dir_stream> __stack_;
206   directory_options __options_;
207 };
208 
209 recursive_directory_iterator::recursive_directory_iterator(
210     const path& p, directory_options opt, error_code* ec)
211     : __imp_(nullptr), __rec_(true) {
212   ErrorHandler<void> err("recursive_directory_iterator", ec, &p);
213 
214   error_code m_ec;
215   __dir_stream new_s(p, opt, m_ec);
216   if (m_ec)
217     err.report(m_ec);
218   if (m_ec || !new_s.good())
219     return;
220 
221   __imp_ = make_shared<__shared_imp>();
222   __imp_->__options_ = opt;
223   __imp_->__stack_.push(move(new_s));
224 }
225 
226 void recursive_directory_iterator::__pop(error_code* ec) {
227   _LIBCPP_ASSERT(__imp_, "Popping the end iterator");
228   if (ec)
229     ec->clear();
230   __imp_->__stack_.pop();
231   if (__imp_->__stack_.size() == 0)
232     __imp_.reset();
233   else
234     __advance(ec);
235 }
236 
237 directory_options recursive_directory_iterator::options() const {
238   return __imp_->__options_;
239 }
240 
241 int recursive_directory_iterator::depth() const {
242   return __imp_->__stack_.size() - 1;
243 }
244 
245 const directory_entry& recursive_directory_iterator::__dereference() const {
246   return __imp_->__stack_.top().__entry_;
247 }
248 
249 recursive_directory_iterator&
250 recursive_directory_iterator::__increment(error_code* ec) {
251   if (ec)
252     ec->clear();
253   if (recursion_pending()) {
254     if (__try_recursion(ec) || (ec && *ec))
255       return *this;
256   }
257   __rec_ = true;
258   __advance(ec);
259   return *this;
260 }
261 
262 void recursive_directory_iterator::__advance(error_code* ec) {
263   ErrorHandler<void> err("recursive_directory_iterator::operator++()", ec);
264 
265   const directory_iterator end_it;
266   auto& stack = __imp_->__stack_;
267   error_code m_ec;
268   while (stack.size() > 0) {
269     if (stack.top().advance(m_ec))
270       return;
271     if (m_ec)
272       break;
273     stack.pop();
274   }
275 
276   if (m_ec) {
277     path root = move(stack.top().__root_);
278     __imp_.reset();
279     err.report(m_ec, "at root " PATH_CSTR_FMT, root.c_str());
280   } else {
281     __imp_.reset();
282   }
283 }
284 
285 bool recursive_directory_iterator::__try_recursion(error_code* ec) {
286   ErrorHandler<void> err("recursive_directory_iterator::operator++()", ec);
287 
288   bool rec_sym = bool(options() & directory_options::follow_directory_symlink);
289 
290   auto& curr_it = __imp_->__stack_.top();
291 
292   bool skip_rec = false;
293   error_code m_ec;
294   if (!rec_sym) {
295     file_status st(curr_it.__entry_.__get_sym_ft(&m_ec));
296     if (m_ec && status_known(st))
297       m_ec.clear();
298     if (m_ec || is_symlink(st) || !is_directory(st))
299       skip_rec = true;
300   } else {
301     file_status st(curr_it.__entry_.__get_ft(&m_ec));
302     if (m_ec && status_known(st))
303       m_ec.clear();
304     if (m_ec || !is_directory(st))
305       skip_rec = true;
306   }
307 
308   if (!skip_rec) {
309     __dir_stream new_it(curr_it.__entry_.path(), __imp_->__options_, m_ec);
310     if (new_it.good()) {
311       __imp_->__stack_.push(move(new_it));
312       return true;
313     }
314   }
315   if (m_ec) {
316     const bool allow_eacess =
317         bool(__imp_->__options_ & directory_options::skip_permission_denied);
318     if (m_ec.value() == EACCES && allow_eacess) {
319       if (ec)
320         ec->clear();
321     } else {
322       path at_ent = move(curr_it.__entry_.__p_);
323       __imp_.reset();
324       err.report(m_ec, "attempting recursion into " PATH_CSTR_FMT,
325                  at_ent.c_str());
326     }
327   }
328   return false;
329 }
330 
331 _LIBCPP_END_NAMESPACE_FILESYSTEM
332