Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/libcxx/src/filesystem/operations.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--------------------- filesystem/ops.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 "array"
11
#include "iterator"
12
#include "fstream"
13
#include "random" /* for unique_path */
14
#include "string_view"
15
#include "type_traits"
16
#include "vector"
17
#include "cstdlib"
18
#include "climits"
19
20
#include "filesystem_common.h"
21
22
#include <unistd.h>
23
#include <sys/stat.h>
24
#include <sys/statvfs.h>
25
#include <time.h>
26
#include <fcntl.h> /* values for fchmodat */
27
28
#if defined(__linux__)
29
#include <linux/version.h>
30
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 33)
31
#include <sys/sendfile.h>
32
#define _LIBCPP_USE_SENDFILE
33
#endif
34
#elif defined(__APPLE__) || __has_include(<copyfile.h>)
35
#include <copyfile.h>
36
#define _LIBCPP_USE_COPYFILE
37
#endif
38
39
#if !defined(__APPLE__)
40
#define _LIBCPP_USE_CLOCK_GETTIME
41
#endif
42
43
#if !defined(CLOCK_REALTIME) || !defined(_LIBCPP_USE_CLOCK_GETTIME)
44
#include <sys/time.h> // for gettimeofday and timeval
45
#endif                // !defined(CLOCK_REALTIME)
46
47
#if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB)
48
#pragma comment(lib, "rt")
49
#endif
50
51
#if defined(_LIBCPP_COMPILER_GCC)
52
#if _GNUC_VER < 500
53
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
54
#endif
55
#endif
56
57
_LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
58
59
namespace {
60
namespace parser {
61
62
using string_view_t = path::__string_view;
63
using string_view_pair = pair<string_view_t, string_view_t>;
64
using PosPtr = path::value_type const*;
65
66
struct PathParser {
67
  enum ParserState : unsigned char {
68
    // Zero is a special sentinel value used by default constructed iterators.
69
    PS_BeforeBegin = path::iterator::_BeforeBegin,
70
    PS_InRootName = path::iterator::_InRootName,
71
    PS_InRootDir = path::iterator::_InRootDir,
72
    PS_InFilenames = path::iterator::_InFilenames,
73
    PS_InTrailingSep = path::iterator::_InTrailingSep,
74
    PS_AtEnd = path::iterator::_AtEnd
75
  };
76
77
  const string_view_t Path;
78
  string_view_t RawEntry;
79
  ParserState State;
80
81
private:
82
  PathParser(string_view_t P, ParserState State) noexcept : Path(P),
83
0
                                                            State(State) {}
84
85
public:
86
  PathParser(string_view_t P, string_view_t E, unsigned char S)
87
0
      : Path(P), RawEntry(E), State(static_cast<ParserState>(S)) {
88
0
    // S cannot be '0' or PS_BeforeBegin.
89
0
  }
90
91
0
  static PathParser CreateBegin(string_view_t P) noexcept {
92
0
    PathParser PP(P, PS_BeforeBegin);
93
0
    PP.increment();
94
0
    return PP;
95
0
  }
96
97
0
  static PathParser CreateEnd(string_view_t P) noexcept {
98
0
    PathParser PP(P, PS_AtEnd);
99
0
    return PP;
100
0
  }
101
102
0
  PosPtr peek() const noexcept {
103
0
    auto TkEnd = getNextTokenStartPos();
104
0
    auto End = getAfterBack();
105
0
    return TkEnd == End ? nullptr : TkEnd;
106
0
  }
107
108
0
  void increment() noexcept {
109
0
    const PosPtr End = getAfterBack();
110
0
    const PosPtr Start = getNextTokenStartPos();
111
0
    if (Start == End)
112
0
      return makeState(PS_AtEnd);
113
0
114
0
    switch (State) {
115
0
    case PS_BeforeBegin: {
116
0
      PosPtr TkEnd = consumeSeparator(Start, End);
117
0
      if (TkEnd)
118
0
        return makeState(PS_InRootDir, Start, TkEnd);
119
0
      else
120
0
        return makeState(PS_InFilenames, Start, consumeName(Start, End));
121
0
    }
122
0
    case PS_InRootDir:
123
0
      return makeState(PS_InFilenames, Start, consumeName(Start, End));
124
0
125
0
    case PS_InFilenames: {
126
0
      PosPtr SepEnd = consumeSeparator(Start, End);
127
0
      if (SepEnd != End) {
128
0
        PosPtr TkEnd = consumeName(SepEnd, End);
129
0
        if (TkEnd)
130
0
          return makeState(PS_InFilenames, SepEnd, TkEnd);
131
0
      }
132
0
      return makeState(PS_InTrailingSep, Start, SepEnd);
133
0
    }
134
0
135
0
    case PS_InTrailingSep:
136
0
      return makeState(PS_AtEnd);
137
0
138
0
    case PS_InRootName:
139
0
    case PS_AtEnd:
140
0
      _LIBCPP_UNREACHABLE();
141
0
    }
142
0
  }
143
144
0
  void decrement() noexcept {
145
0
    const PosPtr REnd = getBeforeFront();
146
0
    const PosPtr RStart = getCurrentTokenStartPos() - 1;
147
0
    if (RStart == REnd) // we're decrementing the begin
148
0
      return makeState(PS_BeforeBegin);
149
0
150
0
    switch (State) {
151
0
    case PS_AtEnd: {
152
0
      // Try to consume a trailing separator or root directory first.
153
0
      if (PosPtr SepEnd = consumeSeparator(RStart, REnd)) {
154
0
        if (SepEnd == REnd)
155
0
          return makeState(PS_InRootDir, Path.data(), RStart + 1);
156
0
        return makeState(PS_InTrailingSep, SepEnd + 1, RStart + 1);
157
0
      } else {
158
0
        PosPtr TkStart = consumeName(RStart, REnd);
159
0
        return makeState(PS_InFilenames, TkStart + 1, RStart + 1);
160
0
      }
161
0
    }
162
0
    case PS_InTrailingSep:
163
0
      return makeState(PS_InFilenames, consumeName(RStart, REnd) + 1,
164
0
                       RStart + 1);
165
0
    case PS_InFilenames: {
166
0
      PosPtr SepEnd = consumeSeparator(RStart, REnd);
167
0
      if (SepEnd == REnd)
168
0
        return makeState(PS_InRootDir, Path.data(), RStart + 1);
169
0
      PosPtr TkEnd = consumeName(SepEnd, REnd);
170
0
      return makeState(PS_InFilenames, TkEnd + 1, SepEnd + 1);
171
0
    }
172
0
    case PS_InRootDir:
173
0
      // return makeState(PS_InRootName, Path.data(), RStart + 1);
174
0
    case PS_InRootName:
175
0
    case PS_BeforeBegin:
176
0
      _LIBCPP_UNREACHABLE();
177
0
    }
178
0
  }
179
180
  /// \brief Return a view with the "preferred representation" of the current
181
  ///   element. For example trailing separators are represented as a '.'
182
0
  string_view_t operator*() const noexcept {
183
0
    switch (State) {
184
0
    case PS_BeforeBegin:
185
0
    case PS_AtEnd:
186
0
      return "";
187
0
    case PS_InRootDir:
188
0
      return "/";
189
0
    case PS_InTrailingSep:
190
0
      return "";
191
0
    case PS_InRootName:
192
0
    case PS_InFilenames:
193
0
      return RawEntry;
194
0
    }
195
0
    _LIBCPP_UNREACHABLE();
196
0
  }
197
198
0
  explicit operator bool() const noexcept {
199
0
    return State != PS_BeforeBegin && State != PS_AtEnd;
200
0
  }
201
202
0
  PathParser& operator++() noexcept {
203
0
    increment();
204
0
    return *this;
205
0
  }
206
207
0
  PathParser& operator--() noexcept {
208
0
    decrement();
209
0
    return *this;
210
0
  }
211
212
0
  bool atEnd() const noexcept {
213
0
    return State == PS_AtEnd;
214
0
  }
215
216
0
  bool inRootDir() const noexcept {
217
0
    return State == PS_InRootDir;
218
0
  }
219
220
0
  bool inRootName() const noexcept {
221
0
    return State == PS_InRootName;
222
0
  }
223
224
0
  bool inRootPath() const noexcept {
225
0
    return inRootName() || inRootDir();
226
0
  }
227
228
private:
229
0
  void makeState(ParserState NewState, PosPtr Start, PosPtr End) noexcept {
230
0
    State = NewState;
231
0
    RawEntry = string_view_t(Start, End - Start);
232
0
  }
233
0
  void makeState(ParserState NewState) noexcept {
234
0
    State = NewState;
235
0
    RawEntry = {};
236
0
  }
237
238
0
  PosPtr getAfterBack() const noexcept { return Path.data() + Path.size(); }
239
240
0
  PosPtr getBeforeFront() const noexcept { return Path.data() - 1; }
241
242
  /// \brief Return a pointer to the first character after the currently
243
  ///   lexed element.
244
0
  PosPtr getNextTokenStartPos() const noexcept {
245
0
    switch (State) {
246
0
    case PS_BeforeBegin:
247
0
      return Path.data();
248
0
    case PS_InRootName:
249
0
    case PS_InRootDir:
250
0
    case PS_InFilenames:
251
0
      return &RawEntry.back() + 1;
252
0
    case PS_InTrailingSep:
253
0
    case PS_AtEnd:
254
0
      return getAfterBack();
255
0
    }
256
0
    _LIBCPP_UNREACHABLE();
257
0
  }
258
259
  /// \brief Return a pointer to the first character in the currently lexed
260
  ///   element.
261
0
  PosPtr getCurrentTokenStartPos() const noexcept {
262
0
    switch (State) {
263
0
    case PS_BeforeBegin:
264
0
    case PS_InRootName:
265
0
      return &Path.front();
266
0
    case PS_InRootDir:
267
0
    case PS_InFilenames:
268
0
    case PS_InTrailingSep:
269
0
      return &RawEntry.front();
270
0
    case PS_AtEnd:
271
0
      return &Path.back() + 1;
272
0
    }
273
0
    _LIBCPP_UNREACHABLE();
274
0
  }
275
276
0
  PosPtr consumeSeparator(PosPtr P, PosPtr End) const noexcept {
277
0
    if (P == End || *P != '/')
278
0
      return nullptr;
279
0
    const int Inc = P < End ? 1 : -1;
280
0
    P += Inc;
281
0
    while (P != End && *P == '/')
282
0
      P += Inc;
283
0
    return P;
284
0
  }
285
286
0
  PosPtr consumeName(PosPtr P, PosPtr End) const noexcept {
287
0
    if (P == End || *P == '/')
288
0
      return nullptr;
289
0
    const int Inc = P < End ? 1 : -1;
290
0
    P += Inc;
291
0
    while (P != End && *P != '/')
292
0
      P += Inc;
293
0
    return P;
294
0
  }
295
};
296
297
0
string_view_pair separate_filename(string_view_t const& s) {
298
0
  if (s == "." || s == ".." || s.empty())
299
0
    return string_view_pair{s, ""};
300
0
  auto pos = s.find_last_of('.');
301
0
  if (pos == string_view_t::npos || pos == 0)
302
0
    return string_view_pair{s, string_view_t{}};
303
0
  return string_view_pair{s.substr(0, pos), s.substr(pos)};
304
0
}
305
306
0
string_view_t createView(PosPtr S, PosPtr E) noexcept {
307
0
  return {S, static_cast<size_t>(E - S) + 1};
308
0
}
309
310
} // namespace parser
311
} // namespace
312
313
//                       POSIX HELPERS
314
315
namespace detail {
316
namespace {
317
318
using value_type = path::value_type;
319
using string_type = path::string_type;
320
321
struct FileDescriptor {
322
  const path& name;
323
  int fd = -1;
324
  StatT m_stat;
325
  file_status m_status;
326
327
  template <class... Args>
328
0
  static FileDescriptor create(const path* p, error_code& ec, Args... args) {
329
0
    ec.clear();
330
0
    int fd;
331
0
    if ((fd = ::open(p->c_str(), args...)) == -1) {
332
0
      ec = capture_errno();
333
0
      return FileDescriptor{p};
334
0
    }
335
0
    return FileDescriptor(p, fd);
336
0
  }
Unexecuted instantiation: operations.cpp:std::__1::__fs::filesystem::detail::(anonymous namespace)::FileDescriptor std::__1::__fs::filesystem::detail::(anonymous namespace)::FileDescriptor::create<int>(std::__1::__fs::filesystem::path const*, std::__1::error_code&, int)
Unexecuted instantiation: operations.cpp:std::__1::__fs::filesystem::detail::(anonymous namespace)::FileDescriptor std::__1::__fs::filesystem::detail::(anonymous namespace)::FileDescriptor::create<int, unsigned short>(std::__1::__fs::filesystem::path const*, std::__1::error_code&, int, unsigned short)
337
338
  template <class... Args>
339
  static FileDescriptor create_with_status(const path* p, error_code& ec,
340
0
                                           Args... args) {
341
0
    FileDescriptor fd = create(p, ec, args...);
342
0
    if (!ec)
343
0
      fd.refresh_status(ec);
344
0
345
0
    return fd;
346
0
  }
Unexecuted instantiation: operations.cpp:std::__1::__fs::filesystem::detail::(anonymous namespace)::FileDescriptor std::__1::__fs::filesystem::detail::(anonymous namespace)::FileDescriptor::create_with_status<int>(std::__1::__fs::filesystem::path const*, std::__1::error_code&, int)
Unexecuted instantiation: operations.cpp:std::__1::__fs::filesystem::detail::(anonymous namespace)::FileDescriptor std::__1::__fs::filesystem::detail::(anonymous namespace)::FileDescriptor::create_with_status<int, unsigned short>(std::__1::__fs::filesystem::path const*, std::__1::error_code&, int, unsigned short)
347
348
0
  file_status get_status() const { return m_status; }
349
0
  StatT const& get_stat() const { return m_stat; }
350
351
0
  bool status_known() const { return _VSTD_FS::status_known(m_status); }
352
353
  file_status refresh_status(error_code& ec);
354
355
0
  void close() noexcept {
356
0
    if (fd != -1)
357
0
      ::close(fd);
358
0
    fd = -1;
359
0
  }
360
361
  FileDescriptor(FileDescriptor&& other)
362
      : name(other.name), fd(other.fd), m_stat(other.m_stat),
363
0
        m_status(other.m_status) {
364
0
    other.fd = -1;
365
0
    other.m_status = file_status{};
366
0
  }
367
368
0
  ~FileDescriptor() { close(); }
369
370
  FileDescriptor(FileDescriptor const&) = delete;
371
  FileDescriptor& operator=(FileDescriptor const&) = delete;
372
373
private:
374
0
  explicit FileDescriptor(const path* p, int fd = -1) : name(*p), fd(fd) {}
375
};
376
377
0
perms posix_get_perms(const StatT& st) noexcept {
378
0
  return static_cast<perms>(st.st_mode) & perms::mask;
379
0
}
380
381
0
::mode_t posix_convert_perms(perms prms) {
382
0
  return static_cast< ::mode_t>(prms & perms::mask);
383
0
}
384
385
file_status create_file_status(error_code& m_ec, path const& p,
386
0
                               const StatT& path_stat, error_code* ec) {
387
0
  if (ec)
388
0
    *ec = m_ec;
389
0
  if (m_ec && (m_ec.value() == ENOENT || m_ec.value() == ENOTDIR)) {
390
0
    return file_status(file_type::not_found);
391
0
  } else if (m_ec) {
392
0
    ErrorHandler<void> err("posix_stat", ec, &p);
393
0
    err.report(m_ec, "failed to determine attributes for the specified path");
394
0
    return file_status(file_type::none);
395
0
  }
396
0
  // else
397
0
398
0
  file_status fs_tmp;
399
0
  auto const mode = path_stat.st_mode;
400
0
  if (S_ISLNK(mode))
401
0
    fs_tmp.type(file_type::symlink);
402
0
  else if (S_ISREG(mode))
403
0
    fs_tmp.type(file_type::regular);
404
0
  else if (S_ISDIR(mode))
405
0
    fs_tmp.type(file_type::directory);
406
0
  else if (S_ISBLK(mode))
407
0
    fs_tmp.type(file_type::block);
408
0
  else if (S_ISCHR(mode))
409
0
    fs_tmp.type(file_type::character);
410
0
  else if (S_ISFIFO(mode))
411
0
    fs_tmp.type(file_type::fifo);
412
0
  else if (S_ISSOCK(mode))
413
0
    fs_tmp.type(file_type::socket);
414
0
  else
415
0
    fs_tmp.type(file_type::unknown);
416
0
417
0
  fs_tmp.permissions(detail::posix_get_perms(path_stat));
418
0
  return fs_tmp;
419
0
}
420
421
0
file_status posix_stat(path const& p, StatT& path_stat, error_code* ec) {
422
0
  error_code m_ec;
423
0
  if (::stat(p.c_str(), &path_stat) == -1)
424
0
    m_ec = detail::capture_errno();
425
0
  return create_file_status(m_ec, p, path_stat, ec);
426
0
}
427
428
0
file_status posix_stat(path const& p, error_code* ec) {
429
0
  StatT path_stat;
430
0
  return posix_stat(p, path_stat, ec);
431
0
}
432
433
0
file_status posix_lstat(path const& p, StatT& path_stat, error_code* ec) {
434
0
  error_code m_ec;
435
0
  if (::lstat(p.c_str(), &path_stat) == -1)
436
0
    m_ec = detail::capture_errno();
437
0
  return create_file_status(m_ec, p, path_stat, ec);
438
0
}
439
440
0
file_status posix_lstat(path const& p, error_code* ec) {
441
0
  StatT path_stat;
442
0
  return posix_lstat(p, path_stat, ec);
443
0
}
444
445
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
446
0
bool posix_ftruncate(const FileDescriptor& fd, off_t to_size, error_code& ec) {
447
0
  if (::ftruncate(fd.fd, to_size) == -1) {
448
0
    ec = capture_errno();
449
0
    return true;
450
0
  }
451
0
  ec.clear();
452
0
  return false;
453
0
}
454
455
0
bool posix_fchmod(const FileDescriptor& fd, const StatT& st, error_code& ec) {
456
0
  if (::fchmod(fd.fd, st.st_mode) == -1) {
457
0
    ec = capture_errno();
458
0
    return true;
459
0
  }
460
0
  ec.clear();
461
0
  return false;
462
0
}
463
464
0
bool stat_equivalent(const StatT& st1, const StatT& st2) {
465
0
  return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
466
0
}
467
468
0
file_status FileDescriptor::refresh_status(error_code& ec) {
469
0
  // FD must be open and good.
470
0
  m_status = file_status{};
471
0
  m_stat = {};
472
0
  error_code m_ec;
473
0
  if (::fstat(fd, &m_stat) == -1)
474
0
    m_ec = capture_errno();
475
0
  m_status = create_file_status(m_ec, name, m_stat, &ec);
476
0
  return m_status;
477
0
}
478
} // namespace
479
} // end namespace detail
480
481
using detail::capture_errno;
482
using detail::ErrorHandler;
483
using detail::StatT;
484
using detail::TimeSpec;
485
using parser::createView;
486
using parser::PathParser;
487
using parser::string_view_t;
488
489
const bool _FilesystemClock::is_steady;
490
491
0
_FilesystemClock::time_point _FilesystemClock::now() noexcept {
492
0
  typedef chrono::duration<rep> __secs;
493
0
#if defined(_LIBCPP_USE_CLOCK_GETTIME) && defined(CLOCK_REALTIME)
494
0
  typedef chrono::duration<rep, nano> __nsecs;
495
0
  struct timespec tp;
496
0
  if (0 != clock_gettime(CLOCK_REALTIME, &tp))
497
0
    __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
498
0
  return time_point(__secs(tp.tv_sec) +
499
0
                    chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
500
#else
501
  typedef chrono::duration<rep, micro> __microsecs;
502
  timeval tv;
503
  gettimeofday(&tv, 0);
504
  return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
505
#endif // _LIBCPP_USE_CLOCK_GETTIME && CLOCK_REALTIME
506
}
507
508
0
filesystem_error::~filesystem_error() {}
509
510
0
void filesystem_error::__create_what(int __num_paths) {
511
0
  const char* derived_what = system_error::what();
512
0
  __storage_->__what_ = [&]() -> string {
513
0
    const char* p1 = path1().native().empty() ? "\"\"" : path1().c_str();
514
0
    const char* p2 = path2().native().empty() ? "\"\"" : path2().c_str();
515
0
    switch (__num_paths) {
516
0
    default:
517
0
      return detail::format_string("filesystem error: %s", derived_what);
518
0
    case 1:
519
0
      return detail::format_string("filesystem error: %s [%s]", derived_what,
520
0
                                   p1);
521
0
    case 2:
522
0
      return detail::format_string("filesystem error: %s [%s] [%s]",
523
0
                                   derived_what, p1, p2);
524
0
    }
525
0
  }();
526
0
}
527
528
0
static path __do_absolute(const path& p, path* cwd, error_code* ec) {
529
0
  if (ec)
530
0
    ec->clear();
531
0
  if (p.is_absolute())
532
0
    return p;
533
0
  *cwd = __current_path(ec);
534
0
  if (ec && *ec)
535
0
    return {};
536
0
  return (*cwd) / p;
537
0
}
538
539
0
path __absolute(const path& p, error_code* ec) {
540
0
  path cwd;
541
0
  return __do_absolute(p, &cwd, ec);
542
0
}
543
544
0
path __canonical(path const& orig_p, error_code* ec) {
545
0
  path cwd;
546
0
  ErrorHandler<path> err("canonical", ec, &orig_p, &cwd);
547
0
548
0
  path p = __do_absolute(orig_p, &cwd, ec);
549
0
#if _POSIX_VERSION >= 200112
550
0
  std::unique_ptr<char, decltype(&::free)>
551
0
    hold(::realpath(p.c_str(), nullptr), &::free);
552
0
  if (hold.get() == nullptr)
553
0
    return err.report(capture_errno());
554
0
  return {hold.get()};
555
#else
556
  char buff[PATH_MAX + 1];
557
  char* ret;
558
  if ((ret = ::realpath(p.c_str(), buff)) == nullptr)
559
    return err.report(capture_errno());
560
  return {ret};
561
#endif
562
}
563
564
void __copy(const path& from, const path& to, copy_options options,
565
0
            error_code* ec) {
566
0
  ErrorHandler<void> err("copy", ec, &from, &to);
567
0
568
0
  const bool sym_status = bool(
569
0
      options & (copy_options::create_symlinks | copy_options::skip_symlinks));
570
0
571
0
  const bool sym_status2 = bool(options & copy_options::copy_symlinks);
572
0
573
0
  error_code m_ec1;
574
0
  StatT f_st = {};
575
0
  const file_status f = sym_status || sym_status2
576
0
                            ? detail::posix_lstat(from, f_st, &m_ec1)
577
0
                            : detail::posix_stat(from, f_st, &m_ec1);
578
0
  if (m_ec1)
579
0
    return err.report(m_ec1);
580
0
581
0
  StatT t_st = {};
582
0
  const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1)
583
0
                                   : detail::posix_stat(to, t_st, &m_ec1);
584
0
585
0
  if (not status_known(t))
586
0
    return err.report(m_ec1);
587
0
588
0
  if (!exists(f) || is_other(f) || is_other(t) ||
589
0
      (is_directory(f) && is_regular_file(t)) ||
590
0
      detail::stat_equivalent(f_st, t_st)) {
591
0
    return err.report(errc::function_not_supported);
592
0
  }
593
0
594
0
  if (ec)
595
0
    ec->clear();
596
0
597
0
  if (is_symlink(f)) {
598
0
    if (bool(copy_options::skip_symlinks & options)) {
599
0
      // do nothing
600
0
    } else if (not exists(t)) {
601
0
      __copy_symlink(from, to, ec);
602
0
    } else {
603
0
      return err.report(errc::file_exists);
604
0
    }
605
0
    return;
606
0
  } else if (is_regular_file(f)) {
607
0
    if (bool(copy_options::directories_only & options)) {
608
0
      // do nothing
609
0
    } else if (bool(copy_options::create_symlinks & options)) {
610
0
      __create_symlink(from, to, ec);
611
0
    } else if (bool(copy_options::create_hard_links & options)) {
612
0
      __create_hard_link(from, to, ec);
613
0
    } else if (is_directory(t)) {
614
0
      __copy_file(from, to / from.filename(), options, ec);
615
0
    } else {
616
0
      __copy_file(from, to, options, ec);
617
0
    }
618
0
    return;
619
0
  } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
620
0
    return err.report(errc::is_a_directory);
621
0
  } else if (is_directory(f) && (bool(copy_options::recursive & options) ||
622
0
                                 copy_options::none == options)) {
623
0
624
0
    if (!exists(t)) {
625
0
      // create directory to with attributes from 'from'.
626
0
      __create_directory(to, from, ec);
627
0
      if (ec && *ec) {
628
0
        return;
629
0
      }
630
0
    }
631
0
    directory_iterator it =
632
0
        ec ? directory_iterator(from, *ec) : directory_iterator(from);
633
0
    if (ec && *ec) {
634
0
      return;
635
0
    }
636
0
    error_code m_ec2;
637
0
    for (; it != directory_iterator(); it.increment(m_ec2)) {
638
0
      if (m_ec2) {
639
0
        return err.report(m_ec2);
640
0
      }
641
0
      __copy(it->path(), to / it->path().filename(),
642
0
             options | copy_options::__in_recursive_copy, ec);
643
0
      if (ec && *ec) {
644
0
        return;
645
0
      }
646
0
    }
647
0
  }
