xref: /freebsd/contrib/llvm-project/libcxx/src/filesystem/directory_iterator.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
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 #if defined(_LIBCPP_WIN32API)
13 #define WIN32_LEAN_AND_MEAN
14 #define NOMINMAX
15 #include <windows.h>
16 #else
17 #include <dirent.h>
18 #endif
19 #include <errno.h>
20 
21 #include "filesystem_common.h"
22 
23 _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
24 
25 namespace detail {
26 namespace {
27 
28 #if !defined(_LIBCPP_WIN32API)
29 
30 #if defined(DT_BLK)
31 template <class DirEntT, class = decltype(DirEntT::d_type)>
32 static file_type get_file_type(DirEntT* ent, int) {
33   switch (ent->d_type) {
34   case DT_BLK:
35     return file_type::block;
36   case DT_CHR:
37     return file_type::character;
38   case DT_DIR:
39     return file_type::directory;
40   case DT_FIFO:
41     return file_type::fifo;
42   case DT_LNK:
43     return file_type::symlink;
44   case DT_REG:
45     return file_type::regular;
46   case DT_SOCK:
47     return file_type::socket;
48   // Unlike in lstat, hitting "unknown" here simply means that the underlying
49   // filesystem doesn't support d_type. Report is as 'none' so we correctly
50   // set the cache to empty.
51   case DT_UNKNOWN:
52     break;
53   }
54   return file_type::none;
55 }
56 #endif // defined(DT_BLK)
57 
58 template <class DirEntT>
59 static file_type get_file_type(DirEntT* ent, long) {
60   return file_type::none;
61 }
62 
63 static pair<string_view, file_type> posix_readdir(DIR* dir_stream,
64                                                   error_code& ec) {
65   struct dirent* dir_entry_ptr = nullptr;
66   errno = 0; // zero errno in order to detect errors
67   ec.clear();
68   if ((dir_entry_ptr = ::readdir(dir_stream)) == nullptr) {
69     if (errno)
70       ec = capture_errno();
71     return {};
72   } else {
73     return {dir_entry_ptr->d_name, get_file_type(dir_entry_ptr, 0)};
74   }
75 }
76 #else
77 // defined(_LIBCPP_WIN32API)
78 
79 static file_type get_file_type(const WIN32_FIND_DATAW& data) {
80   if (data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT &&
81       data.dwReserved0 == IO_REPARSE_TAG_SYMLINK)
82     return file_type::symlink;
83   if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
84     return file_type::directory;
85   return file_type::regular;
86 }
87 static uintmax_t get_file_size(const WIN32_FIND_DATAW& data) {
88   return (static_cast<uint64_t>(data.nFileSizeHigh) << 32) + data.nFileSizeLow;
89 }
90 static file_time_type get_write_time(const WIN32_FIND_DATAW& data) {
91   ULARGE_INTEGER tmp;
92   const FILETIME& time = data.ftLastWriteTime;
93   tmp.u.LowPart = time.dwLowDateTime;
94   tmp.u.HighPart = time.dwHighDateTime;
95   return file_time_type(file_time_type::duration(tmp.QuadPart));
96 }
97 
98 #endif
99 
100 } // namespace
101 } // namespace detail
102 
103 using detail::ErrorHandler;
104 
105 #if defined(_LIBCPP_WIN32API)
106 class __dir_stream {
107 public:
108   __dir_stream() = delete;
109   __dir_stream& operator=(const __dir_stream&) = delete;
110 
111   __dir_stream(__dir_stream&& __ds) noexcept : __stream_(__ds.__stream_),
112                                                __root_(move(__ds.__root_)),
113                                                __entry_(move(__ds.__entry_)) {
114     __ds.__stream_ = INVALID_HANDLE_VALUE;
115   }
116 
117   __dir_stream(const path& root, directory_options opts, error_code& ec)
118       : __stream_(INVALID_HANDLE_VALUE), __root_(root) {
119     if (root.native().empty()) {
120       ec = make_error_code(errc::no_such_file_or_directory);
121       return;
122     }
123     __stream_ = ::FindFirstFileW((root / "*").c_str(), &__data_);
124     if (__stream_ == INVALID_HANDLE_VALUE) {
125       ec = detail::make_windows_error(GetLastError());
126       const bool ignore_permission_denied =
127           bool(opts & directory_options::skip_permission_denied);
128       if (ignore_permission_denied &&
129           ec.value() == static_cast<int>(errc::permission_denied))
130         ec.clear();
131       return;
132     }
133     if (!assign())
134       advance(ec);
135   }
136 
137   ~__dir_stream() noexcept {
138     if (__stream_ == INVALID_HANDLE_VALUE)
139       return;
140     close();
141   }
142 
143   bool good() const noexcept { return __stream_ != INVALID_HANDLE_VALUE; }
144 
145   bool advance(error_code& ec) {
146     while (::FindNextFileW(__stream_, &__data_)) {
147       if (assign())
148         return true;
149     }
150     close();
151     return false;
152   }
153 
154   bool assign() {
155     if (!wcscmp(__data_.cFileName, L".") || !wcscmp(__data_.cFileName, L".."))
156       return false;
157     // FIXME: Cache more of this
158     //directory_entry::__cached_data cdata;
159     //cdata.__type_ = get_file_type(__data_);
160     //cdata.__size_ = get_file_size(__data_);
161     //cdata.__write_time_ = get_write_time(__data_);
162     __entry_.__assign_iter_entry(
163         __root_ / __data_.cFileName,
164         directory_entry::__create_iter_result(detail::get_file_type(__data_)));
165     return true;
166   }
167 
168 private:
169   error_code close() noexcept {
170     error_code ec;
171     if (!::FindClose(__stream_))
172       ec = detail::make_windows_error(GetLastError());
173     __stream_ = INVALID_HANDLE_VALUE;
174     return ec;
175   }
176 
177   HANDLE __stream_{INVALID_HANDLE_VALUE};
178   WIN32_FIND_DATAW __data_;
179 
180 public:
181   path __root_;
182   directory_entry __entry_;
183 };
184 #else
185 class __dir_stream {
186 public:
187   __dir_stream() = delete;
188   __dir_stream& operator=(const __dir_stream&) = delete;
189 
190   __dir_stream(__dir_stream&& other) noexcept : __stream_(other.__stream_),
191                                                 __root_(move(other.__root_)),
192                                                 __entry_(move(other.__entry_)) {
193     other.__stream_ = nullptr;
194   }
195 
196   __dir_stream(const path& root, directory_options opts, error_code& ec)
197       : __stream_(nullptr), __root_(root) {
198     if ((__stream_ = ::opendir(root.c_str())) == nullptr) {
199       ec = detail::capture_errno();
200       const bool allow_eacess =
201           bool(opts & directory_options::skip_permission_denied);
202       if (allow_eacess && ec.value() == EACCES)
203         ec.clear();
204       return;
205     }
206     advance(ec);
207   }
208 
209   ~__dir_stream() noexcept {
210     if (__stream_)
211       close();
212   }
213 
214   bool good() const noexcept { return __stream_ != nullptr; }
215 
216   bool advance(error_code& ec) {
217     while (true) {
218       auto str_type_pair = detail::posix_readdir(__stream_, ec);
219       auto& str = str_type_pair.first;
220       if (str == "." || str == "..") {
221         continue;
222       } else if (ec || str.empty()) {
223         close();
224         return false;
225       } else {
226         __entry_.__assign_iter_entry(
227             __root_ / str,
228             directory_entry::__create_iter_result(str_type_pair.second));
229         return true;
230       }
231     }
232   }
233 
234 private:
235   error_code close() noexcept {
236     error_code m_ec;
237     if (::closedir(__stream_) == -1)
238       m_ec = detail::capture_errno();
239     __stream_ = nullptr;
240     return m_ec;
241   }
242 
243   DIR* __stream_{nullptr};
244 
245 public:
246   path __root_;
247   directory_entry __entry_;
248 };
249 #endif
250 
251 // directory_iterator
252 
253 directory_iterator::directory_iterator(const path& p, error_code* ec,
254                                        directory_options opts) {
255   ErrorHandler<void> err("directory_iterator::directory_iterator(...)", ec, &p);
256 
257   error_code m_ec;
258   __imp_ = make_shared<__dir_stream>(p, opts, m_ec);
259   if (ec)
260     *ec = m_ec;
261   if (!__imp_->good()) {
262     __imp_.reset();
263     if (m_ec)
264       err.report(m_ec);
265   }
266 }
267 
268 directory_iterator& directory_iterator::__increment(error_code* ec) {
269   _LIBCPP_ASSERT(__imp_, "Attempting to increment an invalid iterator");
270   ErrorHandler<void> err("directory_iterator::operator++()", ec);
271 
272   error_code m_ec;
273   if (!__imp_->advance(m_ec)) {
274     path root = move(__imp_->__root_);
275     __imp_.reset();
276     if (m_ec)
277       err.report(m_ec, "at root " PATH_CSTR_FMT, root.c_str());
278   }
279   return *this;
280 }
281 
282 directory_entry const& directory_iterator::__dereference() const {
283   _LIBCPP_ASSERT(__imp_, "Attempting to dereference an invalid iterator");
284   return __imp_->__entry_;
285 }
286 
287 // recursive_directory_iterator
288 
289 struct recursive_directory_iterator::__shared_imp {
290   stack<__dir_stream> __stack_;
291   directory_options __options_;
292 };
293 
294 recursive_directory_iterator::recursive_directory_iterator(
295     const path& p, directory_options opt, error_code* ec)
296     : __imp_(nullptr), __rec_(true) {
297   ErrorHandler<void> err("recursive_directory_iterator", ec, &p);
298 
299   error_code m_ec;
300   __dir_stream new_s(p, opt, m_ec);
301   if (m_ec)
302     err.report(m_ec);
303   if (m_ec || !new_s.good())
304     return;
305 
306   __imp_ = make_shared<__shared_imp>();
307   __imp_->__options_ = opt;
308   __imp_->__stack_.push(move(new_s));
309 }
310 
311 void recursive_directory_iterator::__pop(error_code* ec) {
312   _LIBCPP_ASSERT(__imp_, "Popping the end iterator");
313   if (ec)
314     ec->clear();
315   __imp_->__stack_.pop();
316   if (__imp_->__stack_.size() == 0)
317     __imp_.reset();
318   else
319     __advance(ec);
320 }
321 
322 directory_options recursive_directory_iterator::options() const {
323   return __imp_->__options_;
324 }
325 
326 int recursive_directory_iterator::depth() const {
327   return __imp_->__stack_.size() - 1;
328 }
329 
330 const directory_entry& recursive_directory_iterator::__dereference() const {
331   return __imp_->__stack_.top().__entry_;
332 }
333 
334 recursive_directory_iterator&
335 recursive_directory_iterator::__increment(error_code* ec) {
336   if (ec)
337     ec->clear();
338   if (recursion_pending()) {
339     if (__try_recursion(ec) || (ec && *ec))
340       return *this;
341   }
342   __rec_ = true;
343   __advance(ec);
344   return *this;
345 }
346 
347 void recursive_directory_iterator::__advance(error_code* ec) {
348   ErrorHandler<void> err("recursive_directory_iterator::operator++()", ec);
349 
350   const directory_iterator end_it;
351   auto& stack = __imp_->__stack_;
352   error_code m_ec;
353   while (stack.size() > 0) {
354     if (stack.top().advance(m_ec))
355       return;
356     if (m_ec)
357       break;
358     stack.pop();
359   }
360 
361   if (m_ec) {
362     path root = move(stack.top().__root_);
363     __imp_.reset();
364     err.report(m_ec, "at root " PATH_CSTR_FMT, root.c_str());
365   } else {
366     __imp_.reset();
367   }
368 }
369 
370 bool recursive_directory_iterator::__try_recursion(error_code* ec) {
371   ErrorHandler<void> err("recursive_directory_iterator::operator++()", ec);
372 
373   bool rec_sym = bool(options() & directory_options::follow_directory_symlink);
374 
375   auto& curr_it = __imp_->__stack_.top();
376 
377   bool skip_rec = false;
378   error_code m_ec;
379   if (!rec_sym) {
380     file_status st(curr_it.__entry_.__get_sym_ft(&m_ec));
381     if (m_ec && status_known(st))
382       m_ec.clear();
383     if (m_ec || is_symlink(st) || !is_directory(st))
384       skip_rec = true;
385   } else {
386     file_status st(curr_it.__entry_.__get_ft(&m_ec));
387     if (m_ec && status_known(st))
388       m_ec.clear();
389     if (m_ec || !is_directory(st))
390       skip_rec = true;
391   }
392 
393   if (!skip_rec) {
394     __dir_stream new_it(curr_it.__entry_.path(), __imp_->__options_, m_ec);
395     if (new_it.good()) {
396       __imp_->__stack_.push(move(new_it));
397       return true;
398     }
399   }
400   if (m_ec) {
401     const bool allow_eacess =
402         bool(__imp_->__options_ & directory_options::skip_permission_denied);
403     if (m_ec.value() == EACCES && allow_eacess) {
404       if (ec)
405         ec->clear();
406     } else {
407       path at_ent = move(curr_it.__entry_.__p_);
408       __imp_.reset();
409       err.report(m_ec, "attempting recursion into " PATH_CSTR_FMT,
410                  at_ent.c_str());
411     }
412   }
413   return false;
414 }
415 
416 _LIBCPP_END_NAMESPACE_FILESYSTEM
417