Coverage Report

Created: 2021-01-23 06:44

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