648
0
}
649
650
namespace detail {
651
namespace {
652
653
#ifdef _LIBCPP_USE_SENDFILE
654
bool copy_file_impl_sendfile(FileDescriptor& read_fd, FileDescriptor& write_fd,
655
                             error_code& ec) {
656
657
  size_t count = read_fd.get_stat().st_size;
658
  do {
659
    ssize_t res;
660
    if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) {
661
      ec = capture_errno();
662
      return false;
663
    }
664
    count -= res;
665
  } while (count > 0);
666
667
  ec.clear();
668
669
  return true;
670
}
671
#elif defined(_LIBCPP_USE_COPYFILE)
672
bool copy_file_impl_copyfile(FileDescriptor& read_fd, FileDescriptor& write_fd,
673
0
                             error_code& ec) {
674
0
  struct CopyFileState {
675
0
    copyfile_state_t state;
676
0
    CopyFileState() { state = copyfile_state_alloc(); }
677
0
    ~CopyFileState() { copyfile_state_free(state); }
678
0
679
0
  private:
680
0
    CopyFileState(CopyFileState const&) = delete;
681
0
    CopyFileState& operator=(CopyFileState const&) = delete;
682
0
  };
683
0
684
0
  CopyFileState cfs;
685
0
  if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {
686
0
    ec = capture_errno();
687
0
    return false;
688
0
  }
689
0
690
0
  ec.clear();
691
0
  return true;
692
0
}
693
#endif
694
695
// Note: This function isn't guarded by ifdef's even though it may be unused
696
// in order to assure it still compiles.
697
__attribute__((unused)) bool copy_file_impl_default(FileDescriptor& read_fd,
698
                                                    FileDescriptor& write_fd,
699
0
                                                    error_code& ec) {
700
0
  ifstream in;
701
0
  in.__open(read_fd.fd, ios::binary);
702
0
  if (!in.is_open()) {
703
0
    // This assumes that __open didn't reset the error code.
704
0
    ec = capture_errno();
705
0
    return false;
706
0
  }
707
0
  ofstream out;
708
0
  out.__open(write_fd.fd, ios::binary);
709
0
  if (!out.is_open()) {
710
0
    ec = capture_errno();
711
0
    return false;
712
0
  }
713
0
714
0
  if (in.good() && out.good()) {
715
0
    using InIt = istreambuf_iterator<char>;
716
0
    using OutIt = ostreambuf_iterator<char>;
717
0
    InIt bin(in);
718
0
    InIt ein;
719
0
    OutIt bout(out);
720
0
    copy(bin, ein, bout);
721
0
  }
722
0
  if (out.fail() || in.fail()) {
723
0
    ec = make_error_code(errc::io_error);
724
0
    return false;
725
0
  }
726
0
727
0
  ec.clear();
728
0
  return true;
729
0
}
730
731
0
bool copy_file_impl(FileDescriptor& from, FileDescriptor& to, error_code& ec) {
732
#if defined(_LIBCPP_USE_SENDFILE)
733
  return copy_file_impl_sendfile(from, to, ec);
734
#elif defined(_LIBCPP_USE_COPYFILE)
735
  return copy_file_impl_copyfile(from, to, ec);
736
#else
737
  return copy_file_impl_default(from, to, ec);
738
#endif
739
}
740
741
} // namespace
742
} // namespace detail
743
744
bool __copy_file(const path& from, const path& to, copy_options options,
745
0
                 error_code* ec) {
746
0
  using detail::FileDescriptor;
747
0
  ErrorHandler<bool> err("copy_file", ec, &to, &from);
748
0
749
0
  error_code m_ec;
750
0
  FileDescriptor from_fd =
751
0
      FileDescriptor::create_with_status(&from, m_ec, O_RDONLY | O_NONBLOCK);
752
0
  if (m_ec)
753
0
    return err.report(m_ec);
754
0
755
0
  auto from_st = from_fd.get_status();
756
0
  StatT const& from_stat = from_fd.get_stat();
757
0
  if (!is_regular_file(from_st)) {
758
0
    if (not m_ec)
759
0
      m_ec = make_error_code(errc::not_supported);
760
0
    return err.report(m_ec);
761
0
  }
762
0
763
0
  const bool skip_existing = bool(copy_options::skip_existing & options);
764
0
  const bool update_existing = bool(copy_options::update_existing & options);
765
0
  const bool overwrite_existing =
766
0
      bool(copy_options::overwrite_existing & options);
767
0
768
0
  StatT to_stat_path;
769
0
  file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);
