summaryrefslogtreecommitdiff
path: root/libstdc++-v3/src/c++17/fs_dir.cc
blob: 2258399da258772913db0fb68d485e95c744837c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
// Class filesystem::directory_entry etc. -*- C++ -*-

// Copyright (C) 2014-2022 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.

// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
// <http://www.gnu.org/licenses/>.

#ifndef _GLIBCXX_USE_CXX11_ABI
# define _GLIBCXX_USE_CXX11_ABI 1
#endif

#include <bits/largefile-config.h>
#include <filesystem>
#include <utility>
#include <stack>
#include <string.h>
#include <errno.h>
#define _GLIBCXX_BEGIN_NAMESPACE_FILESYSTEM namespace filesystem {
#define _GLIBCXX_END_NAMESPACE_FILESYSTEM }
#include "../filesystem/dir-common.h"

namespace fs = std::filesystem;
namespace posix = std::filesystem::__gnu_posix;

template class std::__shared_ptr<fs::_Dir>;
template class std::__shared_ptr<fs::recursive_directory_iterator::_Dir_stack>;

struct fs::_Dir : _Dir_base
{
  _Dir(const fs::path& p, bool skip_permission_denied, bool nofollow,
       [[maybe_unused]] bool filename_only, error_code& ec)
  : _Dir_base(p.c_str(), skip_permission_denied, nofollow, ec)
  {
#if _GLIBCXX_HAVE_DIRFD && _GLIBCXX_HAVE_OPENAT && _GLIBCXX_HAVE_UNLINKAT
    if (filename_only)
      return; // Do not store path p when we aren't going to use it.
#endif

    if (!ec)
      path = p;
  }

  _Dir(_Dir_base&& d, const path& p) : _Dir_base(std::move(d)), path(p) { }

  _Dir(_Dir&&) = default;

  // Returns false when the end of the directory entries is reached.
  // Reports errors by setting ec.
  bool advance(bool skip_permission_denied, error_code& ec) noexcept
  {
    if (const auto entp = _Dir_base::advance(skip_permission_denied, ec))
      {
	auto name = path;
	name /= entp->d_name;
	file_type type = file_type::none;
#ifdef _GLIBCXX_HAVE_STRUCT_DIRENT_D_TYPE
	// Even if the OS supports dirent::d_type the filesystem might not:
	if (entp->d_type != DT_UNKNOWN)
	  type = get_file_type(*entp);
#endif
	entry = fs::directory_entry{std::move(name), type};
	return true;
      }
    else if (!ec)
      {
	// reached the end
	entry = {};
      }
    return false;
  }

  bool advance(error_code& ec) noexcept { return advance(false, ec); }

  // Returns false when the end of the directory entries is reached.
  // Reports errors by throwing.
  bool advance(bool skip_permission_denied = false)
  {
    error_code ec;
    const bool ok = advance(skip_permission_denied, ec);
    if (ec)
      _GLIBCXX_THROW_OR_ABORT(filesystem_error(
	      "directory iterator cannot advance", ec));
    return ok;
  }

  bool should_recurse(bool follow_symlink, error_code& ec) const
  {
    file_type type = entry._M_type;
    if (type == file_type::none)
    {
      type = entry.symlink_status(ec).type();
      if (ec)
	return false;
    }

    if (type == file_type::directory)
      return true;
    if (type == file_type::symlink)
      return follow_symlink && is_directory(entry.status(ec));
    return false;
  }

  // Return a pathname for the current directory entry, as an _At_path.
  _Dir_base::_At_path
  current() const noexcept
  {
    const fs::path& p = entry.path();
#if _GLIBCXX_HAVE_DIRFD
    if (!p.empty()) [[__likely__]]
      {
	auto len = std::prev(p.end())->native().size();
	return {::dirfd(this->dirp), p.c_str(), p.native().size() - len};
      }
#endif
    return p.c_str();
  }

