Coverage Report

Created: 2020-09-22 08:39

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