770
0
  if (!status_known(to_st))
771
0
    return err.report(m_ec);
772
0
773
0
  const bool to_exists = exists(to_st);
774
0
  if (to_exists && !is_regular_file(to_st))
775
0
    return err.report(errc::not_supported);
776
0
777
0
  if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))
778
0
    return err.report(errc::file_exists);
779
0
780
0
  if (to_exists && skip_existing)
781
0
    return false;
782
0
783
0
  bool ShouldCopy = [&]() {
784
0
    if (to_exists && update_existing) {
785
0
      auto from_time = detail::extract_mtime(from_stat);
786
0
      auto to_time = detail::extract_mtime(to_stat_path);
787
0
      if (from_time.tv_sec < to_time.tv_sec)
788
0
        return false;
789
0
      if (from_time.tv_sec == to_time.tv_sec &&
790
0
          from_time.tv_nsec <= to_time.tv_nsec)
791
0
        return false;
792
0
      return true;
793
0
    }
794
0
    if (!to_exists || overwrite_existing)
795
0
      return true;
796
0
    return err.report(errc::file_exists);
797
0
  }();
798
0
  if (!ShouldCopy)
799
0
    return false;
800
0
801
0
  // Don't truncate right away. We may not be opening the file we originally
802
0
  // looked at; we'll check this later.
