Coverage Report

Created: 2022-01-25 06:29

/Users/buildslave/jenkins/workspace/coverage/llvm-project/libcxx/src/filesystem/directory_iterator.cpp
Line
Count
Source (jump to first uncovered line)
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
0
static file_type get_file_type(DirEntT* ent, int) {
33
0
  switch (ent->d_type) {
34
0
  case DT_BLK:
35
0
    return file_type::block;
36
0
  case DT_CHR:
37
0
    return file_type::character;
38
0
  case DT_DIR:
39
0
    return file_type::directory;
40
0
  case DT_FIFO:
41
0
    return file_type::fifo;
42
0
  case DT_LNK:
43
0
    return file_type::symlink;
44
0
  case DT_REG:
45
0
    return file_type::regular;
46
0
  case DT_SOCK:
47
0
    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
0
  case DT_UNKNOWN:
52
0
    break;
53
0
  }
54
0
  return file_type::none;
55
0
}
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
0
                                                  error_code& ec) {
65
0
  struct dirent* dir_entry_ptr = nullptr;
66
0
  errno = 0; // zero errno in order to detect errors
67
0
  ec.clear();
68
0
  if ((dir_entry_ptr = ::readdir(dir_stream)) == nullptr) {
69
0
    if (errno)
70
0
      ec = capture_errno();
71
0
    return {};
72
0
  } else {
73
0
    return {dir_entry_ptr->d_name, get_file_type(dir_entry_ptr, 0)};
74
0
  }
75
0
}
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
0
                                                __entry_(move(other.__entry_)) {
193
0
    other.__stream_ = nullptr;
194
0
  }
195
196
  __dir_stream(const path& root, directory_options opts, error_code& ec)
197
0
      : __stream_(nullptr), __root_(root) {
198
0
    if ((__stream_ = ::opendir(root.c_str())) == nullptr) {
199
0
      ec = detail::capture_errno();
200
0
      const bool allow_eacess =
201
0
          bool(opts & directory_options::skip_permission_denied);
202
0
      if (allow_eacess && ec.value() == EACCES)
203
0
        ec.clear();
204
0
      return;
205
0
    }
206
0
    advance(ec);
207
0
  }
208
209
0
  ~__dir_stream() noexcept {
210
0
    if (__stream_)
211
0
      close();
212
0
  }
213
214
0
  bool good() const noexcept { return __stream_ != nullptr; }
215
216
0
  bool advance(error_code& ec) {
217
0
    while (true) {
218
0
      auto str_type_pair = detail::posix_readdir(__stream_, ec);
219
0
      auto& str = str_type_pair.first;
220
0
      if (str == "." || str == "..") {
221
0
        continue;
222
0
      } else if (ec || str.empty()) {
223
0
        close();
224
0
        return false;
225
0
      } else {
226
0
        __entry_.__assign_iter_entry(
227
0
            __root_ / str,
228
0
            directory_entry::__create_iter_result(str_type_pair.second));
229
0
        return true;
230
0
      }
231
0
    }
232
0
  }
