blob: 12592f2cc02640202543cf2b6db40ae81f5889c3 [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"
Eric Fiselier91a182b2018-04-02 23:03:41 +000012#include "string_view"
13#include "type_traits"
14#include "vector"
Eric Fiselier435db152016-06-17 19:46:40 +000015#include "cstdlib"
16#include "climits"
17
Eric Fiselier70474082018-07-20 01:22:32 +000018#include "filesystem_common.h"
Eric Fiselier42d6d2c2017-07-08 04:18:41 +000019
Eric Fiselier435db152016-06-17 19:46:40 +000020#include <unistd.h>
21#include <sys/stat.h>
22#include <sys/statvfs.h>
Eric Fiselier7eba47e2018-07-25 20:51:49 +000023#include <time.h>
Eric Fiselier02cea5e2018-07-27 03:07:09 +000024#include <fcntl.h> /* values for fchmodat */
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000025
Louis Dionne27bf9862020-10-15 13:14:22 -040026#if __has_include(<sys/sendfile.h>)
27# include <sys/sendfile.h>
28# define _LIBCPP_FILESYSTEM_USE_SENDFILE
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000029#elif defined(__APPLE__) || __has_include(<copyfile.h>)
Louis Dionne27bf9862020-10-15 13:14:22 -040030# include <copyfile.h>
31# define _LIBCPP_FILESYSTEM_USE_COPYFILE
32#else
33# include "fstream"
34# define _LIBCPP_FILESYSTEM_USE_FSTREAM
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000035#endif
Nico Weber4f1d63a2018-02-06 19:17:41 +000036
Louis Dionne678dc852020-02-12 17:01:19 +010037#if !defined(CLOCK_REALTIME)
Louis Dionne27bf9862020-10-15 13:14:22 -040038# include <sys/time.h> // for gettimeofday and timeval
39#endif
Eric Fiselier7eba47e2018-07-25 20:51:49 +000040
Michał Górny8d676fb2019-12-02 11:49:20 +010041#if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB)
Louis Dionne27bf9862020-10-15 13:14:22 -040042# pragma comment(lib, "rt")
Eric Fiselierd8b25e32018-07-23 03:06:57 +000043#endif
44
Eric Fiselier02cea5e2018-07-27 03:07:09 +000045_LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
Eric Fiselier435db152016-06-17 19:46:40 +000046
Eric Fiselier02cea5e2018-07-27 03:07:09 +000047namespace {
48namespace parser {
Eric Fiselier91a182b2018-04-02 23:03:41 +000049
50using string_view_t = path::__string_view;
51using string_view_pair = pair<string_view_t, string_view_t>;
52using PosPtr = path::value_type const*;
53
54struct PathParser {
55 enum ParserState : unsigned char {
56 // Zero is a special sentinel value used by default constructed iterators.
Eric Fiselier23a120c2018-07-25 03:31:48 +000057 PS_BeforeBegin = path::iterator::_BeforeBegin,
58 PS_InRootName = path::iterator::_InRootName,
59 PS_InRootDir = path::iterator::_InRootDir,
60 PS_InFilenames = path::iterator::_InFilenames,
61 PS_InTrailingSep = path::iterator::_InTrailingSep,
62 PS_AtEnd = path::iterator::_AtEnd
Eric Fiselier91a182b2018-04-02 23:03:41 +000063 };
64
65 const string_view_t Path;
66 string_view_t RawEntry;
67 ParserState State;
68
69private:
Eric Fiselier02cea5e2018-07-27 03:07:09 +000070 PathParser(string_view_t P, ParserState State) noexcept : Path(P),
71 State(State) {}
Eric Fiselier91a182b2018-04-02 23:03:41 +000072
73public:
74 PathParser(string_view_t P, string_view_t E, unsigned char S)
75 : Path(P), RawEntry(E), State(static_cast<ParserState>(S)) {
76 // S cannot be '0' or PS_BeforeBegin.
77 }
78
79 static PathParser CreateBegin(string_view_t P) noexcept {
80 PathParser PP(P, PS_BeforeBegin);
81 PP.increment();
82 return PP;
83 }
84
85 static PathParser CreateEnd(string_view_t P) noexcept {
86 PathParser PP(P, PS_AtEnd);
87 return PP;
88 }
89
90 PosPtr peek() const noexcept {
91 auto TkEnd = getNextTokenStartPos();
92 auto End = getAfterBack();
93 return TkEnd == End ? nullptr : TkEnd;
94 }
95
96 void increment() noexcept {
97 const PosPtr End = getAfterBack();
98 const PosPtr Start = getNextTokenStartPos();
99 if (Start == End)
100 return makeState(PS_AtEnd);
101
102 switch (State) {
103 case PS_BeforeBegin: {
104 PosPtr TkEnd = consumeSeparator(Start, End);
105 if (TkEnd)
106 return makeState(PS_InRootDir, Start, TkEnd);
107 else
108 return makeState(PS_InFilenames, Start, consumeName(Start, End));
109 }
110 case PS_InRootDir:
111 return makeState(PS_InFilenames, Start, consumeName(Start, End));
112
113 case PS_InFilenames: {
114 PosPtr SepEnd = consumeSeparator(Start, End);
115 if (SepEnd != End) {
116 PosPtr TkEnd = consumeName(SepEnd, End);
117 if (TkEnd)
118 return makeState(PS_InFilenames, SepEnd, TkEnd);
119 }
120 return makeState(PS_InTrailingSep, Start, SepEnd);
121 }
122
123 case PS_InTrailingSep:
124 return makeState(PS_AtEnd);
125
126 case PS_InRootName:
127 case PS_AtEnd:
128 _LIBCPP_UNREACHABLE();
129 }
130 }
131
132 void decrement() noexcept {
133 const PosPtr REnd = getBeforeFront();
134 const PosPtr RStart = getCurrentTokenStartPos() - 1;
135 if (RStart == REnd) // we're decrementing the begin
136 return makeState(PS_BeforeBegin);
137
138 switch (State) {
139 case PS_AtEnd: {
140 // Try to consume a trailing separator or root directory first.
141 if (PosPtr SepEnd = consumeSeparator(RStart, REnd)) {
142 if (SepEnd == REnd)
143 return makeState(PS_InRootDir, Path.data(), RStart + 1);
144 return makeState(PS_InTrailingSep, SepEnd + 1, RStart + 1);
145 } else {
146 PosPtr TkStart = consumeName(RStart, REnd);
147 return makeState(PS_InFilenames, TkStart + 1, RStart + 1);
148 }
149 }
150 case PS_InTrailingSep:
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000151 return makeState(PS_InFilenames, consumeName(RStart, REnd) + 1,
152 RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000153 case PS_InFilenames: {
154 PosPtr SepEnd = consumeSeparator(RStart, REnd);
155 if (SepEnd == REnd)
156 return makeState(PS_InRootDir, Path.data(), RStart + 1);
157 PosPtr TkEnd = consumeName(SepEnd, REnd);
158 return makeState(PS_InFilenames, TkEnd + 1, SepEnd + 1);
159 }
160 case PS_InRootDir:
161 // return makeState(PS_InRootName, Path.data(), RStart + 1);
162 case PS_InRootName:
163 case PS_BeforeBegin:
164 _LIBCPP_UNREACHABLE();
165 }
166 }
167
168 /// \brief Return a view with the "preferred representation" of the current
169 /// element. For example trailing separators are represented as a '.'
170 string_view_t operator*() const noexcept {
171 switch (State) {
172 case PS_BeforeBegin:
173 case PS_AtEnd:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200174 return PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000175 case PS_InRootDir:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200176 if (RawEntry[0] == '\\')
177 return PS("\\");
178 else
179 return PS("/");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000180 case PS_InTrailingSep:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200181 return PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000182 case PS_InRootName:
183 case PS_InFilenames:
184 return RawEntry;
185 }
186 _LIBCPP_UNREACHABLE();
187 }
188
189 explicit operator bool() const noexcept {
190 return State != PS_BeforeBegin && State != PS_AtEnd;
191 }
192
193 PathParser& operator++() noexcept {
194 increment();
195 return *this;
196 }
197
198 PathParser& operator--() noexcept {
199 decrement();
200 return *this;
201 }
202
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000203 bool atEnd() const noexcept {
204 return State == PS_AtEnd;
205 }
206
207 bool inRootDir() const noexcept {
208 return State == PS_InRootDir;
209 }
210
211 bool inRootName() const noexcept {
212 return State == PS_InRootName;
213 }
214
Eric Fiselier91a182b2018-04-02 23:03:41 +0000215 bool inRootPath() const noexcept {
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000216 return inRootName() || inRootDir();
Eric Fiselier91a182b2018-04-02 23:03:41 +0000217 }
218
219private:
220 void makeState(ParserState NewState, PosPtr Start, PosPtr End) noexcept {
221 State = NewState;
222 RawEntry = string_view_t(Start, End - Start);
223 }
224 void makeState(ParserState NewState) noexcept {
225 State = NewState;
226 RawEntry = {};
227 }
228
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000229 PosPtr getAfterBack() const noexcept { return Path.data() + Path.size(); }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000230
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000231 PosPtr getBeforeFront() const noexcept { return Path.data() - 1; }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000232
233 /// \brief Return a pointer to the first character after the currently
234 /// lexed element.
235 PosPtr getNextTokenStartPos() const noexcept {
236 switch (State) {
237 case PS_BeforeBegin:
238 return Path.data();
239 case PS_InRootName:
240 case PS_InRootDir:
241 case PS_InFilenames:
242 return &RawEntry.back() + 1;
243 case PS_InTrailingSep:
244 case PS_AtEnd:
245 return getAfterBack();
246 }
247 _LIBCPP_UNREACHABLE();
248 }
249
250 /// \brief Return a pointer to the first character in the currently lexed
251 /// element.
252 PosPtr getCurrentTokenStartPos() const noexcept {
253 switch (State) {
254 case PS_BeforeBegin:
255 case PS_InRootName:
256 return &Path.front();
257 case PS_InRootDir:
258 case PS_InFilenames:
259 case PS_InTrailingSep:
260 return &RawEntry.front();
261 case PS_AtEnd:
262 return &Path.back() + 1;
263 }
264 _LIBCPP_UNREACHABLE();
265 }
266
267 PosPtr consumeSeparator(PosPtr P, PosPtr End) const noexcept {
268 if (P == End || *P != '/')
269 return nullptr;
270 const int Inc = P < End ? 1 : -1;
271 P += Inc;
272 while (P != End && *P == '/')
273 P += Inc;
274 return P;
275 }
276
277 PosPtr consumeName(PosPtr P, PosPtr End) const noexcept {
278 if (P == End || *P == '/')
279 return nullptr;
280 const int Inc = P < End ? 1 : -1;
281 P += Inc;
282 while (P != End && *P != '/')
283 P += Inc;
284 return P;
285 }
286};
287
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000288string_view_pair separate_filename(string_view_t const& s) {
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200289 if (s == PS(".") || s == PS("..") || s.empty())
290 return string_view_pair{s, PS("")};
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000291 auto pos = s.find_last_of('.');
292 if (pos == string_view_t::npos || pos == 0)
293 return string_view_pair{s, string_view_t{}};
294 return string_view_pair{s.substr(0, pos), s.substr(pos)};
Eric Fiselier91a182b2018-04-02 23:03:41 +0000295}
296
297string_view_t createView(PosPtr S, PosPtr E) noexcept {
298 return {S, static_cast<size_t>(E - S) + 1};
299}
300
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000301} // namespace parser
302} // namespace
Eric Fiselier91a182b2018-04-02 23:03:41 +0000303
Eric Fiselier435db152016-06-17 19:46:40 +0000304// POSIX HELPERS
305
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000306namespace detail {
307namespace {
Eric Fiselier435db152016-06-17 19:46:40 +0000308
309using value_type = path::value_type;
310using string_type = path::string_type;
311
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000312struct FileDescriptor {
313 const path& name;
314 int fd = -1;
315 StatT m_stat;
316 file_status m_status;
317
318 template <class... Args>
319 static FileDescriptor create(const path* p, error_code& ec, Args... args) {
320 ec.clear();
321 int fd;
322 if ((fd = ::open(p->c_str(), args...)) == -1) {
323 ec = capture_errno();
324 return FileDescriptor{p};
325 }
326 return FileDescriptor(p, fd);
327 }
328
329 template <class... Args>
330 static FileDescriptor create_with_status(const path* p, error_code& ec,
331 Args... args) {
332 FileDescriptor fd = create(p, ec, args...);
333 if (!ec)
334 fd.refresh_status(ec);
335
336 return fd;
337 }
338
339 file_status get_status() const { return m_status; }
340 StatT const& get_stat() const { return m_stat; }
341
342 bool status_known() const { return _VSTD_FS::status_known(m_status); }
343
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000344 file_status refresh_status(error_code& ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000345
346 void close() noexcept {
347 if (fd != -1)
348 ::close(fd);
349 fd = -1;
350 }
351
352 FileDescriptor(FileDescriptor&& other)
353 : name(other.name), fd(other.fd), m_stat(other.m_stat),
354 m_status(other.m_status) {
355 other.fd = -1;
356 other.m_status = file_status{};
357 }
358
359 ~FileDescriptor() { close(); }
360
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000361 FileDescriptor(FileDescriptor const&) = delete;
362 FileDescriptor& operator=(FileDescriptor const&) = delete;
363
364private:
365 explicit FileDescriptor(const path* p, int fd = -1) : name(*p), fd(fd) {}
366};
367
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000368perms posix_get_perms(const StatT& st) noexcept {
Eric Fiselier70474082018-07-20 01:22:32 +0000369 return static_cast<perms>(st.st_mode) & perms::mask;
Eric Fiselier435db152016-06-17 19:46:40 +0000370}
371
372::mode_t posix_convert_perms(perms prms) {
Eric Fiselier70474082018-07-20 01:22:32 +0000373 return static_cast< ::mode_t>(prms & perms::mask);
Eric Fiselier435db152016-06-17 19:46:40 +0000374}
375
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000376file_status create_file_status(error_code& m_ec, path const& p,
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000377 const StatT& path_stat, error_code* ec) {
Eric Fiselier70474082018-07-20 01:22:32 +0000378 if (ec)
379 *ec = m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000380 if (m_ec && (m_ec.value() == ENOENT || m_ec.value() == ENOTDIR)) {
381 return file_status(file_type::not_found);
382 } else if (m_ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000383 ErrorHandler<void> err("posix_stat", ec, &p);
384 err.report(m_ec, "failed to determine attributes for the specified path");
Eric Fiselier70474082018-07-20 01:22:32 +0000385 return file_status(file_type::none);
386 }
387 // else
Eric Fiselier435db152016-06-17 19:46:40 +0000388
Eric Fiselier70474082018-07-20 01:22:32 +0000389 file_status fs_tmp;
390 auto const mode = path_stat.st_mode;
391 if (S_ISLNK(mode))
392 fs_tmp.type(file_type::symlink);
393 else if (S_ISREG(mode))
394 fs_tmp.type(file_type::regular);
395 else if (S_ISDIR(mode))
396 fs_tmp.type(file_type::directory);
397 else if (S_ISBLK(mode))
398 fs_tmp.type(file_type::block);
399 else if (S_ISCHR(mode))
400 fs_tmp.type(file_type::character);
401 else if (S_ISFIFO(mode))
402 fs_tmp.type(file_type::fifo);
403 else if (S_ISSOCK(mode))
404 fs_tmp.type(file_type::socket);
405 else
406 fs_tmp.type(file_type::unknown);
Eric Fiselier435db152016-06-17 19:46:40 +0000407
Eric Fiselier70474082018-07-20 01:22:32 +0000408 fs_tmp.permissions(detail::posix_get_perms(path_stat));
409 return fs_tmp;
Eric Fiselier435db152016-06-17 19:46:40 +0000410}
411
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000412file_status posix_stat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000413 error_code m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000414 if (::stat(p.c_str(), &path_stat) == -1)
415 m_ec = detail::capture_errno();
416 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000417}
418
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000419file_status posix_stat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000420 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000421 return posix_stat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000422}
423
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000424file_status posix_lstat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000425 error_code m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000426 if (::lstat(p.c_str(), &path_stat) == -1)
427 m_ec = detail::capture_errno();
428 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000429}
430
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000431file_status posix_lstat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000432 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000433 return posix_lstat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000434}
435
Dan Albert39b981d2019-01-15 19:16:25 +0000436// http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
437bool posix_ftruncate(const FileDescriptor& fd, off_t to_size, error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000438 if (::ftruncate(fd.fd, to_size) == -1) {
439 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000440 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000441 }
442 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000443 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000444}
445
446bool posix_fchmod(const FileDescriptor& fd, const StatT& st, error_code& ec) {
447 if (::fchmod(fd.fd, st.st_mode) == -1) {
448 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000449 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000450 }
451 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000452 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000453}
454
455bool stat_equivalent(const StatT& st1, const StatT& st2) {
Eric Fiselier70474082018-07-20 01:22:32 +0000456 return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
Eric Fiselier435db152016-06-17 19:46:40 +0000457}
458
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000459file_status FileDescriptor::refresh_status(error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000460 // FD must be open and good.
461 m_status = file_status{};
Eric Fiselierd8b25e32018-07-23 03:06:57 +0000462 m_stat = {};
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000463 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000464 if (::fstat(fd, &m_stat) == -1)
465 m_ec = capture_errno();
466 m_status = create_file_status(m_ec, name, m_stat, &ec);
467 return m_status;
Eric Fiselier435db152016-06-17 19:46:40 +0000468}
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000469} // namespace
470} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000471
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000472using detail::capture_errno;
473using detail::ErrorHandler;
474using detail::StatT;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000475using detail::TimeSpec;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000476using parser::createView;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000477using parser::PathParser;
478using parser::string_view_t;
479
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000480const bool _FilesystemClock::is_steady;
481
482_FilesystemClock::time_point _FilesystemClock::now() noexcept {
483 typedef chrono::duration<rep> __secs;
Louis Dionne678dc852020-02-12 17:01:19 +0100484#if defined(CLOCK_REALTIME)
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000485 typedef chrono::duration<rep, nano> __nsecs;
486 struct timespec tp;
487 if (0 != clock_gettime(CLOCK_REALTIME, &tp))
488 __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
489 return time_point(__secs(tp.tv_sec) +
490 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
491#else
492 typedef chrono::duration<rep, micro> __microsecs;
493 timeval tv;
494 gettimeofday(&tv, 0);
495 return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
Louis Dionne678dc852020-02-12 17:01:19 +0100496#endif // CLOCK_REALTIME
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000497}
498
499filesystem_error::~filesystem_error() {}
500
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200501#if defined(_LIBCPP_WIN32API)
502#define PS_FMT "%ls"
503#else
504#define PS_FMT "%s"
505#endif
506
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000507void filesystem_error::__create_what(int __num_paths) {
508 const char* derived_what = system_error::what();
509 __storage_->__what_ = [&]() -> string {
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200510 const path::value_type* p1 = path1().native().empty() ? PS("\"\"") : path1().c_str();
511 const path::value_type* p2 = path2().native().empty() ? PS("\"\"") : path2().c_str();
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000512 switch (__num_paths) {
513 default:
514 return detail::format_string("filesystem error: %s", derived_what);
515 case 1:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200516 return detail::format_string("filesystem error: %s [" PS_FMT "]", derived_what,
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000517 p1);
518 case 2:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200519 return detail::format_string("filesystem error: %s [" PS_FMT "] [" PS_FMT "]",
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000520 derived_what, p1, p2);
521 }
522 }();
523}
Eric Fiselier435db152016-06-17 19:46:40 +0000524
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000525static path __do_absolute(const path& p, path* cwd, error_code* ec) {
526 if (ec)
527 ec->clear();
528 if (p.is_absolute())
529 return p;
530 *cwd = __current_path(ec);
531 if (ec && *ec)
532 return {};
533 return (*cwd) / p;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000534}
535
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000536path __absolute(const path& p, error_code* ec) {
537 path cwd;
538 return __do_absolute(p, &cwd, ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000539}
540
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000541path __canonical(path const& orig_p, error_code* ec) {
542 path cwd;
543 ErrorHandler<path> err("canonical", ec, &orig_p, &cwd);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000544
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000545 path p = __do_absolute(orig_p, &cwd, ec);
YAMAMOTO Takashi43f19082020-10-28 15:40:16 -0400546#if defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112
Eric Fiselierb5215302019-01-17 02:59:28 +0000547 std::unique_ptr<char, decltype(&::free)>
548 hold(::realpath(p.c_str(), nullptr), &::free);
549 if (hold.get() == nullptr)
550 return err.report(capture_errno());
551 return {hold.get()};
552#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000553 char buff[PATH_MAX + 1];
554 char* ret;
555 if ((ret = ::realpath(p.c_str(), buff)) == nullptr)
556 return err.report(capture_errno());
557 return {ret};
Eric Fiselierb5215302019-01-17 02:59:28 +0000558#endif
Eric Fiselier435db152016-06-17 19:46:40 +0000559}
560
561void __copy(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000562 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000563 ErrorHandler<void> err("copy", ec, &from, &to);
Eric Fiselier435db152016-06-17 19:46:40 +0000564
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000565 const bool sym_status = bool(
566 options & (copy_options::create_symlinks | copy_options::skip_symlinks));
Eric Fiselier435db152016-06-17 19:46:40 +0000567
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000568 const bool sym_status2 = bool(options & copy_options::copy_symlinks);
Eric Fiselier435db152016-06-17 19:46:40 +0000569
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000570 error_code m_ec1;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000571 StatT f_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000572 const file_status f = sym_status || sym_status2
573 ? detail::posix_lstat(from, f_st, &m_ec1)
574 : detail::posix_stat(from, f_st, &m_ec1);
575 if (m_ec1)
576 return err.report(m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000577
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000578 StatT t_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000579 const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1)
580 : detail::posix_stat(to, t_st, &m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000581
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000582 if (not status_known(t))
583 return err.report(m_ec1);
584
585 if (!exists(f) || is_other(f) || is_other(t) ||
586 (is_directory(f) && is_regular_file(t)) ||
587 detail::stat_equivalent(f_st, t_st)) {
588 return err.report(errc::function_not_supported);
589 }
Eric Fiselier435db152016-06-17 19:46:40 +0000590
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000591 if (ec)
592 ec->clear();
Eric Fiselier435db152016-06-17 19:46:40 +0000593
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000594 if (is_symlink(f)) {
595 if (bool(copy_options::skip_symlinks & options)) {
596 // do nothing
597 } else if (not exists(t)) {
598 __copy_symlink(from, to, ec);
599 } else {
600 return err.report(errc::file_exists);
Eric Fiselier435db152016-06-17 19:46:40 +0000601 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000602 return;
603 } else if (is_regular_file(f)) {
604 if (bool(copy_options::directories_only & options)) {
605 // do nothing
606 } else if (bool(copy_options::create_symlinks & options)) {
607 __create_symlink(from, to, ec);
608 } else if (bool(copy_options::create_hard_links & options)) {
609 __create_hard_link(from, to, ec);
610 } else if (is_directory(t)) {
611 __copy_file(from, to / from.filename(), options, ec);
612 } else {
613 __copy_file(from, to, options, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000614 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000615 return;
616 } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
617 return err.report(errc::is_a_directory);
618 } else if (is_directory(f) && (bool(copy_options::recursive & options) ||
619 copy_options::none == options)) {
Eric Fiselier435db152016-06-17 19:46:40 +0000620
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000621 if (!exists(t)) {
622 // create directory to with attributes from 'from'.
623 __create_directory(to, from, ec);
624 if (ec && *ec) {
625 return;
626 }
Eric Fiselier435db152016-06-17 19:46:40 +0000627 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000628 directory_iterator it =
629 ec ? directory_iterator(from, *ec) : directory_iterator(from);
630 if (ec && *ec) {
631 return;
632 }
633 error_code m_ec2;
634 for (; it != directory_iterator(); it.increment(m_ec2)) {
635 if (m_ec2) {
636 return err.report(m_ec2);
637 }
638 __copy(it->path(), to / it->path().filename(),
639 options | copy_options::__in_recursive_copy, ec);
640 if (ec && *ec) {
641 return;
642 }
643 }
644 }
Eric Fiselier435db152016-06-17 19:46:40 +0000645}
646
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000647namespace detail {
648namespace {
649
Louis Dionne27bf9862020-10-15 13:14:22 -0400650#if defined(_LIBCPP_FILESYSTEM_USE_SENDFILE)
651 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
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);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000661
Louis Dionne27bf9862020-10-15 13:14:22 -0400662 ec.clear();
663
664 return true;
665 }
666#elif defined(_LIBCPP_FILESYSTEM_USE_COPYFILE)
667 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
668 struct CopyFileState {
669 copyfile_state_t state;
670 CopyFileState() { state = copyfile_state_alloc(); }
671 ~CopyFileState() { copyfile_state_free(state); }
672
673 private:
674 CopyFileState(CopyFileState const&) = delete;
675 CopyFileState& operator=(CopyFileState const&) = delete;
676 };
677
678 CopyFileState cfs;
679 if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000680 ec = capture_errno();
681 return false;
682 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000683
Louis Dionne27bf9862020-10-15 13:14:22 -0400684 ec.clear();
685 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000686 }
Louis Dionne27bf9862020-10-15 13:14:22 -0400687#elif defined(_LIBCPP_FILESYSTEM_USE_FSTREAM)
688 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
689 ifstream in;
690 in.__open(read_fd.fd, ios::binary);
691 if (!in.is_open()) {
692 // This assumes that __open didn't reset the error code.
693 ec = capture_errno();
694 return false;
695 }
Martin Storsjö64104352020-11-02 10:19:42 +0200696 read_fd.fd = -1;
Louis Dionne27bf9862020-10-15 13:14:22 -0400697 ofstream out;
698 out.__open(write_fd.fd, ios::binary);
699 if (!out.is_open()) {
700 ec = capture_errno();
701 return false;
702 }
Martin Storsjö64104352020-11-02 10:19:42 +0200703 write_fd.fd = -1;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000704
Louis Dionne27bf9862020-10-15 13:14:22 -0400705 if (in.good() && out.good()) {
706 using InIt = istreambuf_iterator<char>;
707 using OutIt = ostreambuf_iterator<char>;
708 InIt bin(in);
709 InIt ein;
710 OutIt bout(out);
711 copy(bin, ein, bout);
712 }
713 if (out.fail() || in.fail()) {
714 ec = make_error_code(errc::io_error);
715 return false;
716 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000717
Louis Dionne27bf9862020-10-15 13:14:22 -0400718 ec.clear();
719 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000720 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000721#else
Louis Dionne27bf9862020-10-15 13:14:22 -0400722# error "Unknown implementation for copy_file_impl"
723#endif // copy_file_impl implementation
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000724
Louis Dionne27bf9862020-10-15 13:14:22 -0400725} // end anonymous namespace
726} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000727
728bool __copy_file(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000729 error_code* ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000730 using detail::FileDescriptor;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000731 ErrorHandler<bool> err("copy_file", ec, &to, &from);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000732
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000733 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000734 FileDescriptor from_fd =
735 FileDescriptor::create_with_status(&from, m_ec, O_RDONLY | O_NONBLOCK);
736 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000737 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000738
739 auto from_st = from_fd.get_status();
740 StatT const& from_stat = from_fd.get_stat();
741 if (!is_regular_file(from_st)) {
742 if (not m_ec)
743 m_ec = make_error_code(errc::not_supported);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000744 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000745 }
746
747 const bool skip_existing = bool(copy_options::skip_existing & options);
748 const bool update_existing = bool(copy_options::update_existing & options);
749 const bool overwrite_existing =
750 bool(copy_options::overwrite_existing & options);
751
752 StatT to_stat_path;
753 file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);
754 if (!status_known(to_st))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000755 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000756
757 const bool to_exists = exists(to_st);
758 if (to_exists && !is_regular_file(to_st))
Eric Fiselier268fa832018-07-23 11:55:13 +0000759 return err.report(errc::not_supported);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000760
761 if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))
Eric Fiselier268fa832018-07-23 11:55:13 +0000762 return err.report(errc::file_exists);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000763
764 if (to_exists && skip_existing)
765 return false;
766
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000767 bool ShouldCopy = [&]() {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000768 if (to_exists && update_existing) {
769 auto from_time = detail::extract_mtime(from_stat);
770 auto to_time = detail::extract_mtime(to_stat_path);
771 if (from_time.tv_sec < to_time.tv_sec)
Eric Fiselier435db152016-06-17 19:46:40 +0000772 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000773 if (from_time.tv_sec == to_time.tv_sec &&
774 from_time.tv_nsec <= to_time.tv_nsec)
Eric Fiseliere7359252016-10-16 00:47:59 +0000775 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000776 return true;
Eric Fiseliere7359252016-10-16 00:47:59 +0000777 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000778 if (!to_exists || overwrite_existing)
779 return true;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000780 return err.report(errc::file_exists);
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000781 }();
782 if (!ShouldCopy)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000783 return false;
Eric Fiseliere7359252016-10-16 00:47:59 +0000784
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000785 // Don't truncate right away. We may not be opening the file we originally
786 // looked at; we'll check this later.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000787 int to_open_flags = O_WRONLY;
788 if (!to_exists)
789 to_open_flags |= O_CREAT;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000790 FileDescriptor to_fd = FileDescriptor::create_with_status(
791 &to, m_ec, to_open_flags, from_stat.st_mode);
792 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000793 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000794
795 if (to_exists) {
796 // Check that the file we initially stat'ed is equivalent to the one
797 // we opened.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000798 // FIXME: report this better.
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000799 if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000800 return err.report(errc::bad_file_descriptor);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000801
802 // Set the permissions and truncate the file we opened.
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000803 if (detail::posix_fchmod(to_fd, from_stat, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000804 return err.report(m_ec);
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000805 if (detail::posix_ftruncate(to_fd, 0, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000806 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000807 }
808
809 if (!copy_file_impl(from_fd, to_fd, m_ec)) {
810 // FIXME: Remove the dest file if we failed, and it didn't exist previously.
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000811 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000812 }
813
814 return true;
Eric Fiselier435db152016-06-17 19:46:40 +0000815}
816
817void __copy_symlink(const path& existing_symlink, const path& new_symlink,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000818 error_code* ec) {
819 const path real_path(__read_symlink(existing_symlink, ec));
820 if (ec && *ec) {
821 return;
822 }
823 // NOTE: proposal says you should detect if you should call
824 // create_symlink or create_directory_symlink. I don't think this
825 // is needed with POSIX
826 __create_symlink(real_path, new_symlink, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000827}
828
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000829bool __create_directories(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000830 ErrorHandler<bool> err("create_directories", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +0000831
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000832 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000833 auto const st = detail::posix_stat(p, &m_ec);
834 if (!status_known(st))
835 return err.report(m_ec);
836 else if (is_directory(st))
837 return false;
838 else if (exists(st))
839 return err.report(errc::file_exists);
840
841 const path parent = p.parent_path();
842 if (!parent.empty()) {
843 const file_status parent_st = status(parent, m_ec);
844 if (not status_known(parent_st))
845 return err.report(m_ec);
846 if (not exists(parent_st)) {
847 __create_directories(parent, ec);
848 if (ec && *ec) {
849 return false;
850 }
Eric Fiselier435db152016-06-17 19:46:40 +0000851 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000852 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000853 return __create_directory(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000854}
855
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000856bool __create_directory(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000857 ErrorHandler<bool> err("create_directory", ec, &p);
858
859 if (::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
860 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +0100861
862 if (errno == EEXIST) {
863 error_code mec = capture_errno();
864 error_code ignored_ec;
865 const file_status st = status(p, ignored_ec);
866 if (!is_directory(st)) {
867 err.report(mec);
868 }
869 } else {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000870 err.report(capture_errno());
Marek Kurdej9c129772020-12-10 08:38:41 +0100871 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000872 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000873}
874
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000875bool __create_directory(path const& p, path const& attributes, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000876 ErrorHandler<bool> err("create_directory", ec, &p, &attributes);
877
878 StatT attr_stat;
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000879 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000880 auto st = detail::posix_stat(attributes, attr_stat, &mec);
881 if (!status_known(st))
882 return err.report(mec);
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000883 if (!is_directory(st))
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000884 return err.report(errc::not_a_directory,
885 "the specified attribute path is invalid");
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000886
887 if (::mkdir(p.c_str(), attr_stat.st_mode) == 0)
888 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +0100889
890 if (errno == EEXIST) {
891 error_code mec = capture_errno();
892 error_code ignored_ec;
893 const file_status st = status(p, ignored_ec);
894 if (!is_directory(st)) {
895 err.report(mec);
896 }
897 } else {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000898 err.report(capture_errno());
Marek Kurdej9c129772020-12-10 08:38:41 +0100899 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000900 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000901}
902
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000903void __create_directory_symlink(path const& from, path const& to,
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000904 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000905 ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
906 if (::symlink(from.c_str(), to.c_str()) != 0)
907 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000908}
909
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000910void __create_hard_link(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000911 ErrorHandler<void> err("create_hard_link", ec, &from, &to);
912 if (::link(from.c_str(), to.c_str()) == -1)
913 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000914}
915
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000916void __create_symlink(path const& from, path const& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000917 ErrorHandler<void> err("create_symlink", ec, &from, &to);
918 if (::symlink(from.c_str(), to.c_str()) == -1)
919 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000920}
921
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000922path __current_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000923 ErrorHandler<path> err("current_path", ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000924
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000925 auto size = ::pathconf(".", _PC_PATH_MAX);
926 _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
927
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000928 auto buff = unique_ptr<char[]>(new char[size + 1]);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000929 char* ret;
930 if ((ret = ::getcwd(buff.get(), static_cast<size_t>(size))) == nullptr)
931 return err.report(capture_errno(), "call to getcwd failed");
932
933 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +0000934}
935
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000936void __current_path(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000937 ErrorHandler<void> err("current_path", ec, &p);
938 if (::chdir(p.c_str()) == -1)
939 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000940}
941
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000942bool __equivalent(const path& p1, const path& p2, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000943 ErrorHandler<bool> err("equivalent", ec, &p1, &p2);
944
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000945 error_code ec1, ec2;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000946 StatT st1 = {}, st2 = {};
947 auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
948 if (!exists(s1))
949 return err.report(errc::not_supported);
950 auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
951 if (!exists(s2))
952 return err.report(errc::not_supported);
953
954 return detail::stat_equivalent(st1, st2);
Eric Fiselier435db152016-06-17 19:46:40 +0000955}
956
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000957uintmax_t __file_size(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000958 ErrorHandler<uintmax_t> err("file_size", ec, &p);
959
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000960 error_code m_ec;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000961 StatT st;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000962 file_status fst = detail::posix_stat(p, st, &m_ec);
963 if (!exists(fst) || !is_regular_file(fst)) {
964 errc error_kind =
965 is_directory(fst) ? errc::is_a_directory : errc::not_supported;
966 if (!m_ec)
967 m_ec = make_error_code(error_kind);
968 return err.report(m_ec);
969 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000970 // is_regular_file(p) == true
971 return static_cast<uintmax_t>(st.st_size);
Eric Fiselier435db152016-06-17 19:46:40 +0000972}
973
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000974uintmax_t __hard_link_count(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000975 ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);
976
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000977 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000978 StatT st;
979 detail::posix_stat(p, st, &m_ec);
980 if (m_ec)
981 return err.report(m_ec);
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000982 return static_cast<uintmax_t>(st.st_nlink);
Eric Fiselier435db152016-06-17 19:46:40 +0000983}
984
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000985bool __fs_is_empty(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000986 ErrorHandler<bool> err("is_empty", ec, &p);
Eric Fiselieraa8c61f2016-10-15 23:05:04 +0000987
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000988 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000989 StatT pst;
990 auto st = detail::posix_stat(p, pst, &m_ec);
991 if (m_ec)
992 return err.report(m_ec);
993 else if (!is_directory(st) && !is_regular_file(st))
994 return err.report(errc::not_supported);
995 else if (is_directory(st)) {
996 auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
997 if (ec && *ec)
998 return false;
999 return it == directory_iterator{};
1000 } else if (is_regular_file(st))
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001001 return static_cast<uintmax_t>(pst.st_size) == 0;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001002
1003 _LIBCPP_UNREACHABLE();
Eric Fiselier435db152016-06-17 19:46:40 +00001004}
1005
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001006static file_time_type __extract_last_write_time(const path& p, const StatT& st,
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001007 error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001008 using detail::fs_time;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001009 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
1010
Eric Fiselier70474082018-07-20 01:22:32 +00001011 auto ts = detail::extract_mtime(st);
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001012 if (!fs_time::is_representable(ts))
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001013 return err.report(errc::value_too_large);
1014
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001015 return fs_time::convert_from_timespec(ts);
Eric Fiselier70474082018-07-20 01:22:32 +00001016}
Eric Fiselier42d6d2c2017-07-08 04:18:41 +00001017
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001018file_time_type __last_write_time(const path& p, error_code* ec) {
1019 using namespace chrono;
1020 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001021
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001022 error_code m_ec;
1023 StatT st;
1024 detail::posix_stat(p, st, &m_ec);
1025 if (m_ec)
1026 return err.report(m_ec);
1027 return __extract_last_write_time(p, st, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001028}
1029
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001030void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
1031 using detail::fs_time;
1032 ErrorHandler<void> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001033
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001034 error_code m_ec;
1035 array<TimeSpec, 2> tbuf;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001036#if !defined(_LIBCPP_USE_UTIMENSAT)
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001037 // This implementation has a race condition between determining the
1038 // last access time and attempting to set it to the same value using
1039 // ::utimes
1040 StatT st;
1041 file_status fst = detail::posix_stat(p, st, &m_ec);
1042 if (m_ec)
1043 return err.report(m_ec);
1044 tbuf[0] = detail::extract_atime(st);
Eric Fiselier435db152016-06-17 19:46:40 +00001045#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001046 tbuf[0].tv_sec = 0;
1047 tbuf[0].tv_nsec = UTIME_OMIT;
Eric Fiselier435db152016-06-17 19:46:40 +00001048#endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001049 if (!fs_time::convert_to_timespec(tbuf[1], new_time))
1050 return err.report(errc::value_too_large);
Eric Fiselier70474082018-07-20 01:22:32 +00001051
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001052 detail::set_file_times(p, tbuf, m_ec);
1053 if (m_ec)
1054 return err.report(m_ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001055}
1056
Eric Fiselier4f3dc0e2018-03-26 06:23:55 +00001057void __permissions(const path& p, perms prms, perm_options opts,
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001058 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001059 ErrorHandler<void> err("permissions", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001060
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001061 auto has_opt = [&](perm_options o) { return bool(o & opts); };
1062 const bool resolve_symlinks = !has_opt(perm_options::nofollow);
1063 const bool add_perms = has_opt(perm_options::add);
1064 const bool remove_perms = has_opt(perm_options::remove);
1065 _LIBCPP_ASSERT(
1066 (add_perms + remove_perms + has_opt(perm_options::replace)) == 1,
1067 "One and only one of the perm_options constants replace, add, or remove "
1068 "is present in opts");
1069
1070 bool set_sym_perms = false;
1071 prms &= perms::mask;
1072 if (!resolve_symlinks || (add_perms || remove_perms)) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001073 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001074 file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
1075 : detail::posix_lstat(p, &m_ec);
1076 set_sym_perms = is_symlink(st);
1077 if (m_ec)
1078 return err.report(m_ec);
1079 _LIBCPP_ASSERT(st.permissions() != perms::unknown,
1080 "Permissions unexpectedly unknown");
1081 if (add_perms)
1082 prms |= st.permissions();
1083 else if (remove_perms)
1084 prms = st.permissions() & ~prms;
1085 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001086 const auto real_perms = detail::posix_convert_perms(prms);
Eric Fiselier435db152016-06-17 19:46:40 +00001087
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001088#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
1089 const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
1090 if (::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
1091 return err.report(capture_errno());
1092 }
1093#else
1094 if (set_sym_perms)
1095 return err.report(errc::operation_not_supported);
1096 if (::chmod(p.c_str(), real_perms) == -1) {
1097 return err.report(capture_errno());
1098 }
1099#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001100}
1101
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001102path __read_symlink(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001103 ErrorHandler<path> err("read_symlink", ec, &p);
1104
Eric Fiselierb5215302019-01-17 02:59:28 +00001105#ifdef PATH_MAX
1106 struct NullDeleter { void operator()(void*) const {} };
1107 const size_t size = PATH_MAX + 1;
1108 char stack_buff[size];
1109 auto buff = std::unique_ptr<char[], NullDeleter>(stack_buff);
1110#else
1111 StatT sb;
1112 if (::lstat(p.c_str(), &sb) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001113 return err.report(capture_errno());
1114 }
Eric Fiselierb5215302019-01-17 02:59:28 +00001115 const size_t size = sb.st_size + 1;
1116 auto buff = unique_ptr<char[]>(new char[size]);
1117#endif
1118 ::ssize_t ret;
1119 if ((ret = ::readlink(p.c_str(), buff.get(), size)) == -1)
1120 return err.report(capture_errno());
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001121 _LIBCPP_ASSERT(ret > 0, "TODO");
Eric Fiselierb5215302019-01-17 02:59:28 +00001122 if (static_cast<size_t>(ret) >= size)
1123 return err.report(errc::value_too_large);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001124 buff[ret] = 0;
Eric Fiselierb5215302019-01-17 02:59:28 +00001125 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001126}
1127
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001128bool __remove(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001129 ErrorHandler<bool> err("remove", ec, &p);
1130 if (::remove(p.c_str()) == -1) {
1131 if (errno != ENOENT)
1132 err.report(capture_errno());
1133 return false;
1134 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001135 return true;
Eric Fiselier435db152016-06-17 19:46:40 +00001136}
1137
1138namespace {
1139
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001140uintmax_t remove_all_impl(path const& p, error_code& ec) {
1141 const auto npos = static_cast<uintmax_t>(-1);
1142 const file_status st = __symlink_status(p, &ec);
1143 if (ec)
1144 return npos;
1145 uintmax_t count = 1;
1146 if (is_directory(st)) {
1147 for (directory_iterator it(p, ec); !ec && it != directory_iterator();
1148 it.increment(ec)) {
1149 auto other_count = remove_all_impl(it->path(), ec);
1150 if (ec)
1151 return npos;
1152 count += other_count;
Eric Fiselier435db152016-06-17 19:46:40 +00001153 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001154 if (ec)
1155 return npos;
1156 }
1157 if (!__remove(p, &ec))
1158 return npos;
1159 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001160}
1161
1162} // end namespace
1163
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001164uintmax_t __remove_all(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001165 ErrorHandler<uintmax_t> err("remove_all", ec, &p);
Ekaterina Vaartis52668f72018-01-11 17:04:29 +00001166
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001167 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001168 auto count = remove_all_impl(p, mec);
1169 if (mec) {
1170 if (mec == errc::no_such_file_or_directory)
1171 return 0;
1172 return err.report(mec);
1173 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001174 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001175}
1176
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001177void __rename(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001178 ErrorHandler<void> err("rename", ec, &from, &to);
1179 if (::rename(from.c_str(), to.c_str()) == -1)
1180 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001181}
1182
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001183void __resize_file(const path& p, uintmax_t size, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001184 ErrorHandler<void> err("resize_file", ec, &p);
1185 if (::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
1186 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001187}
1188
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001189space_info __space(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001190 ErrorHandler<void> err("space", ec, &p);
1191 space_info si;
1192 struct statvfs m_svfs = {};
1193 if (::statvfs(p.c_str(), &m_svfs) == -1) {
1194 err.report(capture_errno());
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001195 si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001196 return si;
1197 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001198 // Multiply with overflow checking.
1199 auto do_mult = [&](uintmax_t& out, uintmax_t other) {
1200 out = other * m_svfs.f_frsize;
1201 if (other == 0 || out / other != m_svfs.f_frsize)
1202 out = static_cast<uintmax_t>(-1);
1203 };
1204 do_mult(si.capacity, m_svfs.f_blocks);
1205 do_mult(si.free, m_svfs.f_bfree);
1206 do_mult(si.available, m_svfs.f_bavail);
1207 return si;
Eric Fiselier435db152016-06-17 19:46:40 +00001208}
1209
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001210file_status __status(const path& p, error_code* ec) {
1211 return detail::posix_stat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001212}
1213
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001214file_status __symlink_status(const path& p, error_code* ec) {
1215 return detail::posix_lstat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001216}
1217
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001218path __temp_directory_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001219 ErrorHandler<path> err("temp_directory_path", ec);
1220
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001221 const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1222 const char* ret = nullptr;
1223
1224 for (auto& ep : env_paths)
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001225 if ((ret = getenv(ep)))
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001226 break;
1227 if (ret == nullptr)
1228 ret = "/tmp";
1229
1230 path p(ret);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001231 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001232 file_status st = detail::posix_stat(p, &m_ec);
1233 if (!status_known(st))
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001234 return err.report(m_ec, "cannot access path \"" PS_FMT "\"", p);
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001235
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001236 if (!exists(st) || !is_directory(st))
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001237 return err.report(errc::not_a_directory, "path \"" PS_FMT "\" is not a directory",
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001238 p);
1239
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001240 return p;
Eric Fiselier435db152016-06-17 19:46:40 +00001241}
1242
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001243path __weakly_canonical(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001244 ErrorHandler<path> err("weakly_canonical", ec, &p);
1245
Eric Fiselier91a182b2018-04-02 23:03:41 +00001246 if (p.empty())
1247 return __canonical("", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001248
Eric Fiselier91a182b2018-04-02 23:03:41 +00001249 path result;
1250 path tmp;
1251 tmp.__reserve(p.native().size());
1252 auto PP = PathParser::CreateEnd(p.native());
1253 --PP;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001254 vector<string_view_t> DNEParts;
Eric Fiselier435db152016-06-17 19:46:40 +00001255
Eric Fiselier91a182b2018-04-02 23:03:41 +00001256 while (PP.State != PathParser::PS_BeforeBegin) {
1257 tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001258 error_code m_ec;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001259 file_status st = __status(tmp, &m_ec);
1260 if (!status_known(st)) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001261 return err.report(m_ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001262 } else if (exists(st)) {
1263 result = __canonical(tmp, ec);
1264 break;
Eric Fiselier435db152016-06-17 19:46:40 +00001265 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001266 DNEParts.push_back(*PP);
1267 --PP;
1268 }
1269 if (PP.State == PathParser::PS_BeforeBegin)
1270 result = __canonical("", ec);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001271 if (ec)
1272 ec->clear();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001273 if (DNEParts.empty())
1274 return result;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001275 for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001276 result /= *It;
1277 return result.lexically_normal();
Eric Fiselier435db152016-06-17 19:46:40 +00001278}
1279
Eric Fiselier91a182b2018-04-02 23:03:41 +00001280///////////////////////////////////////////////////////////////////////////////
1281// path definitions
1282///////////////////////////////////////////////////////////////////////////////
1283
1284constexpr path::value_type path::preferred_separator;
1285
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001286path& path::replace_extension(path const& replacement) {
1287 path p = extension();
1288 if (not p.empty()) {
1289 __pn_.erase(__pn_.size() - p.native().size());
1290 }
1291 if (!replacement.empty()) {
1292 if (replacement.native()[0] != '.') {
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001293 __pn_ += PS(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001294 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001295 __pn_.append(replacement.__pn_);
1296 }
1297 return *this;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001298}
1299
1300///////////////////////////////////////////////////////////////////////////////
1301// path.decompose
1302
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001303string_view_t path::__root_name() const {
1304 auto PP = PathParser::CreateBegin(__pn_);
1305 if (PP.State == PathParser::PS_InRootName)
1306 return *PP;
1307 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001308}
1309
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001310string_view_t path::__root_directory() const {
1311 auto PP = PathParser::CreateBegin(__pn_);
1312 if (PP.State == PathParser::PS_InRootName)
1313 ++PP;
1314 if (PP.State == PathParser::PS_InRootDir)
1315 return *PP;
1316 return {};
1317}
1318
1319string_view_t path::__root_path_raw() const {
1320 auto PP = PathParser::CreateBegin(__pn_);
1321 if (PP.State == PathParser::PS_InRootName) {
1322 auto NextCh = PP.peek();
1323 if (NextCh && *NextCh == '/') {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001324 ++PP;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001325 return createView(__pn_.data(), &PP.RawEntry.back());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001326 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001327 return PP.RawEntry;
1328 }
1329 if (PP.State == PathParser::PS_InRootDir)
1330 return *PP;
1331 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001332}
1333
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001334static bool ConsumeRootName(PathParser *PP) {
1335 static_assert(PathParser::PS_BeforeBegin == 1 &&
1336 PathParser::PS_InRootName == 2,
1337 "Values for enums are incorrect");
1338 while (PP->State <= PathParser::PS_InRootName)
1339 ++(*PP);
1340 return PP->State == PathParser::PS_AtEnd;
1341}
1342
Eric Fiselier91a182b2018-04-02 23:03:41 +00001343static bool ConsumeRootDir(PathParser* PP) {
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001344 static_assert(PathParser::PS_BeforeBegin == 1 &&
1345 PathParser::PS_InRootName == 2 &&
1346 PathParser::PS_InRootDir == 3, "Values for enums are incorrect");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001347 while (PP->State <= PathParser::PS_InRootDir)
1348 ++(*PP);
1349 return PP->State == PathParser::PS_AtEnd;
1350}
1351
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001352string_view_t path::__relative_path() const {
1353 auto PP = PathParser::CreateBegin(__pn_);
1354 if (ConsumeRootDir(&PP))
1355 return {};
1356 return createView(PP.RawEntry.data(), &__pn_.back());
1357}
1358
1359string_view_t path::__parent_path() const {
1360 if (empty())
1361 return {};
1362 // Determine if we have a root path but not a relative path. In that case
1363 // return *this.
1364 {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001365 auto PP = PathParser::CreateBegin(__pn_);
1366 if (ConsumeRootDir(&PP))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001367 return __pn_;
1368 }
1369 // Otherwise remove a single element from the end of the path, and return
1370 // a string representing that path
1371 {
1372 auto PP = PathParser::CreateEnd(__pn_);
1373 --PP;
1374 if (PP.RawEntry.data() == __pn_.data())
Eric Fiselier91a182b2018-04-02 23:03:41 +00001375 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001376 --PP;
1377 return createView(__pn_.data(), &PP.RawEntry.back());
1378 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001379}
1380
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001381string_view_t path::__filename() const {
1382 if (empty())
1383 return {};
1384 {
1385 PathParser PP = PathParser::CreateBegin(__pn_);
1386 if (ConsumeRootDir(&PP))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001387 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001388 }
1389 return *(--PathParser::CreateEnd(__pn_));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001390}
1391
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001392string_view_t path::__stem() const {
1393 return parser::separate_filename(__filename()).first;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001394}
1395
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001396string_view_t path::__extension() const {
1397 return parser::separate_filename(__filename()).second;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001398}
1399
1400////////////////////////////////////////////////////////////////////////////
1401// path.gen
1402
Eric Fiselier91a182b2018-04-02 23:03:41 +00001403enum PathPartKind : unsigned char {
1404 PK_None,
1405 PK_RootSep,
1406 PK_Filename,
1407 PK_Dot,
1408 PK_DotDot,
1409 PK_TrailingSep
1410};
1411
1412static PathPartKind ClassifyPathPart(string_view_t Part) {
1413 if (Part.empty())
1414 return PK_TrailingSep;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001415 if (Part == PS("."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001416 return PK_Dot;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001417 if (Part == PS(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001418 return PK_DotDot;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001419 if (Part == PS("/"))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001420 return PK_RootSep;
1421 return PK_Filename;
1422}
1423
1424path path::lexically_normal() const {
1425 if (__pn_.empty())
1426 return *this;
1427
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001428 using PartKindPair = pair<string_view_t, PathPartKind>;
1429 vector<PartKindPair> Parts;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001430 // Guess as to how many elements the path has to avoid reallocating.
1431 Parts.reserve(32);
1432
1433 // Track the total size of the parts as we collect them. This allows the
1434 // resulting path to reserve the correct amount of memory.
1435 size_t NewPathSize = 0;
1436 auto AddPart = [&](PathPartKind K, string_view_t P) {
1437 NewPathSize += P.size();
1438 Parts.emplace_back(P, K);
1439 };
1440 auto LastPartKind = [&]() {
1441 if (Parts.empty())
1442 return PK_None;
1443 return Parts.back().second;
1444 };
1445
1446 bool MaybeNeedTrailingSep = false;
1447 // Build a stack containing the remaining elements of the path, popping off
1448 // elements which occur before a '..' entry.
1449 for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) {
1450 auto Part = *PP;
1451 PathPartKind Kind = ClassifyPathPart(Part);
1452 switch (Kind) {
1453 case PK_Filename:
1454 case PK_RootSep: {
1455 // Add all non-dot and non-dot-dot elements to the stack of elements.
1456 AddPart(Kind, Part);
1457 MaybeNeedTrailingSep = false;
1458 break;
1459 }
1460 case PK_DotDot: {
1461 // Only push a ".." element if there are no elements preceding the "..",
1462 // or if the preceding element is itself "..".
1463 auto LastKind = LastPartKind();
1464 if (LastKind == PK_Filename) {
1465 NewPathSize -= Parts.back().first.size();
1466 Parts.pop_back();
1467 } else if (LastKind != PK_RootSep)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001468 AddPart(PK_DotDot, PS(".."));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001469 MaybeNeedTrailingSep = LastKind == PK_Filename;
1470 break;
1471 }
1472 case PK_Dot:
1473 case PK_TrailingSep: {
1474 MaybeNeedTrailingSep = true;
1475 break;
1476 }
1477 case PK_None:
1478 _LIBCPP_UNREACHABLE();
1479 }
1480 }
1481 // [fs.path.generic]p6.8: If the path is empty, add a dot.
1482 if (Parts.empty())
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001483 return PS(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001484
1485 // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any
1486 // trailing directory-separator.
1487 bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename;
1488
1489 path Result;
1490 Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001491 for (auto& PK : Parts)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001492 Result /= PK.first;
1493
1494 if (NeedTrailingSep)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001495 Result /= PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001496
1497 return Result;
1498}
1499
1500static int DetermineLexicalElementCount(PathParser PP) {
1501 int Count = 0;
1502 for (; PP; ++PP) {
1503 auto Elem = *PP;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001504 if (Elem == PS(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001505 --Count;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001506 else if (Elem != PS(".") && Elem != PS(""))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001507 ++Count;
1508 }
1509 return Count;
1510}
1511
1512path path::lexically_relative(const path& base) const {
1513 { // perform root-name/root-directory mismatch checks
1514 auto PP = PathParser::CreateBegin(__pn_);
1515 auto PPBase = PathParser::CreateBegin(base.__pn_);
1516 auto CheckIterMismatchAtBase = [&]() {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001517 return PP.State != PPBase.State &&
1518 (PP.inRootPath() || PPBase.inRootPath());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001519 };
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001520 if (PP.inRootName() && PPBase.inRootName()) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001521 if (*PP != *PPBase)
1522 return {};
1523 } else if (CheckIterMismatchAtBase())
1524 return {};
1525
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001526 if (PP.inRootPath())
1527 ++PP;
1528 if (PPBase.inRootPath())
1529 ++PPBase;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001530 if (CheckIterMismatchAtBase())
1531 return {};
1532 }
1533
1534 // Find the first mismatching element
1535 auto PP = PathParser::CreateBegin(__pn_);
1536 auto PPBase = PathParser::CreateBegin(base.__pn_);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001537 while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001538 ++PP;
1539 ++PPBase;
1540 }
1541
1542 // If there is no mismatch, return ".".
1543 if (!PP && !PPBase)
1544 return ".";
1545
1546 // Otherwise, determine the number of elements, 'n', which are not dot or
1547 // dot-dot minus the number of dot-dot elements.
1548 int ElemCount = DetermineLexicalElementCount(PPBase);
1549 if (ElemCount < 0)
1550 return {};
1551
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001552 // if n == 0 and (a == end() || a->empty()), returns path("."); otherwise
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001553 if (ElemCount == 0 && (PP.atEnd() || *PP == PS("")))
1554 return PS(".");
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001555
Eric Fiselier91a182b2018-04-02 23:03:41 +00001556 // return a path constructed with 'n' dot-dot elements, followed by the the
1557 // elements of '*this' after the mismatch.
1558 path Result;
1559 // FIXME: Reserve enough room in Result that it won't have to re-allocate.
1560 while (ElemCount--)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001561 Result /= PS("..");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001562 for (; PP; ++PP)
1563 Result /= *PP;
1564 return Result;
1565}
1566
1567////////////////////////////////////////////////////////////////////////////
1568// path.comparisons
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001569static int CompareRootName(PathParser *LHS, PathParser *RHS) {
1570 if (!LHS->inRootName() && !RHS->inRootName())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001571 return 0;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001572
1573 auto GetRootName = [](PathParser *Parser) -> string_view_t {
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001574 return Parser->inRootName() ? **Parser : PS("");
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001575 };
1576 int res = GetRootName(LHS).compare(GetRootName(RHS));
1577 ConsumeRootName(LHS);
1578 ConsumeRootName(RHS);
1579 return res;
1580}
1581
1582static int CompareRootDir(PathParser *LHS, PathParser *RHS) {
1583 if (!LHS->inRootDir() && RHS->inRootDir())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001584 return -1;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001585 else if (LHS->inRootDir() && !RHS->inRootDir())
1586 return 1;
1587 else {
1588 ConsumeRootDir(LHS);
1589 ConsumeRootDir(RHS);
1590 return 0;
1591 }
1592}
1593
1594static int CompareRelative(PathParser *LHSPtr, PathParser *RHSPtr) {
1595 auto &LHS = *LHSPtr;
1596 auto &RHS = *RHSPtr;
Stephan T. Lavavejfb39ad72019-10-23 11:45:36 -07001597
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001598 int res;
1599 while (LHS && RHS) {
1600 if ((res = (*LHS).compare(*RHS)) != 0)
1601 return res;
1602 ++LHS;
1603 ++RHS;
1604 }
1605 return 0;
1606}
1607
1608static int CompareEndState(PathParser *LHS, PathParser *RHS) {
1609 if (LHS->atEnd() && !RHS->atEnd())
1610 return -1;
1611 else if (!LHS->atEnd() && RHS->atEnd())
1612 return 1;
1613 return 0;
1614}
1615
1616int path::__compare(string_view_t __s) const {
1617 auto LHS = PathParser::CreateBegin(__pn_);
1618 auto RHS = PathParser::CreateBegin(__s);
1619 int res;
1620
1621 if ((res = CompareRootName(&LHS, &RHS)) != 0)
1622 return res;
1623
1624 if ((res = CompareRootDir(&LHS, &RHS)) != 0)
1625 return res;
1626
1627 if ((res = CompareRelative(&LHS, &RHS)) != 0)
1628 return res;
1629
1630 return CompareEndState(&LHS, &RHS);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001631}
1632
1633////////////////////////////////////////////////////////////////////////////
1634// path.nonmembers
1635size_t hash_value(const path& __p) noexcept {
1636 auto PP = PathParser::CreateBegin(__p.native());
1637 size_t hash_value = 0;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001638 hash<string_view_t> hasher;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001639 while (PP) {
1640 hash_value = __hash_combine(hash_value, hasher(*PP));
1641 ++PP;
1642 }
1643 return hash_value;
1644}
1645
1646////////////////////////////////////////////////////////////////////////////
1647// path.itr
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001648path::iterator path::begin() const {
1649 auto PP = PathParser::CreateBegin(__pn_);
1650 iterator it;
1651 it.__path_ptr_ = this;
1652 it.__state_ = static_cast<path::iterator::_ParserState>(PP.State);
1653 it.__entry_ = PP.RawEntry;
1654 it.__stashed_elem_.__assign_view(*PP);
1655 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001656}
1657
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001658path::iterator path::end() const {
1659 iterator it{};
1660 it.__state_ = path::iterator::_AtEnd;
1661 it.__path_ptr_ = this;
1662 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001663}
1664
1665path::iterator& path::iterator::__increment() {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001666 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1667 ++PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001668 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001669 __entry_ = PP.RawEntry;
1670 __stashed_elem_.__assign_view(*PP);
1671 return *this;
1672}
1673
1674path::iterator& path::iterator::__decrement() {
1675 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1676 --PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001677 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001678 __entry_ = PP.RawEntry;
1679 __stashed_elem_.__assign_view(*PP);
1680 return *this;
1681}
1682
Eric Fiselier70474082018-07-20 01:22:32 +00001683///////////////////////////////////////////////////////////////////////////////
1684// directory entry definitions
1685///////////////////////////////////////////////////////////////////////////////
1686
1687#ifndef _LIBCPP_WIN32API
1688error_code directory_entry::__do_refresh() noexcept {
1689 __data_.__reset();
1690 error_code failure_ec;
1691
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001692 StatT full_st;
Eric Fiselier70474082018-07-20 01:22:32 +00001693 file_status st = detail::posix_lstat(__p_, full_st, &failure_ec);
1694 if (!status_known(st)) {
1695 __data_.__reset();
1696 return failure_ec;
1697 }
1698
1699 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1700 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1701 __data_.__type_ = st.type();
1702 __data_.__non_sym_perms_ = st.permissions();
1703 } else { // we have a symlink
1704 __data_.__sym_perms_ = st.permissions();
1705 // Get the information about the linked entity.
1706 // Ignore errors from stat, since we don't want errors regarding symlink
1707 // resolution to be reported to the user.
1708 error_code ignored_ec;
1709 st = detail::posix_stat(__p_, full_st, &ignored_ec);
1710
1711 __data_.__type_ = st.type();
1712 __data_.__non_sym_perms_ = st.permissions();
1713
1714 // If we failed to resolve the link, then only partially populate the
1715 // cache.
1716 if (!status_known(st)) {
1717 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1718 return error_code{};
1719 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001720 // Otherwise, we resolved the link, potentially as not existing.
Eric Fiseliere39cea92018-07-20 08:36:45 +00001721 // That's OK.
Eric Fiselier70474082018-07-20 01:22:32 +00001722 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1723 }
1724
1725 if (_VSTD_FS::is_regular_file(st))
1726 __data_.__size_ = static_cast<uintmax_t>(full_st.st_size);
1727
1728 if (_VSTD_FS::exists(st)) {
1729 __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink);
1730
1731 // Attempt to extract the mtime, and fail if it's not representable using
1732 // file_time_type. For now we ignore the error, as we'll report it when
1733 // the value is actually used.
1734 error_code ignored_ec;
1735 __data_.__write_time_ =
1736 __extract_last_write_time(__p_, full_st, &ignored_ec);
1737 }
1738
1739 return failure_ec;
1740}
1741#else
1742error_code directory_entry::__do_refresh() noexcept {
1743 __data_.__reset();
1744 error_code failure_ec;
1745
1746 file_status st = _VSTD_FS::symlink_status(__p_, failure_ec);
1747 if (!status_known(st)) {
1748 __data_.__reset();
1749 return failure_ec;
1750 }
1751
1752 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1753 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1754 __data_.__type_ = st.type();
1755 __data_.__non_sym_perms_ = st.permissions();
1756 } else { // we have a symlink
1757 __data_.__sym_perms_ = st.permissions();
1758 // Get the information about the linked entity.
1759 // Ignore errors from stat, since we don't want errors regarding symlink
1760 // resolution to be reported to the user.
1761 error_code ignored_ec;
1762 st = _VSTD_FS::status(__p_, ignored_ec);
1763
1764 __data_.__type_ = st.type();
1765 __data_.__non_sym_perms_ = st.permissions();
1766
1767 // If we failed to resolve the link, then only partially populate the
1768 // cache.
1769 if (!status_known(st)) {
1770 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1771 return error_code{};
1772 }
Eric Fiselier70474082018-07-20 01:22:32 +00001773 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1774 }
1775
1776 // FIXME: This is currently broken, and the implementation only a placeholder.
1777 // We need to cache last_write_time, file_size, and hard_link_count here before
1778 // the implementation actually works.
1779
1780 return failure_ec;
1781}
1782#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001783
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001784_LIBCPP_END_NAMESPACE_FILESYSTEM