803
0
  int to_open_flags = O_WRONLY;
804
0
  if (!to_exists)
805
0
    to_open_flags |= O_CREAT;
806
0
  FileDescriptor to_fd = FileDescriptor::create_with_status(
807
0
      &to, m_ec, to_open_flags, from_stat.st_mode);
808
0
  if (m_ec)
809
0
    return err.report(m_ec);
810
0
811
0
  if (to_exists) {
812
0
    // Check that the file we initially stat'ed is equivalent to the one
813
0
    // we opened.
814
0
    // FIXME: report this better.
815
0
    if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))
816
0
      return err.report(errc::bad_file_descriptor);
817
0
818
0
    // Set the permissions and truncate the file we opened.
819
0
    if (detail::posix_fchmod(to_fd, from_stat, m_ec))
820
0
      return err.report(m_ec);
821
0
    if (detail::posix_ftruncate(to_fd, 0, m_ec))
822
0
      return err.report(m_ec);
823
0
  }
824
0
825
0
  if (!copy_file_impl(from_fd, to_fd, m_ec)) {
826
0
    // FIXME: Remove the dest file if we failed, and it didn't exist previously.
827
0
    return err.report(m_ec);
828
0
  }
829
0
830
0
  return true;
831
0
}
832
833
void __copy_symlink(const path& existing_symlink, const path& new_symlink,
834
0
                    error_code* ec) {
835
0
  const path real_path(__read_symlink(existing_symlink, ec));
836
0
  if (ec && *ec) {
837
0
    return;
838
0
  }
839
0
  // NOTE: proposal says you should detect if you should call
840
0
  // create_symlink or create_directory_symlink. I don't think this
841
0
  // is needed with POSIX
842
0
  __create_symlink(real_path, new_symlink, ec);
843
0
}
844
845
0
bool __create_directories(const path& p, error_code* ec) {
846
0
  ErrorHandler<bool> err("create_directories", ec, &p);
847
0
848
0
  error_code m_ec;
849
0
  auto const st = detail::posix_stat(p, &m_ec);
850
0
  if (!status_known(st))
851
0
    return err.report(m_ec);
852
0
  else if (is_directory(st))
853
0
    return false;
854
0
  else if (exists(st))
855
0
    return err.report(errc::file_exists);
856
0
857
0
  const path parent = p.parent_path();
858
0
  if (!parent.empty()) {
859
0
    const file_status parent_st = status(parent, m_ec);
860
0
    if (not status_known(parent_st))
861
0
      return err.report(m_ec);
862
0
    if (not exists(parent_st)) {
863
0
      __create_directories(parent, ec);
864
0
      if (ec && *ec) {
865
0
        return false;
866
0
      }
867
0
    }
868
0
  }
869
0
  return __create_directory(p, ec);
870
0
}
871
872
0
bool __create_directory(const path& p, error_code* ec) {
873
0
  ErrorHandler<bool> err("create_directory", ec, &p);
874
0
875
0
  if (::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
876
0
    return true;
877
0
  if (errno != EEXIST)
878
0
    err.report(capture_errno());
879
0
  return false;
880
0
}
881
882
0
bool __create_directory(path const& p, path const& attributes, error_code* ec) {
883
0
  ErrorHandler<bool> err("create_directory", ec, &p, &attributes);
884
0
885
0
  StatT attr_stat;
886
0
  error_code mec;
887
0
  auto st = detail::posix_stat(attributes, attr_stat, &mec);
888
0
  if (!status_known(st))
889
0
    return err.report(mec);
890
0
  if (!is_directory(st))
891
0
    return err.report(errc::not_a_directory,
892
0
                      "the specified attribute path is invalid");
893
0
894
0
  if (::mkdir(p.c_str(), attr_stat.st_mode) == 0)
895
0
    return true;
896
0
  if (errno != EEXIST)
897
0
    err.report(capture_errno());
898
0
  return false;
899
0
}
900
901
void __create_directory_symlink(path const& from, path const& to,
902
0
                                error_code* ec) {
903
0
  ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
904
0
  if (::symlink(from.c_str(), to.c_str()) != 0)
905
0
    return err.report(capture_errno());
906
0
}
907
908
0
void __create_hard_link(const path& from, const path& to, error_code* ec) {
909
0
  ErrorHandler<void> err("create_hard_link", ec, &from, &to);
910
0
  if (::link(from.c_str(), to.c_str()) == -1)
911
0
    return err.report(capture_errno());
912
0
}
913
914
0
void __create_symlink(path const& from, path const& to, error_code* ec) {
915
0
  ErrorHandler<void> err("create_symlink", ec, &from, &to);
916
0
  if (::symlink(from.c_str(), to.c_str()) == -1)
917
0
    return err.report(capture_errno());
918
0
}
919
920
0
path __current_path(error_code* ec) {
921
0
  ErrorHandler<path> err("current_path", ec);
922
0
923
0
  auto size = ::pathconf(".", _PC_PATH_MAX);
924
0
  _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
925
0
926
0
  auto buff = unique_ptr<char[]>(new char[size + 1]);
927
0
  char* ret;
928
0
  if ((ret = ::getcwd(buff.get(), static_cast<size_t>(size))) == nullptr)
929
0
    return err.report(capture_errno(), "call to getcwd failed");
930
0
931
0
  return {buff.get()};
932
0
}
933
934
0
void __current_path(const path& p, error_code* ec) {
935
0
  ErrorHandler<void> err("current_path", ec, &p);
936
0
  if (::chdir(p.c_str()) == -1)
937
0
    err.report(capture_errno());
938
0
}
939
940
0
bool __equivalent(const path& p1, const path& p2, error_code* ec) {
941
0
  ErrorHandler<bool> err("equivalent", ec, &p1, &p2);
942
0
943
0
  error_code ec1, ec2;
944
0
  StatT st1 = {}, st2 = {};
945
0
  auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
946
0
  if (!exists(s1))
947
0
    return err.report(errc::not_supported);
948
0
  auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
949
0
  if (!exists(s2))
950
0
    return err.report(errc::not_supported);
951
0
952
0
  return detail::stat_equivalent(st1, st2);
953
0
}
954
955
0
uintmax_t __file_size(const path& p, error_code* ec) {
956
0
  ErrorHandler<uintmax_t> err("file_size", ec, &p);
957
0
958
0
  error_code m_ec;
959
0
  StatT st;
960
0
  file_status fst = detail::posix_stat(p, st, &m_ec);
961
0
  if (!exists(fst) || !is_regular_file(fst)) {
962
0
    errc error_kind =
963
0
        is_directory(fst) ? errc::is_a_directory : errc::not_supported;
964
0
    if (!m_ec)
965
0
      m_ec = make_error_code(error_kind);
966
0
    return err.report(m_ec);
967
0
  }
968
0
  // is_regular_file(p) == true
969
0
  return static_cast<uintmax_t>(st.st_size);
970
0
}
971
972
0
uintmax_t __hard_link_count(const path& p, error_code* ec) {
973
0
  ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);
974
0
975
0
  error_code m_ec;
976
0
  StatT st;
977
0
  detail::posix_stat(p, st, &m_ec);
978
0
  if (m_ec)
979
0
    return err.report(m_ec);
980
0
  return static_cast<uintmax_t>(st.st_nlink);
981
0
}
982
983
0
bool __fs_is_empty(const path& p, error_code* ec) {
984
0
  ErrorHandler<bool> err("is_empty", ec, &p);
985
0
986
0
  error_code m_ec;
987
0
  StatT pst;
988
0
  auto st = detail::posix_stat(p, pst, &m_ec);
989
0
  if (m_ec)
990
0
    return err.report(m_ec);
991
0
  else if (!is_directory(st) && !is_regular_file(st))
992
0
    return err.report(errc::not_supported);
993
0
  else if (is_directory(st)) {
994
0
    auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
995
0
    if (ec && *ec)
996
0
      return false;
997
0
    return it == directory_iterator{};
998
0
  } else if (is_regular_file(st))
999
0
    return static_cast<uintmax_t>(pst.st_size) == 0;
1000
0
1001
0
  _LIBCPP_UNREACHABLE();
1002
0
}
1003
1004
static file_time_type __extract_last_write_time(const path& p, const StatT& st,
1005
0
                                                error_code* ec) {
1006
0
  using detail::fs_time;
1007
0
  ErrorHandler<file_time_type> err("last_write_time", ec, &p);
1008
0
1009
0
  auto ts = detail::extract_mtime(st);
1010
0
  if (!fs_time::is_representable(ts))
1011
0
    return err.report(errc::value_too_large);
1012
0
1013
0
  return fs_time::convert_from_timespec(ts);
1014
0
}
1015
1016
0
file_time_type __last_write_time(const path& p, error_code* ec) {
1017
0
  using namespace chrono;
1018
0
  ErrorHandler<file_time_type> err("last_write_time", ec, &p);
1019
0
1020
0
  error_code m_ec;
1021
0
  StatT st;
1022
0
  detail::posix_stat(p, st, &m_ec);
1023
0
  if (m_ec)
1024
0
    return err.report(m_ec);
1025
0
  return __extract_last_write_time(p, st, ec);
1026
0
}
1027
1028
0
void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
1029
0
  using detail::fs_time;
