blob: 58fbd1c61bf42f2bd8a56db3bd4c7bb914a8a38d [file] [log] [blame]
Eric Fiselier435db152016-06-17 19:46:40 +00001//===--------------------- filesystem/ops.cpp -----------------------------===//
2//
Chandler Carruthd2012102019-01-19 10:56:40 +00003// 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
Eric Fiselier435db152016-06-17 19:46:40 +00006//
7//===----------------------------------------------------------------------===//
8
Eric Fiselier02cea5e2018-07-27 03:07:09 +00009#include "filesystem"
Eric Fiseliera75bbde2018-07-23 02:00:52 +000010#include "array"
Eric Fiselier435db152016-06-17 19:46:40 +000011#include "iterator"
12#include "fstream"
Eric Fiselier91a182b2018-04-02 23:03:41 +000013#include "string_view"
14#include "type_traits"
15#include "vector"
Eric Fiselier435db152016-06-17 19:46:40 +000016#include "cstdlib"
17#include "climits"
18
Eric Fiselier70474082018-07-20 01:22:32 +000019#include "filesystem_common.h"
Eric Fiselier42d6d2c2017-07-08 04:18:41 +000020
Eric Fiselier435db152016-06-17 19:46:40 +000021#include <unistd.h>
22#include <sys/stat.h>
23#include <sys/statvfs.h>
Eric Fiselier7eba47e2018-07-25 20:51:49 +000024#include <time.h>
Eric Fiselier02cea5e2018-07-27 03:07:09 +000025#include <fcntl.h> /* values for fchmodat */
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000026
27#if defined(__linux__)
Eric Fiselier02cea5e2018-07-27 03:07:09 +000028#include <linux/version.h>
29#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 33)
30#include <sys/sendfile.h>
31#define _LIBCPP_USE_SENDFILE
32#endif
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000033#elif defined(__APPLE__) || __has_include(<copyfile.h>)
34#include <copyfile.h>
Eric Fiselier02cea5e2018-07-27 03:07:09 +000035#define _LIBCPP_USE_COPYFILE
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000036#endif
Nico Weber4f1d63a2018-02-06 19:17:41 +000037
Louis Dionne678dc852020-02-12 17:01:19 +010038#if !defined(CLOCK_REALTIME)
Eric Fiselier7eba47e2018-07-25 20:51:49 +000039#include <sys/time.h> // for gettimeofday and timeval
Louis Dionne678dc852020-02-12 17:01:19 +010040#endif // !defined(CLOCK_REALTIME)
Eric Fiselier7eba47e2018-07-25 20:51:49 +000041
Michał Górny8d676fb2019-12-02 11:49:20 +010042#if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB)
Petr Hosek99575aa2019-05-30 01:34:41 +000043#pragma comment(lib, "rt")
44#endif
45
Eric Fiselierd8b25e32018-07-23 03:06:57 +000046#if defined(_LIBCPP_COMPILER_GCC)
47#if _GNUC_VER < 500
48#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
49#endif
50#endif
51
Eric Fiselier02cea5e2018-07-27 03:07:09 +000052_LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
Eric Fiselier435db152016-06-17 19:46:40 +000053
Eric Fiselier02cea5e2018-07-27 03:07:09 +000054namespace {
55namespace parser {
Eric Fiselier91a182b2018-04-02 23:03:41 +000056
57using string_view_t = path::__string_view;
58using string_view_pair = pair<string_view_t, string_view_t>;
59using PosPtr = path::value_type const*;
60
61struct PathParser {
62 enum ParserState : unsigned char {
63 // Zero is a special sentinel value used by default constructed iterators.
Eric Fiselier23a120c2018-07-25 03:31:48 +000064 PS_BeforeBegin = path::iterator::_BeforeBegin,
65 PS_InRootName = path::iterator::_InRootName,
66 PS_InRootDir = path::iterator::_InRootDir,
67 PS_InFilenames = path::iterator::_InFilenames,
68 PS_InTrailingSep = path::iterator::_InTrailingSep,
69 PS_AtEnd = path::iterator::_AtEnd
Eric Fiselier91a182b2018-04-02 23:03:41 +000070 };
71
72 const string_view_t Path;
73 string_view_t RawEntry;
74 ParserState State;
75
76private:
Eric Fiselier02cea5e2018-07-27 03:07:09 +000077 PathParser(string_view_t P, ParserState State) noexcept : Path(P),
78 State(State) {}
Eric Fiselier91a182b2018-04-02 23:03:41 +000079
80public:
81 PathParser(string_view_t P, string_view_t E, unsigned char S)
82 : Path(P), RawEntry(E), State(static_cast<ParserState>(S)) {
83 // S cannot be '0' or PS_BeforeBegin.
84 }
85
86 static PathParser CreateBegin(string_view_t P) noexcept {
87 PathParser PP(P, PS_BeforeBegin);
88 PP.increment();
89 return PP;
90 }
91
92 static PathParser CreateEnd(string_view_t P) noexcept {
93 PathParser PP(P, PS_AtEnd);
94 return PP;
95 }
96
97 PosPtr peek() const noexcept {
98 auto TkEnd = getNextTokenStartPos();
99 auto End = getAfterBack();
100 return TkEnd == End ? nullptr : TkEnd;
101 }
102
103 void increment() noexcept {
104 const PosPtr End = getAfterBack();
105 const PosPtr Start = getNextTokenStartPos();
106 if (Start == End)
107 return makeState(PS_AtEnd);
108
109 switch (State) {
110 case PS_BeforeBegin: {
111 PosPtr TkEnd = consumeSeparator(Start, End);
112 if (TkEnd)
113 return makeState(PS_InRootDir, Start, TkEnd);
114 else
115 return makeState(PS_InFilenames, Start, consumeName(Start, End));
116 }
117 case PS_InRootDir:
118 return makeState(PS_InFilenames, Start, consumeName(Start, End));
119
120 case PS_InFilenames: {
121 PosPtr SepEnd = consumeSeparator(Start, End);
122 if (SepEnd != End) {
123 PosPtr TkEnd = consumeName(SepEnd, End);
124 if (TkEnd)
125 return makeState(PS_InFilenames, SepEnd, TkEnd);
126 }
127 return makeState(PS_InTrailingSep, Start, SepEnd);
128 }
129
130 case PS_InTrailingSep:
131 return makeState(PS_AtEnd);
132
133 case PS_InRootName:
134 case PS_AtEnd:
135 _LIBCPP_UNREACHABLE();
136 }
137 }
138
139 void decrement() noexcept {
140 const PosPtr REnd = getBeforeFront();
141 const PosPtr RStart = getCurrentTokenStartPos() - 1;
142 if (RStart == REnd) // we're decrementing the begin
143 return makeState(PS_BeforeBegin);
144
145 switch (State) {
146 case PS_AtEnd: {
147 // Try to consume a trailing separator or root directory first.
148 if (PosPtr SepEnd = consumeSeparator(RStart, REnd)) {
149 if (SepEnd == REnd)
150 return makeState(PS_InRootDir, Path.data(), RStart + 1);
151 return makeState(PS_InTrailingSep, SepEnd + 1, RStart + 1);
152 } else {
153 PosPtr TkStart = consumeName(RStart, REnd);
154 return makeState(PS_InFilenames, TkStart + 1, RStart + 1);
155 }
156 }
157 case PS_InTrailingSep:
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000158 return makeState(PS_InFilenames, consumeName(RStart, REnd) + 1,
159 RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000160 case PS_InFilenames: {
161 PosPtr SepEnd = consumeSeparator(RStart, REnd);
162 if (SepEnd == REnd)
163 return makeState(PS_InRootDir, Path.data(), RStart + 1);
164 PosPtr TkEnd = consumeName(SepEnd, REnd);
165 return makeState(PS_InFilenames, TkEnd + 1, SepEnd + 1);
166 }
167 case PS_InRootDir:
168 // return makeState(PS_InRootName, Path.data(), RStart + 1);
169 case PS_InRootName:
170 case PS_BeforeBegin:
171 _LIBCPP_UNREACHABLE();
172 }
173 }
174
175 /// \brief Return a view with the "preferred representation" of the current
176 /// element. For example trailing separators are represented as a '.'
177 string_view_t operator*() const noexcept {
178 switch (State) {
179 case PS_BeforeBegin:
180 case PS_AtEnd:
181 return "";
182 case PS_InRootDir:
183 return "/";
184 case PS_InTrailingSep:
185 return "";
186 case PS_InRootName:
187 case PS_InFilenames:
188 return RawEntry;
189 }
190 _LIBCPP_UNREACHABLE();
191 }
192
193 explicit operator bool() const noexcept {
194 return State != PS_BeforeBegin && State != PS_AtEnd;
195 }
196
197 PathParser& operator++() noexcept {
198 increment();
199 return *this;
200 }
201
202 PathParser& operator--() noexcept {
203 decrement();
204 return *this;
205 }
206
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000207 bool atEnd() const noexcept {
208 return State == PS_AtEnd;
209 }
210
211 bool inRootDir() const noexcept {
212 return State == PS_InRootDir;
213 }
214
215 bool inRootName() const noexcept {
216 return State == PS_InRootName;
217 }
218
Eric Fiselier91a182b2018-04-02 23:03:41 +0000219 bool inRootPath() const noexcept {
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000220 return inRootName() || inRootDir();
Eric Fiselier91a182b2018-04-02 23:03:41 +0000221 }
222
223private:
224 void makeState(ParserState NewState, PosPtr Start, PosPtr End) noexcept {
225 State = NewState;
226 RawEntry = string_view_t(Start, End - Start);
227 }
228 void makeState(ParserState NewState) noexcept {
229 State = NewState;
230 RawEntry = {};
231 }
232
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000233 PosPtr getAfterBack() const noexcept { return Path.data() + Path.size(); }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000234
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000235 PosPtr getBeforeFront() const noexcept { return Path.data() - 1; }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000236
237 /// \brief Return a pointer to the first character after the currently
238 /// lexed element.
239 PosPtr getNextTokenStartPos() const noexcept {
240 switch (State) {
241 case PS_BeforeBegin:
242 return Path.data();
243 case PS_InRootName:
244 case PS_InRootDir:
245 case PS_InFilenames:
246 return &RawEntry.back() + 1;
247 case PS_InTrailingSep:
248 case PS_AtEnd:
249 return getAfterBack();
250 }
251 _LIBCPP_UNREACHABLE();
252 }
253
254 /// \brief Return a pointer to the first character in the currently lexed
255 /// element.
256 PosPtr getCurrentTokenStartPos() const noexcept {
257 switch (State) {
258 case PS_BeforeBegin:
259 case PS_InRootName:
260 return &Path.front();
261 case PS_InRootDir:
262 case PS_InFilenames:
263 case PS_InTrailingSep:
264 return &RawEntry.front();
265 case PS_AtEnd:
266 return &Path.back() + 1;
267 }
268 _LIBCPP_UNREACHABLE();
269 }
270
271 PosPtr consumeSeparator(PosPtr P, PosPtr End) const noexcept {
272 if (P == End || *P != '/')
273 return nullptr;
274 const int Inc = P < End ? 1 : -1;
275 P += Inc;
276 while (P != End && *P == '/')
277 P += Inc;
278 return P;
279 }
280
281 PosPtr consumeName(PosPtr P, PosPtr End) const noexcept {
282 if (P == End || *P == '/')
283 return nullptr;
284 const int Inc = P < End ? 1 : -1;
285 P += Inc;
286 while (P != End && *P != '/')
287 P += Inc;
288 return P;
289 }
290};
291
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000292string_view_pair separate_filename(string_view_t const& s) {
293 if (s == "." || s == ".." || s.empty())
294 return string_view_pair{s, ""};
295 auto pos = s.find_last_of('.');
296 if (pos == string_view_t::npos || pos == 0)
297 return string_view_pair{s, string_view_t{}};
298 return string_view_pair{s.substr(0, pos), s.substr(pos)};
Eric Fiselier91a182b2018-04-02 23:03:41 +0000299}
300
301string_view_t createView(PosPtr S, PosPtr E) noexcept {
302 return {S, static_cast<size_t>(E - S) + 1};
303}
304
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000305} // namespace parser
306} // namespace
Eric Fiselier91a182b2018-04-02 23:03:41 +0000307
Eric Fiselier435db152016-06-17 19:46:40 +0000308// POSIX HELPERS
309
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000310namespace detail {
311namespace {
Eric Fiselier435db152016-06-17 19:46:40 +0000312
313using value_type = path::value_type;
314using string_type = path::string_type;
315
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000316struct FileDescriptor {
317 const path& name;
318 int fd = -1;
319 StatT m_stat;
320 file_status m_status;
321
322 template <class... Args>
323 static FileDescriptor create(const path* p, error_code& ec, Args... args) {
324 ec.clear();
325 int fd;
326 if ((fd = ::open(p->c_str(), args...)) == -1) {
327 ec = capture_errno();
328 return FileDescriptor{p};
329 }
330 return FileDescriptor(p, fd);
331 }
332
333 template <class... Args>
334 static FileDescriptor create_with_status(const path* p, error_code& ec,
335 Args... args) {
336 FileDescriptor fd = create(p, ec, args...);
337 if (!ec)
338 fd.refresh_status(ec);
339
340 return fd;
341 }
342
343 file_status get_status() const { return m_status; }
344 StatT const& get_stat() const { return m_stat; }
345
346 bool status_known() const { return _VSTD_FS::status_known(m_status); }
347
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000348 file_status refresh_status(error_code& ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000349
350 void close() noexcept {
351 if (fd != -1)
352 ::close(fd);
353 fd = -1;
354 }
355
356 FileDescriptor(FileDescriptor&& other)
357 : name(other.name), fd(other.fd), m_stat(other.m_stat),
358 m_status(other.m_status) {
359 other.fd = -1;
360 other.m_status = file_status{};
361 }
362
363 ~FileDescriptor() { close(); }
364
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000365 FileDescriptor(FileDescriptor const&) = delete;
366 FileDescriptor& operator=(FileDescriptor const&) = delete;
367
368private:
369 explicit FileDescriptor(const path* p, int fd = -1) : name(*p), fd(fd) {}
370};
371
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000372perms posix_get_perms(const StatT& st) noexcept {
Eric Fiselier70474082018-07-20 01:22:32 +0000373 return static_cast<perms>(st.st_mode) & perms::mask;
Eric Fiselier435db152016-06-17 19:46:40 +0000374}
375
376::mode_t posix_convert_perms(perms prms) {
Eric Fiselier70474082018-07-20 01:22:32 +0000377 return static_cast< ::mode_t>(prms & perms::mask);
Eric Fiselier435db152016-06-17 19:46:40 +0000378}
379
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000380file_status create_file_status(error_code& m_ec, path const& p,
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000381 const StatT& path_stat, error_code* ec) {
Eric Fiselier70474082018-07-20 01:22:32 +0000382 if (ec)
383 *ec = m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000384 if (m_ec && (m_ec.value() == ENOENT || m_ec.value() == ENOTDIR)) {
385 return file_status(file_type::not_found);
386 } else if (m_ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000387 ErrorHandler<void> err("posix_stat", ec, &p);
388 err.report(m_ec, "failed to determine attributes for the specified path");
Eric Fiselier70474082018-07-20 01:22:32 +0000389 return file_status(file_type::none);
390 }
391 // else
Eric Fiselier435db152016-06-17 19:46:40 +0000392
Eric Fiselier70474082018-07-20 01:22:32 +0000393 file_status fs_tmp;
394 auto const mode = path_stat.st_mode;
395 if (S_ISLNK(mode))
396 fs_tmp.type(file_type::symlink);
397 else if (S_ISREG(mode))
398 fs_tmp.type(file_type::regular);
399 else if (S_ISDIR(mode))
400 fs_tmp.type(file_type::directory);
401 else if (S_ISBLK(mode))
402 fs_tmp.type(file_type::block);
403 else if (S_ISCHR(mode))
404 fs_tmp.type(file_type::character);
405 else if (S_ISFIFO(mode))
406 fs_tmp.type(file_type::fifo);
407 else if (S_ISSOCK(mode))
408 fs_tmp.type(file_type::socket);
409 else
410 fs_tmp.type(file_type::unknown);
Eric Fiselier435db152016-06-17 19:46:40 +0000411
Eric Fiselier70474082018-07-20 01:22:32 +0000412 fs_tmp.permissions(detail::posix_get_perms(path_stat));
413 return fs_tmp;
Eric Fiselier435db152016-06-17 19:46:40 +0000414}
415
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000416file_status posix_stat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000417 error_code m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000418 if (::stat(p.c_str(), &path_stat) == -1)
419 m_ec = detail::capture_errno();
420 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000421}
422
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000423file_status posix_stat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000424 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000425 return posix_stat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000426}
427
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000428file_status posix_lstat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000429 error_code m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000430 if (::lstat(p.c_str(), &path_stat) == -1)
431 m_ec = detail::capture_errno();
432 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000433}
434
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000435file_status posix_lstat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000436 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000437 return posix_lstat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000438}
439
Dan Albert39b981d2019-01-15 19:16:25 +0000440// http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
441bool posix_ftruncate(const FileDescriptor& fd, off_t to_size, error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000442 if (::ftruncate(fd.fd, to_size) == -1) {
443 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000444 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000445 }
446 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000447 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000448}
449
450bool posix_fchmod(const FileDescriptor& fd, const StatT& st, error_code& ec) {
451 if (::fchmod(fd.fd, st.st_mode) == -1) {
452 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000453 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000454 }
455 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000456 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000457}
458
459bool stat_equivalent(const StatT& st1, const StatT& st2) {
Eric Fiselier70474082018-07-20 01:22:32 +0000460 return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
Eric Fiselier435db152016-06-17 19:46:40 +0000461}
462
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000463file_status FileDescriptor::refresh_status(error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000464 // FD must be open and good.
465 m_status = file_status{};
Eric Fiselierd8b25e32018-07-23 03:06:57 +0000466 m_stat = {};
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000467 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000468 if (::fstat(fd, &m_stat) == -1)
469 m_ec = capture_errno();
470 m_status = create_file_status(m_ec, name, m_stat, &ec);
471 return m_status;
Eric Fiselier435db152016-06-17 19:46:40 +0000472}
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000473} // namespace
474} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000475
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000476using detail::capture_errno;
477using detail::ErrorHandler;
478using detail::StatT;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000479using detail::TimeSpec;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000480using parser::createView;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000481using parser::PathParser;
482using parser::string_view_t;
483
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000484const bool _FilesystemClock::is_steady;
485
486_FilesystemClock::time_point _FilesystemClock::now() noexcept {
487 typedef chrono::duration<rep> __secs;
Louis Dionne678dc852020-02-12 17:01:19 +0100488#if defined(CLOCK_REALTIME)
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000489 typedef chrono::duration<rep, nano> __nsecs;
490 struct timespec tp;
491 if (0 != clock_gettime(CLOCK_REALTIME, &tp))
492 __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
493 return time_point(__secs(tp.tv_sec) +
494 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
495#else
496 typedef chrono::duration<rep, micro> __microsecs;
497 timeval tv;
498 gettimeofday(&tv, 0);
499 return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
Louis Dionne678dc852020-02-12 17:01:19 +0100500#endif // CLOCK_REALTIME
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000501}
502
503filesystem_error::~filesystem_error() {}
504
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000505void filesystem_error::__create_what(int __num_paths) {
506 const char* derived_what = system_error::what();
507 __storage_->__what_ = [&]() -> string {
508 const char* p1 = path1().native().empty() ? "\"\"" : path1().c_str();
509 const char* p2 = path2().native().empty() ? "\"\"" : path2().c_str();
510 switch (__num_paths) {
511 default:
512 return detail::format_string("filesystem error: %s", derived_what);
513 case 1:
514 return detail::format_string("filesystem error: %s [%s]", derived_what,
515 p1);
516 case 2:
517 return detail::format_string("filesystem error: %s [%s] [%s]",
518 derived_what, p1, p2);
519 }
520 }();
521}
Eric Fiselier435db152016-06-17 19:46:40 +0000522
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000523static path __do_absolute(const path& p, path* cwd, error_code* ec) {
524 if (ec)
525 ec->clear();
526 if (p.is_absolute())
527 return p;
528 *cwd = __current_path(ec);
529 if (ec && *ec)
530 return {};
531 return (*cwd) / p;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000532}
533
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000534path __absolute(const path& p, error_code* ec) {
535 path cwd;
536 return __do_absolute(p, &cwd, ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000537}
538
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000539path __canonical(path const& orig_p, error_code* ec) {
540 path cwd;
541 ErrorHandler<path> err("canonical", ec, &orig_p, &cwd);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000542
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000543 path p = __do_absolute(orig_p, &cwd, ec);
Eric Fiselierb5215302019-01-17 02:59:28 +0000544#if _POSIX_VERSION >= 200112
545 std::unique_ptr<char, decltype(&::free)>
546 hold(::realpath(p.c_str(), nullptr), &::free);
547 if (hold.get() == nullptr)
548 return err.report(capture_errno());
549 return {hold.get()};
550#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000551 char buff[PATH_MAX + 1];
552 char* ret;
553 if ((ret = ::realpath(p.c_str(), buff)) == nullptr)
554 return err.report(capture_errno());
555 return {ret};
Eric Fiselierb5215302019-01-17 02:59:28 +0000556#endif
Eric Fiselier435db152016-06-17 19:46:40 +0000557}
558
559void __copy(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000560 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000561 ErrorHandler<void> err("copy", ec, &from, &to);
Eric Fiselier435db152016-06-17 19:46:40 +0000562
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000563 const bool sym_status = bool(
564 options & (copy_options::create_symlinks | copy_options::skip_symlinks));
Eric Fiselier435db152016-06-17 19:46:40 +0000565
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000566 const bool sym_status2 = bool(options & copy_options::copy_symlinks);
Eric Fiselier435db152016-06-17 19:46:40 +0000567
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000568 error_code m_ec1;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000569 StatT f_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000570 const file_status f = sym_status || sym_status2
571 ? detail::posix_lstat(from, f_st, &m_ec1)
572 : detail::posix_stat(from, f_st, &m_ec1);
573 if (m_ec1)
574 return err.report(m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000575
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000576 StatT t_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000577 const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1)
578 : detail::posix_stat(to, t_st, &m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000579
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000580 if (not status_known(t))
581 return err.report(m_ec1);
582
583 if (!exists(f) || is_other(f) || is_other(t) ||
584 (is_directory(f) && is_regular_file(t)) ||
585 detail::stat_equivalent(f_st, t_st)) {
586 return err.report(errc::function_not_supported);
587 }
Eric Fiselier435db152016-06-17 19:46:40 +0000588
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000589 if (ec)
590 ec->clear();
Eric Fiselier435db152016-06-17 19:46:40 +0000591
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000592 if (is_symlink(f)) {
593 if (bool(copy_options::skip_symlinks & options)) {
594 // do nothing
595 } else if (not exists(t)) {
596 __copy_symlink(from, to, ec);
597 } else {
598 return err.report(errc::file_exists);
Eric Fiselier435db152016-06-17 19:46:40 +0000599 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000600 return;
601 } else if (is_regular_file(f)) {
602 if (bool(copy_options::directories_only & options)) {
603 // do nothing
604 } else if (bool(copy_options::create_symlinks & options)) {
605 __create_symlink(from, to, ec);
606 } else if (bool(copy_options::create_hard_links & options)) {
607 __create_hard_link(from, to, ec);
608 } else if (is_directory(t)) {
609 __copy_file(from, to / from.filename(), options, ec);
610 } else {
611 __copy_file(from, to, options, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000612 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000613 return;
614 } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
615 return err.report(errc::is_a_directory);
616 } else if (is_directory(f) && (bool(copy_options::recursive & options) ||
617 copy_options::none == options)) {
Eric Fiselier435db152016-06-17 19:46:40 +0000618
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000619 if (!exists(t)) {
620 // create directory to with attributes from 'from'.
621 __create_directory(to, from, ec);
622 if (ec && *ec) {
623 return;
624 }
Eric Fiselier435db152016-06-17 19:46:40 +0000625 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000626 directory_iterator it =
627 ec ? directory_iterator(from, *ec) : directory_iterator(from);
628 if (ec && *ec) {
629 return;
630 }
631 error_code m_ec2;
632 for (; it != directory_iterator(); it.increment(m_ec2)) {
633 if (m_ec2) {
634 return err.report(m_ec2);
635 }
636 __copy(it->path(), to / it->path().filename(),
637 options | copy_options::__in_recursive_copy, ec);
638 if (ec && *ec) {
639 return;
640 }
641 }
642 }
Eric Fiselier435db152016-06-17 19:46:40 +0000643}
644
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000645namespace detail {
646namespace {
647
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000648#ifdef _LIBCPP_USE_SENDFILE
649bool copy_file_impl_sendfile(FileDescriptor& read_fd, FileDescriptor& write_fd,
650 error_code& ec) {
651
652 size_t count = read_fd.get_stat().st_size;
653 do {
654 ssize_t res;
655 if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) {
656 ec = capture_errno();
657 return false;
658 }
659 count -= res;
660 } while (count > 0);
661
662 ec.clear();
663
664 return true;
665}
666#elif defined(_LIBCPP_USE_COPYFILE)
667bool copy_file_impl_copyfile(FileDescriptor& read_fd, FileDescriptor& write_fd,
668 error_code& ec) {
669 struct CopyFileState {
670 copyfile_state_t state;
671 CopyFileState() { state = copyfile_state_alloc(); }
672 ~CopyFileState() { copyfile_state_free(state); }
673
674 private:
675 CopyFileState(CopyFileState const&) = delete;
676 CopyFileState& operator=(CopyFileState const&) = delete;
677 };
678
679 CopyFileState cfs;
680 if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {
681 ec = capture_errno();
682 return false;
683 }
684
685 ec.clear();
686 return true;
687}
688#endif
689
690// Note: This function isn't guarded by ifdef's even though it may be unused
691// in order to assure it still compiles.
692__attribute__((unused)) bool copy_file_impl_default(FileDescriptor& read_fd,
693 FileDescriptor& write_fd,
694 error_code& ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000695 ifstream in;
696 in.__open(read_fd.fd, ios::binary);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000697 if (!in.is_open()) {
698 // This assumes that __open didn't reset the error code.
699 ec = capture_errno();
700 return false;
701 }
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000702 ofstream out;
703 out.__open(write_fd.fd, ios::binary);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000704 if (!out.is_open()) {
705 ec = capture_errno();
706 return false;
707 }
708
709 if (in.good() && out.good()) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000710 using InIt = istreambuf_iterator<char>;
711 using OutIt = ostreambuf_iterator<char>;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000712 InIt bin(in);
713 InIt ein;
714 OutIt bout(out);
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000715 copy(bin, ein, bout);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000716 }
717 if (out.fail() || in.fail()) {
718 ec = make_error_code(errc::io_error);
719 return false;
720 }
721
722 ec.clear();
723 return true;
724}
725
726bool copy_file_impl(FileDescriptor& from, FileDescriptor& to, error_code& ec) {
727#if defined(_LIBCPP_USE_SENDFILE)
728 return copy_file_impl_sendfile(from, to, ec);
729#elif defined(_LIBCPP_USE_COPYFILE)
730 return copy_file_impl_copyfile(from, to, ec);
731#else
732 return copy_file_impl_default(from, to, ec);
733#endif
734}
735
736} // namespace
737} // namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000738
739bool __copy_file(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000740 error_code* ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000741 using detail::FileDescriptor;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000742 ErrorHandler<bool> err("copy_file", ec, &to, &from);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000743
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000744 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000745 FileDescriptor from_fd =
746 FileDescriptor::create_with_status(&from, m_ec, O_RDONLY | O_NONBLOCK);
747 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000748 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000749
750 auto from_st = from_fd.get_status();
751 StatT const& from_stat = from_fd.get_stat();
752 if (!is_regular_file(from_st)) {
753 if (not m_ec)
754 m_ec = make_error_code(errc::not_supported);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000755 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000756 }
757
758 const bool skip_existing = bool(copy_options::skip_existing & options);
759 const bool update_existing = bool(copy_options::update_existing & options);
760 const bool overwrite_existing =
761 bool(copy_options::overwrite_existing & options);
762
763 StatT to_stat_path;
764 file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);
765 if (!status_known(to_st))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000766 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000767
768 const bool to_exists = exists(to_st);
769 if (to_exists && !is_regular_file(to_st))
Eric Fiselier268fa832018-07-23 11:55:13 +0000770 return err.report(errc::not_supported);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000771
772 if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))
Eric Fiselier268fa832018-07-23 11:55:13 +0000773 return err.report(errc::file_exists);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000774
775 if (to_exists && skip_existing)
776 return false;
777
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000778 bool ShouldCopy = [&]() {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000779 if (to_exists && update_existing) {
780 auto from_time = detail::extract_mtime(from_stat);
781 auto to_time = detail::extract_mtime(to_stat_path);
782 if (from_time.tv_sec < to_time.tv_sec)
Eric Fiselier435db152016-06-17 19:46:40 +0000783 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000784 if (from_time.tv_sec == to_time.tv_sec &&
785 from_time.tv_nsec <= to_time.tv_nsec)
Eric Fiseliere7359252016-10-16 00:47:59 +0000786 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000787 return true;
Eric Fiseliere7359252016-10-16 00:47:59 +0000788 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000789 if (!to_exists || overwrite_existing)
790 return true;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000791 return err.report(errc::file_exists);
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000792 }();
793 if (!ShouldCopy)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000794 return false;
Eric Fiseliere7359252016-10-16 00:47:59 +0000795
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000796 // Don't truncate right away. We may not be opening the file we originally
797 // looked at; we'll check this later.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000798 int to_open_flags = O_WRONLY;
799 if (!to_exists)
800 to_open_flags |= O_CREAT;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000801 FileDescriptor to_fd = FileDescriptor::create_with_status(
802 &to, m_ec, to_open_flags, from_stat.st_mode);
803 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000804 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000805
806 if (to_exists) {
807 // Check that the file we initially stat'ed is equivalent to the one
808 // we opened.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000809 // FIXME: report this better.
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000810 if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000811 return err.report(errc::bad_file_descriptor);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000812
813 // Set the permissions and truncate the file we opened.
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000814 if (detail::posix_fchmod(to_fd, from_stat, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000815 return err.report(m_ec);
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000816 if (detail::posix_ftruncate(to_fd, 0, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000817 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000818 }
819
820 if (!copy_file_impl(from_fd, to_fd, m_ec)) {
821 // FIXME: Remove the dest file if we failed, and it didn't exist previously.
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000822 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000823 }
824
825 return true;
Eric Fiselier435db152016-06-17 19:46:40 +0000826}
827
828void __copy_symlink(const path& existing_symlink, const path& new_symlink,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000829 error_code* ec) {
830 const path real_path(__read_symlink(existing_symlink, ec));
831 if (ec && *ec) {
832 return;
833 }
834 // NOTE: proposal says you should detect if you should call
835 // create_symlink or create_directory_symlink. I don't think this
836 // is needed with POSIX
837 __create_symlink(real_path, new_symlink, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000838}
839
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000840bool __create_directories(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000841 ErrorHandler<bool> err("create_directories", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +0000842
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000843 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000844 auto const st = detail::posix_stat(p, &m_ec);
845 if (!status_known(st))
846 return err.report(m_ec);
847 else if (is_directory(st))
848 return false;
849 else if (exists(st))
850 return err.report(errc::file_exists);
851
852 const path parent = p.parent_path();
853 if (!parent.empty()) {
854 const file_status parent_st = status(parent, m_ec);
855 if (not status_known(parent_st))
856 return err.report(m_ec);
857 if (not exists(parent_st)) {
858 __create_directories(parent, ec);
859 if (ec && *ec) {
860 return false;
861 }
Eric Fiselier435db152016-06-17 19:46:40 +0000862 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000863 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000864 return __create_directory(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000865}
866
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000867bool __create_directory(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000868 ErrorHandler<bool> err("create_directory", ec, &p);
869
870 if (::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
871 return true;
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000872 if (errno != EEXIST)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000873 err.report(capture_errno());
874 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000875}
876
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000877bool __create_directory(path const& p, path const& attributes, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000878 ErrorHandler<bool> err("create_directory", ec, &p, &attributes);
879
880 StatT attr_stat;
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000881 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000882 auto st = detail::posix_stat(attributes, attr_stat, &mec);
883 if (!status_known(st))
884 return err.report(mec);
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000885 if (!is_directory(st))
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000886 return err.report(errc::not_a_directory,
887 "the specified attribute path is invalid");
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000888
889 if (::mkdir(p.c_str(), attr_stat.st_mode) == 0)
890 return true;
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000891 if (errno != EEXIST)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000892 err.report(capture_errno());
893 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000894}
895
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000896void __create_directory_symlink(path const& from, path const& to,
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000897 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000898 ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
899 if (::symlink(from.c_str(), to.c_str()) != 0)
900 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000901}
902
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000903void __create_hard_link(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000904 ErrorHandler<void> err("create_hard_link", ec, &from, &to);
905 if (::link(from.c_str(), to.c_str()) == -1)
906 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000907}
908
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000909void __create_symlink(path const& from, path const& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000910 ErrorHandler<void> err("create_symlink", ec, &from, &to);
911 if (::symlink(from.c_str(), to.c_str()) == -1)
912 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000913}
914
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000915path __current_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000916 ErrorHandler<path> err("current_path", ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000917
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000918 auto size = ::pathconf(".", _PC_PATH_MAX);
919 _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
920
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000921 auto buff = unique_ptr<char[]>(new char[size + 1]);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000922 char* ret;
923 if ((ret = ::getcwd(buff.get(), static_cast<size_t>(size))) == nullptr)
924 return err.report(capture_errno(), "call to getcwd failed");
925
926 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +0000927}
928
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000929void __current_path(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000930 ErrorHandler<void> err("current_path", ec, &p);
931 if (::chdir(p.c_str()) == -1)
932 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000933}
934
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000935bool __equivalent(const path& p1, const path& p2, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000936 ErrorHandler<bool> err("equivalent", ec, &p1, &p2);
937
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000938 error_code ec1, ec2;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000939 StatT st1 = {}, st2 = {};
940 auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
941 if (!exists(s1))
942 return err.report(errc::not_supported);
943 auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
944 if (!exists(s2))
945 return err.report(errc::not_supported);
946
947 return detail::stat_equivalent(st1, st2);
Eric Fiselier435db152016-06-17 19:46:40 +0000948}
949
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000950uintmax_t __file_size(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000951 ErrorHandler<uintmax_t> err("file_size", ec, &p);
952
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000953 error_code m_ec;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000954 StatT st;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000955 file_status fst = detail::posix_stat(p, st, &m_ec);
956 if (!exists(fst) || !is_regular_file(fst)) {
957 errc error_kind =
958 is_directory(fst) ? errc::is_a_directory : errc::not_supported;
959 if (!m_ec)
960 m_ec = make_error_code(error_kind);
961 return err.report(m_ec);
962 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000963 // is_regular_file(p) == true
964 return static_cast<uintmax_t>(st.st_size);
Eric Fiselier435db152016-06-17 19:46:40 +0000965}
966
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000967uintmax_t __hard_link_count(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000968 ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);
969
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000970 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000971 StatT st;
972 detail::posix_stat(p, st, &m_ec);
973 if (m_ec)
974 return err.report(m_ec);
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000975 return static_cast<uintmax_t>(st.st_nlink);
Eric Fiselier435db152016-06-17 19:46:40 +0000976}
977
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000978bool __fs_is_empty(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000979 ErrorHandler<bool> err("is_empty", ec, &p);
Eric Fiselieraa8c61f2016-10-15 23:05:04 +0000980
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000981 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000982 StatT pst;
983 auto st = detail::posix_stat(p, pst, &m_ec);
984 if (m_ec)
985 return err.report(m_ec);
986 else if (!is_directory(st) && !is_regular_file(st))
987 return err.report(errc::not_supported);
988 else if (is_directory(st)) {
989 auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
990 if (ec && *ec)
991 return false;
992 return it == directory_iterator{};
993 } else if (is_regular_file(st))
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000994 return static_cast<uintmax_t>(pst.st_size) == 0;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000995
996 _LIBCPP_UNREACHABLE();
Eric Fiselier435db152016-06-17 19:46:40 +0000997}
998
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000999static file_time_type __extract_last_write_time(const path& p, const StatT& st,
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001000 error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001001 using detail::fs_time;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001002 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
1003
Eric Fiselier70474082018-07-20 01:22:32 +00001004 auto ts = detail::extract_mtime(st);
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001005 if (!fs_time::is_representable(ts))
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001006 return err.report(errc::value_too_large);
1007
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001008 return fs_time::convert_from_timespec(ts);
Eric Fiselier70474082018-07-20 01:22:32 +00001009}
Eric Fiselier42d6d2c2017-07-08 04:18:41 +00001010
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001011file_time_type __last_write_time(const path& p, error_code* ec) {
1012 using namespace chrono;
1013 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001014
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001015 error_code m_ec;
1016 StatT st;
1017 detail::posix_stat(p, st, &m_ec);
1018 if (m_ec)
1019 return err.report(m_ec);
1020 return __extract_last_write_time(p, st, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001021}
1022
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001023void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
1024 using detail::fs_time;
1025 ErrorHandler<void> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001026
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001027 error_code m_ec;
1028 array<TimeSpec, 2> tbuf;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001029#if !defined(_LIBCPP_USE_UTIMENSAT)
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001030 // This implementation has a race condition between determining the
1031 // last access time and attempting to set it to the same value using
1032 // ::utimes
1033 StatT st;
1034 file_status fst = detail::posix_stat(p, st, &m_ec);
1035 if (m_ec)
1036 return err.report(m_ec);
1037 tbuf[0] = detail::extract_atime(st);
Eric Fiselier435db152016-06-17 19:46:40 +00001038#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001039 tbuf[0].tv_sec = 0;
1040 tbuf[0].tv_nsec = UTIME_OMIT;
Eric Fiselier435db152016-06-17 19:46:40 +00001041#endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001042 if (!fs_time::convert_to_timespec(tbuf[1], new_time))
1043 return err.report(errc::value_too_large);
Eric Fiselier70474082018-07-20 01:22:32 +00001044
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001045 detail::set_file_times(p, tbuf, m_ec);
1046 if (m_ec)
1047 return err.report(m_ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001048}
1049
Eric Fiselier4f3dc0e2018-03-26 06:23:55 +00001050void __permissions(const path& p, perms prms, perm_options opts,
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001051 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001052 ErrorHandler<void> err("permissions", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001053
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001054 auto has_opt = [&](perm_options o) { return bool(o & opts); };
1055 const bool resolve_symlinks = !has_opt(perm_options::nofollow);
1056 const bool add_perms = has_opt(perm_options::add);
1057 const bool remove_perms = has_opt(perm_options::remove);
1058 _LIBCPP_ASSERT(
1059 (add_perms + remove_perms + has_opt(perm_options::replace)) == 1,
1060 "One and only one of the perm_options constants replace, add, or remove "
1061 "is present in opts");
1062
1063 bool set_sym_perms = false;
1064 prms &= perms::mask;
1065 if (!resolve_symlinks || (add_perms || remove_perms)) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001066 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001067 file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
1068 : detail::posix_lstat(p, &m_ec);
1069 set_sym_perms = is_symlink(st);
1070 if (m_ec)
1071 return err.report(m_ec);
1072 _LIBCPP_ASSERT(st.permissions() != perms::unknown,
1073 "Permissions unexpectedly unknown");
1074 if (add_perms)
1075 prms |= st.permissions();
1076 else if (remove_perms)
1077 prms = st.permissions() & ~prms;
1078 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001079 const auto real_perms = detail::posix_convert_perms(prms);
Eric Fiselier435db152016-06-17 19:46:40 +00001080
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001081#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
1082 const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
1083 if (::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
1084 return err.report(capture_errno());
1085 }
1086#else
1087 if (set_sym_perms)
1088 return err.report(errc::operation_not_supported);
1089 if (::chmod(p.c_str(), real_perms) == -1) {
1090 return err.report(capture_errno());
1091 }
1092#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001093}
1094
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001095path __read_symlink(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001096 ErrorHandler<path> err("read_symlink", ec, &p);
1097
Eric Fiselierb5215302019-01-17 02:59:28 +00001098#ifdef PATH_MAX
1099 struct NullDeleter { void operator()(void*) const {} };
1100 const size_t size = PATH_MAX + 1;
1101 char stack_buff[size];
1102 auto buff = std::unique_ptr<char[], NullDeleter>(stack_buff);
1103#else
1104 StatT sb;
1105 if (::lstat(p.c_str(), &sb) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001106 return err.report(capture_errno());
1107 }
Eric Fiselierb5215302019-01-17 02:59:28 +00001108 const size_t size = sb.st_size + 1;
1109 auto buff = unique_ptr<char[]>(new char[size]);
1110#endif
1111 ::ssize_t ret;
1112 if ((ret = ::readlink(p.c_str(), buff.get(), size)) == -1)
1113 return err.report(capture_errno());
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001114 _LIBCPP_ASSERT(ret > 0, "TODO");
Eric Fiselierb5215302019-01-17 02:59:28 +00001115 if (static_cast<size_t>(ret) >= size)
1116 return err.report(errc::value_too_large);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001117 buff[ret] = 0;
Eric Fiselierb5215302019-01-17 02:59:28 +00001118 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001119}
1120
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001121bool __remove(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001122 ErrorHandler<bool> err("remove", ec, &p);
1123 if (::remove(p.c_str()) == -1) {
1124 if (errno != ENOENT)
1125 err.report(capture_errno());
1126 return false;
1127 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001128 return true;
Eric Fiselier435db152016-06-17 19:46:40 +00001129}
1130
1131namespace {
1132
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001133uintmax_t remove_all_impl(path const& p, error_code& ec) {
1134 const auto npos = static_cast<uintmax_t>(-1);
1135 const file_status st = __symlink_status(p, &ec);
1136 if (ec)
1137 return npos;
1138 uintmax_t count = 1;
1139 if (is_directory(st)) {
1140 for (directory_iterator it(p, ec); !ec && it != directory_iterator();
1141 it.increment(ec)) {
1142 auto other_count = remove_all_impl(it->path(), ec);
1143 if (ec)
1144 return npos;
1145 count += other_count;
Eric Fiselier435db152016-06-17 19:46:40 +00001146 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001147 if (ec)
1148 return npos;
1149 }
1150 if (!__remove(p, &ec))
1151 return npos;
1152 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001153}
1154
1155} // end namespace
1156
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001157uintmax_t __remove_all(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001158 ErrorHandler<uintmax_t> err("remove_all", ec, &p);
Ekaterina Vaartis52668f72018-01-11 17:04:29 +00001159
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001160 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001161 auto count = remove_all_impl(p, mec);
1162 if (mec) {
1163 if (mec == errc::no_such_file_or_directory)
1164 return 0;
1165 return err.report(mec);
1166 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001167 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001168}
1169
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001170void __rename(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001171 ErrorHandler<void> err("rename", ec, &from, &to);
1172 if (::rename(from.c_str(), to.c_str()) == -1)
1173 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001174}
1175
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001176void __resize_file(const path& p, uintmax_t size, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001177 ErrorHandler<void> err("resize_file", ec, &p);
1178 if (::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
1179 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001180}
1181
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001182space_info __space(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001183 ErrorHandler<void> err("space", ec, &p);
1184 space_info si;
1185 struct statvfs m_svfs = {};
1186 if (::statvfs(p.c_str(), &m_svfs) == -1) {
1187 err.report(capture_errno());
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001188 si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001189 return si;
1190 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001191 // Multiply with overflow checking.
1192 auto do_mult = [&](uintmax_t& out, uintmax_t other) {
1193 out = other * m_svfs.f_frsize;
1194 if (other == 0 || out / other != m_svfs.f_frsize)
1195 out = static_cast<uintmax_t>(-1);
1196 };
1197 do_mult(si.capacity, m_svfs.f_blocks);
1198 do_mult(si.free, m_svfs.f_bfree);
1199 do_mult(si.available, m_svfs.f_bavail);
1200 return si;
Eric Fiselier435db152016-06-17 19:46:40 +00001201}
1202
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001203file_status __status(const path& p, error_code* ec) {
1204 return detail::posix_stat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001205}
1206
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001207file_status __symlink_status(const path& p, error_code* ec) {
1208 return detail::posix_lstat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001209}
1210
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001211path __temp_directory_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001212 ErrorHandler<path> err("temp_directory_path", ec);
1213
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001214 const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1215 const char* ret = nullptr;
1216
1217 for (auto& ep : env_paths)
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001218 if ((ret = getenv(ep)))
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001219 break;
1220 if (ret == nullptr)
1221 ret = "/tmp";
1222
1223 path p(ret);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001224 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001225 file_status st = detail::posix_stat(p, &m_ec);
1226 if (!status_known(st))
1227 return err.report(m_ec, "cannot access path \"%s\"", p);
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001228
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001229 if (!exists(st) || !is_directory(st))
1230 return err.report(errc::not_a_directory, "path \"%s\" is not a directory",
1231 p);
1232
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001233 return p;
Eric Fiselier435db152016-06-17 19:46:40 +00001234}
1235
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001236path __weakly_canonical(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001237 ErrorHandler<path> err("weakly_canonical", ec, &p);
1238
Eric Fiselier91a182b2018-04-02 23:03:41 +00001239 if (p.empty())
1240 return __canonical("", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001241
Eric Fiselier91a182b2018-04-02 23:03:41 +00001242 path result;
1243 path tmp;
1244 tmp.__reserve(p.native().size());
1245 auto PP = PathParser::CreateEnd(p.native());
1246 --PP;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001247 vector<string_view_t> DNEParts;
Eric Fiselier435db152016-06-17 19:46:40 +00001248
Eric Fiselier91a182b2018-04-02 23:03:41 +00001249 while (PP.State != PathParser::PS_BeforeBegin) {
1250 tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001251 error_code m_ec;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001252 file_status st = __status(tmp, &m_ec);
1253 if (!status_known(st)) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001254 return err.report(m_ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001255 } else if (exists(st)) {
1256 result = __canonical(tmp, ec);
1257 break;
Eric Fiselier435db152016-06-17 19:46:40 +00001258 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001259 DNEParts.push_back(*PP);
1260 --PP;
1261 }
1262 if (PP.State == PathParser::PS_BeforeBegin)
1263 result = __canonical("", ec);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001264 if (ec)
1265 ec->clear();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001266 if (DNEParts.empty())
1267 return result;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001268 for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001269 result /= *It;
1270 return result.lexically_normal();
Eric Fiselier435db152016-06-17 19:46:40 +00001271}
1272
Eric Fiselier91a182b2018-04-02 23:03:41 +00001273///////////////////////////////////////////////////////////////////////////////
1274// path definitions
1275///////////////////////////////////////////////////////////////////////////////
1276
1277constexpr path::value_type path::preferred_separator;
1278
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001279path& path::replace_extension(path const& replacement) {
1280 path p = extension();
1281 if (not p.empty()) {
1282 __pn_.erase(__pn_.size() - p.native().size());
1283 }
1284 if (!replacement.empty()) {
1285 if (replacement.native()[0] != '.') {
1286 __pn_ += ".";
Eric Fiselier91a182b2018-04-02 23:03:41 +00001287 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001288 __pn_.append(replacement.__pn_);
1289 }
1290 return *this;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001291}
1292
1293///////////////////////////////////////////////////////////////////////////////
1294// path.decompose
1295
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001296string_view_t path::__root_name() const {
1297 auto PP = PathParser::CreateBegin(__pn_);
1298 if (PP.State == PathParser::PS_InRootName)
1299 return *PP;
1300 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001301}
1302
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001303string_view_t path::__root_directory() const {
1304 auto PP = PathParser::CreateBegin(__pn_);
1305 if (PP.State == PathParser::PS_InRootName)
1306 ++PP;
1307 if (PP.State == PathParser::PS_InRootDir)
1308 return *PP;
1309 return {};
1310}
1311
1312string_view_t path::__root_path_raw() const {
1313 auto PP = PathParser::CreateBegin(__pn_);
1314 if (PP.State == PathParser::PS_InRootName) {
1315 auto NextCh = PP.peek();
1316 if (NextCh && *NextCh == '/') {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001317 ++PP;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001318 return createView(__pn_.data(), &PP.RawEntry.back());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001319 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001320 return PP.RawEntry;
1321 }
1322 if (PP.State == PathParser::PS_InRootDir)
1323 return *PP;
1324 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001325}
1326
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001327static bool ConsumeRootName(PathParser *PP) {
1328 static_assert(PathParser::PS_BeforeBegin == 1 &&
1329 PathParser::PS_InRootName == 2,
1330 "Values for enums are incorrect");
1331 while (PP->State <= PathParser::PS_InRootName)
1332 ++(*PP);
1333 return PP->State == PathParser::PS_AtEnd;
1334}
1335
Eric Fiselier91a182b2018-04-02 23:03:41 +00001336static bool ConsumeRootDir(PathParser* PP) {
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001337 static_assert(PathParser::PS_BeforeBegin == 1 &&
1338 PathParser::PS_InRootName == 2 &&
1339 PathParser::PS_InRootDir == 3, "Values for enums are incorrect");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001340 while (PP->State <= PathParser::PS_InRootDir)
1341 ++(*PP);
1342 return PP->State == PathParser::PS_AtEnd;
1343}
1344
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001345string_view_t path::__relative_path() const {
1346 auto PP = PathParser::CreateBegin(__pn_);
1347 if (ConsumeRootDir(&PP))
1348 return {};
1349 return createView(PP.RawEntry.data(), &__pn_.back());
1350}
1351
1352string_view_t path::__parent_path() const {
1353 if (empty())
1354 return {};
1355 // Determine if we have a root path but not a relative path. In that case
1356 // return *this.
1357 {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001358 auto PP = PathParser::CreateBegin(__pn_);
1359 if (ConsumeRootDir(&PP))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001360 return __pn_;
1361 }
1362 // Otherwise remove a single element from the end of the path, and return
1363 // a string representing that path
1364 {
1365 auto PP = PathParser::CreateEnd(__pn_);
1366 --PP;
1367 if (PP.RawEntry.data() == __pn_.data())
Eric Fiselier91a182b2018-04-02 23:03:41 +00001368 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001369 --PP;
1370 return createView(__pn_.data(), &PP.RawEntry.back());
1371 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001372}
1373
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001374string_view_t path::__filename() const {
1375 if (empty())
1376 return {};
1377 {
1378 PathParser PP = PathParser::CreateBegin(__pn_);
1379 if (ConsumeRootDir(&PP))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001380 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001381 }
1382 return *(--PathParser::CreateEnd(__pn_));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001383}
1384
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001385string_view_t path::__stem() const {
1386 return parser::separate_filename(__filename()).first;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001387}
1388
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001389string_view_t path::__extension() const {
1390 return parser::separate_filename(__filename()).second;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001391}
1392
1393////////////////////////////////////////////////////////////////////////////
1394// path.gen
1395
Eric Fiselier91a182b2018-04-02 23:03:41 +00001396enum PathPartKind : unsigned char {
1397 PK_None,
1398 PK_RootSep,
1399 PK_Filename,
1400 PK_Dot,
1401 PK_DotDot,
1402 PK_TrailingSep
1403};
1404
1405static PathPartKind ClassifyPathPart(string_view_t Part) {
1406 if (Part.empty())
1407 return PK_TrailingSep;
1408 if (Part == ".")
1409 return PK_Dot;
1410 if (Part == "..")
1411 return PK_DotDot;
1412 if (Part == "/")
1413 return PK_RootSep;
1414 return PK_Filename;
1415}
1416
1417path path::lexically_normal() const {
1418 if (__pn_.empty())
1419 return *this;
1420
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001421 using PartKindPair = pair<string_view_t, PathPartKind>;
1422 vector<PartKindPair> Parts;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001423 // Guess as to how many elements the path has to avoid reallocating.
1424 Parts.reserve(32);
1425
1426 // Track the total size of the parts as we collect them. This allows the
1427 // resulting path to reserve the correct amount of memory.
1428 size_t NewPathSize = 0;
1429 auto AddPart = [&](PathPartKind K, string_view_t P) {
1430 NewPathSize += P.size();
1431 Parts.emplace_back(P, K);
1432 };
1433 auto LastPartKind = [&]() {
1434 if (Parts.empty())
1435 return PK_None;
1436 return Parts.back().second;
1437 };
1438
1439 bool MaybeNeedTrailingSep = false;
1440 // Build a stack containing the remaining elements of the path, popping off
1441 // elements which occur before a '..' entry.
1442 for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) {
1443 auto Part = *PP;
1444 PathPartKind Kind = ClassifyPathPart(Part);
1445 switch (Kind) {
1446 case PK_Filename:
1447 case PK_RootSep: {
1448 // Add all non-dot and non-dot-dot elements to the stack of elements.
1449 AddPart(Kind, Part);
1450 MaybeNeedTrailingSep = false;
1451 break;
1452 }
1453 case PK_DotDot: {
1454 // Only push a ".." element if there are no elements preceding the "..",
1455 // or if the preceding element is itself "..".
1456 auto LastKind = LastPartKind();
1457 if (LastKind == PK_Filename) {
1458 NewPathSize -= Parts.back().first.size();
1459 Parts.pop_back();
1460 } else if (LastKind != PK_RootSep)
1461 AddPart(PK_DotDot, "..");
1462 MaybeNeedTrailingSep = LastKind == PK_Filename;
1463 break;
1464 }
1465 case PK_Dot:
1466 case PK_TrailingSep: {
1467 MaybeNeedTrailingSep = true;
1468 break;
1469 }
1470 case PK_None:
1471 _LIBCPP_UNREACHABLE();
1472 }
1473 }
1474 // [fs.path.generic]p6.8: If the path is empty, add a dot.
1475 if (Parts.empty())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001476 return ".";
Eric Fiselier91a182b2018-04-02 23:03:41 +00001477
1478 // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any
1479 // trailing directory-separator.
1480 bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename;
1481
1482 path Result;
1483 Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001484 for (auto& PK : Parts)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001485 Result /= PK.first;
1486
1487 if (NeedTrailingSep)
1488 Result /= "";
1489
1490 return Result;
1491}
1492
1493static int DetermineLexicalElementCount(PathParser PP) {
1494 int Count = 0;
1495 for (; PP; ++PP) {
1496 auto Elem = *PP;
1497 if (Elem == "..")
1498 --Count;
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001499 else if (Elem != "." && Elem != "")
Eric Fiselier91a182b2018-04-02 23:03:41 +00001500 ++Count;
1501 }
1502 return Count;
1503}
1504
1505path path::lexically_relative(const path& base) const {
1506 { // perform root-name/root-directory mismatch checks
1507 auto PP = PathParser::CreateBegin(__pn_);
1508 auto PPBase = PathParser::CreateBegin(base.__pn_);
1509 auto CheckIterMismatchAtBase = [&]() {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001510 return PP.State != PPBase.State &&
1511 (PP.inRootPath() || PPBase.inRootPath());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001512 };
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001513 if (PP.inRootName() && PPBase.inRootName()) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001514 if (*PP != *PPBase)
1515 return {};
1516 } else if (CheckIterMismatchAtBase())
1517 return {};
1518
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001519 if (PP.inRootPath())
1520 ++PP;
1521 if (PPBase.inRootPath())
1522 ++PPBase;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001523 if (CheckIterMismatchAtBase())
1524 return {};
1525 }
1526
1527 // Find the first mismatching element
1528 auto PP = PathParser::CreateBegin(__pn_);
1529 auto PPBase = PathParser::CreateBegin(base.__pn_);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001530 while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001531 ++PP;
1532 ++PPBase;
1533 }
1534
1535 // If there is no mismatch, return ".".
1536 if (!PP && !PPBase)
1537 return ".";
1538
1539 // Otherwise, determine the number of elements, 'n', which are not dot or
1540 // dot-dot minus the number of dot-dot elements.
1541 int ElemCount = DetermineLexicalElementCount(PPBase);
1542 if (ElemCount < 0)
1543 return {};
1544
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001545 // if n == 0 and (a == end() || a->empty()), returns path("."); otherwise
1546 if (ElemCount == 0 && (PP.atEnd() || *PP == ""))
1547 return ".";
1548
Eric Fiselier91a182b2018-04-02 23:03:41 +00001549 // return a path constructed with 'n' dot-dot elements, followed by the the
1550 // elements of '*this' after the mismatch.
1551 path Result;
1552 // FIXME: Reserve enough room in Result that it won't have to re-allocate.
1553 while (ElemCount--)
1554 Result /= "..";
1555 for (; PP; ++PP)
1556 Result /= *PP;
1557 return Result;
1558}
1559
1560////////////////////////////////////////////////////////////////////////////
1561// path.comparisons
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001562static int CompareRootName(PathParser *LHS, PathParser *RHS) {
1563 if (!LHS->inRootName() && !RHS->inRootName())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001564 return 0;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001565
1566 auto GetRootName = [](PathParser *Parser) -> string_view_t {
1567 return Parser->inRootName() ? **Parser : "";
1568 };
1569 int res = GetRootName(LHS).compare(GetRootName(RHS));
1570 ConsumeRootName(LHS);
1571 ConsumeRootName(RHS);
1572 return res;
1573}
1574
1575static int CompareRootDir(PathParser *LHS, PathParser *RHS) {
1576 if (!LHS->inRootDir() && RHS->inRootDir())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001577 return -1;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001578 else if (LHS->inRootDir() && !RHS->inRootDir())
1579 return 1;
1580 else {
1581 ConsumeRootDir(LHS);
1582 ConsumeRootDir(RHS);
1583 return 0;
1584 }
1585}
1586
1587static int CompareRelative(PathParser *LHSPtr, PathParser *RHSPtr) {
1588 auto &LHS = *LHSPtr;
1589 auto &RHS = *RHSPtr;
Stephan T. Lavavejfb39ad72019-10-23 11:45:36 -07001590
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001591 int res;
1592 while (LHS && RHS) {
1593 if ((res = (*LHS).compare(*RHS)) != 0)
1594 return res;
1595 ++LHS;
1596 ++RHS;
1597 }
1598 return 0;
1599}
1600
1601static int CompareEndState(PathParser *LHS, PathParser *RHS) {
1602 if (LHS->atEnd() && !RHS->atEnd())
1603 return -1;
1604 else if (!LHS->atEnd() && RHS->atEnd())
1605 return 1;
1606 return 0;
1607}
1608
1609int path::__compare(string_view_t __s) const {
1610 auto LHS = PathParser::CreateBegin(__pn_);
1611 auto RHS = PathParser::CreateBegin(__s);
1612 int res;
1613
1614 if ((res = CompareRootName(&LHS, &RHS)) != 0)
1615 return res;
1616
1617 if ((res = CompareRootDir(&LHS, &RHS)) != 0)
1618 return res;
1619
1620 if ((res = CompareRelative(&LHS, &RHS)) != 0)
1621 return res;
1622
1623 return CompareEndState(&LHS, &RHS);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001624}
1625
1626////////////////////////////////////////////////////////////////////////////
1627// path.nonmembers
1628size_t hash_value(const path& __p) noexcept {
1629 auto PP = PathParser::CreateBegin(__p.native());
1630 size_t hash_value = 0;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001631 hash<string_view_t> hasher;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001632 while (PP) {
1633 hash_value = __hash_combine(hash_value, hasher(*PP));
1634 ++PP;
1635 }
1636 return hash_value;
1637}
1638
1639////////////////////////////////////////////////////////////////////////////
1640// path.itr
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001641path::iterator path::begin() const {
1642 auto PP = PathParser::CreateBegin(__pn_);
1643 iterator it;
1644 it.__path_ptr_ = this;
1645 it.__state_ = static_cast<path::iterator::_ParserState>(PP.State);
1646 it.__entry_ = PP.RawEntry;
1647 it.__stashed_elem_.__assign_view(*PP);
1648 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001649}
1650
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001651path::iterator path::end() const {
1652 iterator it{};
1653 it.__state_ = path::iterator::_AtEnd;
1654 it.__path_ptr_ = this;
1655 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001656}
1657
1658path::iterator& path::iterator::__increment() {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001659 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1660 ++PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001661 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001662 __entry_ = PP.RawEntry;
1663 __stashed_elem_.__assign_view(*PP);
1664 return *this;
1665}
1666
1667path::iterator& path::iterator::__decrement() {
1668 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1669 --PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001670 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001671 __entry_ = PP.RawEntry;
1672 __stashed_elem_.__assign_view(*PP);
1673 return *this;
1674}
1675
Eric Fiselier70474082018-07-20 01:22:32 +00001676///////////////////////////////////////////////////////////////////////////////
1677// directory entry definitions
1678///////////////////////////////////////////////////////////////////////////////
1679
1680#ifndef _LIBCPP_WIN32API
1681error_code directory_entry::__do_refresh() noexcept {
1682 __data_.__reset();
1683 error_code failure_ec;
1684
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001685 StatT full_st;
Eric Fiselier70474082018-07-20 01:22:32 +00001686 file_status st = detail::posix_lstat(__p_, full_st, &failure_ec);
1687 if (!status_known(st)) {
1688 __data_.__reset();
1689 return failure_ec;
1690 }
1691
1692 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1693 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1694 __data_.__type_ = st.type();
1695 __data_.__non_sym_perms_ = st.permissions();
1696 } else { // we have a symlink
1697 __data_.__sym_perms_ = st.permissions();
1698 // Get the information about the linked entity.
1699 // Ignore errors from stat, since we don't want errors regarding symlink
1700 // resolution to be reported to the user.
1701 error_code ignored_ec;
1702 st = detail::posix_stat(__p_, full_st, &ignored_ec);
1703
1704 __data_.__type_ = st.type();
1705 __data_.__non_sym_perms_ = st.permissions();
1706
1707 // If we failed to resolve the link, then only partially populate the
1708 // cache.
1709 if (!status_known(st)) {
1710 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1711 return error_code{};
1712 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001713 // Otherwise, we resolved the link, potentially as not existing.
Eric Fiseliere39cea92018-07-20 08:36:45 +00001714 // That's OK.
Eric Fiselier70474082018-07-20 01:22:32 +00001715 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1716 }
1717
1718 if (_VSTD_FS::is_regular_file(st))
1719 __data_.__size_ = static_cast<uintmax_t>(full_st.st_size);
1720
1721 if (_VSTD_FS::exists(st)) {
1722 __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink);
1723
1724 // Attempt to extract the mtime, and fail if it's not representable using
1725 // file_time_type. For now we ignore the error, as we'll report it when
1726 // the value is actually used.
1727 error_code ignored_ec;
1728 __data_.__write_time_ =
1729 __extract_last_write_time(__p_, full_st, &ignored_ec);
1730 }
1731
1732 return failure_ec;
1733}
1734#else
1735error_code directory_entry::__do_refresh() noexcept {
1736 __data_.__reset();
1737 error_code failure_ec;
1738
1739 file_status st = _VSTD_FS::symlink_status(__p_, failure_ec);
1740 if (!status_known(st)) {
1741 __data_.__reset();
1742 return failure_ec;
1743 }
1744
1745 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1746 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1747 __data_.__type_ = st.type();
1748 __data_.__non_sym_perms_ = st.permissions();
1749 } else { // we have a symlink
1750 __data_.__sym_perms_ = st.permissions();
1751 // Get the information about the linked entity.
1752 // Ignore errors from stat, since we don't want errors regarding symlink
1753 // resolution to be reported to the user.
1754 error_code ignored_ec;
1755 st = _VSTD_FS::status(__p_, ignored_ec);
1756
1757 __data_.__type_ = st.type();
1758 __data_.__non_sym_perms_ = st.permissions();
1759
1760 // If we failed to resolve the link, then only partially populate the
1761 // cache.
1762 if (!status_known(st)) {
1763 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1764 return error_code{};
1765 }
Eric Fiselier70474082018-07-20 01:22:32 +00001766 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1767 }
1768
1769 // FIXME: This is currently broken, and the implementation only a placeholder.
1770 // We need to cache last_write_time, file_size, and hard_link_count here before
1771 // the implementation actually works.
1772
1773 return failure_ec;
1774}
1775#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001776
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001777_LIBCPP_END_NAMESPACE_FILESYSTEM