  // Create a new _Dir for the directory this->entry.path().
  _Dir
  open_subdir(bool skip_permission_denied, bool nofollow,
	      error_code& ec) const noexcept
  {
    _Dir_base d(current(), skip_permission_denied, nofollow, ec);
    // If this->path is empty, the new _Dir should have an empty path too.
    const fs::path& p = this->path.empty() ? this->path : this->entry.path();
    return _Dir(std::move(d), p);
  }

  bool
  do_unlink(bool is_directory, error_code& ec) const noexcept
  {
#if _GLIBCXX_HAVE_UNLINKAT
    const auto atp = current();
    if (::unlinkat(atp.dir(), atp.path_at_dir(),
		   is_directory ? AT_REMOVEDIR : 0) == -1)
      {
	ec.assign(errno, std::generic_category());
	return false;
      }
    else
      {
	ec.clear();
	return true;
      }
#else
    return fs::remove(entry.path(), ec);
#endif
  }

  // Remove the non-directory that this->entry refers to.
  bool
  unlink(error_code& ec) const noexcept
  { return do_unlink(/* is_directory*/ false, ec); }

  // Remove the directory that this->entry refers to.
  bool
  rmdir(error_code& ec) const noexcept
  { return do_unlink(/* is_directory*/ true, ec); }

  fs::path		path; // Empty if only using unlinkat with file descr.
  directory_entry	entry;
};

namespace
{
  template<typename Bitmask>
    inline bool
    is_set(Bitmask obj, Bitmask bits)
    {
      return (obj & bits) != Bitmask::none;
    }

// Non-standard directory option flags, currently only for internal use:
//
// Do not allow directory iterator to open a symlink.
// This might seem redundant given directory_options::follow_directory_symlink
// but that is only checked for recursing into sub-directories, and we need
// something that controls the initial opendir() call in the constructor.
constexpr fs::directory_options __directory_iterator_nofollow{64};
// Do not store full paths in std::filesystem::recursive_directory_iterator.
// When fs::remove_all uses recursive_directory_iterator::__erase and unlinkat
// is available in libc, we do not need the parent directory's path, only the
// filenames of the directory entries (and a file descriptor for the parent).
// This flag avoids allocating memory for full paths that won't be needed.
constexpr fs::directory_options __directory_iterator_filename_only{128};
}

fs::directory_iterator::
directory_iterator(const path& p, directory_options options, error_code* ecptr)
{
  // Do not report an error for permission denied errors.
  const bool skip_permission_denied
    = is_set(options, directory_options::skip_permission_denied);
  // Do not allow opening a symlink.
  const bool nofollow = is_set(options, __directory_iterator_nofollow);

  error_code ec;
  _Dir dir(p, skip_permission_denied, nofollow, /*filename only*/false, ec);

  if (dir.dirp)
    {
      auto sp = std::__make_shared<fs::_Dir>(std::move(dir));
      if (sp->advance(skip_permission_denied, ec))
	_M_dir.swap(sp);
    }
  if (ecptr)
    *ecptr = ec;
  else if (ec)
    _GLIBCXX_THROW_OR_ABORT(fs::filesystem_error(
	  "directory iterator cannot open directory", p, ec));
}

const fs::directory_entry&
fs::directory_iterator::operator*() const noexcept
{
  return _M_dir->entry;
}

fs::directory_iterator&
fs::directory_iterator::operator++()
{
  if (!_M_dir)
    _GLIBCXX_THROW_OR_ABORT(filesystem_error(
	  "cannot advance non-dereferenceable directory iterator",
	  std::make_error_code(errc::invalid_argument)));
  if (!_M_dir->advance())
    _M_dir.reset();
  return *this;
}

fs::directory_iterator&
fs::directory_iterator::increment(error_code& ec)
{
  if (!_M_dir)
    {
      ec = std::make_error_code(errc::invalid_argument);
      return *this;
    }
  if (!_M_dir->advance(ec))
    _M_dir.reset();
  return *this;
}

struct fs::recursive_directory_iterator::_Dir_stack : std::stack<_Dir>
{
  _Dir_stack(directory_options opts, _Dir&& dir)
  : options(opts), pending(true)
  {
    this->push(std::move(dir));
  }

  path::string_type orig;
  const directory_options options;
  bool pending;