1030
0
  ErrorHandler<void> err("last_write_time", ec, &p);
1031
0
1032
0
  error_code m_ec;
1033
0
  array<TimeSpec, 2> tbuf;
1034
#if !defined(_LIBCPP_USE_UTIMENSAT)
1035
  // This implementation has a race condition between determining the
1036
  // last access time and attempting to set it to the same value using
1037
  // ::utimes
1038
  StatT st;
1039
  file_status fst = detail::posix_stat(p, st, &m_ec);
1040
  if (m_ec)
1041
    return err.report(m_ec);
1042
  tbuf[0] = detail::extract_atime(st);
1043
#else
1044
  tbuf[0].tv_sec = 0;
1045
0
  tbuf[0].tv_nsec = UTIME_OMIT;
1046
0
#endif
1047
0
  if (!fs_time::convert_to_timespec(tbuf[1], new_time))
1048
0
    return err.report(errc::value_too_large);
1049
0
1050
0
  detail::set_file_times(p, tbuf, m_ec);
1051
0
  if (m_ec)
1052
0
    return err.report(m_ec);
1053
0
}
1054
1055
void __permissions(const path& p, perms prms, perm_options opts,
1056
0
                   error_code* ec) {
1057
0
  ErrorHandler<void> err("permissions", ec, &p);
1058
0
1059
0
  auto has_opt = [&](perm_options o) { return bool(o & opts); };
1060
0
  const bool resolve_symlinks = !has_opt(perm_options::nofollow);
1061
0
  const bool add_perms = has_opt(perm_options::add);
1062
0
  const bool remove_perms = has_opt(perm_options::remove);
1063
0
  _LIBCPP_ASSERT(
1064
0
      (add_perms + remove_perms + has_opt(perm_options::replace)) == 1,
1065
0
      "One and only one of the perm_options constants replace, add, or remove "
1066
0
      "is present in opts");
1067
0
1068
0
  bool set_sym_perms = false;
1069
0
  prms &= perms::mask;
1070
0
  if (!resolve_symlinks || (add_perms || remove_perms)) {
1071
0
    error_code m_ec;
1072
0
    file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
1073
0
                                      : detail::posix_lstat(p, &m_ec);
1074
0
    set_sym_perms = is_symlink(st);
1075
0
    if (m_ec)
1076
0
      return err.report(m_ec);
1077
0
    _LIBCPP_ASSERT(st.permissions() != perms::unknown,
1078
0
                   "Permissions unexpectedly unknown");
1079
0
    if (add_perms)
1080
0
      prms |= st.permissions();
1081
0
    else if (remove_perms)
1082
0
      prms = st.permissions() & ~prms;
1083
0
  }
1084
0
  const auto real_perms = detail::posix_convert_perms(prms);
1085
0
1086
0
#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
1087
0
  const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
1088
0
  if (::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
1089
0
    return err.report(capture_errno());
1090
0
  }
1091
#else
1092
  if (set_sym_perms)
1093
    return err.report(errc::operation_not_supported);
1094
  if (::chmod(p.c_str(), real_perms) == -1) {
1095
    return err.report(capture_errno());
1096
  }
1097
#endif
1098
}
1099
1100
0
path __read_symlink(const path& p, error_code* ec) {
1101
0
  ErrorHandler<path> err("read_symlink", ec, &p);
1102
0
1103
0
#ifdef PATH_MAX
1104
0
  struct NullDeleter { void operator()(void*) const {} };
1105
0
  const size_t size = PATH_MAX + 1;
1106
0
  char stack_buff[size];
1107
0
  auto buff = std::unique_ptr<char[], NullDeleter>(stack_buff);
1108
#else
1109
  StatT sb;
1110
  if (::lstat(p.c_str(), &sb) == -1) {
1111
    return err.report(capture_errno());
1112
  }
1113
  const size_t size = sb.st_size + 1;
1114
  auto buff = unique_ptr<char[]>(new char[size]);
1115
#endif
1116
  ::ssize_t ret;
1117
0
  if ((ret = ::readlink(p.c_str(), buff.get(), size)) == -1)
1118
0
    return err.report(capture_errno());
1119
0
  _LIBCPP_ASSERT(ret > 0, "TODO");
1120
0
  if (static_cast<size_t>(ret) >= size)
1121
0
    return err.report(errc::value_too_large);
1122
0
  buff[ret] = 0;
1123
0
  return {buff.get()};
1124
0
}
1125
1126
0
bool __remove(const path& p, error_code* ec) {
1127
0
  ErrorHandler<bool> err("remove", ec, &p);
1128
0
  if (::remove(p.c_str()) == -1) {
1129
0
    if (errno != ENOENT)
1130
0
      err.report(capture_errno());
1131
0
    return false;
1132
0
  }
1133
0
  return true;
1134
0
}
1135
1136
namespace {
1137
1138
0
uintmax_t remove_all_impl(path const& p, error_code& ec) {
1139
0
  const auto npos = static_cast<uintmax_t>(-1);
1140
0
  const file_status st = __symlink_status(p, &ec);
1141
0
  if (ec)
1142
0
    return npos;
1143
0
  uintmax_t count = 1;
1144
0
  if (is_directory(st)) {
1145
0
    for (directory_iterator it(p, ec); !ec && it != directory_iterator();
1146
0
         it.increment(ec)) {
1147
0
      auto other_count = remove_all_impl(it->path(), ec);
1148
0
      if (ec)
1149
0
        return npos;
1150
0
      count += other_count;
1151
0
    }
1152
0
    if (ec)
1153
0
      return npos;
1154
0
  }
1155
0
  if (!__remove(p, &ec))
1156
0
    return npos;
1157
0
  return count;
1158
0
}
1159
1160
} // end namespace
1161
1162
0
uintmax_t __remove_all(const path& p, error_code* ec) {
1163
0
  ErrorHandler<uintmax_t> err("remove_all", ec, &p);
1164
0
1165
0
  error_code mec;
1166
0
  auto count = remove_all_impl(p, mec);
1167
0
  if (mec) {
1168
0
    if (mec == errc::no_such_file_or_directory)
1169
0
      return 0;
1170
0
    return err.report(mec);
1171
0
  }
1172
0
  return count;
1173
0
}
1174
1175
0
void __rename(const path& from, const path& to, error_code* ec) {
1176
0
  ErrorHandler<void> err("rename", ec, &from, &to);
1177
0
  if (::rename(from.c_str(), to.c_str()) == -1)
1178
0
    err.report(capture_errno());
1179
0
}
1180
1181
0
void __resize_file(const path& p, uintmax_t size, error_code* ec) {
1182
0
  ErrorHandler<void> err("resize_file", ec, &p);
1183
0
  if (::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
1184
0
    return err.report(capture_errno());
1185
0
}
1186
1187
0
space_info __space(const path& p, error_code* ec) {
1188
0
  ErrorHandler<void> err("space", ec, &p);
1189
0
  space_info si;
1190
0
  struct statvfs m_svfs = {};
1191
0
  if (::statvfs(p.c_str(), &m_svfs) == -1) {
1192
0
    err.report(capture_errno());
1193
0
    si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
1194
0
    return si;
1195
0
  }
1196
0
  // Multiply with overflow checking.
1197
0
  auto do_mult = [&](uintmax_t& out, uintmax_t other) {
1198
0
    out = other * m_svfs.f_frsize;
1199
0
    if (other == 0 || out / other != m_svfs.f_frsize)
1200
0
      out = static_cast<uintmax_t>(-1);
1201
0
  };
1202
0
  do_mult(si.capacity, m_svfs.f_blocks);
1203
0
  do_mult(si.free, m_svfs.f_bfree);
1204
0
  do_mult(si.available, m_svfs.f_bavail);
1205
0
  return si;
1206
0
}
1207
1208
0
file_status __status(const path& p, error_code* ec) {
1209
0
  return detail::posix_stat(p, ec);
1210
0
}
1211
1212
0
file_status __symlink_status(const path& p, error_code* ec) {
1213
0
  return detail::posix_lstat(p, ec);
1214
0
}
1215
1216
0
path __temp_directory_path(error_code* ec) {
1217
0
  ErrorHandler<path> err("temp_directory_path", ec);
1218
0
1219
0
  const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1220
0
  const char* ret = nullptr;
1221
0
1222
0
  for (auto& ep : env_paths)
1223
0
    if ((ret = getenv(ep)))
1224
0
      break;
1225
0
  if (ret == nullptr)
1226
0
    ret = "/tmp";
1227
0
1228
0
  path p(ret);
1229
0
  error_code m_ec;
1230
0
  file_status st = detail::posix_stat(p, &m_ec);
1231
0
  if (!status_known(st))
1232
0
    return err.report(m_ec, "cannot access path \"%s\"", p);
1233
0
1234
0
  if (!exists(st) || !is_directory(st))
1235
0
    return err.report(errc::not_a_directory, "path \"%s\" is not a directory",
1236
0
                      p);
1237
0
1238
0
  return p;
1239
0
}
1240
1241
0
path __weakly_canonical(const path& p, error_code* ec) {
1242
0
  ErrorHandler<path> err("weakly_canonical", ec, &p);
1243
0
1244
0
  if (p.empty())
1245
0
    return __canonical("", ec);
1246
0
1247
0
  path result;
1248
0
  path tmp;
1249
0
  tmp.__reserve(p.native().size());
1250
0
  auto PP = PathParser::CreateEnd(p.native());
1251
0
  --PP;
1252
0
  vector<string_view_t> DNEParts;
1253
0
1254
0
  while (PP.State != PathParser::PS_BeforeBegin) {
1255
0
    tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));
1256
0
    error_code m_ec;
1257
0
    file_status st = __status(tmp, &m_ec);
1258
0
    if (!status_known(st)) {
1259
0
      return err.report(m_ec);
1260
0
    } else if (exists(st)) {
1261
0
      result = __canonical(tmp, ec);
1262
0
      break;
1263
0
    }
1264
0
    DNEParts.push_back(*PP);
1265
0
    --PP;
1266
0
  }