233
234
private:
235
0
  error_code close() noexcept {
236
0
    error_code m_ec;
237
0
    if (::closedir(__stream_) == -1)
238
0
      m_ec = detail::capture_errno();
239
0
    __stream_ = nullptr;
240
0
    return m_ec;
241
0
  }
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
0
                                       directory_options opts) {
255
0
  ErrorHandler<void> err("directory_iterator::directory_iterator(...)", ec, &p);
256
257
0
  error_code m_ec;
258
0
  __imp_ = make_shared<__dir_stream>(p, opts, m_ec);
259
0
  if (ec)
260
0
    *ec = m_ec;
261
0
  if (!__imp_->good()) {
262
0
    __imp_.reset();
263
0
    if (m_ec)
264
0
      err.report(m_ec);
265
0
  }
266
0
}
267
268
0
directory_iterator& directory_iterator::__increment(error_code* ec) {
269
0
  _LIBCPP_ASSERT(__imp_, "Attempting to increment an invalid iterator");
270
0
  ErrorHandler<void> err("directory_iterator::operator++()", ec);
271
272
0
  error_code m_ec;
273
0
  if (!__imp_->advance(m_ec)) {
274
0
    path root = move(__imp_->__root_);
275
0
    __imp_.reset();
276
0
    if (m_ec)
277
0
      err.report(m_ec, "at root " PATH_CSTR_FMT, root.c_str());
278
0
  }
279
0
  return *this;
280
0
}
281
282
0
directory_entry const& directory_iterator::__dereference() const {
283
0
  _LIBCPP_ASSERT(__imp_, "Attempting to dereference an invalid iterator");
284
0
  return __imp_->__entry_;
285
0
}
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
0
    : __imp_(nullptr), __rec_(true) {
297
0
  ErrorHandler<void> err("recursive_directory_iterator", ec, &p);
298
299
0
  error_code m_ec;
300
0
  __dir_stream new_s(p, opt, m_ec);
301
0
  if (m_ec)
302
0
    err.report(m_ec);
303
0
  if (m_ec || !new_s.good())
304
0
    return;
305
306
0
  __imp_ = make_shared<__shared_imp>();
307
0
  __imp_->__options_ = opt;
308
0
  __imp_->__stack_.push(move(new_s));
309
0
}
310
311
0
void recursive_directory_iterator::__pop(error_code* ec) {
312
0
  _LIBCPP_ASSERT(__imp_, "Popping the end iterator");
313
0
  if (ec)
314
0
    ec->clear();
315
0
  __imp_->__stack_.pop();
316
0
  if (__imp_->__stack_.size() == 0)
317
0
    __imp_.reset();
318
0
  else
319
0
    __advance(ec);
320
0
}
321
322
0
directory_options recursive_directory_iterator::options() const {
323
0
  return __imp_->__options_;
324
0
}
325
326
0
int recursive_directory_iterator::depth() const {
327
0
  return __imp_->__stack_.size() - 1;
328
0
}
329
330
0
const directory_entry& recursive_directory_iterator::__dereference() const {
331
0
  return __imp_->__stack_.top().__entry_;
332
0
}
333
334
recursive_directory_iterator&
335
0
recursive_directory_iterator::__increment(error_code* ec) {
336
0
  if (ec)
337
0
    ec->clear();
338
0
  if (recursion_pending()) {
339
0
    if (__try_recursion(ec) || (ec && *ec))
340
0
      return *this;
341
0
  }
342
0
  __rec_ = true;
343
0
  __advance(ec);
344
0
  return *this;
345
0
}
346
347
0
void recursive_directory_iterator::__advance(error_code* ec) {
348
0
  ErrorHandler<void> err("recursive_directory_iterator::operator++()", ec);
349
350
0
  const directory_iterator end_it;
351
0
  auto& stack = __imp_->__stack_;
352
0
  error_code m_ec;
353
0
  while (stack.size() > 0) {
354
0
    if (stack.top().advance(m_ec))
355
0
      return;
356
0
    if (m_ec)
357
0
      break;
358
0
    stack.pop();
359
0
  }
360
361
0
  if (m_ec) {
362
0
    path root = move(stack.top().__root_);
363
0
    __imp_.reset();
364
0
    err.report(m_ec, "at root " PATH_CSTR_FMT, root.c_str());
365
0
  } else {
366
0
    __imp_.reset();
367
0
  }
368
0
}
369
370
0
bool recursive_directory_iterator::__try_recursion(error_code* ec) {
371
0
  ErrorHandler<void> err("recursive_directory_iterator::operator++()", ec);
372
373
0
  bool rec_sym = bool(options() & directory_options::follow_directory_symlink);
374
375
0
  auto& curr_it = __imp_->__stack_.top();
376
377
0
  bool skip_rec = false;
378
0
  error_code m_ec;
379
0
  if (!rec_sym) {
380
0
    file_status st(curr_it.__entry_.__get_sym_ft(&m_ec));
381
0
    if (m_ec && status_known(st))
382
0
      m_ec.clear();
383
0
    if (m_ec || is_symlink(st) || !is_directory(st))
384
0
      skip_rec = true;
385
0
  } else {
386
0
    file_status st(curr_it.__entry_.__get_ft(&m_ec));
387
0
    if (m_ec && status_known(st))
388
0
      m_ec.clear();
389
0
    if (m_ec || !is_directory(st))
390
0
      skip_rec = true;
391
0
  }
392
393
0
  if (!skip_rec) {
394
0
    __dir_stream new_it(curr_it.__entry_.path(), __imp_->__options_, m_ec);
395
0
    if (new_it.good()) {
396
0
      __imp_->__stack_.push(move(new_it));
397
0
      return true;
398
0
    }
399
0
  }
400
0
  if (m_ec) {
401
0
    const bool allow_eacess =
402
0
        bool(__imp_->__options_ & directory_options::skip_permission_denied);
403
0
    if (m_ec.value() == EACCES && allow_eacess) {
404
0
      if (ec)
405
0
        ec->clear();
406
0
    } else {
407
0
      path at_ent = move(curr_it.__entry_.__p_);
408
0
      __imp_.reset();
409
0
      err.report(m_ec, "attempting recursion into " PATH_CSTR_FMT,
410
0
                 at_ent.c_str());
411
0
    }
412
0
  }
413
0
  return false;
414
0
}
415
416
_LIBCPP_END_NAMESPACE_FILESYSTEM