Coverage Report

Created: 2021-08-24 07:12

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