1267
0
  if (PP.State == PathParser::PS_BeforeBegin)
1268
0
    result = __canonical("", ec);
1269
0
  if (ec)
1270
0
    ec->clear();
1271
0
  if (DNEParts.empty())
1272
0
    return result;
1273
0
  for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)
1274
0
    result /= *It;
1275
0
  return result.lexically_normal();
1276
0
}
1277
1278
///////////////////////////////////////////////////////////////////////////////
1279
//                            path definitions
1280
///////////////////////////////////////////////////////////////////////////////
1281
1282
constexpr path::value_type path::preferred_separator;
1283
1284
0
path& path::replace_extension(path const& replacement) {
1285
0
  path p = extension();
1286
0
  if (not p.empty()) {
1287
0
    __pn_.erase(__pn_.size() - p.native().size());
1288
0
  }
1289
0
  if (!replacement.empty()) {
1290
0
    if (replacement.native()[0] != '.') {
1291
0
      __pn_ += ".";
1292
0
    }
1293
0
    __pn_.append(replacement.__pn_);
1294
0
  }
1295
0
  return *this;
1296
0
}
1297
1298
///////////////////////////////////////////////////////////////////////////////
1299
// path.decompose
1300
1301
0
string_view_t path::__root_name() const {
1302
0
  auto PP = PathParser::CreateBegin(__pn_);
1303
0
  if (PP.State == PathParser::PS_InRootName)
1304
0
    return *PP;
1305
0
  return {};
1306
0
}
1307
1308
0
string_view_t path::__root_directory() const {
1309
0
  auto PP = PathParser::CreateBegin(__pn_);
1310
0
  if (PP.State == PathParser::PS_InRootName)
1311
0
    ++PP;
1312
0
  if (PP.State == PathParser::PS_InRootDir)
1313
0
    return *PP;
1314
0
  return {};
1315
0
}
1316
1317
0
string_view_t path::__root_path_raw() const {
1318
0
  auto PP = PathParser::CreateBegin(__pn_);
1319
0
  if (PP.State == PathParser::PS_InRootName) {
1320
0
    auto NextCh = PP.peek();
1321
0
    if (NextCh && *NextCh == '/') {
1322
0
      ++PP;
1323
0
      return createView(__pn_.data(), &PP.RawEntry.back());
1324
0
    }
1325
0
    return PP.RawEntry;
1326
0
  }
1327
0
  if (PP.State == PathParser::PS_InRootDir)
1328
0
    return *PP;
1329
0
  return {};
1330
0
}
1331
1332
0
static bool ConsumeRootName(PathParser *PP) {
1333
0
  static_assert(PathParser::PS_BeforeBegin == 1 &&
1334
0
      PathParser::PS_InRootName == 2,
1335
0
      "Values for enums are incorrect");
1336
0
  while (PP->State <= PathParser::PS_InRootName)
1337
0
    ++(*PP);
1338
0
  return PP->State == PathParser::PS_AtEnd;
1339
0
}
1340
1341
0
static bool ConsumeRootDir(PathParser* PP) {
1342
0
  static_assert(PathParser::PS_BeforeBegin == 1 &&
1343
0
                PathParser::PS_InRootName == 2 &&
1344
0
                PathParser::PS_InRootDir == 3, "Values for enums are incorrect");
1345
0
  while (PP->State <= PathParser::PS_InRootDir)
1346
0
    ++(*PP);
1347
0
  return PP->State == PathParser::PS_AtEnd;
1348
0
}
1349
1350
0
string_view_t path::__relative_path() const {
1351
0
  auto PP = PathParser::CreateBegin(__pn_);
1352
0
  if (ConsumeRootDir(&PP))
1353
0
    return {};
1354
0
  return createView(PP.RawEntry.data(), &__pn_.back());
1355
0
}
1356
1357
0
string_view_t path::__parent_path() const {
1358
0
  if (empty())
1359
0
    return {};
1360
0
  // Determine if we have a root path but not a relative path. In that case
1361
0
  // return *this.
1362
0
  {
1363
0
    auto PP = PathParser::CreateBegin(__pn_);
1364
0
    if (ConsumeRootDir(&PP))
1365
0
      return __pn_;
1366
0
  }
1367
0
  // Otherwise remove a single element from the end of the path, and return
1368
0
  // a string representing that path
1369
0
  {
1370
0
    auto PP = PathParser::CreateEnd(__pn_);
1371
0
    --PP;
1372
0
    if (PP.RawEntry.data() == __pn_.data())
1373
0
      return {};
1374
0
    --PP;
1375
0
    return createView(__pn_.data(), &PP.RawEntry.back());
1376
0
  }
1377
0
}
1378
1379
0
string_view_t path::__filename() const {
1380
0
  if (empty())
1381
0
    return {};
1382
0
  {
1383
0
    PathParser PP = PathParser::CreateBegin(__pn_);
1384
0
    if (ConsumeRootDir(&PP))
1385
0
      return {};
1386
0
  }
1387
0
  return *(--PathParser::CreateEnd(__pn_));
1388
0
}
1389
1390
0
string_view_t path::__stem() const {
1391
0
  return parser::separate_filename(__filename()).first;
1392
0
}
1393
1394
0
string_view_t path::__extension() const {
1395
0
  return parser::separate_filename(__filename()).second;
1396
0
}
1397
1398
////////////////////////////////////////////////////////////////////////////
1399
// path.gen
1400
1401
enum PathPartKind : unsigned char {
1402
  PK_None,
1403
  PK_RootSep,
1404
  PK_Filename,
1405
  PK_Dot,
1406
  PK_DotDot,
1407
  PK_TrailingSep
1408
};
1409
1410
0
static PathPartKind ClassifyPathPart(string_view_t Part) {
1411
0
  if (Part.empty())
1412
0
    return PK_TrailingSep;
1413
0
  if (Part == ".")
1414
0
    return PK_Dot;
1415
0
  if (Part == "..")
1416
0
    return PK_DotDot;
1417
0
  if (Part == "/")
1418
0
    return PK_RootSep;
1419
0
  return PK_Filename;
1420
0
}
1421
1422
0
path path::lexically_normal() const {
1423
0
  if (__pn_.empty())
1424
0
    return *this;
1425
0
1426
0
  using PartKindPair = pair<string_view_t, PathPartKind>;
1427
0
  vector<PartKindPair> Parts;
1428
0
  // Guess as to how many elements the path has to avoid reallocating.
1429
0
  Parts.reserve(32);
1430
0
1431
0
  // Track the total size of the parts as we collect them. This allows the
1432
0
  // resulting path to reserve the correct amount of memory.
1433
0
  size_t NewPathSize = 0;
1434
0
  auto AddPart = [&](PathPartKind K, string_view_t P) {
1435
0
    NewPathSize += P.size();
1436
0
    Parts.emplace_back(P, K);
1437
0
  };
1438
0
  auto LastPartKind = [&]() {
1439
0
    if (Parts.empty())
1440
0
      return PK_None;
1441
0
    return Parts.back().second;
1442
0
  };
1443
0
1444
0
  bool MaybeNeedTrailingSep = false;
1445
0
  // Build a stack containing the remaining elements of the path, popping off
1446
0
  // elements which occur before a '..' entry.
1447
0
  for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) {
1448
0
    auto Part = *PP;
1449
0
    PathPartKind Kind = ClassifyPathPart(Part);
1450
0
    switch (Kind) {
1451
0
    case PK_Filename:
1452
0
    case PK_RootSep: {
1453
0
      // Add all non-dot and non-dot-dot elements to the stack of elements.
1454
0
      AddPart(Kind, Part);
1455
0
      MaybeNeedTrailingSep = false;
1456
0
      break;
1457
0
    }
1458
0
    case PK_DotDot: {
1459
0
      // Only push a ".." element if there are no elements preceding the "..",
1460
0
      // or if the preceding element is itself "..".
1461
0
      auto LastKind = LastPartKind();
1462
0
      if (LastKind == PK_Filename) {
1463
0
        NewPathSize -= Parts.back().first.size();
1464
0
        Parts.pop_back();
1465
0
      } else if (LastKind != PK_RootSep)
1466
0
        AddPart(PK_DotDot, "..");
1467
0
      MaybeNeedTrailingSep = LastKind == PK_Filename;
1468
0
      break;
1469
0
    }
1470
0
    case PK_Dot:
1471
0
    case PK_TrailingSep: {
1472
0
      MaybeNeedTrailingSep = true;
1473
0
      break;
1474
0
    }
1475
0
    case PK_None:
1476
0
      _LIBCPP_UNREACHABLE();
1477
0
    }
1478
0
  }
