Coverage Report

Created: 2021-09-21 08:58

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