  void clear() { c.clear(); }

  path current_path() const
  {
    path p;
    if (top().path.empty())
      {
	// Reconstruct path that failed from dir stack.
	p = orig;
	for (auto& d : this->c)
	  p /= d.entry.path();
      }
    else
      p = top().entry.path();
    return p;
  }
};

fs::recursive_directory_iterator::
recursive_directory_iterator(const path& p, directory_options options,
                             error_code* ecptr)
{
  // Do not report an error for permission denied errors.
  const bool skip_permission_denied
    = is_set(options, directory_options::skip_permission_denied);
  // Do not allow opening a symlink as the starting directory.
  const bool nofollow = is_set(options, __directory_iterator_nofollow);
  // Prefer to store only filenames (not full paths) in directory_entry values.
  const bool filename_only
     = is_set(options, __directory_iterator_filename_only);

  error_code ec;
  _Dir dir(p, skip_permission_denied, nofollow, filename_only, ec);

  if (dir.dirp)
    {
      auto sp = std::__make_shared<_Dir_stack>(options, std::move(dir));
      if (ecptr ? sp->top().advance(skip_permission_denied, *ecptr)
		: sp->top().advance(skip_permission_denied))
	{
	  _M_dirs.swap(sp);
	  if (filename_only) // Need to save original path for error reporting.
	    _M_dirs->orig = p.native();
	}
    }
  else if (ecptr)
    *ecptr = ec;
  else if (ec)
    _GLIBCXX_THROW_OR_ABORT(fs::filesystem_error(
	  "recursive directory iterator cannot open directory", p, ec));
}

fs::recursive_directory_iterator::~recursive_directory_iterator() = default;

fs::directory_options
fs::recursive_directory_iterator::options() const noexcept
{
  return _M_dirs->options;
}

int
fs::recursive_directory_iterator::depth() const noexcept
{
  return int(_M_dirs->size()) - 1;
}

bool
fs::recursive_directory_iterator::recursion_pending() const noexcept
{
  return _M_dirs->pending;
}

const fs::directory_entry&
fs::recursive_directory_iterator::operator*() const noexcept
{
  return _M_dirs->top().entry;
}

fs::recursive_directory_iterator&
fs::recursive_directory_iterator::
operator=(const recursive_directory_iterator& other) noexcept = default;

fs::recursive_directory_iterator&
fs::recursive_directory_iterator::
operator=(recursive_directory_iterator&& other) noexcept = default;

fs::recursive_directory_iterator&
fs::recursive_directory_iterator::operator++()
{
  error_code ec;
  increment(ec);
  if (ec)
    _GLIBCXX_THROW_OR_ABORT(filesystem_error(
	  "cannot increment recursive directory iterator", ec));
  return *this;
}

fs::recursive_directory_iterator&
fs::recursive_directory_iterator::increment(error_code& ec)
{
  if (!_M_dirs)
    {
      ec = std::make_error_code(errc::invalid_argument);
      return *this;
    }

  const bool follow
    = is_set(_M_dirs->options, directory_options::follow_directory_symlink);
  const bool skip_permission_denied
    = is_set(_M_dirs->options, directory_options::skip_permission_denied);

  auto& top = _M_dirs->top();

  if (std::exchange(_M_dirs->pending, true) && top.should_recurse(follow, ec))
    {
      _Dir dir = top.open_subdir(skip_permission_denied, !follow, ec);
      if (ec)
	{
	  _M_dirs.reset();
	  return *this;
	}
      if (dir.dirp)
	_M_dirs->push(std::move(dir));
    }

  while (!_M_dirs->top().advance(skip_permission_denied, ec) && !ec)
    {
      _M_dirs->pop();
      if (_M_dirs->empty())
	{
	  _M_dirs.reset();
	  return *this;
	}
    }

  if (ec)
    _M_dirs.reset();

  return *this;
}