1479
0
  // [fs.path.generic]p6.8: If the path is empty, add a dot.
1480
0
  if (Parts.empty())
1481
0
    return ".";
1482
0
1483
0
  // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any
1484
0
  // trailing directory-separator.
1485
0
  bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename;
1486
0
1487
0
  path Result;
1488
0
  Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep);
1489
0
  for (auto& PK : Parts)
1490
0
    Result /= PK.first;
1491
0
1492
0
  if (NeedTrailingSep)
1493
0
    Result /= "";
1494
0
1495
0
  return Result;
1496
0
}
1497
1498
0
static int DetermineLexicalElementCount(PathParser PP) {
1499
0
  int Count = 0;
1500
0
  for (; PP; ++PP) {
1501
0
    auto Elem = *PP;
1502
0
    if (Elem == "..")
1503
0
      --Count;
1504
0
    else if (Elem != "." && Elem != "")
1505
0
      ++Count;
1506
0
  }
1507
0
  return Count;
1508
0
}
1509
1510
0
path path::lexically_relative(const path& base) const {
1511
0
  { // perform root-name/root-directory mismatch checks
1512
0
    auto PP = PathParser::CreateBegin(__pn_);
1513
0
    auto PPBase = PathParser::CreateBegin(base.__pn_);
1514
0
    auto CheckIterMismatchAtBase = [&]() {
1515
0
      return PP.State != PPBase.State &&
1516
0
             (PP.inRootPath() || PPBase.inRootPath());
1517
0
    };
1518
0
    if (PP.inRootName() && PPBase.inRootName()) {
1519
0
      if (*PP != *PPBase)
1520
0
        return {};
1521
0
    } else if (CheckIterMismatchAtBase())
1522
0
      return {};
1523
0
1524
0
    if (PP.inRootPath())
1525
0
      ++PP;
1526
0
    if (PPBase.inRootPath())
1527
0
      ++PPBase;
1528
0
    if (CheckIterMismatchAtBase())
1529
0
      return {};
1530
0
  }
1531
0
1532
0
  // Find the first mismatching element
1533
0
  auto PP = PathParser::CreateBegin(__pn_);
1534
0
  auto PPBase = PathParser::CreateBegin(base.__pn_);
1535
0
  while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) {
1536
0
    ++PP;
1537
0
    ++PPBase;
1538
0
  }
1539
0
1540
0
  // If there is no mismatch, return ".".
1541
0
  if (!PP && !PPBase)
1542
0
    return ".";
1543
0
1544
0
  // Otherwise, determine the number of elements, 'n', which are not dot or
1545
0
  // dot-dot minus the number of dot-dot elements.
1546
0
  int ElemCount = DetermineLexicalElementCount(PPBase);
1547
0
  if (ElemCount < 0)
1548
0
    return {};
1549
0
1550
0
  // if n == 0 and (a == end() || a->empty()), returns path("."); otherwise
1551
0
  if (ElemCount == 0 && (PP.atEnd() || *PP == ""))
1552
0
    return ".";
1553
0
1554
0
  // return a path constructed with 'n' dot-dot elements, followed by the the
1555
0
  // elements of '*this' after the mismatch.
1556
0
  path Result;
1557
0
  // FIXME: Reserve enough room in Result that it won't have to re-allocate.
1558
0
  while (ElemCount--)
1559
0
    Result /= "..";
1560
0
  for (; PP; ++PP)
1561
0
    Result /= *PP;
1562
0
  return Result;
1563
0
}
1564
1565
////////////////////////////////////////////////////////////////////////////
1566
// path.comparisons
1567
0
static int CompareRootName(PathParser *LHS, PathParser *RHS) {
1568
0
  if (!LHS->inRootName() && !RHS->inRootName())
1569
0
    return 0;
1570
0
1571
0
  auto GetRootName = [](PathParser *Parser) -> string_view_t {
1572
0
    return Parser->inRootName() ? **Parser : "";
1573
0
  };
1574
0
  int res = GetRootName(LHS).compare(GetRootName(RHS));
1575
0
  ConsumeRootName(LHS);
1576
0
  ConsumeRootName(RHS);
1577
0
  return res;
1578
0
}
1579
1580
0
static int CompareRootDir(PathParser *LHS, PathParser *RHS) {
1581
0
  if (!LHS->inRootDir() && RHS->inRootDir())
1582
0
    return -1;
1583
0
  else if (LHS->inRootDir() && !RHS->inRootDir())
1584
0
    return 1;
1585
0
  else {
1586
0
    ConsumeRootDir(LHS);
1587
0
    ConsumeRootDir(RHS);
1588
0
    return 0;
1589
0
  }
1590
0
}
1591
1592
0
static int CompareRelative(PathParser *LHSPtr, PathParser *RHSPtr) {
1593
0
  auto &LHS = *LHSPtr;
1594
0
  auto &RHS = *RHSPtr;
1595
0
1596
0
  int res;
1597
0
  while (LHS && RHS) {
1598
0
    if ((res = (*LHS).compare(*RHS)) != 0)
1599
0
      return res;
1600
0
    ++LHS;
1601
0
    ++RHS;
1602
0
  }
1603
0
  return 0;
1604
0
}
1605
1606
0
static int CompareEndState(PathParser *LHS, PathParser *RHS) {
1607
0
  if (LHS->atEnd() && !RHS->atEnd())
1608
0
    return -1;
1609
0
  else if (!LHS->atEnd() && RHS->atEnd())
1610
0
    return 1;
1611
0
  return 0;
1612
0
}
1613
1614
0
int path::__compare(string_view_t __s) const {
1615
0
  auto LHS = PathParser::CreateBegin(__pn_);
1616
0
  auto RHS = PathParser::CreateBegin(__s);
1617
0
  int res;
1618
0
1619
0
  if ((res = CompareRootName(&LHS, &RHS)) != 0)
1620
0
    return res;
1621
0
1622
0
  if ((res = CompareRootDir(&LHS, &RHS)) != 0)
1623
0
    return res;
1624
0
1625
0
  if ((res = CompareRelative(&LHS, &RHS)) != 0)
1626
0
    return res;
1627
0
1628
0
  return CompareEndState(&LHS, &RHS);
1629
0
}
1630
1631
////////////////////////////////////////////////////////////////////////////
1632
// path.nonmembers
1633
0
size_t hash_value(const path& __p) noexcept {
1634
0
  auto PP = PathParser::CreateBegin(__p.native());
1635
0
  size_t hash_value = 0;
1636
0
  hash<string_view_t> hasher;
1637
0
  while (PP) {
1638
0
    hash_value = __hash_combine(hash_value, hasher(*PP));
1639
0
    ++PP;
1640
0
  }
1641
0
  return hash_value;
1642
0
}
1643
1644
////////////////////////////////////////////////////////////////////////////
1645
// path.itr
1646
0
path::iterator path::begin() const {
1647
0
  auto PP = PathParser::CreateBegin(__pn_);
1648
0
  iterator it;
1649
0
  it.__path_ptr_ = this;
1650
0
  it.__state_ = static_cast<path::iterator::_ParserState>(PP.State);
1651
0
  it.__entry_ = PP.RawEntry;
1652
0
  it.__stashed_elem_.__assign_view(*PP);
1653
0
  return it;
1654
0
}
1655
1656
0
path::iterator path::end() const {
1657
0
  iterator it{};
1658
0
  it.__state_ = path::iterator::_AtEnd;
1659
0
  it.__path_ptr_ = this;
1660
0
  return it;
1661
0
}
1662
1663
0
path::iterator& path::iterator::__increment() {
1664
0
  PathParser PP(__path_ptr_->native(), __entry_, __state_);
1665
0
  ++PP;
1666
0
  __state_ = static_cast<_ParserState>(PP.State);
1667
0
  __entry_ = PP.RawEntry;
1668
0
  __stashed_elem_.__assign_view(*PP);
1669
0
  return *this;
1670
0
}
1671
1672
0
path::iterator& path::iterator::__decrement() {
1673
0
  PathParser PP(__path_ptr_->native(), __entry_, __state_);
1674
0
  --PP;
1675
0
  __state_ = static_cast<_ParserState>(PP.State);
1676
0
  __entry_ = PP.RawEntry;
1677
0
  __stashed_elem_.__assign_view(*PP);
1678
0
  return *this;
1679
0
}
1680
1681
///////////////////////////////////////////////////////////////////////////////
1682
//                           directory entry definitions
1683
///////////////////////////////////////////////////////////////////////////////
1684
1685
#ifndef _LIBCPP_WIN32API
1686
0
error_code directory_entry::__do_refresh() noexcept {
1687
0
  __data_.__reset();
1688
0
  error_code failure_ec;
1689
0
1690
0
  StatT full_st;
1691
0
  file_status st = detail::posix_lstat(__p_, full_st, &failure_ec);
1692
0
  if (!status_known(st)) {
1693
0
    __data_.__reset();
1694
0
    return failure_ec;
1695
0
  }
1696
0
1697
0
  if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1698
0
    __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1699
0
    __data_.__type_ = st.type();
1700
0
    __data_.__non_sym_perms_ = st.permissions();
1701
0
  } else { // we have a symlink
1702
0
    __data_.__sym_perms_ = st.permissions();
1703
0
    // Get the information about the linked entity.
1704
0
    // Ignore errors from stat, since we don't want errors regarding symlink
1705
0
    // resolution to be reported to the user.
1706
0
    error_code ignored_ec;
1707
0
    st = detail::posix_stat(__p_, full_st, &ignored_ec);
1708
0
1709
0
    __data_.__type_ = st.type();
1710
0
    __data_.__non_sym_perms_ = st.permissions();
1711
0
1712
0
    // If we failed to resolve the link, then only partially populate the
1713
0
    // cache.
1714
0
    if (!status_known(st)) {
1715
0
      __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1716
0
      return error_code{};
1717
0
    }
1718
0
    // Otherwise, we resolved the link, potentially as not existing.
1719
0
    // That's OK.
1720
0
    __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1721
0
  }
1722
0
1723
0
  if (_VSTD_FS::is_regular_file(st))
1724
0
    __data_.__size_ = static_cast<uintmax_t>(full_st.st_size);
1725
0
1726
0
  if (_VSTD_FS::exists(st)) {
1727
0
    __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink);
1728
0
1729
0
    // Attempt to extract the mtime, and fail if it's not representable using
1730
0
    // file_time_type. For now we ignore the error, as we'll report it when
1731
0
    // the value is actually used.
1732
0
    error_code ignored_ec;
1733
0
    __data_.__write_time_ =
1734
0
        __extract_last_write_time(__p_, full_st, &ignored_ec);
1735
0
  }
1736
0
1737
0
  return failure_ec;
1738
0
}
1739
#else
1740
error_code directory_entry::__do_refresh() noexcept {
1741
  __data_.__reset();
1742
  error_code failure_ec;
1743
1744
  file_status st = _VSTD_FS::symlink_status(__p_, failure_ec);
1745
  if (!status_known(st)) {
1746
    __data_.__reset();
1747
    return failure_ec;
1748
  }
1749
1750
  if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1751
    __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1752
    __data_.__type_ = st.type();
1753
    __data_.__non_sym_perms_ = st.permissions();
1754
  } else { // we have a symlink
1755
    __data_.__sym_perms_ = st.permissions();
1756
    // Get the information about the linked entity.
1757
    // Ignore errors from stat, since we don't want errors regarding symlink
1758
    // resolution to be reported to the user.
1759
    error_code ignored_ec;
1760
    st = _VSTD_FS::status(__p_, ignored_ec);
1761
1762
    __data_.__type_ = st.type();
1763
    __data_.__non_sym_perms_ = st.permissions();
1764
1765
    // If we failed to resolve the link, then only partially populate the
1766
    // cache.
1767
    if (!status_known(st)) {
1768
      __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1769
      return error_code{};
1770
    }
1771
    __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1772
  }
1773
1774
  // FIXME: This is currently broken, and the implementation only a placeholder.
1775
  // We need to cache last_write_time, file_size, and hard_link_count here before
1776
  // the implementation actually works.
1777
1778
  return failure_ec;
1779
}
1780
#endif
1781
1782
_LIBCPP_END_NAMESPACE_FILESYSTEM