void
fs::recursive_directory_iterator::pop(error_code& ec)
{
  if (!_M_dirs)
    {
      ec = std::make_error_code(errc::invalid_argument);
      return;
    }

  const bool skip_permission_denied
    = is_set(_M_dirs->options, directory_options::skip_permission_denied);

  do {
    _M_dirs->pop();
    if (_M_dirs->empty())
      {
	_M_dirs.reset();
	ec.clear();
	return;
      }
  } while (!_M_dirs->top().advance(skip_permission_denied, ec) && !ec);

  if (ec)
    _M_dirs.reset();
}

void
fs::recursive_directory_iterator::pop()
{
  [[maybe_unused]] const bool dereferenceable = _M_dirs != nullptr;
  error_code ec;
  pop(ec);
  if (ec)
    _GLIBCXX_THROW_OR_ABORT(filesystem_error(dereferenceable
	  ? "recursive directory iterator cannot pop"
	  : "non-dereferenceable recursive directory iterator cannot pop",
	  ec));
}

void
fs::recursive_directory_iterator::disable_recursion_pending() noexcept
{
  _M_dirs->pending = false;
}

// Used to implement filesystem::remove_all.
fs::recursive_directory_iterator&
fs::recursive_directory_iterator::__erase(error_code* ecptr)
{
  error_code ec;
  if (!_M_dirs)
    {
      ec = std::make_error_code(errc::invalid_argument);
      return *this;
    }

  // We never want to skip permission denied when removing files.
  const bool skip_permission_denied = false;
  // We never want to follow directory symlinks when removing files.
  const bool nofollow = true;

  // Loop until we find something we can remove.
  while (!ec)
    {
      auto& top = _M_dirs->top();

#if _GLIBCXX_FILESYSTEM_IS_WINDOWS
      // _Dir::unlink uses fs::remove which uses std::system_category() for
      // Windows errror codes, so we can't just check for EPERM and EISDIR.
      // Use directory_entry::refresh() here to check if we have a directory.
      // This can be a TOCTTOU race, but we don't have openat or unlinkat to
      // solve that on Windows, and generally don't support symlinks anyway.
      if (top.entry._M_type == file_type::none)
	top.entry.refresh();
#endif

      if (top.entry._M_type == file_type::directory)
	{
	  _Dir dir = top.open_subdir(skip_permission_denied, nofollow, ec);
	  if (!ec)
	    {
	      __glibcxx_assert(dir.dirp != nullptr);
	      if (dir.advance(skip_permission_denied, ec))
		{
		  // Non-empty directory, recurse into it.
		  _M_dirs->push(std::move(dir));
		  continue;
		}
	      if (!ec)
		{
		  // Directory is empty so we can remove it.
		  if (top.rmdir(ec))
		    break; // Success
		}
	    }
	}
      else if (top.unlink(ec))
	break; // Success
#if ! _GLIBCXX_FILESYSTEM_IS_WINDOWS
      else if (top.entry._M_type == file_type::none)
	{
	  // We did not have a cached type, so it's possible that top.entry
	  // is actually a directory, and that's why the unlink above failed.
#ifdef EPERM
	  // POSIX.1-2017 says unlink on a directory returns EPERM,
	  // but LSB allows EISDIR too. Some targets don't even define EPERM.
	  if (ec.value() == EPERM || ec.value() == EISDIR)
#else
	  if (ec.value() == EISDIR)
#endif
	    {
	      // Retry, treating it as a directory.
	      top.entry._M_type = file_type::directory;
	      ec.clear();
	      continue;
	    }
	}
#endif
    }

  if (!ec)
    {
      // We successfully removed the current entry, so advance to the next one.
      if (_M_dirs->top().advance(skip_permission_denied, ec))
	return *this;
      else if (!ec)
	{
	  // Reached the end of the current directory.
	  _M_dirs->pop();
	  if (_M_dirs->empty())
	    _M_dirs.reset();
	  return *this;
	}
    }

  // Reset _M_dirs to empty.
  auto dirs = std::move(_M_dirs);

  // Need to report an error
  if (ecptr)
    *ecptr = ec;
  else
    _GLIBCXX_THROW_OR_ABORT(fs::filesystem_error("cannot remove all",
						 dirs->orig,
						 dirs->current_path(),
						 ec));

  return *this;
}